source: src/mlx/gui/cef.py@ 1110:67a5ba8a8664

python3
Last change on this file since 1110:67a5ba8a8664 was 1108:0d45f3dff91b, checked in by István Váradi <ivaradi@…>, 8 months ago

On Linux the CEF message loop is run

File size: 14.8 KB
RevLine 
[919]1from .common import *
[648]2
[682]3from mlx.util import secondaryInstallation
4
5from cefpython3 import cefpython
6
[648]7import platform
8import json
[682]9import time
[648]10import os
11import re
[919]12import _thread
[682]13import threading
14import tempfile
15import traceback
[945]16import ctypes
[919]17import urllib.request, urllib.error, urllib.parse
[805]18from lxml import etree
[919]19from io import StringIO
[805]20import lxml.html
[1096]21import shutil
[648]22
23#------------------------------------------------------------------------------
24
25## @package mlx.gui.cef
26#
27# Some helper stuff related to the Chrome Embedded Framework
28
29#------------------------------------------------------------------------------
30
31# Indicate if we should quit
32_toQuit = False
33
[805]34# The SimBrief handler
35_simBriefHandler = None
[682]36
[1097]37# The cache directory
38cacheDir = os.path.join(GLib.get_user_cache_dir(), "mlxcef")
39
[682]40#------------------------------------------------------------------------------
41
[805]42SIMBRIEF_PROGRESS_SEARCHING_BROWSER = 1
43SIMBRIEF_PROGRESS_LOADING_FORM = 2
44SIMBRIEF_PROGRESS_FILLING_FORM = 3
45SIMBRIEF_PROGRESS_WAITING_LOGIN = 4
46SIMBRIEF_PROGRESS_LOGGING_IN = 5
47SIMBRIEF_PROGRESS_WAITING_RESULT = 6
[682]48
[805]49SIMBRIEF_PROGRESS_RETRIEVING_BRIEFING = 7
50SIMBRIEF_PROGRESS_DONE = 1000
[682]51
[805]52SIMBRIEF_RESULT_NONE = 0
53SIMBRIEF_RESULT_OK = 1
54SIMBRIEF_RESULT_ERROR_OTHER = 2
55SIMBRIEF_RESULT_ERROR_NO_FORM = 11
56SIMBRIEF_RESULT_ERROR_NO_POPUP = 12
57SIMBRIEF_RESULT_ERROR_LOGIN_FAILED = 13
[682]58
[648]59#------------------------------------------------------------------------------
60
[805]61class SimBriefHandler(object):
62 """An object to store the state of a SimBrief query."""
[1084]63 _formURLBase = MAVA_BASE_URL + "/simbrief_form.php"
64
65 _resultURLBase = MAVA_BASE_URL + "/simbrief_briefing.php"
66
67 @staticmethod
68 def getFormURL(plan):
69 """Get the form URL for the given plan."""
70 return SimBriefHandler._formURLBase + "?" + \
71 urllib.parse.urlencode(plan)
[692]72
[805]73 _querySettings = {
74 'navlog': True,
75 'etops': True,
76 'stepclimbs': True,
77 'tlr': True,
78 'notams': True,
79 'firnot': True,
80 'maps': 'Simple',
81 };
[682]82
83
[805]84 def __init__(self):
85 """Construct the handler."""
86 self._browser = None
87 self._plan = None
88 self._getCredentials = None
89 self._getCredentialsCount = 0
90 self._updateProgressFn = None
91 self._htmlFilePath = None
92 self._lastProgress = SIMBRIEF_PROGRESS_SEARCHING_BROWSER
93 self._timeoutID = None
[682]94
[805]95 def initialize(self):
[695]96 """Create and initialize the browser used for Simbrief."""
97 windowInfo = cefpython.WindowInfo()
98 windowInfo.SetAsOffscreen(int(0))
99
[805]100 self._browser = \
[1084]101 cefpython.CreateBrowserSync(windowInfo, browserSettings = {})
[805]102 self._browser.SetClientHandler(OffscreenRenderHandler())
103 self._browser.SetFocus(True)
104 self._browser.SetClientCallback("OnLoadEnd", self._onLoadEnd)
[1083]105 self._browser.SetClientCallback("OnLoadError", self._onLoadError)
106 self._browser.SetClientCallback("OnBeforeBrowse",
107 lambda browser, frame, request,
108 user_gesture, is_redirect: False)
[805]109
110 def call(self, plan, getCredentials, updateProgress, htmlFilePath):
[685]111 """Call SimBrief with the given plan."""
[995]112 self._timeoutID = GObject.timeout_add(120*1000, self._timedOut)
[805]113
114 self._plan = plan
115 self._getCredentials = getCredentials
116 self._getCredentialsCount = 0
117 self._updateProgressFn = updateProgress
118 self._htmlFilePath = htmlFilePath
119
[1084]120 self._browser.LoadUrl(SimBriefHandler.getFormURL(plan))
[805]121 self._updateProgress(SIMBRIEF_PROGRESS_LOADING_FORM,
122 SIMBRIEF_RESULT_NONE, None)
123
[1083]124 def finalize(self):
125 """Close the browser and release it."""
[1099]126 if self._browser is not None:
127 self._browser.CloseBrowser(True)
128 self._browser = None
[1083]129
[943]130 def _onLoadEnd(self, browser, frame, http_code):
[805]131 """Called when a page has been loaded in the SimBrief browser."""
132 url = frame.GetUrl()
[943]133 print("gui.cef.SimBriefHandler._onLoadEnd", http_code, url)
134 if http_code>=300:
[805]135 self._updateProgress(self._lastProgress,
136 SIMBRIEF_RESULT_ERROR_OTHER, None)
[1084]137 elif url.startswith(SimBriefHandler._formURLBase):
138 self._updateProgress(SIMBRIEF_PROGRESS_WAITING_LOGIN,
[805]139 SIMBRIEF_RESULT_NONE, None)
[1084]140 elif url.startswith("https://www.simbrief.com/system/login.api.sso.php"):
141 js = "document.getElementsByClassName(\"login_option navigraph\")[0].click();"
[805]142 frame.ExecuteJavascript(js)
[1084]143 elif url.startswith("https://identity.api.navigraph.com/login?"):
[805]144 (user, password) = self._getCredentials(self._getCredentialsCount)
145 if user is None or password is None:
146 self._updateProgress(SIMBRIEF_PROGRESS_WAITING_LOGIN,
147 SIMBRIEF_RESULT_ERROR_LOGIN_FAILED, None)
148 return
[682]149
[805]150 self._getCredentialsCount += 1
[1084]151
152 js = "form=document.getElementsByName(\"form\")[0];"
153 js +="form.username.value=\"" + user + "\";"
154 js +="form.password.value=\"" + password + "\";"
155 js +="form.submit();"
[805]156 frame.ExecuteJavascript(js)
[1084]157 elif url.startswith("https://www.simbrief.com/ofp/ofp.loader.api.php"):
[805]158 self._updateProgress(SIMBRIEF_PROGRESS_WAITING_RESULT,
159 SIMBRIEF_RESULT_NONE, None)
[1084]160 elif url.startswith(SimBriefHandler._resultURLBase):
[805]161 self._updateProgress(SIMBRIEF_PROGRESS_RETRIEVING_BRIEFING,
[1084]162 SIMBRIEF_RESULT_OK, None)
[805]163
[1083]164 def _onLoadError(self, browser, frame, error_code, error_text_out,
165 failed_url):
166 """Called when loading of an URL fails."""
167 print("gui.cef.SimBriefHandler._onLoadError", browser, frame, error_code, error_text_out, failed_url)
[1095]168 if error_code==-3 and \
169 failed_url.startswith("https://identity.api.navigraph.com/connect/authorize"):
170 self._browser.LoadUrl(SimBriefHandler.getFormURL(self._plan))
171 self._updateProgress(SIMBRIEF_PROGRESS_LOADING_FORM,
172 SIMBRIEF_RESULT_NONE, None)
173 else:
174 self._updateProgress(self._lastProgress,
175 SIMBRIEF_RESULT_ERROR_OTHER, None)
[805]176
177 def _updateProgress(self, progress, results, flightInfo):
178 """Update the progress."""
179 self._lastProgress = progress
180 if results!=SIMBRIEF_RESULT_NONE:
[944]181 if self._timeoutID is not None:
[995]182 GObject.source_remove(self._timeoutID)
[805]183 self._plan = None
184
[944]185 if self._updateProgressFn is not None:
186 self._updateProgressFn(progress, results, flightInfo)
[805]187
188 def _timedOut(self):
189 """Called when the timeout occurs."""
190 if self._lastProgress==SIMBRIEF_PROGRESS_LOADING_FORM:
191 result = SIMBRIEF_RESULT_ERROR_NO_FORM
192 elif self._lastProgress==SIMBRIEF_PROGRESS_WAITING_LOGIN:
193 result = SIMBRIEF_RESULT_ERROR_NO_POPUP
194 else:
195 result = SIMBRIEF_RESULT_ERROR_OTHER
[685]196
[805]197 self._updateProgress(self._lastProgress, result, None)
198
199 return False
[685]200
[682]201#------------------------------------------------------------------------------
202
[805]203def initialize(initializedCallback):
[648]204 """Initialize the Chrome Embedded Framework."""
[805]205 global _toQuit, _simBriefHandler
[648]206 _toQuit = False
207
[995]208 GObject.threads_init()
[648]209
[805]210 _simBriefHandler = SimBriefHandler()
211 _initializeCEF([], initializedCallback)
[682]212
213#------------------------------------------------------------------------------
214
215def _initializeCEF(args, initializedCallback):
216 """Perform the actual initialization of CEF using the given arguments."""
[919]217 print("Initializing CEF with args:", args)
[682]218
[648]219 settings = {
220 "debug": True, # cefpython debug messages in console and in log_file
221 "log_severity": cefpython.LOGSEVERITY_VERBOSE, # LOGSEVERITY_VERBOSE
222 "log_file": "", # Set to "" to disable
223 "release_dcheck_enabled": True, # Enable only when debugging
224 # This directories must be set on Linux
225 "locales_dir_path": os.path.join(cefpython.GetModuleDirectory(), "locales"),
226 "resources_dir_path": cefpython.GetModuleDirectory(),
227 "browser_subprocess_path": "%s/%s" % \
228 (cefpython.GetModuleDirectory(), "subprocess"),
[1083]229 "windowless_rendering_enabled": True,
[1097]230 "cache_path": cacheDir,
231 "persist_session_cookies": True,
232 "persist_user_preferences": True
[648]233 }
234
[682]235 switches={}
236 for arg in args:
237 if arg.startswith("--"):
238 if arg != "--enable-logging":
239 assignIndex = arg.find("=")
240 if assignIndex<0:
241 switches[arg[2:]] = ""
242 else:
243 switches[arg[2:assignIndex]] = arg[assignIndex+1:]
244 else:
[919]245 print("Unhandled switch", arg)
[682]246
247 cefpython.Initialize(settings, switches)
[648]248
[995]249 GObject.timeout_add(10, _handleTimeout)
[648]250
[919]251 print("Initialized, executing callback...")
[682]252 initializedCallback()
[1091]253 return False
[682]254
[648]255#------------------------------------------------------------------------------
256
[1108]257def messageLoop():
258 """Run the CEF message loop"""
259 cefpython.MessageLoop()
260
261#------------------------------------------------------------------------------
262
[648]263def getContainer():
264 """Get a container object suitable for running a browser instance
265 within."""
[1083]266 container = Gtk.DrawingArea()
267 container.set_property("can-focus", True)
268 container.connect("size-allocate", _handleSizeAllocate)
[648]269 container.show()
270
271 return container
272
273#------------------------------------------------------------------------------
274
275def startInContainer(container, url, browserSettings = {}):
276 """Start a browser instance in the given container with the given URL."""
277 if os.name=="nt":
[997]278 Gdk.threads_enter()
[945]279 ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p
280 ctypes.pythonapi.PyCapsule_GetPointer.argtypes = \
281 [ctypes.py_object]
282 gpointer = ctypes.pythonapi.PyCapsule_GetPointer(
283 container.get_property("window").__gpointer__, None)
284 libgdk = ctypes.CDLL("libgdk-3-0.dll")
285 windowID = libgdk.gdk_win32_window_get_handle(gpointer)
286 container.windowID = windowID
[997]287 Gdk.threads_leave()
[1083]288 windowRect = [0, 0, 1, 1]
[648]289 else:
[924]290 container.set_visual(container.get_screen().lookup_visual(0x21))
291 windowID = container.get_window().get_xid()
[1083]292 windowRect = None
[648]293
294 windowInfo = cefpython.WindowInfo()
[805]295 if windowID is not None:
[1083]296 windowInfo.SetAsChild(windowID, windowRect = windowRect)
[648]297
[1083]298 browser = cefpython.CreateBrowserSync(windowInfo,
299 browserSettings = browserSettings,
300 navigateUrl = url)
301 container.browser = browser
302
303 return browser
[648]304
305#------------------------------------------------------------------------------
306
[685]307class OffscreenRenderHandler(object):
[943]308 def GetRootScreenRect(self, browser, rect_out):
[685]309 #print "GetRootScreenRect"
[1083]310 rect_out += [0, 0, 1920, 1080]
[685]311 return True
312
[943]313 def GetViewRect(self, browser, rect_out):
[685]314 #print "GetViewRect"
[1083]315 rect_out += [0, 40, 1920, 1040]
[685]316 return True
317
318 def GetScreenPoint(self, browser, viewX, viewY, screenCoordinates):
319 #print "GetScreenPoint", viewX, viewY
320 rect += [viewX, viewY]
321 return True
322
323 def GetScreenInfo(self, browser, screenInfo):
324 #print "GetScreenInfo"
325 pass
326
327 def OnPopupShow(self, browser, show):
328 #print "OnPopupShow", show
329 pass
330
331 def OnPopupSize(self, browser, rect):
332 #print "OnPopupSize", rect
333 pass
334
[943]335 def OnPaint(self, browser, element_type, dirty_rects, paint_buffer, width, height):
[685]336 #print "OnPaint", paintElementType, dirtyRects, buffer, width, height
337 pass
338
339 def OnCursorChange(self, browser, cursor):
340 #print "OnCursorChange", cursor
341 pass
342
343 def OnScrollOffsetChanged(self, browser):
344 #print "OnScrollOffsetChange"
345 pass
346
[1083]347 def OnBeforePopup(self, browser, frame, target_url, target_frame_name,
348 target_disposition, user_gesture,
349 popup_features, window_info_out, client,
350 browser_settings_out, no_javascript_access_out,
351 **kwargs):
[685]352 wInfo = cefpython.WindowInfo()
353 wInfo.SetAsOffscreen(int(0))
354
[1083]355 window_info_out.append(wInfo)
[685]356
357 return False
358
359#------------------------------------------------------------------------------
360
361def initializeSimBrief():
362 """Initialize the (hidden) browser window for SimBrief."""
[805]363 _simBriefHandler.initialize()
[685]364
365#------------------------------------------------------------------------------
366
367def callSimBrief(plan, getCredentials, updateProgress, htmlFilePath):
[805]368 """Call SimBrief with the given plan.
369
370 The callbacks will be called in the main GUI thread."""
371 _simBriefHandler.call(plan, getCredentials, updateProgress, htmlFilePath)
[685]372
373#------------------------------------------------------------------------------
374
[1097]375def finalizeSimBrief():
376 """Finallize the (hidden) browser window for SimBrief."""
377 if _simBriefHandler is not None:
378 _simBriefHandler.finalize()
379
380#------------------------------------------------------------------------------
381
[1108]382def quitMessageLoop():
383 """Quit the CEF message loop"""
384 cefpython.QuitMessageLoop()
385
386#------------------------------------------------------------------------------
387
[648]388def finalize():
389 """Finalize the Chrome Embedded Framework."""
[805]390 global _toQuit
391 _toQuit = True
[1083]392
[1097]393 if os.name!="nt":
394 cefpython.Shutdown()
395
396#------------------------------------------------------------------------------
[1083]397
[1097]398def clearCache():
399 """Clear the CEF cache directory."""
400 try:
401 shutil.rmtree(cacheDir)
402 print("gui.cef.clearCache: the cache directory is removed")
403 except Exception as e:
404 print("gui.cef.clearCache: cache directory removal failed:", e)
[648]405
406#------------------------------------------------------------------------------
407
408def _handleTimeout():
409 """Handle the timeout by running the CEF message loop."""
410 if _toQuit:
411 return False
412 else:
413 cefpython.MessageLoopWork()
414 return True
415
416#------------------------------------------------------------------------------
417
418def _handleSizeAllocate(widget, sizeAlloc):
[945]419 """Handle the size-allocate event on Windows."""
[1083]420 if os.name=="nt":
421 if widget is not None and hasattr(widget, "windowID"):
422 cefpython.WindowUtils.OnSize(widget.windowID, 0, 0, 0)
423 else:
424 if widget is not None and hasattr(widget, "browser") and \
425 widget.browser is not None:
426 widget.browser.SetBounds(sizeAlloc.x, sizeAlloc.y,
427 sizeAlloc.width, sizeAlloc.height)
Note: See TracBrowser for help on using the repository browser.