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