source: src/mlx/gui/cef.py@ 1109:986abbce32ef

python3
Last change on this file since 1109:986abbce32ef was 1108:0d45f3dff91b, checked in by István Váradi <ivaradi@…>, 14 months ago

On Linux the CEF message loop is run

File size: 14.8 KB
Line 
1from .common import *
2
3from mlx.util import secondaryInstallation
4
5from cefpython3 import cefpython
6
7import platform
8import json
9import time
10import os
11import re
12import _thread
13import threading
14import tempfile
15import traceback
16import ctypes
17import urllib.request, urllib.error, urllib.parse
18from lxml import etree
19from io import StringIO
20import lxml.html
21import shutil
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
34# The SimBrief handler
35_simBriefHandler = None
36
37# The cache directory
38cacheDir = os.path.join(GLib.get_user_cache_dir(), "mlxcef")
39
40#------------------------------------------------------------------------------
41
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
48
49SIMBRIEF_PROGRESS_RETRIEVING_BRIEFING = 7
50SIMBRIEF_PROGRESS_DONE = 1000
51
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
58
59#------------------------------------------------------------------------------
60
61class SimBriefHandler(object):
62 """An object to store the state of a SimBrief query."""
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)
72
73 _querySettings = {
74 'navlog': True,
75 'etops': True,
76 'stepclimbs': True,
77 'tlr': True,
78 'notams': True,
79 'firnot': True,
80 'maps': 'Simple',
81 };
82
83
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
94
95 def initialize(self):
96 """Create and initialize the browser used for Simbrief."""
97 windowInfo = cefpython.WindowInfo()
98 windowInfo.SetAsOffscreen(int(0))
99
100 self._browser = \
101 cefpython.CreateBrowserSync(windowInfo, browserSettings = {})
102 self._browser.SetClientHandler(OffscreenRenderHandler())
103 self._browser.SetFocus(True)
104 self._browser.SetClientCallback("OnLoadEnd", self._onLoadEnd)
105 self._browser.SetClientCallback("OnLoadError", self._onLoadError)
106 self._browser.SetClientCallback("OnBeforeBrowse",
107 lambda browser, frame, request,
108 user_gesture, is_redirect: False)
109
110 def call(self, plan, getCredentials, updateProgress, htmlFilePath):
111 """Call SimBrief with the given plan."""
112 self._timeoutID = GObject.timeout_add(120*1000, self._timedOut)
113
114 self._plan = plan
115 self._getCredentials = getCredentials
116 self._getCredentialsCount = 0
117 self._updateProgressFn = updateProgress
118 self._htmlFilePath = htmlFilePath
119
120 self._browser.LoadUrl(SimBriefHandler.getFormURL(plan))
121 self._updateProgress(SIMBRIEF_PROGRESS_LOADING_FORM,
122 SIMBRIEF_RESULT_NONE, None)
123
124 def finalize(self):
125 """Close the browser and release it."""
126 if self._browser is not None:
127 self._browser.CloseBrowser(True)
128 self._browser = None
129
130 def _onLoadEnd(self, browser, frame, http_code):
131 """Called when a page has been loaded in the SimBrief browser."""
132 url = frame.GetUrl()
133 print("gui.cef.SimBriefHandler._onLoadEnd", http_code, url)
134 if http_code>=300:
135 self._updateProgress(self._lastProgress,
136 SIMBRIEF_RESULT_ERROR_OTHER, None)
137 elif url.startswith(SimBriefHandler._formURLBase):
138 self._updateProgress(SIMBRIEF_PROGRESS_WAITING_LOGIN,
139 SIMBRIEF_RESULT_NONE, None)
140 elif url.startswith("https://www.simbrief.com/system/login.api.sso.php"):
141 js = "document.getElementsByClassName(\"login_option navigraph\")[0].click();"
142 frame.ExecuteJavascript(js)
143 elif url.startswith("https://identity.api.navigraph.com/login?"):
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
149
150 self._getCredentialsCount += 1
151
152 js = "form=document.getElementsByName(\"form\")[0];"
153 js +="form.username.value=\"" + user + "\";"
154 js +="form.password.value=\"" + password + "\";"
155 js +="form.submit();"
156 frame.ExecuteJavascript(js)
157 elif url.startswith("https://www.simbrief.com/ofp/ofp.loader.api.php"):
158 self._updateProgress(SIMBRIEF_PROGRESS_WAITING_RESULT,
159 SIMBRIEF_RESULT_NONE, None)
160 elif url.startswith(SimBriefHandler._resultURLBase):
161 self._updateProgress(SIMBRIEF_PROGRESS_RETRIEVING_BRIEFING,
162 SIMBRIEF_RESULT_OK, None)
163
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)
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)
176
177 def _updateProgress(self, progress, results, flightInfo):
178 """Update the progress."""
179 self._lastProgress = progress
180 if results!=SIMBRIEF_RESULT_NONE:
181 if self._timeoutID is not None:
182 GObject.source_remove(self._timeoutID)
183 self._plan = None
184
185 if self._updateProgressFn is not None:
186 self._updateProgressFn(progress, results, flightInfo)
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
196
197 self._updateProgress(self._lastProgress, result, None)
198
199 return False
200
201#------------------------------------------------------------------------------
202
203def initialize(initializedCallback):
204 """Initialize the Chrome Embedded Framework."""
205 global _toQuit, _simBriefHandler
206 _toQuit = False
207
208 GObject.threads_init()
209
210 _simBriefHandler = SimBriefHandler()
211 _initializeCEF([], initializedCallback)
212
213#------------------------------------------------------------------------------
214
215def _initializeCEF(args, initializedCallback):
216 """Perform the actual initialization of CEF using the given arguments."""
217 print("Initializing CEF with args:", args)
218
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"),
229 "windowless_rendering_enabled": True,
230 "cache_path": cacheDir,
231 "persist_session_cookies": True,
232 "persist_user_preferences": True
233 }
234
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:
245 print("Unhandled switch", arg)
246
247 cefpython.Initialize(settings, switches)
248
249 GObject.timeout_add(10, _handleTimeout)
250
251 print("Initialized, executing callback...")
252 initializedCallback()
253 return False
254
255#------------------------------------------------------------------------------
256
257def messageLoop():
258 """Run the CEF message loop"""
259 cefpython.MessageLoop()
260
261#------------------------------------------------------------------------------
262
263def getContainer():
264 """Get a container object suitable for running a browser instance
265 within."""
266 container = Gtk.DrawingArea()
267 container.set_property("can-focus", True)
268 container.connect("size-allocate", _handleSizeAllocate)
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":
278 Gdk.threads_enter()
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
287 Gdk.threads_leave()
288 windowRect = [0, 0, 1, 1]
289 else:
290 container.set_visual(container.get_screen().lookup_visual(0x21))
291 windowID = container.get_window().get_xid()
292 windowRect = None
293
294 windowInfo = cefpython.WindowInfo()
295 if windowID is not None:
296 windowInfo.SetAsChild(windowID, windowRect = windowRect)
297
298 browser = cefpython.CreateBrowserSync(windowInfo,
299 browserSettings = browserSettings,
300 navigateUrl = url)
301 container.browser = browser
302
303 return browser
304
305#------------------------------------------------------------------------------
306
307class OffscreenRenderHandler(object):
308 def GetRootScreenRect(self, browser, rect_out):
309 #print "GetRootScreenRect"
310 rect_out += [0, 0, 1920, 1080]
311 return True
312
313 def GetViewRect(self, browser, rect_out):
314 #print "GetViewRect"
315 rect_out += [0, 40, 1920, 1040]
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
335 def OnPaint(self, browser, element_type, dirty_rects, paint_buffer, width, height):
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
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):
352 wInfo = cefpython.WindowInfo()
353 wInfo.SetAsOffscreen(int(0))
354
355 window_info_out.append(wInfo)
356
357 return False
358
359#------------------------------------------------------------------------------
360
361def initializeSimBrief():
362 """Initialize the (hidden) browser window for SimBrief."""
363 _simBriefHandler.initialize()
364
365#------------------------------------------------------------------------------
366
367def callSimBrief(plan, getCredentials, updateProgress, htmlFilePath):
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)
372
373#------------------------------------------------------------------------------
374
375def finalizeSimBrief():
376 """Finallize the (hidden) browser window for SimBrief."""
377 if _simBriefHandler is not None:
378 _simBriefHandler.finalize()
379
380#------------------------------------------------------------------------------
381
382def quitMessageLoop():
383 """Quit the CEF message loop"""
384 cefpython.QuitMessageLoop()
385
386#------------------------------------------------------------------------------
387
388def finalize():
389 """Finalize the Chrome Embedded Framework."""
390 global _toQuit
391 _toQuit = True
392
393 if os.name!="nt":
394 cefpython.Shutdown()
395
396#------------------------------------------------------------------------------
397
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)
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):
419 """Handle the size-allocate event on Windows."""
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.