def Initialize(settings=None, debug=False): """Initializes CEF, We should do it before initializing wx If no settings passed a default is used """ global g_settings if not settings: settings = {} if not "log_severity" in settings: settings["log_severity"] = cefpython.LOGSEVERITY_INFO if not "log_file" in settings: settings["log_file"] = "" if platform.system() == "Linux": # On Linux we need to set locales and resources directories. if not "locales_dir_path" in settings: settings["locales_dir_path"] = \ cefpython.GetModuleDirectory() + "/locales" if not "resources_dir_path" in settings: settings["resources_dir_path"] = cefpython.GetModuleDirectory() if not "browser_subprocess_path" in settings: settings["browser_subprocess_path"] = \ "%s/%s" % (cefpython.GetModuleDirectory(), "subprocess") # DEBUGGING options: # ------------------ if debug: settings["debug"] = True # cefpython messages in console and log_file settings["log_severity"] = cefpython.LOGSEVERITY_VERBOSE settings["log_file"] = "debug.log" # Set to "" to disable. settings["release_dcheck_enabled"] = True g_settings = settings cefpython.Initialize(settings)
def __init__(self): Backend.__init__(self) sys.excepthook = ExceptHook # TODO: ?????????????? # Application settings settings = { # "cache_path": "webcache/", # Disk cache # "debug": True, # cefpython debug messages in console and in log_file # TODO "log_severity": cefpython.LOGSEVERITY_INFO, # LOGSEVERITY_VERBOSE "log_file": GetApplicationPath("debug.log"), # Set to "" to disable. "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") } # Command line switches set programmatically switches = { # "proxy-server": "socks5://127.0.0.1:8888", # "enable-media-stream": "", # "--invalid-switch": "" -> Invalid switch name } cefpython.Initialize(settings, switches)
def Initialize(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 = {} if not "log_severity" in settings: settings["log_severity"] = cefpython.LOGSEVERITY_INFO if not "log_file" in settings: settings["log_file"] = "" if platform.system() == "Linux": # On Linux we need to set locales and resources directories. if not "locales_dir_path" in settings: settings["locales_dir_path"] = \ cefpython.GetModuleDirectory() + "/locales" if not "resources_dir_path" in settings: settings["resources_dir_path"] = cefpython.GetModuleDirectory() if not "browser_subprocess_path" in settings: settings["browser_subprocess_path"] = \ "%s/%s" % (cefpython.GetModuleDirectory(), "subprocess") # DEBUGGING options: # ------------------ # cefpython.g_debug = True # cefpython.g_debugFile = "debug.log" # settings["log_severity"] = cefpython.LOGSEVERITY_VERBOSE # settings["log_file"] = "debug.log" # Set to "" to disable. # settings["release_dcheck_enabled"] = True cefpython.Initialize(settings)
def initialize(): check_versions() sys.excepthook = cef.ExceptHook settings = { "debug": False, "log_severity": cef.LOGSEVERITY_DISABLE, # cef.LOGSEVERITY_INFO, "locales_dir_path": cef.GetModuleDirectory() + "/locales", "resources_dir_path": cef.GetModuleDirectory(), "browser_subprocess_path": cef.GetModuleDirectory() + "/subprocess", "downloads_enabled": True, "remote_debugging_port": -1, "context_menu": { "enabled": True, "navigation": True, "print": True, "view_source": True, "external_browser": True, "devtools": True, }, "ignore_certificate_errors": True, } switches = { # "disable-gpu": "1", "no-proxy-server": "1", "disable-web-security": "1", } cef.Initialize(settings, switches=switches)
def __init__(self): cefpython.Initialize({ #"log_severity": cefpython.LOGSEVERITY_INFO, #"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(), "browser_subprocess_path": "%s/%s" % (cefpython.GetModuleDirectory(), "subprocess"), }) self._cef_texture = Texture() self._cef_texture.set_compression(Texture.CMOff) self._cef_texture.set_component_type(Texture.TUnsignedByte) self._cef_texture.set_format(Texture.FRgba4) card_maker = CardMaker("browser2d") card_maker.set_frame(-self._UI_SCALE, self._UI_SCALE, -self._UI_SCALE, self._UI_SCALE) node = card_maker.generate() self._cef_node = render2d.attachNewNode(node) self._cef_node.set_texture(self._cef_texture) self._cef_node.set_transparency(TransparencyAttrib.MAlpha) winhnd = base.win.getWindowHandle().getIntHandle() wininfo = cefpython.WindowInfo() wininfo.SetAsOffscreen(winhnd) wininfo.SetTransparentPainting(True) self.browser = cefpython.CreateBrowserSync(wininfo, {}, navigateUrl='') self.browser.SetClientHandler( CefClientHandler(self.browser, self._cef_texture)) self._is_loaded = False self._js_onload_queue = [] self.browser.SetClientCallback("OnLoadEnd", self._load_end) self.jsbindings = cefpython.JavascriptBindings() self.browser.SetJavascriptBindings(self.jsbindings) self._js_func_queue = [] self._set_browser_size() base.accept('window-event', self._set_browser_size) base.buttonThrowers[0].node().setKeystrokeEvent('keystroke') base.accept('keystroke', self._handle_key) base.taskMgr.add(self._cef_message_loop, "CefMessageLoop") def shutdown_cef(): cefpython.Shutdown() atexit.register(shutdown_cef)
def initialize(self, settings=None): """ Initializes PandaChrome and CEFPython """ # Retrieve logging level notify_level = config.GetString('notify-level', 'info') custom_level = config.GetString('cefpython-level', 'info') log_level = notify_level if custom_level != notify_level: log_level = custom_level cef_levels = { 'info': cefpython.LOGSEVERITY_INFO, 'warning': cefpython.LOGSEVERITY_WARNING, 'error': cefpython.LOGSEVERITY_ERROR } if log_level not in cef_levels: self.notify.warning( '%s is not a valid CEFPython log level; Defaulting to info' % log_level) log_level = 'info' log_level = cef_levels[log_level] # Attempt to build settings from prc prc_settings = { 'log_severity': log_level, 'release_dcheck_enabled': config.GetBool('cefpython-release-dcheck-enabled', False), 'locales_dir_path': cefpython.GetModuleDirectory() + "/locales", 'resources_dir_path': cefpython.GetModuleDirectory(), 'browser_subprocess_path': '%s/%s' % (cefpython.GetModuleDirectory(), 'subprocess') } # update with supplied settings if present if settings is not None: prc_settings.update(settings) cefpython.g_debug = config.GetBool('cefpython-gdebug', False) cefpython.Initialize(settings) #Initialize looping task taskMgr.add(self._perform_cef_loop, 'CefPythonMessageLoop')
def Initialize(settings=None, debug=False): """Initializes CEF, We should do it before initializing wx If no settings passed a default is used """ switches = {} global g_settings if not settings: settings = {} if not "log_severity" in settings: settings["log_severity"] = cefpython.LOGSEVERITY_INFO if not "log_file" in settings: settings["log_file"] = "" if platform.system() == "Linux": # On Linux we need to set locales and resources directories. if not "locales_dir_path" in settings: settings["locales_dir_path"] = \ cefpython.GetModuleDirectory() + "/locales" if not "resources_dir_path" in settings: settings["resources_dir_path"] = cefpython.GetModuleDirectory() elif platform.system() == "Darwin": # On Mac we need to set the resoures dir and the locale_pak switch if not "resources_dir_path" in settings: settings["resources_dir_path"] = (cefpython.GetModuleDirectory() + "/Resources") locale_pak = (cefpython.GetModuleDirectory() + "/Resources/en.lproj/locale.pak") if "locale_pak" in settings: locale_pak = settings["locale_pak"] del settings["locale_pak"] switches["locale_pak"] = locale_pak if not "browser_subprocess_path" in settings: settings["browser_subprocess_path"] = \ "%s/%s" % (cefpython.GetModuleDirectory(), "subprocess") # DEBUGGING options: # ------------------ if debug: settings["debug"] = True # cefpython messages in console and log_file settings["log_severity"] = cefpython.LOGSEVERITY_VERBOSE settings["log_file"] = "debug.log" # Set to "" to disable. g_settings = settings cefpython.Initialize(settings, switches)
def cef_init(): global CEF_INITIATED, TIMER if not CEF_INITIATED: CEF_INITIATED = True def on_timer(event): cef.MessageLoopWork() frame = wx.GetApp().GetTopWindow() frame.on_cef_timer = on_timer TIMER = wx.Timer(frame) TIMER.Start(25) frame.Bind(wx.EVT_TIMER, on_timer, TIMER) settings = { "debug": False, "log_severity": cef.LOGSEVERITY_DISABLE, #cef.LOGSEVERITY_INFO, "locales_dir_path": cef.GetModuleDirectory() + "/locales", "resources_dir_path": cef.GetModuleDirectory(), "browser_subprocess_path": cef.GetModuleDirectory() + "/subprocess", "downloads_enabled": True, "remote_debugging_port": -1, "context_menu": { "enabled": True, "navigation": True, "print": True, "view_source": True, "external_browser": True, "devtools": True, }, "ignore_certificate_errors": True, } switches = { #"disable-gpu": "1", "no-proxy-server": "1", 'disable-web-security': "1" } cef.Initialize(settings, switches=switches) frame.run_on_close.append(cef_close)
def InitCefApp(): appSettings = dict() if DEBUG: # cefpython debug messages in console and in log_file appSettings["debug"] = False cefwindow.g_debug = True appSettings["log_file"] = GetApplicationPath("HGui.log") appSettings["log_severity"] = cefpython.LOGSEVERITY_ERROR appSettings["release_dcheck_enabled"] = True # Enable only when debugging appSettings["browser_subprocess_path"] = "%s/%s" % ( cefpython.GetModuleDirectory(), "subprocess") cefpython.Initialize(appSettings)
def __init__(self, width=512, height=512, capabilities=None): cefpython.g_debug = True application_settings = { "log_severity": cefpython.LOGSEVERITY_INFO, # LOGSEVERITY_VERBOSE #"log_file": cefpython.GetApplicationPath("debug.log"), # Set to "" to disable. # "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(), "pack_loading_disabled": True, #"multi_threaded_message_loop": False, #"remote_debugging_port": 8080, "browser_subprocess_path": "%s/%s" % (cefpython.GetModuleDirectory(), "subprocess"), # nefunguje"disable_blink_features": "CSSIndependentTransformProperties", } cli_switches = { # "enable-blink-features": 'CSSMotionPath', #"enable-blink-features": "CSS3TextDecorations,CSSBackDropFilter", } cefpython.Initialize(application_settings, cli_switches) windowInfo = cefpython.WindowInfo() windowInfo.SetAsOffscreen(0) browserSettings = { "local_storage_disabled": True, } self.browser = cefpython.CreateBrowserSync( windowInfo, browserSettings, "http://localhost/transform.html") self.browser.SendFocusEvent(True) #set_js_bindings(browser) self.client_handler = ClientHandler(self.browser, width, height, "screenshot.png") self.browser.SetClientHandler(self.client_handler) self.bind()
def main(argv): detect_os() print(g_ardutag + "OS: %s" % g_platform_os) print(g_ardutag + "Python version: %s" % platform.python_version()) print(g_ardutag + "wx.version: %s" % wx.version()) print(g_ardutag + "cefpython GetModuleDirectory: %s" % cefpython.GetModuleDirectory()) # Intercept python exceptions. Exit app immediately when exception # happens on any of the threads. sys.excepthook = ExceptHook # Checking command line arguments server_root = None if len(argv) > 0: print("\n======= Parsing Command line arguments =======") # Windows only issue: In BlocklyRequestHandler, if chdir is fed an # 'incorrect' path like 'C:' instead of 'C:\' or C:/' it fails silently # maintaining the current working directory. Use regular expressions # to catch this corner case. if re.match("^[a-zA-Z]:$", argv[0]): print('The windows drive letter needs to end in a slash, ' + 'eg. %s\\' % arg) sys.exit(1) # Check if the value is a valid directory if os.path.isdir(argv[0]): print("Server root will be set to: %s" % argv[0]) server_root = argv[0] else: print('Invalid directory: %s ' % argv[0]) sys.exit(1) # Initialise the chromium embedded framework cef_init() # Launch ArdublocklyServer launch_server(server_root) # Launch CEF application app = ArdublocklyApp(False) #splash_screen() 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(). if g_platform_os != "mac": print(g_ardutag + "End of main: Exiting") cefpython.Shutdown()
def StartCefPython(self): ''' Start CefPython ''' settings = {} settings["browser_subprocess_path"] = "%s/%s" % ( cefpython.GetModuleDirectory(), "subprocess") settings["log_severity"] = cefpython.LOGSEVERITY_DISABLE settings["context_menu"] = { "enabled": False, "navigation": False, # Back, Forward, Reload "print": False, "view_source": False, "external_browser": False, # Open in external browser "devtools": False, # Developer Tools } cefpython.Initialize(settings)
def main(): winId = sys.argv[1] windowInfo = cef.WindowInfo() # print cef # print dir(cef) # print windowInfo # print dir(windowInfo) windowInfo.SetAsChild(int(winId)) settings = {} settings["browser_subprocess_path"] = "%s/%s" % (cef.GetModuleDirectory(), "subprocess") settings["context_menu"] = { "enabled": False, "navigation": False, # Back, Forward, Reload "print": False, "view_source": False, "external_browser": False, # Open in external browser "devtools": False, # Developer Tools } cef.Initialize(settings) # # browser = cef.CreateBrowserSync(url="https://www.baidu.com", browser = cef.CreateBrowserSync(windowInfo, url="https://www.baidu.com", window_title="Hello World!") print browser print dir(browser) # # print browser.GetWindowHandle() # # print dir(browser.GetWindowHandle()) # cef.WindowUtils.OnSize(int(winId), 0, 0, 0) # set_interval(lambda: cef.WindowUtils.OnSize(int(winId), 0, 0, 0),.2) while True: # time.sleep(0.1) cef.MessageLoopWork() cef.Shutdown()
def StartCefPython(self): ''' Start CefPython ''' qgsutils.showUserAndLogMessage(self, u"Information: ", u"Create Viewer.", QgsMessageBar.INFO, onlyLog=True) settings = {} settings["browser_subprocess_path"] = "%s/%s" % ( cefpython.GetModuleDirectory(), "subprocess") settings["log_severity"] = cefpython.LOGSEVERITY_DISABLE settings["context_menu"] = { "enabled": False, "navigation": False, # Back, Forward, Reload "print": False, "view_source": False, "external_browser": False, # Open in external browser "devtools": False, # Developer Tools } cefpython.Initialize(settings)
def main(): winId = sys.argv[1] windowInfo = cef.WindowInfo() windowInfo.SetAsChild(int(winId)) settings = {} settings["browser_subprocess_path"] = "%s/%s" % (cef.GetModuleDirectory(), "subprocess") settings["context_menu"] = { "enabled": False, "navigation": False, # Back, Forward, Reload "print": False, "view_source": False, "external_browser": False, # Open in external browser "devtools": False, # Developer Tools } cef.Initialize(settings) cef.CreateBrowserSync(windowInfo, url="https://www.baidu.com", window_title="Hello World!")
# Intercept python exceptions. Exit app immediately when exception # happens on any of the threads. sys.excepthook = ExceptHook # Application settings settings = { "debug": True, # 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 "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"), } cefpython.Initialize(settings) gobject.threads_init() # Timer for the message loop PyGTKExample() gtk.main() cefpython.Shutdown()
### --- CEF --- ### settings = { "multi_threaded_message_loop": False, "log_severity": cefpython.LOGSEVERITY_INFO, # LOGSEVERITY_VERBOSE #"log_file": GetApplicationPath("debug.log"), # Set to "" to disable. "release_dcheck_enabled": True, # Enable only when debugging. # This directories must be set on Linux # "locale": "en", "locales_dir_path": cefpython.GetModuleDirectory() + "/locales", "resources_dir_path": cefpython.GetModuleDirectory() + "/Resources", "browser_subprocess_path": "%s/%s" % (cefpython.GetModuleDirectory(), "subprocess") } class ClientHandler: """A client handler is required for the browser to do built in callbacks back into the application.""" browser = None def __init__(self, browser): self.browser = browser def OnPaint(self, browser, paintElementType, dirtyRects, buffer, width,
def start_cef(self): """Starts CEF.""" # create texture & add it to canvas # noinspection PyArgumentList 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 = { "browser_subprocess_path": "%s/%s" % (cef.GetModuleDirectory(), "subprocess"), "windowless_rendering_enabled": True, "context_menu": { # Disable context menu, popup widgets not supported "enabled": False, }, "external_message_pump": False, # See Issue #246 "multi_threaded_message_loop": False, } if sys.platform == 'linux': # This directories must be set on Linux settings["locales_dir_path"] = cef.GetModuleDirectory( ) + "/locales" settings["resources_dir_path"] = cef.GetModuleDirectory() if sys.platform == 'darwin': settings[ "external_message_pump"] = True # Temporary fix for Issue #246 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 # To shutdown all CEF processes on error sys.excepthook = cef.ExceptHook # noinspection PyArgumentList cef.WindowUtils.InstallX11ErrorHandlers() global g_switches g_switches = switches cef.Initialize(settings, switches) # Start idle - CEF message loop work. Clock.schedule_once(self._message_loop_work, 0) windowInfo = cef.WindowInfo() # TODO: For printing to work in off-screen-rendering mode # it is enough to call gtk_init(). It is not required # to provide window handle when calling SetAsOffscreen(). # However it still needs to be tested whether providing # window handle is required for mouse context menu and # popup widgets to work. # WindowInfo offscreen flag if sys.platform == 'linux': gtkwin = gtk.Window() gtkwin.realize() windowInfo.SetAsOffscreen(gtkwin.window.xid) elif sys.platform == 'darwin' or sys.platform == 'win32': windowInfo.SetAsOffscreen(0) # 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 = cef.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()
def cefpython_initialize(CEFBrowser): global cefpython_loop_event if cefpython_loop_event: Logger.warning( "CEFLoader: Attempt to initialize CEFPython another time") return try: md = cefpython.GetModuleDirectory() except Exception as e: raise Exception("CEFLoader: Could not define module-directory: %s" % e) Logger.debug("CEFLoader: Module Directory: %s", md) def cef_loop(*largs): try: cefpython.MessageLoopWork() except Exception as e: print("EXCEPTION IN CEF LOOP", e) cefpython_loop_event = Clock.schedule_interval(cef_loop, 0.01) default_settings = { "debug": False, "log_severity": cefpython.LOGSEVERITY_INFO, "release_dcheck_enabled": True, # Enable only when debugging. "locales_dir_path": os.path.join(md, "locales"), "resources_dir_path": md, "browser_subprocess_path": os.path.join(md, SUBPROCESS), "unique_request_context_per_browser": True, "windowless_rendering_enabled": True, "context_menu": { "enabled": False, }, } default_settings.update(CEFBrowser._settings) caches_path = os.path.join(md, "caches") cookies_path = os.path.join(md, "cookies") logs_path = os.path.join(md, "logs") if CEFBrowser._caches_path and os.path.isdir( os.path.dirname(CEFBrowser._caches_path)): caches_path = CEFBrowser._caches_path if CEFBrowser._cookies_path and os.path.isdir( os.path.dirname(CEFBrowser._cookies_path)): cookies_path = CEFBrowser._cookies_path if CEFBrowser._logs_path and os.path.isdir( os.path.dirname(CEFBrowser._logs_path)): logs_path = CEFBrowser._logs_path Logger.debug("CEFLoader: Caches path: %s", caches_path) Logger.debug("CEFLoader: Cookies path: %s", cookies_path) Logger.debug("CEFLoader: Logs path: %s", logs_path) if not os.path.isdir(caches_path): os.makedirs(caches_path, 0o0700) default_settings["cache_path"] = caches_path if not os.path.isdir(cookies_path): os.makedirs(cookies_path, 0o0700) if not os.path.isdir(logs_path): os.makedirs(logs_path, 0o0700) default_settings["log_file"] = os.path.join(logs_path, "cefpython.log") if platform == "linux": cefpython.WindowUtils.InstallX11ErrorHandlers() try: cefpython.Initialize(default_settings, CEFBrowser._command_line_switches) except Exception as err: del default_settings["debug"] cefpython.g_debug = True cefpython.g_debugFile = "debug.log" try: cefpython.Initialize(default_settings, CEFBrowser._command_line_switches) except Exception as err: raise Exception("CEFLoader: Failed to initialize cefpython %s", err) try: cookie_manager = cefpython.CookieManager.GetGlobalManager() cookie_manager.SetStoragePath(cookies_path, True) CEFBrowser._cookie_manager = cookie_manager except Exception as e: Logger.warning("CEFLoader: Failed to set up cookie manager: %s" % e) def cefpython_shutdown(*largs): print("CEFPYTHON SHUTDOWN", largs, App.get_running_app()) cefpython.Shutdown() App.get_running_app().stop() def cefpython_exit(*largs): cefpython_shutdown() sys.exit() atexit.register(cefpython_shutdown) signal.signal(signal.SIGINT, cefpython_exit)
def __init__(self, transparent=True, size=None, parent=None): super().__init__() # Common application settings app_settings = { "windowless_rendering_enabled": True, } cef_mod_dir_root = cefpython.GetModuleDirectory() if sys.platform == "darwin": app_settings['external_message_pump'] = True # Detect if we are running in a bundled app, and if so fix the path # to the framework resources main_dir = p3d.ExecutionEnvironment.getEnvironmentVariable( "MAIN_DIR") if main_dir.startswith(cef_mod_dir_root): app_settings['browser_subprocess_path'] = os.path.normpath( os.path.join(cef_mod_dir_root, '../Frameworks/subprocess')) app_settings['framework_dir_path'] = os.path.normpath( os.path.join( cef_mod_dir_root, '../Resources/Chromium Embedded Framework.framework')) else: app_settings['locales_dir_path'] = os.path.join( cef_mod_dir_root, 'locales') app_settings['resources_dir_path'] = cef_mod_dir_root app_settings['browser_subprocess_path'] = os.path.join( cef_mod_dir_root, 'subprocess') command_line_settings = { # Tweaking OSR performance by setting the same Chromium flags as the # cefpython SDL2 example (also see cefpython issue #240) "disable-gpu-compositing": "", "enable-begin-frame-scheduling": "", } browser_settings = { "windowless_frame_rate": 60, } cefpython.Initialize(app_settings, command_line_settings) self._cef_texture = p3d.Texture() self._cef_texture.set_compression(p3d.Texture.CMOff) self._cef_texture.set_component_type(p3d.Texture.TUnsignedByte) self._cef_texture.set_format(p3d.Texture.FRgba4) card_maker = p3d.CardMaker("browser2d") if size is None: size = [-1, 1, -1, 1] card_maker.set_frame(*size) self._size = size node = card_maker.generate() if parent is None: self._cef_node = base.render2d.attachNewNode(node) else: self._cef_node = parent.attachNewNode(node) self._cef_node.set_texture(self._cef_texture) if transparent: self._cef_node.set_transparency(p3d.TransparencyAttrib.MAlpha) winhnd = base.win.getWindowHandle().getIntHandle() wininfo = cefpython.WindowInfo() wininfo.SetAsOffscreen(winhnd) wininfo.SetTransparentPainting(True) self.browser = cefpython.CreateBrowserSync(wininfo, browser_settings, navigateUrl='') self.browser.SetClientHandler(CefClientHandler(self._cef_texture)) self._is_loaded = False self._js_onload_queue = [] self._js_func_onload_queue = [] self.browser.SetClientCallback("OnLoadEnd", self._load_end) self.jsbindings = cefpython.JavascriptBindings() self.browser.SendFocusEvent(True) self._set_browser_size(base.win) self.accept('window-event', self._set_browser_size) base.buttonThrowers[0].node().setKeystrokeEvent('keystroke') self.accept('keystroke', self._handle_text) self.accept('arrow_left', self._handle_key, [cefpython.VK_LEFT]) self.accept('arrow_right', self._handle_key, [cefpython.VK_RIGHT]) self.accept('arrow_up', self._handle_key, [cefpython.VK_UP]) self.accept('arrow_down', self._handle_key, [cefpython.VK_DOWN]) self.accept('home', self._handle_key, [cefpython.VK_HOME]) self.accept('end', self._handle_key, [cefpython.VK_END]) self.accept('mouse1', self._handle_mouse, [False]) self.accept('mouse1-up', self._handle_mouse, [True]) self._msg_loop_task = base.taskMgr.add(self._cef_message_loop, 'CEFMessageLoop') sys.excepthook = cefpython.ExceptHook atexit.register(self._shutdown_cef) self.use_mouse = True
from cefpython3 import cefpython # TODO: CEF 5 from ..backend import Backend from ..utils import ExceptHook, GetApplicationPath import sys from ..config import Config path_string = Config.FormatString( holders={ '%(CEF_DIR)s': cefpython.GetModuleDirectory(), '%(App_DIR)s': GetApplicationPath(), }) application_settings = Config({ 'accept_language_list': Config.String, 'auto_zooming': Config.String, 'background_color': (Config.Int, Config.Hex), 'browser_subprocess_path': path_string, 'cache_path': path_string, 'command_line_args_disabled': Config.Bool, 'context_menu': { 'enabled': Config.Bool, 'navigation': Config.Bool, 'print': Config.Bool, 'view_source': Config.Bool, 'external_browser': Config.Bool, 'devtools': Config.Bool,
def __init__(self): super().__init__() cef_mod_dir = cefpython.GetModuleDirectory() app_settings = { "windowless_rendering_enabled": True, "locales_dir_path": os.path.join(cef_mod_dir, 'locales'), "resources_dir_path": cefpython.GetModuleDirectory(), "browser_subprocess_path": os.path.join(cef_mod_dir, 'subprocess'), } command_line_settings = { # Tweaking OSR performance by setting the same Chromium flags as the # cefpython SDL2 example (also see cefpython issue #240) "disable-gpu-compositing": "", "enable-begin-frame-scheduling": "", } browser_settings = { "windowless_frame_rate": 60, } cefpython.Initialize(app_settings, command_line_settings) self._cef_texture = p3d.Texture() self._cef_texture.set_compression(p3d.Texture.CMOff) self._cef_texture.set_component_type(p3d.Texture.TUnsignedByte) self._cef_texture.set_format(p3d.Texture.FRgba4) card_maker = p3d.CardMaker("browser2d") card_maker.set_frame(-self._UI_SCALE, self._UI_SCALE, -self._UI_SCALE, self._UI_SCALE) node = card_maker.generate() self._cef_node = base.render2d.attachNewNode(node) self._cef_node.set_texture(self._cef_texture) self._cef_node.set_transparency(p3d.TransparencyAttrib.MAlpha) winhnd = base.win.getWindowHandle().getIntHandle() wininfo = cefpython.WindowInfo() wininfo.SetAsOffscreen(winhnd) wininfo.SetTransparentPainting(True) self.browser = cefpython.CreateBrowserSync(wininfo, browser_settings, navigateUrl='') self.browser.SetClientHandler(CefClientHandler(self._cef_texture)) self._is_loaded = False self._js_onload_queue = [] self._js_func_onload_queue = [] self.browser.SetClientCallback("OnLoadEnd", self._load_end) self.jsbindings = cefpython.JavascriptBindings() self.browser.SendFocusEvent(True) self._set_browser_size() self.accept('window-event', self._set_browser_size) base.buttonThrowers[0].node().setKeystrokeEvent('keystroke') self.accept('keystroke', self._handle_text) self.accept('arrow_left', self._handle_key, [cefpython.VK_LEFT]) self.accept('arrow_right', self._handle_key, [cefpython.VK_RIGHT]) self.accept('arrow_up', self._handle_key, [cefpython.VK_UP]) self.accept('arrow_down', self._handle_key, [cefpython.VK_DOWN]) self.accept('home', self._handle_key, [cefpython.VK_HOME]) self.accept('end', self._handle_key, [cefpython.VK_END]) self.accept('mouse1', self._handle_mouse, [False]) self.accept('mouse1-up', self._handle_mouse, [True]) self._msg_loop_task = base.taskMgr.add(self._cef_message_loop, 'CEFMessageLoop') sys.excepthook = cefpython.ExceptHook atexit.register(self._shutdown_cef) self.use_mouse = True
] return ctypes.pythonapi.PyCObject_AsVoidPtr(self.winId()) elif sys.version_info[0] == 3: ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ ctypes.py_object ] return ctypes.pythonapi.PyCapsule_GetPointer( self.winId(), None) if __name__ == "__main__": settings = {} settings["browser_subprocess_path"] = "%s/%s" % ( cefpython.GetModuleDirectory(), "subprocess") settings["context_menu"] = { "enabled": False, "navigation": False, # Back, Forward, Reload "print": False, "view_source": False, "external_browser": False, # Open in external browser "devtools": False, # Developer Tools } cefpython.Initialize(settings) app = QApplication(sys.argv) win = MainWindow() win.show() print win.winIdFixed()
def start_cef(self): """Starts CEF.""" # create texture & add it to canvas # noinspection PyArgumentList 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, # debug messages in console and in log_file "log_severity": cef.LOGSEVERITY_INFO, "log_file": "debug.log", # This directories must be set on Linux "locales_dir_path": cef.GetModuleDirectory() + "/locales", "resources_dir_path": cef.GetModuleDirectory(), "browser_subprocess_path": "%s/%s" % (cef.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 # noinspection PyArgumentList cef.WindowUtils.InstallX11ErrorHandlers() global g_switches g_switches = switches cef.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 = cef.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 = cef.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()
# -*- coding: UTF-8 -*- from cefpython3 import cefpython from threading import Thread, Lock import signal import Queue import wx import os import HTMLParser application_settings = { "cache_path": "/tmp/cef/cache/", "debug": False, "log_severity": cefpython.LOGSEVERITY_WARNING, "log_file": "/tmp/cef/debug.log", "resources_dir_path": cefpython.GetModuleDirectory() + "/Resources", "browser_subprocess_path": "%s/%s" % (cefpython.GetModuleDirectory(), "subprocess"), "unique_request_context_per_browser": True, "downloads_enabled": True, "remote_debugging_port": 0, "context_menu": { "enabled": True, "navigation": True, "print": True, "view_source": True, "external_browser": True, "devtools": True, }, "ignore_certificate_errors": True, }
if __name__ == '__main__': version = '.'.join(map(str, list(gtk.gtk_version))) print('[pygtk_.py] GTK version: %s' % version) # Intercept python exceptions. Exit app immediately when exception # happens on any of the threads. sys.excepthook = ExceptHook # Application settings settings = { "debug": True, # 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 "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"), } cefpython.Initialize(settings) gobject.threads_init() # Timer for the message loop PyGTKExample() gtk.main() cefpython.Shutdown()
def cef_init(): # Browser settings. Individual settings per browser in CreateBrowserSync. # https://code.google.com/p/cefpython/wiki/BrowserSettings global g_browserSettings g_browserSettings = { "plugins_disabled": True, "file_access_from_file_urls_allowed": True, "universal_access_from_file_urls_allowed": True, "java_disabled": True, "local_storage_disabled": False } # Application settings # https://code.google.com/p/cefpython/wiki/ApplicationSettings global g_applicationSettings g_applicationSettings = { "browser_subprocess_path": "%s%s%s" % (cefpython.GetModuleDirectory(), os.sep, "subprocess"), "cache_path": "webcache" + os.sep, "context_menu": { "enabled": True, "navigation": True, # Back, Forward, Reload "print": False, "view_source": False, "external_browser": True, # Open in external browser "devtools": True }, # Developer Tools "downloads_enabled": True, "ignore_certificate_errors": True, "debug": True, "log_file": GetApplicationPath("cef_debug.log"), "log_severity": cefpython.LOGSEVERITY_INFO, "release_dcheck_enabled": False, "remote_debugging_port": 0, "unique_request_context_per_browser": True, "auto_zooming": "system_dpi" } # "resources_dir_path" must be set on Mac, "locales_dir_path" not. if g_platform_os == "mac": g_applicationSettings["resources_dir_path"] = \ cefpython.GetModuleDirectory() + os.sep + "Resources" else: g_applicationSettings["resources_dir_path"] = \ cefpython.GetModuleDirectory() g_applicationSettings["locales_dir_path"] = \ cefpython.GetModuleDirectory() + os.sep + "locales" # High DPI support is available only on Windows. # 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 if g_platform_os == "windows": #g_applicationSettings["auto_zooming"] = "system_dpi" print(g_ardutag + "Calling SetProcessDpiAware") cefpython.DpiAware.SetProcessDpiAware() # Command line switches set programmatically # https://code.google.com/p/cefpython/wiki/CommandLineSwitches g_commandLineSwitches = { "enable-media-stream": "", "no-proxy-server": "", #"disable-remote-fonts": False, "disable-gpu": "", } # 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. if g_platform_os == "mac": g_commandLineSwitches["locale_pak"] = cefpython.GetModuleDirectory() + \ "/Resources/en.lproj/locale.pak" cefpython.Initialize(g_applicationSettings, g_commandLineSwitches)