Ignore:
Timestamp:
10/01/15 18:11:10 (7 years ago)
Author:
István Váradi <ivaradi@…>
Branch:
cef
hg-Phase:
(<MercurialRepository 1 'hg:/home/ivaradi/mlx/hg' '/'>, 'public')
Message:

CEF is now started from Selenium

File:
1 edited

Legend:

Unmodified
Added
Removed
  • src/mlx/gui/cef.py

    r648 r682  
    11from common import *
     2
     3from mlx.util import secondaryInstallation
     4
     5from cefpython3 import cefpython
     6from selenium import webdriver
     7from selenium.webdriver.chrome.options import Options
    28
    39import platform
    410import json
    5 
    6 from cefpython3 import cefpython
    7 
     11import time
    812import os
    913import re
     14import threading
     15import tempfile
     16import traceback
    1017
    1118#------------------------------------------------------------------------------
     
    2027_toQuit = False
    2128
    22 #------------------------------------------------------------------------------
    23 
    24 def initialize():
     29# The Selenium thread
     30_seleniumHandler = None
     31
     32#------------------------------------------------------------------------------
     33
     34def getArgsFilePath():
     35    """Get the path of the argument file."""
     36    if os.name=="nt":
     37        return os.path.join(tempfile.gettempdir(),
     38                            "mlxcef.args" +
     39                            (".secondary" if secondaryInstallation else ""))
     40    else:
     41        import pwd
     42        return os.path.join(tempfile.gettempdir(),
     43                            "mlxcef." + pwd.getpwuid(os.getuid())[0] + ".args" +
     44                            (".secondary" if secondaryInstallation else ""))
     45
     46#------------------------------------------------------------------------------
     47
     48class ArgsFileWaiter(threading.Thread):
     49    """A thread to wait for the appearance of the arguments file."""
     50    def __init__(self, initializedCallback):
     51        """Construct the thread."""
     52        threading.Thread.__init__(self)
     53        self.daemon = True
     54
     55        self._initializedCallback = initializedCallback
     56
     57    def run(self):
     58        """Repeatedly check for the existence of the arguments file.
     59
     60        If it is found, read it, extract the arguments and insert a job into
     61        the GUI loop to perform the actual initialization of CEF."""
     62        argsFilePath = getArgsFilePath()
     63        print "Waiting for the arguments file '%s' to appear" % (argsFilePath,)
     64
     65        while not os.path.exists(argsFilePath):
     66            time.sleep(0.1)
     67
     68        print "Got arguments, reading them."""
     69
     70        with open(argsFilePath, "rt") as f:
     71            args = f.read().split()
     72
     73        gobject.idle_add(_initializeCEF, args, self._initializedCallback)
     74
     75#------------------------------------------------------------------------------
     76
     77class SeleniumHandler(threading.Thread):
     78    """Thread to handle Selenium operations."""
     79    def __init__(self, programDirectory):
     80        """Construct the thread."""
     81        threading.Thread.__init__(self)
     82        self.daemon = False
     83
     84        self._programDirectory = programDirectory
     85
     86        self._commandsCondition = threading.Condition()
     87        self._commands = []
     88
     89        self._toQuit = False
     90
     91    def run(self):
     92        """Create the Selenium driver and the perform any operations
     93        requested."""
     94        scriptName = "mlx_cef_caller"
     95        if secondaryInstallation:
     96            scriptName += "_secondary"
     97        scriptName += ".bat" if os.name=="nt" else ".sh"
     98
     99        scriptPath = os.path.join(self._programDirectory, scriptName)
     100        print "Creating the Selenium driver to call script", scriptPath
     101
     102        options = Options()
     103        options.binary_location = scriptPath
     104        driver = webdriver.Chrome(chrome_options = options)
     105        # try:
     106        # except:
     107        #     traceback.print_exc()
     108
     109        print "Created Selenium driver."
     110        while not self._toQuit:
     111            with self._commandsCondition:
     112                while not self._commands:
     113                    self._commandsCondition.wait()
     114
     115                command = self._commands[0]
     116                del self._commands[0]
     117
     118            command()
     119
     120        driver.quit()
     121
     122    def quit(self):
     123        """Instruct the thread to quit and then join it."""
     124        self._enqueue(self._quit)
     125        self.join()
     126
     127    def _enqueue(self, command):
     128        """Enqueue the given command.
     129
     130        command should be a function to be executed in the thread."""
     131        with self._commandsCondition:
     132            self._commands.append(command)
     133            self._commandsCondition.notify()
     134
     135    def _quit(self):
     136        """Set the _toQuit member variable to indicate that the thread should
     137        quit."""
     138        self._toQuit = True
     139
     140#------------------------------------------------------------------------------
     141
     142def initialize(programDirectory, initializedCallback):
    25143    """Initialize the Chrome Embedded Framework."""
    26     global _toQuit
     144    global _toQuit, _seleniumHandler
    27145    _toQuit = False
    28146
    29147    gobject.threads_init()
     148
     149    argsFilePath = getArgsFilePath()
     150    try:
     151        os.unlink(argsFilePath)
     152    except:
     153        pass
     154
     155    _seleniumHandler = SeleniumHandler(programDirectory)
     156    _seleniumHandler.start()
     157
     158    ArgsFileWaiter(initializedCallback).start()
     159
     160#------------------------------------------------------------------------------
     161
     162def _initializeCEF(args, initializedCallback):
     163    """Perform the actual initialization of CEF using the given arguments."""
     164    print "Initializing CEF with args:", args
    30165
    31166    settings = {
     
    41176    }
    42177
    43     cefpython.Initialize(settings, {})
     178    switches={}
     179    for arg in args:
     180        if arg.startswith("--"):
     181            if arg != "--enable-logging":
     182                assignIndex = arg.find("=")
     183                if assignIndex<0:
     184                    switches[arg[2:]] = ""
     185                else:
     186                    switches[arg[2:assignIndex]] = arg[assignIndex+1:]
     187        else:
     188            print "Unhandled switch", arg
     189
     190    cefpython.Initialize(settings, switches)
    44191
    45192    gobject.timeout_add(10, _handleTimeout)
     193
     194    print "Initialized, executing callback..."
     195    initializedCallback()
    46196
    47197#------------------------------------------------------------------------------
     
    83233def finalize():
    84234    """Finalize the Chrome Embedded Framework."""
    85     global _toQuit
     235    global _toQuit, _seleniumHandler
    86236    toQuit = True
     237    _seleniumHandler.quit()
    87238    cefpython.Shutdown()
    88239
Note: See TracChangeset for help on using the changeset viewer.