1 | from .common import *
|
---|
2 |
|
---|
3 | from mlx.util import secondaryInstallation
|
---|
4 |
|
---|
5 | from cefpython3 import cefpython
|
---|
6 |
|
---|
7 | import platform
|
---|
8 | import json
|
---|
9 | import time
|
---|
10 | import os
|
---|
11 | import re
|
---|
12 | import _thread
|
---|
13 | import threading
|
---|
14 | import tempfile
|
---|
15 | import traceback
|
---|
16 | import ctypes
|
---|
17 | import urllib.request, urllib.error, urllib.parse
|
---|
18 | from lxml import etree
|
---|
19 | from io import StringIO
|
---|
20 | import lxml.html
|
---|
21 | import 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
|
---|
38 | cacheDir = os.path.join(GLib.get_user_cache_dir(), "mlxcef")
|
---|
39 |
|
---|
40 | #------------------------------------------------------------------------------
|
---|
41 |
|
---|
42 | SIMBRIEF_PROGRESS_SEARCHING_BROWSER = 1
|
---|
43 | SIMBRIEF_PROGRESS_LOADING_FORM = 2
|
---|
44 | SIMBRIEF_PROGRESS_FILLING_FORM = 3
|
---|
45 | SIMBRIEF_PROGRESS_WAITING_LOGIN = 4
|
---|
46 | SIMBRIEF_PROGRESS_LOGGING_IN = 5
|
---|
47 | SIMBRIEF_PROGRESS_WAITING_RESULT = 6
|
---|
48 |
|
---|
49 | SIMBRIEF_PROGRESS_RETRIEVING_BRIEFING = 7
|
---|
50 | SIMBRIEF_PROGRESS_DONE = 1000
|
---|
51 |
|
---|
52 | SIMBRIEF_RESULT_NONE = 0
|
---|
53 | SIMBRIEF_RESULT_OK = 1
|
---|
54 | SIMBRIEF_RESULT_ERROR_OTHER = 2
|
---|
55 | SIMBRIEF_RESULT_ERROR_NO_FORM = 11
|
---|
56 | SIMBRIEF_RESULT_ERROR_NO_POPUP = 12
|
---|
57 | SIMBRIEF_RESULT_ERROR_LOGIN_FAILED = 13
|
---|
58 |
|
---|
59 | #------------------------------------------------------------------------------
|
---|
60 |
|
---|
61 | class 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 |
|
---|
203 | def 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 | GObject.timeout_add(100, _initializeCEF, [], initializedCallback)
|
---|
212 |
|
---|
213 | #------------------------------------------------------------------------------
|
---|
214 |
|
---|
215 | def _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 |
|
---|
254 | if os.name != "nt":
|
---|
255 | Gtk.main_quit()
|
---|
256 |
|
---|
257 | return False
|
---|
258 |
|
---|
259 | #------------------------------------------------------------------------------
|
---|
260 |
|
---|
261 | def messageLoop():
|
---|
262 | """Run the CEF message loop"""
|
---|
263 | cefpython.MessageLoop()
|
---|
264 |
|
---|
265 | #------------------------------------------------------------------------------
|
---|
266 |
|
---|
267 | def getContainer():
|
---|
268 | """Get a container object suitable for running a browser instance
|
---|
269 | within."""
|
---|
270 | container = Gtk.DrawingArea()
|
---|
271 | container.set_property("can-focus", True)
|
---|
272 | container.connect("size-allocate", _handleSizeAllocate)
|
---|
273 | container.show()
|
---|
274 |
|
---|
275 | return container
|
---|
276 |
|
---|
277 | #------------------------------------------------------------------------------
|
---|
278 |
|
---|
279 | def startInContainer(container, url, browserSettings = {}):
|
---|
280 | """Start a browser instance in the given container with the given URL."""
|
---|
281 | if os.name=="nt":
|
---|
282 | Gdk.threads_enter()
|
---|
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
|
---|
291 | Gdk.threads_leave()
|
---|
292 | windowRect = [0, 0, 1, 1]
|
---|
293 | else:
|
---|
294 | container.set_visual(container.get_screen().lookup_visual(0x21))
|
---|
295 | windowID = container.get_window().get_xid()
|
---|
296 | windowRect = None
|
---|
297 |
|
---|
298 | windowInfo = cefpython.WindowInfo()
|
---|
299 | if windowID is not None:
|
---|
300 | windowInfo.SetAsChild(windowID, windowRect = windowRect)
|
---|
301 |
|
---|
302 | browser = cefpython.CreateBrowserSync(windowInfo,
|
---|
303 | browserSettings = browserSettings,
|
---|
304 | navigateUrl = url)
|
---|
305 | container.browser = browser
|
---|
306 |
|
---|
307 | return browser
|
---|
308 |
|
---|
309 | #------------------------------------------------------------------------------
|
---|
310 |
|
---|
311 | class OffscreenRenderHandler(object):
|
---|
312 | def GetRootScreenRect(self, browser, rect_out):
|
---|
313 | #print "GetRootScreenRect"
|
---|
314 | rect_out += [0, 0, 1920, 1080]
|
---|
315 | return True
|
---|
316 |
|
---|
317 | def GetViewRect(self, browser, rect_out):
|
---|
318 | #print "GetViewRect"
|
---|
319 | rect_out += [0, 40, 1920, 1040]
|
---|
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 |
|
---|
339 | def OnPaint(self, browser, element_type, dirty_rects, paint_buffer, width, height):
|
---|
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 |
|
---|
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):
|
---|
356 | wInfo = cefpython.WindowInfo()
|
---|
357 | wInfo.SetAsOffscreen(int(0))
|
---|
358 |
|
---|
359 | window_info_out.append(wInfo)
|
---|
360 |
|
---|
361 | return False
|
---|
362 |
|
---|
363 | #------------------------------------------------------------------------------
|
---|
364 |
|
---|
365 | def initializeSimBrief():
|
---|
366 | """Initialize the (hidden) browser window for SimBrief."""
|
---|
367 | _simBriefHandler.initialize()
|
---|
368 |
|
---|
369 | #------------------------------------------------------------------------------
|
---|
370 |
|
---|
371 | def callSimBrief(plan, getCredentials, updateProgress, htmlFilePath):
|
---|
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)
|
---|
376 |
|
---|
377 | #------------------------------------------------------------------------------
|
---|
378 |
|
---|
379 | def finalizeSimBrief():
|
---|
380 | """Finallize the (hidden) browser window for SimBrief."""
|
---|
381 | if _simBriefHandler is not None:
|
---|
382 | _simBriefHandler.finalize()
|
---|
383 |
|
---|
384 | #------------------------------------------------------------------------------
|
---|
385 |
|
---|
386 | def quitMessageLoop():
|
---|
387 | """Quit the CEF message loop"""
|
---|
388 | cefpython.QuitMessageLoop()
|
---|
389 |
|
---|
390 | #------------------------------------------------------------------------------
|
---|
391 |
|
---|
392 | def finalize():
|
---|
393 | """Finalize the Chrome Embedded Framework."""
|
---|
394 | global _toQuit
|
---|
395 | _toQuit = True
|
---|
396 |
|
---|
397 | if os.name!="nt":
|
---|
398 | cefpython.Shutdown()
|
---|
399 |
|
---|
400 | #------------------------------------------------------------------------------
|
---|
401 |
|
---|
402 | def 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)
|
---|
409 |
|
---|
410 | #------------------------------------------------------------------------------
|
---|
411 |
|
---|
412 | def _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 |
|
---|
422 | def _handleSizeAllocate(widget, sizeAlloc):
|
---|
423 | """Handle the size-allocate event on Windows."""
|
---|
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)
|
---|