Ejemplo n.º 1
0
    def run(self):
        logging.info("PySide2 version: %s" % PySide2.__version__)
        logging.info("QtCore version: %s" % QtCore.__version__)

        sys.excepthook = ExceptHook
        settings = {}
        settings["log_file"] = GetApplicationPath("debug.log")
        settings["log_severity"] = cefpython.LOGSEVERITY_INFO
        settings["release_dcheck_enabled"] = True  # Enable only when debugging
        settings["browser_subprocess_path"] = "%s/%s" % (
            cefpython.GetModuleDirectory(), "subprocess")
        cefpython.Initialize(settings)

        app = CefApplication(sys.argv)
        mainWindow = MainWindow(self.url)
        mainWindow.show()
        app.exec_()
        app.stopTimer()

        # Need to destroy QApplication(), otherwise Shutdown() fails.
        # Unset main window also just to be safe.
        del mainWindow
        del app

        cefpython.Shutdown()
Ejemplo n.º 2
0
def CefAdvanced():
    sys.excepthook = ExceptHook
    InitDebugging()

    appSettings = dict()
    appSettings["log_file"] = GetApplicationPath("debug.log")

    # LOGSEVERITY_INFO - less debug oput.
    # LOGSEVERITY_DISABLE - will not create "debug.log" file.
    appSettings["log_severity"] = cefpython.LOGSEVERITY_VERBOSE

    # Enable only when debugging, otherwise performance might hurt.
    appSettings["release_dcheck_enabled"] = True

    # Must be set so that OnUncaughtException() is called.
    appSettings["uncaught_exception_stack_size"] = 100

    cefpython.Initialize(applicationSettings=appSettings)

    # Closing main window quits the application as we define
    # WM_DESTOROY message.
    wndproc = {
        win32con.WM_CLOSE: CloseWindow,
        win32con.WM_DESTROY: QuitApplication,
        win32con.WM_SIZE: cefpython.WindowUtils.OnSize,
        win32con.WM_SETFOCUS: cefpython.WindowUtils.OnSetFocus,
        win32con.WM_ERASEBKGND: cefpython.WindowUtils.OnEraseBackground
    }

    windowHandle = cefwindow.CreateWindow(
            title="CefAdvanced", className="cefadvanced",
            width=900, height=710, icon="icon.ico", windowProc=wndproc)

    browserSettings = dict()
    browserSettings["history_disabled"] = False
    browserSettings["universal_access_from_file_urls_allowed"] = True
    browserSettings["file_access_from_file_urls_allowed"] = True

    javascriptBindings = cefpython.JavascriptBindings(
            bindToFrames=False, bindToPopups=True)
    windowInfo = cefpython.WindowInfo()
    windowInfo.SetAsChild(windowHandle)
    browser = cefpython.CreateBrowserSync(
            windowInfo, browserSettings=browserSettings,
            navigateUrl=GetApplicationPath("cefadvanced.html"))
    browser.SetUserData("outerWindowHandle", windowInfo.parentWindowHandle)
    browser.SetClientHandler(ClientHandler())
    browser.SetJavascriptBindings(javascriptBindings)

    javascriptRebindings = JavascriptRebindings(javascriptBindings, browser)
    javascriptRebindings.Bind()
    browser.SetUserData("javascriptRebindings", javascriptRebindings)

    cefpython.MessageLoop()
    cefpython.Shutdown()
Ejemplo n.º 3
0
def initCEF(settings=None):
    """Initializes CEF, We should do it before initializing wx
       If no settings passed a default is used
    """
    sys.excepthook = ExceptHook
    if not settings:
        settings = {
            "log_severity": cefpython.LOGSEVERITY_INFO,
            "log_file": GetApplicationPath("debug.log"),
            "release_dcheck_enabled": True  # Enable only when debugging.
        }
    cefpython.Initialize(settings)
Ejemplo n.º 4
0
def CefAdvanced():
    sys.excepthook = ExceptHook

    appSettings = dict()
    # appSettings["cache_path"] = "webcache/" # Disk cache
    if DEBUG:
        # cefpython debug messages in console and in log_file
        appSettings["debug"] = True
        cefwindow.g_debug = True
    appSettings["log_file"] = GetApplicationPath("debug.log")
    appSettings["log_severity"] = cefpython.LOGSEVERITY_INFO
    appSettings["release_dcheck_enabled"] = True  # Enable only when debugging
    appSettings["browser_subprocess_path"] = "%s/%s" % (
        cefpython.GetModuleDirectory(), "subprocess")
    cefpython.Initialize(appSettings)

    wndproc = {
        win32con.WM_CLOSE: CloseWindow,
        win32con.WM_DESTROY: QuitApplication,
        win32con.WM_SIZE: cefpython.WindowUtils.OnSize,
        win32con.WM_SETFOCUS: cefpython.WindowUtils.OnSetFocus,
        win32con.WM_ERASEBKGND: cefpython.WindowUtils.OnEraseBackground
    }

    browserSettings = dict()
    browserSettings["universal_access_from_file_urls_allowed"] = True
    browserSettings["file_access_from_file_urls_allowed"] = True

    if os.path.exists("icon.ico"):
        icon = os.path.abspath("icon.ico")
    else:
        icon = ""

    windowHandle = cefwindow.CreateWindow(title="pywin32 example",
                                          className="cefpython3_example",
                                          width=1024,
                                          height=768,
                                          icon=icon,
                                          windowProc=wndproc)
    windowInfo = cefpython.WindowInfo()
    windowInfo.SetAsChild(windowHandle)
    browser = cefpython.CreateBrowserSync(
        windowInfo,
        browserSettings,
        navigateUrl=GetApplicationPath("example.html"))
    cefpython.MessageLoop()
    cefpython.Shutdown()
Ejemplo n.º 5
0
def CefSimple():
    sys.excepthook = ExceptHook
    cefpython.g_debug = True
    cefpython.Initialize()
    wndproc = {
        win32con.WM_CLOSE: CloseWindow,
        win32con.WM_DESTROY: QuitApplication,
        win32con.WM_SIZE: cefpython.WindowUtils.OnSize,
        win32con.WM_SETFOCUS: cefpython.WindowUtils.OnSetFocus,
        win32con.WM_ERASEBKGND: cefpython.WindowUtils.OnEraseBackground }
    windowHandle = cefwindow.CreateWindow(
            title="CefSimple", className="cefsimple", width=800, height=600,
            icon="icon.ico", windowProc=wndproc)
    windowInfo = cefpython.WindowInfo()
    windowInfo.SetAsChild(windowHandle)
    browser = cefpython.CreateBrowserSync(
            windowInfo, browserSettings={},
            navigateUrl=GetApplicationPath("cefsimple.html"))
    cefpython.MessageLoop()
    cefpython.Shutdown()
Ejemplo n.º 6
0
        # not be called anymore.
        if not USE_EVT_IDLE:
            self.timer.Stop()


if __name__ == '__main__':
    sys.excepthook = ExceptHook
    settings = {
        "debug":
        False,  # cefpython debug messages in console and in log_file
        "log_severity":
        cefpython.LOGSEVERITY_INFO,  # LOGSEVERITY_VERBOSE
        "log_file":
        GetApplicationPath("debug.log"),  # Set to "" to disable.
        # This directories must be set on Linux
        "locales_dir_path":
        cefpython.GetModuleDirectory() + "/locales",
        "resources_dir_path":
        cefpython.GetModuleDirectory(),
        "browser_subprocess_path":
        "%s/%s" % (cefpython.GetModuleDirectory(), "subprocess")
    }
    # print("browser_subprocess_path="+settings["browser_subprocess_path"])
    cefpython.Initialize(settings)
    print('wx.version=%s' % wx.version())
    app = MyApp(False)
    app.MainLoop()
    # Let wx.App destructor do the cleanup before calling cefpython.Shutdown().
    del app
    cefpython.Shutdown()
Ejemplo n.º 7
0
def create_embedded_browser(parent_control, start_url):
    class Embedded_Browser(object):
        @staticmethod
        def _find_ctrl_id(ctrl):
            import re
            ctrl_type = ctrl.__class__.__name__
            hexID = re.search(ctrl_type + ' at 0x(\w+)', str(ctrl)).group(1)
            return int(hexID, 16)

        def __init__(self, parent_control, start_url):
            windowID = Embedded_Browser._find_ctrl_id(parent_control)
            windowInfo = cefpython.WindowInfo()
            windowInfo.SetAsChild(windowID)

            self.browser = cefpython.CreateBrowserSync(windowInfo,
                                                       browserSettings={},
                                                       navigateUrl=start_url)

            gobject.timeout_add(10, self._on_timer)
            # TODO: It may be a better idea to look for a page onLoad
            gobject.timeout_add(5000, self._hack_crosshair)

        def _hack_crosshair(self):
            """ Show a crosshair in the middle of the page """
            hack = "" + \
                   "var img = document.createElement('img');" + \
                   "img.src = 'https://github.com/nicolasbrailo/IMGeotagger/blob/master/crosshair.png?raw=true';" + \
                   "img.style.position='absolute';" + \
                   "img.style.left='50%';" + \
                   "img.style.marginLeft='-24px';" + \
                   "img.style.top='50%';" + \
                   "img.style.marginTop='-24px';" + \
                   "document.body.appendChild(img);"
            self.browser.GetMainFrame().ExecuteJavascript(hack)
            # Tell gobject we don't need to trigger this callback again
            return False

        def _on_timer(self):
            cefpython.MessageLoopWork()
            return True

        def get_url(self):
            return self.browser.GetUrl()

    if not Embedded_Browser_Initialized:
        settings = {
            'debug':
            False,
            'log_severity':
            cefpython.LOGSEVERITY_INFO,
            'log_file':
            '',  # Disabled
            # This directories must be set on Linux
            'locales_dir_path':
            cefpython.GetModuleDirectory() + '/locales',
            'resources_dir_path':
            cefpython.GetModuleDirectory(),
            'browser_subprocess_path':
            '%s/%s' % (cefpython.GetModuleDirectory(), 'subprocess'),
        }

        cefpython.Initialize(settings)
        gobject.threads_init()
        import atexit
        atexit.register(cefpython.Shutdown)

    return Embedded_Browser(parent_control, start_url)
Ejemplo n.º 8
0
    g_applicationSettings["auto_zooming"] = "system_dpi"
    print("[wxpython.py] Calling SetProcessDpiAware")
    cefpython.DpiAware.SetProcessDpiAware()

    # Browser settings. You may have different settings for each
    # browser, see the call to CreateBrowserSync.
    g_browserSettings = {
        # "plugins_disabled": True,
        # "file_access_from_file_urls_allowed": True,
        # "universal_access_from_file_urls_allowed": True,
    }

    # Command line switches set programmatically
    g_commandLineSwitches = {
        # "proxy-server": "socks5://127.0.0.1:8888",
        # "no-proxy-server": "",
        # "enable-media-stream": "",
        # "disable-gpu": "",
    }

    cefpython.Initialize(g_applicationSettings, g_commandLineSwitches)

    app = MyApp(False)
    app.MainLoop()

    # Let wx.App destructor do the cleanup before calling
    # cefpython.Shutdown(). This is to ensure reliable CEF shutdown.
    del app

    cefpython.Shutdown()
Ejemplo n.º 9
0
        "ignore_certificate_errors":
        False,
    }

    # Browser settings. You may have different settings for each
    # browser, see the call to CreateBrowserSync.
    g_browserSettings = {
        # "plugins_disabled": True,
        # "file_access_from_file_urls_allowed": True,
        # "universal_access_from_file_urls_allowed": True,
    }

    # Command line switches set programmatically
    switches = {
        # "proxy-server": "socks5://127.0.0.1:8888",
        # "no-proxy-server": "",
        # "enable-media-stream": "",
        # "remote-debugging-port": "12345",
        # "disable-gpu": "",
        # "--invalid-switch": "" -> Invalid switch name
    }

    cefpython.Initialize(settings, switches)

    app = MyApp(False)
    app.MainLoop()
    # Let wx.App destructor do the cleanup before calling cefpython.Shutdown().
    del app

    cefpython.Shutdown()
Ejemplo n.º 10
0
    def __init__(self, *largs, **dargs):
        super(CefBrowser, self).__init__()
        self.url = dargs.get("url", "")
        self.keyboard_mode = dargs.get("keyboard_mode", "local")
        self.resources_dir = dargs.get("resources_dir", "")
        self.keyboard_above_classes = dargs.get("keyboard_above_classes", [])
        switches = dargs.get("switches", {})
        self.__rect = None
        self.browser = None
        self.popup = CefBrowserPopup(self)

        self.register_event_type("on_loading_state_change")
        self.register_event_type("on_address_change")
        self.register_event_type("on_title_change")
        self.register_event_type("on_before_popup")
        self.register_event_type("on_load_start")
        self.register_event_type("on_load_end")
        self.register_event_type("on_load_error")
        self.register_event_type("on_certificate_error")
        self.register_event_type("on_js_dialog")
        self.register_event_type("on_before_unload_dialog")

        self.key_manager = CefKeyboardManager(cefpython=cefpython, browser_widget=self)

        self.texture = Texture.create(size=self.size, colorfmt='rgba', bufferfmt='ubyte')
        self.texture.flip_vertical()
        with self.canvas:
            Color(1, 1, 1)
            self.__rect = Rectangle(pos=self.pos, size=self.size, texture=self.texture)

        md = cefpython.GetModuleDirectory()

        # Determine if default resources dir should be used or a custom
        if self.resources_dir:
            resources = self.resources_dir
        else:
            resources = md

        def cef_loop(*largs):
            cefpython.MessageLoopWork()
        Clock.schedule_interval(cef_loop, 0)

        settings = {
                    #"debug": True,
                    "log_severity": cefpython.LOGSEVERITY_INFO,
                    #"log_file": "debug.log",
                    "persist_session_cookies": True,
                    "release_dcheck_enabled": True,  # Enable only when debugging.
                    "locales_dir_path": os.path.join(md, "locales"),
                    "browser_subprocess_path": "%s/%s" % (cefpython.GetModuleDirectory(), "subprocess")
                }
        cefpython.Initialize(settings, switches)

        windowInfo = cefpython.WindowInfo()
        windowInfo.SetAsOffscreen(0)
        cefpython.SetGlobalClientCallback("OnCertificateError", self.OnCertificateError)
        self.browser = cefpython.CreateBrowserSync(windowInfo, {}, navigateUrl=self.url)

        # Set cookie manager
        cookie_manager = cefpython.CookieManager.GetGlobalManager()
        cookie_path = os.path.join(resources, "cookies")
        cookie_manager.SetStoragePath(cookie_path, True)

        self.browser.SendFocusEvent(True)
        ch = ClientHandler(self)
        self.browser.SetClientHandler(ch)
        self.set_js_bindings()
        self.browser.WasResized()
        self.bind(size=self.realign)
        self.bind(pos=self.realign)
        self.bind(keyboard_mode=self.set_keyboard_mode)
        if self.keyboard_mode == "global":
            self.request_keyboard()
Ejemplo n.º 11
0
def init_CEF():
    global g_applicationSettings
    global g_browserSettings
    global g_commandLineSwitches

    print('[wxpython.py] architecture=%s-bit' % (8 * struct.calcsize("P")))
    print('[wxpython.py] wx.version=%s' % wx.version())

    # Intercept python exceptions. Exit app immediately when exception
    # happens on any of the threads.
    sys.excepthook = ExceptHook

    # Application settings
    g_applicationSettings = {
        # Disk cache
        # "cache_path": "webcache/",

        # CEF Python debug messages in console and in log_file
        "debug":
        True,
        # Set it to LOGSEVERITY_VERBOSE for more details
        "log_severity":
        cefpython.LOGSEVERITY_INFO,
        # Set to "" to disable logging to a file
        "log_file":
        GetApplicationPath("debug.log"),
        # This should be enabled only when debugging
        "release_dcheck_enabled":
        True,

        # These directories must be set on Linux
        "locales_dir_path":
        cefpython.GetModuleDirectory() + "/locales",
        "resources_dir_path":
        cefpython.GetModuleDirectory(),
        # The "subprocess" executable that launches the Renderer
        # and GPU processes among others. You may rename that
        # executable if you like.
        "browser_subprocess_path":
        "%s/%s" % (cefpython.GetModuleDirectory(), "subprocess"),

        # This option is required for the GetCookieManager callback
        # to work. It affects renderer processes, when this option
        # is set to True. It will force a separate renderer process
        # for each browser created using CreateBrowserSync.
        "unique_request_context_per_browser":
        True,
        # Downloads are handled automatically. A default SaveAs file
        # dialog provided by OS will be displayed.
        "downloads_enabled":
        True,
        # Remote debugging port, required for Developer Tools support.
        # A value of 0 will generate a random port. To disable devtools
        # support set it to -1.
        "remote_debugging_port":
        0,
        # Mouse context menu
        "context_menu": {
            "enabled": True,
            "navigation": True,  # Back, Forward, Reload
            "print": True,
            "view_source": True,
            "external_browser": True,  # Open in external browser
            "devtools": True,  # Developer Tools
        },

        # See also OnCertificateError which allows you to ignore
        # certificate errors for specific websites.
        "ignore_certificate_errors":
        True,
    }

    # You can comment out the code below if you do not want High
    # DPI support. If you disable it text will look fuzzy on
    # high DPI displays.
    #
    # Enabling High DPI support in app can be done by
    # embedding a DPI awareness xml manifest in executable
    # (see Issue 112 comment #2), or by calling SetProcessDpiAware
    # function. Embedding xml manifest is the most reliable method.
    # The downside of calling SetProcessDpiAware is that scrollbar
    # in CEF browser is smaller than it should be. This is because
    # DPI awareness was set too late, after the CEF dll was loaded.
    # To fix that embed DPI awareness xml manifest in the .exe file.
    #
    # There is one bug when enabling High DPI support - fonts in
    # javascript dialogs (alert) are tiny. However, you can implement
    # custom javascript dialogs using JavascriptDialogHandler.
    #
    # Additionally you have to set "auto_zomming" application
    # setting. High DPI support is available only on Windows.
    # You may set auto_zooming to "system_dpi" and browser
    # contents will be zoomed using OS DPI settings. On Win7
    # these can be set in: Control Panel > Appearance and
    # Personalization > Display.
    #
    # Example values for auto_zooming are:
    #   "system_dpi", "0.0" (96 DPI), "1.0" (120 DPI),
    #   "2.0" (144 DPI), "-1.0" (72 DPI)
    # Numeric value means a zoom level.
    # Example values that can be set in Win7 DPI settings:
    #   Smaller 100% (Default) = 96 DPI = 0.0 zoom level
    #   Medium 125% = 120 DPI = 1.0 zoom level
    #   Larger 150% = 144 DPI = 2.0 zoom level
    #   Custom 75% = 72 DPI = -1.0 zoom level
    g_applicationSettings["auto_zooming"] = "system_dpi"
    print("[wxpython.py] Calling SetProcessDpiAware")
    cefpython.DpiAware.SetProcessDpiAware()

    # Browser settings. You may have different settings for each
    # browser, see the call to CreateBrowserSync.
    g_browserSettings = {
        # "plugins_disabled": True,
        # "file_access_from_file_urls_allowed": True,
        # "universal_access_from_file_urls_allowed": True,
    }

    # Command line switches set programmatically
    g_commandLineSwitches = {
        # "proxy-server": "socks5://127.0.0.1:8888",
        # "no-proxy-server": "",
        # "enable-media-stream": "",
        # "disable-gpu": "",
    }

    cefpython.Initialize(g_applicationSettings, g_commandLineSwitches)
Ejemplo n.º 12
0
        # "file_access_from_file_urls_allowed": True,
        # "universal_access_from_file_urls_allowed": True,
    }

    # Command line switches set programmatically
    g_switches = {
        # On Mac it is required to provide path to a specific
        # locale.pak file. On Win/Linux you only specify the
        # ApplicationSettings.locales_dir_path option.
        "locale_pak": cefpython.GetModuleDirectory()
            +"/Resources/en.lproj/locale.pak",

        # "proxy-server": "socks5://127.0.0.1:8888",
        # "no-proxy-server": "",
        # "enable-media-stream": "",
        # "remote-debugging-port": "12345",
        # "disable-gpu": "",
        # "--invalid-switch": "" -> Invalid switch name
    }

    cefpython.Initialize(g_applicationSettings, g_switches)

    app = MyApp(False)
    app.MainLoop()

    # Let wx.App destructor do the cleanup before calling
    # cefpython.Shutdown(). This is to ensure reliable CEF shutdown.
    del app

    # On Mac cefpython.Shutdown() is called in MainFrame.OnClose,
    # followed by wx.GetApp.Exit().
Ejemplo n.º 13
0
    def start_cef(self):
        '''Starts CEF.
        '''
        # create texture & add it to canvas
        self.texture = Texture.create(size=self.size,
                                      colorfmt='rgba',
                                      bufferfmt='ubyte')
        self.texture.flip_vertical()
        with self.canvas:
            Color(1, 1, 1)
            self.rect = Rectangle(size=self.size, texture=self.texture)

        #configure cef
        settings = {
            "debug":
            True,  # cefpython debug messages in console and in log_file
            "log_severity":
            cefpython.LOGSEVERITY_INFO,
            "log_file":
            "debug.log",
            # This directories must be set on Linux
            "locales_dir_path":
            cefpython.GetModuleDirectory() + "/locales",
            "resources_dir_path":
            cefpython.GetModuleDirectory(),
            "browser_subprocess_path":
            "%s/%s" % (cefpython.GetModuleDirectory(), "subprocess")
        }

        #start idle
        Clock.schedule_interval(self._cef_mes, 0)

        #init CEF
        cefpython.Initialize(settings)

        #WindowInfo offscreen flag
        windowInfo = cefpython.WindowInfo()
        windowInfo.SetAsOffscreen(0)

        #Create Broswer and naviagte to empty page <= OnPaint won't get called yet
        browserSettings = {}
        # The render handler callbacks are not yet set, thus an
        # error report will be thrown in the console (when release
        # DCHECKS are enabled), however don't worry, it is harmless.
        # This is happening because calling GetViewRect will return
        # false. That's why it is initially navigating to "about:blank".
        # Later, a real url will be loaded using the LoadUrl() method
        # and the GetViewRect will be called again. This time the render
        # handler callbacks will be available, it will work fine from
        # this point.
        # --
        # Do not use "about:blank" as navigateUrl - this will cause
        # the GoBack() and GoForward() methods to not work.
        self.browser = cefpython.CreateBrowserSync(windowInfo,
                                                   browserSettings,
                                                   navigateUrl=self.start_url)

        #set focus
        self.browser.SendFocusEvent(True)

        self._client_handler = ClientHandler(self)
        self.browser.SetClientHandler(self._client_handler)
        self.set_js_bindings()

        #Call WasResized() => force cef to call GetViewRect() and OnPaint afterwards
        self.browser.WasResized()

        # The browserWidget instance is required in OnLoadingStateChange().
        self.browser.SetUserData("browserWidget", self)

        if self.keyboard_mode == "global":
            self.request_keyboard()
Ejemplo n.º 14
0
def snap(command, width=800, height=600):
    metadata = {}
    try:
        logging.info("Snapshot url: %s" % command['url'])
        metadata['timestamp'] = int(time())
        metadata['error'] = "0"
        parent_dir = os.path.dirname(command['file'])
        if parent_dir and not os.path.exists(parent_dir):
            os.makedirs(parent_dir)
        if 'screen_width' in command:
            width = command['screen_width']
        if 'screen_height' in command:
            height = command['screen_height']
        cefpython.g_debug = False
        commandLineSwitches = dict()
        if 'proxies' in command:
            proxy = command['proxies'][0]
            logging.info("Proxy server: %s:1080" % proxy)
            commandLineSwitches['proxy-server'] = "socks5://" + proxy + ":1080"
        settings = {
            "log_severity":
            cefpython.LOGSEVERITY_DISABLE,  # LOGSEVERITY_VERBOSE
            "log_file":
            "",
            "release_dcheck_enabled":
            False,  # Enable only when debugging.
            # This directories must be set on Linux
            "locales_dir_path":
            cefpython.GetModuleDirectory() + "/locales",
            "resources_dir_path":
            cefpython.GetModuleDirectory(),
            "multi_threaded_message_loop":
            False,
            "unique_request_context_per_browser":
            True,
            "browser_subprocess_path":
            "%s/%s" % (cefpython.GetModuleDirectory(), "subprocess")
        }
        cefpython.Initialize(settings, commandLineSwitches)
        windowInfo = cefpython.WindowInfo()
        windowInfo.SetAsOffscreen(0)
        browserSettings = {"default_encoding": "utf-8"}
        browser = cefpython.CreateBrowserSync(windowInfo,
                                              browserSettings,
                                              navigateUrl=command['url'])
        cookieManager = cefpython.CookieManager.CreateManager("")
        if 'cookie' in command:
            for k, v in command['cookie'].items():
                cookie = cefpython.Cookie()
                cookie.SetName(k)
                cookie.SetValue(v)
                cookie.SetHasExpires(False)
                cookieManager.SetCookie(command['url'], cookie)
        browser.SetUserData("cookieManager", cookieManager)
        #browser = cefpython.CreateBrowserSync(windowInfo, browserSettings, navigateUrl="about:blank")
        # TODO handle post data
        #req = cefpython.Request.CreateRequest()
        #req.SetUrl(command['url'])
        # req.SetMethod("POST")
        # a = req.SetPostData([])
        #browser.GetMainFrame().LoadRequest(req)

        browser.SendFocusEvent(True)
        browser.SetUserData("width", width)
        browser.SetUserData("height", height)
        browser.SetUserData("metadata", metadata)
        browser.SetClientHandler(ClientHandler(browser, command))
        jsBindings = cefpython.JavascriptBindings(bindToFrames=True,
                                                  bindToPopups=True)
        jsBindings.SetProperty("delay", int(command['delay']))
        jsBindings.SetProperty("flash_delay", int(command['flash_delay']))
        jsBindings.SetFunction("setPageSize", setPageSize)
        jsBindings.SetFunction("jsCallback", jsCallback)
        jsBindings.SetFunction("log", logging.info)
        browser.SetJavascriptBindings(jsBindings)
        #browser.WasResized()
        cefpython.MessageLoop()
        width = browser.GetUserData("width")
        height = browser.GetUserData("height")
        metadata = browser.GetUserData("metadata")
        image = browser.GetUserData("image")
        html = browser.GetUserData("html")

    except:
        logging.error(sys.exc_info())
        traceback.print_exc()
        metadata['error'] = str(sys.exc_info())
    finally:
        if metadata['error'] == "0":
            metadata['status'] = "OK"
            metadata['finished'] = int(time())
        else:
            metadata['status'] = "error"
            metadata['time_finished'] = int(time())
        cefpython.Shutdown()
        return width, height, image, html, metadata
Ejemplo n.º 15
0
    def start_cef(self):
        '''Starts CEF.
        '''
        # create texture & add it to canvas
        self.texture = Texture.create(size=self.size,
                                      colorfmt='rgba',
                                      bufferfmt='ubyte')
        self.texture.flip_vertical()
        with self.canvas:
            Color(1, 1, 1)
            self.rect = Rectangle(size=self.size, texture=self.texture)

        # Configure CEF
        settings = {
            "debug":
            True,  # cefpython debug messages in console and in log_file
            "log_severity":
            cefpython.LOGSEVERITY_INFO,
            "log_file":
            "debug.log",
            # This directories must be set on Linux
            "locales_dir_path":
            cefpython.GetModuleDirectory() + "/locales",
            "resources_dir_path":
            cefpython.GetModuleDirectory(),
            "browser_subprocess_path":
            "%s/%s" % (cefpython.GetModuleDirectory(), "subprocess"),
            "windowless_rendering_enabled":
            True,
            "context_menu": {
                # Disable context menu, popup widgets not supported
                "enabled": False,
            },
        }
        switches = {
            # Tweaking OSR performance by setting the same Chromium flags
            # as in upstream cefclient (# Issue #240).
            "disable-surfaces": "",
            "disable-gpu": "",
            "disable-gpu-compositing": "",
            "enable-begin-frame-scheduling": "",
        }
        browserSettings = {
            # Tweaking OSR performance (Issue #240)
            "windowless_frame_rate": 60
        }

        # Initialize CEF
        cefpython.WindowUtils.InstallX11ErrorHandlers()

        global g_switches
        g_switches = switches
        cefpython.Initialize(settings, switches)

        # Start idle - CEF message loop work.
        Clock.schedule_once(self._message_loop_work, 0)

        # CEF needs a valid window handle passed to SetAsOffscreen()
        # for Printing to work. There is no API to get Kivy's window
        # handle so creating a dummy hidden Window using GTK.
        gtkwin = gtk.Window()
        gtkwin.realize()

        # WindowInfo offscreen flag
        windowInfo = cefpython.WindowInfo()
        windowInfo.SetAsOffscreen(gtkwin.window.xid)

        # Create Broswer and naviagte to empty page <= OnPaint won't get
        # called yet
        # The render handler callbacks are not yet set, thus an
        # error report will be thrown in the console (when release
        # DCHECKS are enabled), however don't worry, it is harmless.
        # This is happening because calling GetViewRect will return
        # false. That's why it is initially navigating to "about:blank".
        # Later, a real url will be loaded using the LoadUrl() method
        # and the GetViewRect will be called again. This time the render
        # handler callbacks will be available, it will work fine from
        # this point.
        # --
        # Do not use "about:blank" as navigateUrl - this will cause
        # the GoBack() and GoForward() methods to not work.
        #
        self.browser = cefpython.CreateBrowserSync(windowInfo,
                                                   browserSettings,
                                                   navigateUrl=self.start_url)

        # Set focus
        self.browser.SendFocusEvent(True)

        self._client_handler = ClientHandler(self)
        self.browser.SetClientHandler(self._client_handler)
        self.set_js_bindings()

        # Call WasResized() => force cef to call GetViewRect() and OnPaint
        # afterwards
        self.browser.WasResized()

        # The browserWidget instance is required in OnLoadingStateChange().
        self.browser.SetUserData("browserWidget", self)

        if self.keyboard_mode == "global":
            self.request_keyboard()
Ejemplo n.º 16
0
 def start_cef(self, start_url='http://google.com'):
     '''Starts CEF. 
     '''
     # create texture & add it to canvas
     self.texture = Texture.create(size=self.finSize, colorfmt='rgba', bufferfmt='ubyte')
     self.texture.flip_vertical()
     with self.canvas:
         Color(1, 1, 1)
         self.rect = Rectangle(size=self.finSize, texture=self.texture, pos=self.finPos)
         
     #configure cef
     cefpython.g_debug = True
     settings = {"log_severity": cefpython.LOGSEVERITY_INFO,
             #"log_file": GetApplicationPath("debug.log"),
             "release_dcheck_enabled": True, # Enable only when debugging.
             # This directories must be set on Linux
             "locales_dir_path": cefpython.GetModuleDirectory()+"/locales",
             "resources_dir_path": cefpython.GetModuleDirectory(),
             "browser_subprocess_path": "%s/%s" % (cefpython.GetModuleDirectory(), "subprocess")}
     
     #start idle
     Clock.schedule_interval(self._cef_mes, 0)
     
     #init CEF
     cefpython.Initialize(settings)
    
     #WindowInfo offscreen flag
     windowInfo = cefpython.WindowInfo()
     windowInfo.SetAsOffscreen(0)
     
     #Create Broswer and naviagte to empty page <= OnPaint won't get called yet
     browserSettings = {}
     # The render handler callbacks are not yet set, thus an 
     # error report will be thrown in the console (when release
     # DCHECKS are enabled), however don't worry, it is harmless.
     # This is happening because calling GetViewRect will return 
     # false. That's why it is initially navigating to "about:blank".
     # Later, a real url will be loaded using the LoadUrl() method 
     # and the GetViewRect will be called again. This time the render
     # handler callbacks will be available, it will work fine from
     # this point.
     # --
     # Do not use "about:blank" as navigateUrl - this will cause
     # the GoBack() and GoForward() methods to not work.
     # --
     # TODO: get rid of the hard-coded path. Use the __file__ variable
     #       to get the current directory. Using a path to a non-existent
     #       local html file seems to not cause any problems, so it can
     #       stay for a moment.
     self.browser = cefpython.CreateBrowserSync(windowInfo, browserSettings, 
             navigateUrl="file:///home/czarek/cefpython/cefpython/cef3/linux/binaries_64bit/empty2.html")
     
     #set focus
     self.browser.SendFocusEvent(True)
     
     #Create RenderHandler (in ClientHandler)
     CH = ClientHandler(self.texture, self)
     self.browser.SetClientHandler(CH)
     
     #Call WasResized() => force cef to call GetViewRect() and OnPaint afterwards
     self.browser.WasResized() 
     
     # Load desired start URL
     # TODO: let the local html file "empty.html" to finish loading,
     #       call the LoadUrl() method with a 100ms delay. In the 
     #       empty.html you could add a "Loading.." text, this would
     #       event useful, user would see some message instead of the
     #       blank page. Sometimes the lag can cause the website to
     #       load for a few seconds and user would be seeing only a
     #       white screen and wonder of what is happening. The other
     #       solution would be to change the mouse cursor to loading
     #       state - but this won't work in touch screen devices? As
     #       there is no cursor there. In wxpython there is the 
     #       wx.CallLater() method, is there anything similar in Kivy?
     self.browser.GetMainFrame().LoadUrl(start_url)
             
     #Clock.schedule_interval(self.press_key, 5)
     self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
     self._keyboard.bind(on_key_down=self.press_key)