[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."""
|
---|
[1091] | 206 | if os.name=="nt":
|
---|
| 207 | _initializeCEF1(args, initializedCallback)
|
---|
| 208 | else:
|
---|
| 209 | GObject.timeout_add(100, _initializeCEF1, args, initializedCallback)
|
---|
| 210 |
|
---|
| 211 | #------------------------------------------------------------------------------
|
---|
| 212 |
|
---|
| 213 | def _initializeCEF1(args, initializedCallback):
|
---|
| 214 | """Perform the actual initialization of CEF using the given arguments."""
|
---|
[919] | 215 | print("Initializing CEF with args:", args)
|
---|
[682] | 216 |
|
---|
[648] | 217 | settings = {
|
---|
| 218 | "debug": True, # cefpython debug messages in console and in log_file
|
---|
| 219 | "log_severity": cefpython.LOGSEVERITY_VERBOSE, # LOGSEVERITY_VERBOSE
|
---|
| 220 | "log_file": "", # Set to "" to disable
|
---|
| 221 | "release_dcheck_enabled": True, # Enable only when debugging
|
---|
| 222 | # This directories must be set on Linux
|
---|
| 223 | "locales_dir_path": os.path.join(cefpython.GetModuleDirectory(), "locales"),
|
---|
| 224 | "resources_dir_path": cefpython.GetModuleDirectory(),
|
---|
| 225 | "browser_subprocess_path": "%s/%s" % \
|
---|
| 226 | (cefpython.GetModuleDirectory(), "subprocess"),
|
---|
[1083] | 227 | "windowless_rendering_enabled": True,
|
---|
| 228 | "cache_path": os.path.join(GLib.get_user_cache_dir(),
|
---|
| 229 | "mlxcef")
|
---|
[648] | 230 | }
|
---|
| 231 |
|
---|
[682] | 232 | switches={}
|
---|
| 233 | for arg in args:
|
---|
| 234 | if arg.startswith("--"):
|
---|
| 235 | if arg != "--enable-logging":
|
---|
| 236 | assignIndex = arg.find("=")
|
---|
| 237 | if assignIndex<0:
|
---|
| 238 | switches[arg[2:]] = ""
|
---|
| 239 | else:
|
---|
| 240 | switches[arg[2:assignIndex]] = arg[assignIndex+1:]
|
---|
| 241 | else:
|
---|
[919] | 242 | print("Unhandled switch", arg)
|
---|
[682] | 243 |
|
---|
| 244 | cefpython.Initialize(settings, switches)
|
---|
[648] | 245 |
|
---|
[995] | 246 | GObject.timeout_add(10, _handleTimeout)
|
---|
[648] | 247 |
|
---|
[919] | 248 | print("Initialized, executing callback...")
|
---|
[682] | 249 | initializedCallback()
|
---|
[1091] | 250 | return False
|
---|
[682] | 251 |
|
---|
[648] | 252 | #------------------------------------------------------------------------------
|
---|
| 253 |
|
---|
| 254 | def getContainer():
|
---|
| 255 | """Get a container object suitable for running a browser instance
|
---|
| 256 | within."""
|
---|
[1083] | 257 | container = Gtk.DrawingArea()
|
---|
| 258 | container.set_property("can-focus", True)
|
---|
| 259 | container.connect("size-allocate", _handleSizeAllocate)
|
---|
[648] | 260 | container.show()
|
---|
| 261 |
|
---|
| 262 | return container
|
---|
| 263 |
|
---|
| 264 | #------------------------------------------------------------------------------
|
---|
| 265 |
|
---|
| 266 | def startInContainer(container, url, browserSettings = {}):
|
---|
| 267 | """Start a browser instance in the given container with the given URL."""
|
---|
| 268 | if os.name=="nt":
|
---|
[997] | 269 | Gdk.threads_enter()
|
---|
[945] | 270 | ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p
|
---|
| 271 | ctypes.pythonapi.PyCapsule_GetPointer.argtypes = \
|
---|
| 272 | [ctypes.py_object]
|
---|
| 273 | gpointer = ctypes.pythonapi.PyCapsule_GetPointer(
|
---|
| 274 | container.get_property("window").__gpointer__, None)
|
---|
| 275 | libgdk = ctypes.CDLL("libgdk-3-0.dll")
|
---|
| 276 | windowID = libgdk.gdk_win32_window_get_handle(gpointer)
|
---|
| 277 | container.windowID = windowID
|
---|
[997] | 278 | Gdk.threads_leave()
|
---|
[1083] | 279 | windowRect = [0, 0, 1, 1]
|
---|
[648] | 280 | else:
|
---|
[924] | 281 | container.set_visual(container.get_screen().lookup_visual(0x21))
|
---|
| 282 | windowID = container.get_window().get_xid()
|
---|
[1083] | 283 | windowRect = None
|
---|
[648] | 284 |
|
---|
| 285 | windowInfo = cefpython.WindowInfo()
|
---|
[805] | 286 | if windowID is not None:
|
---|
[1083] | 287 | windowInfo.SetAsChild(windowID, windowRect = windowRect)
|
---|
[648] | 288 |
|
---|
[1083] | 289 | browser = cefpython.CreateBrowserSync(windowInfo,
|
---|
| 290 | browserSettings = browserSettings,
|
---|
| 291 | navigateUrl = url)
|
---|
| 292 | container.browser = browser
|
---|
| 293 |
|
---|
| 294 | return browser
|
---|
[648] | 295 |
|
---|
| 296 | #------------------------------------------------------------------------------
|
---|
| 297 |
|
---|
[685] | 298 | class OffscreenRenderHandler(object):
|
---|
[943] | 299 | def GetRootScreenRect(self, browser, rect_out):
|
---|
[685] | 300 | #print "GetRootScreenRect"
|
---|
[1083] | 301 | rect_out += [0, 0, 1920, 1080]
|
---|
[685] | 302 | return True
|
---|
| 303 |
|
---|
[943] | 304 | def GetViewRect(self, browser, rect_out):
|
---|
[685] | 305 | #print "GetViewRect"
|
---|
[1083] | 306 | rect_out += [0, 40, 1920, 1040]
|
---|
[685] | 307 | return True
|
---|
| 308 |
|
---|
| 309 | def GetScreenPoint(self, browser, viewX, viewY, screenCoordinates):
|
---|
| 310 | #print "GetScreenPoint", viewX, viewY
|
---|
| 311 | rect += [viewX, viewY]
|
---|
| 312 | return True
|
---|
| 313 |
|
---|
| 314 | def GetScreenInfo(self, browser, screenInfo):
|
---|
| 315 | #print "GetScreenInfo"
|
---|
| 316 | pass
|
---|
| 317 |
|
---|
| 318 | def OnPopupShow(self, browser, show):
|
---|
| 319 | #print "OnPopupShow", show
|
---|
| 320 | pass
|
---|
| 321 |
|
---|
| 322 | def OnPopupSize(self, browser, rect):
|
---|
| 323 | #print "OnPopupSize", rect
|
---|
| 324 | pass
|
---|
| 325 |
|
---|
[943] | 326 | def OnPaint(self, browser, element_type, dirty_rects, paint_buffer, width, height):
|
---|
[685] | 327 | #print "OnPaint", paintElementType, dirtyRects, buffer, width, height
|
---|
| 328 | pass
|
---|
| 329 |
|
---|
| 330 | def OnCursorChange(self, browser, cursor):
|
---|
| 331 | #print "OnCursorChange", cursor
|
---|
| 332 | pass
|
---|
| 333 |
|
---|
| 334 | def OnScrollOffsetChanged(self, browser):
|
---|
| 335 | #print "OnScrollOffsetChange"
|
---|
| 336 | pass
|
---|
| 337 |
|
---|
[1083] | 338 | def OnBeforePopup(self, browser, frame, target_url, target_frame_name,
|
---|
| 339 | target_disposition, user_gesture,
|
---|
| 340 | popup_features, window_info_out, client,
|
---|
| 341 | browser_settings_out, no_javascript_access_out,
|
---|
| 342 | **kwargs):
|
---|
[685] | 343 | wInfo = cefpython.WindowInfo()
|
---|
| 344 | wInfo.SetAsOffscreen(int(0))
|
---|
| 345 |
|
---|
[1083] | 346 | window_info_out.append(wInfo)
|
---|
[685] | 347 |
|
---|
| 348 | return False
|
---|
| 349 |
|
---|
| 350 | #------------------------------------------------------------------------------
|
---|
| 351 |
|
---|
| 352 | def initializeSimBrief():
|
---|
| 353 | """Initialize the (hidden) browser window for SimBrief."""
|
---|
[805] | 354 | _simBriefHandler.initialize()
|
---|
[685] | 355 |
|
---|
| 356 | #------------------------------------------------------------------------------
|
---|
| 357 |
|
---|
| 358 | def callSimBrief(plan, getCredentials, updateProgress, htmlFilePath):
|
---|
[805] | 359 | """Call SimBrief with the given plan.
|
---|
| 360 |
|
---|
| 361 | The callbacks will be called in the main GUI thread."""
|
---|
| 362 | _simBriefHandler.call(plan, getCredentials, updateProgress, htmlFilePath)
|
---|
[685] | 363 |
|
---|
| 364 | #------------------------------------------------------------------------------
|
---|
| 365 |
|
---|
[648] | 366 | def finalize():
|
---|
| 367 | """Finalize the Chrome Embedded Framework."""
|
---|
[805] | 368 | global _toQuit
|
---|
| 369 | _toQuit = True
|
---|
[1083] | 370 |
|
---|
| 371 | _simBriefHandler.finalize()
|
---|
| 372 |
|
---|
[702] | 373 | cefpython.Shutdown()
|
---|
[648] | 374 |
|
---|
| 375 | #------------------------------------------------------------------------------
|
---|
| 376 |
|
---|
| 377 | def _handleTimeout():
|
---|
| 378 | """Handle the timeout by running the CEF message loop."""
|
---|
| 379 | if _toQuit:
|
---|
| 380 | return False
|
---|
| 381 | else:
|
---|
| 382 | cefpython.MessageLoopWork()
|
---|
| 383 | return True
|
---|
| 384 |
|
---|
| 385 | #------------------------------------------------------------------------------
|
---|
| 386 |
|
---|
| 387 | def _handleSizeAllocate(widget, sizeAlloc):
|
---|
[945] | 388 | """Handle the size-allocate event on Windows."""
|
---|
[1083] | 389 | if os.name=="nt":
|
---|
| 390 | if widget is not None and hasattr(widget, "windowID"):
|
---|
| 391 | cefpython.WindowUtils.OnSize(widget.windowID, 0, 0, 0)
|
---|
| 392 | else:
|
---|
| 393 | if widget is not None and hasattr(widget, "browser") and \
|
---|
| 394 | widget.browser is not None:
|
---|
| 395 | widget.browser.SetBounds(sizeAlloc.x, sizeAlloc.y,
|
---|
| 396 | sizeAlloc.width, sizeAlloc.height)
|
---|