source: src/mlx/gui/cef.py

python3
Last change on this file was 1111:cb25010707a5, checked in by István Váradi <ivaradi@…>, 7 months ago

Yet another trick to make CEF work on Linux properly

File size: 14.9 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()
[1111]211 GObject.timeout_add(100, _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()
[1111]253
254 if os.name != "nt":
255 Gtk.main_quit()
256
[1091]257 return False
[682]258
[648]259#------------------------------------------------------------------------------
260
[1108]261def messageLoop():
262 """Run the CEF message loop"""
263 cefpython.MessageLoop()
264
265#------------------------------------------------------------------------------
266
[648]267def getContainer():
268 """Get a container object suitable for running a browser instance
269 within."""
[1083]270 container = Gtk.DrawingArea()
271 container.set_property("can-focus", True)
272 container.connect("size-allocate", _handleSizeAllocate)
[648]273 container.show()
274
275 return container
276
277#------------------------------------------------------------------------------
278
279def startInContainer(container, url, browserSettings = {}):
280 """Start a browser instance in the given container with the given URL."""
281 if os.name=="nt":
[997]282 Gdk.threads_enter()
[945]283 ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p
284 ctypes.pythonapi.PyCapsule_GetPointer.argtypes = \
285 [ctypes.py_object]
286 gpointer = ctypes.pythonapi.PyCapsule_GetPointer(
287 container.get_property("window").__gpointer__, None)
288 libgdk = ctypes.CDLL("libgdk-3-0.dll")
289 windowID = libgdk.gdk_win32_window_get_handle(gpointer)
290 container.windowID = windowID
[997]291 Gdk.threads_leave()
[1083]292 windowRect = [0, 0, 1, 1]
[648]293 else:
[924]294 container.set_visual(container.get_screen().lookup_visual(0x21))
295 windowID = container.get_window().get_xid()
[1083]296 windowRect = None
[648]297
298 windowInfo = cefpython.WindowInfo()
[805]299 if windowID is not None:
[1083]300 windowInfo.SetAsChild(windowID, windowRect = windowRect)
[648]301
[1083]302 browser = cefpython.CreateBrowserSync(windowInfo,
303 browserSettings = browserSettings,
304 navigateUrl = url)
305 container.browser = browser
306
307 return browser
[648]308
309#------------------------------------------------------------------------------
310
[685]311class OffscreenRenderHandler(object):
[943]312 def GetRootScreenRect(self, browser, rect_out):
[685]313 #print "GetRootScreenRect"
[1083]314 rect_out += [0, 0, 1920, 1080]
[685]315 return True
316
[943]317 def GetViewRect(self, browser, rect_out):
[685]318 #print "GetViewRect"
[1083]319 rect_out += [0, 40, 1920, 1040]
[685]320 return True
321
322 def GetScreenPoint(self, browser, viewX, viewY, screenCoordinates):
323 #print "GetScreenPoint", viewX, viewY
324 rect += [viewX, viewY]
325 return True
326
327 def GetScreenInfo(self, browser, screenInfo):
328 #print "GetScreenInfo"
329 pass
330
331 def OnPopupShow(self, browser, show):
332 #print "OnPopupShow", show
333 pass
334
335 def OnPopupSize(self, browser, rect):
336 #print "OnPopupSize", rect
337 pass
338
[943]339 def OnPaint(self, browser, element_type, dirty_rects, paint_buffer, width, height):
[685]340 #print "OnPaint", paintElementType, dirtyRects, buffer, width, height
341 pass
342
343 def OnCursorChange(self, browser, cursor):
344 #print "OnCursorChange", cursor
345 pass
346
347 def OnScrollOffsetChanged(self, browser):
348 #print "OnScrollOffsetChange"
349 pass
350
[1083]351 def OnBeforePopup(self, browser, frame, target_url, target_frame_name,
352 target_disposition, user_gesture,
353 popup_features, window_info_out, client,
354 browser_settings_out, no_javascript_access_out,
355 **kwargs):
[685]356 wInfo = cefpython.WindowInfo()
357 wInfo.SetAsOffscreen(int(0))
358
[1083]359 window_info_out.append(wInfo)
[685]360
361 return False
362
363#------------------------------------------------------------------------------
364
365def initializeSimBrief():
366 """Initialize the (hidden) browser window for SimBrief."""
[805]367 _simBriefHandler.initialize()
[685]368
369#------------------------------------------------------------------------------
370
371def callSimBrief(plan, getCredentials, updateProgress, htmlFilePath):
[805]372 """Call SimBrief with the given plan.
373
374 The callbacks will be called in the main GUI thread."""
375 _simBriefHandler.call(plan, getCredentials, updateProgress, htmlFilePath)
[685]376
377#------------------------------------------------------------------------------
378
[1097]379def finalizeSimBrief():
380 """Finallize the (hidden) browser window for SimBrief."""
381 if _simBriefHandler is not None:
382 _simBriefHandler.finalize()
383
384#------------------------------------------------------------------------------
385
[1108]386def quitMessageLoop():
387 """Quit the CEF message loop"""
388 cefpython.QuitMessageLoop()
389
390#------------------------------------------------------------------------------
391
[648]392def finalize():
393 """Finalize the Chrome Embedded Framework."""
[805]394 global _toQuit
395 _toQuit = True
[1083]396
[1097]397 if os.name!="nt":
398 cefpython.Shutdown()
399
400#------------------------------------------------------------------------------
[1083]401
[1097]402def clearCache():
403 """Clear the CEF cache directory."""
404 try:
405 shutil.rmtree(cacheDir)
406 print("gui.cef.clearCache: the cache directory is removed")
407 except Exception as e:
408 print("gui.cef.clearCache: cache directory removal failed:", e)
[648]409
410#------------------------------------------------------------------------------
411
412def _handleTimeout():
413 """Handle the timeout by running the CEF message loop."""
414 if _toQuit:
415 return False
416 else:
417 cefpython.MessageLoopWork()
418 return True
419
420#------------------------------------------------------------------------------
421
422def _handleSizeAllocate(widget, sizeAlloc):
[945]423 """Handle the size-allocate event on Windows."""
[1083]424 if os.name=="nt":
425 if widget is not None and hasattr(widget, "windowID"):
426 cefpython.WindowUtils.OnSize(widget.windowID, 0, 0, 0)
427 else:
428 if widget is not None and hasattr(widget, "browser") and \
429 widget.browser is not None:
430 widget.browser.SetBounds(sizeAlloc.x, sizeAlloc.y,
431 sizeAlloc.width, sizeAlloc.height)
Note: See TracBrowser for help on using the repository browser.