def createBrowser(): winId = int(sys.argv[1]) windowInfo = cef.WindowInfo() windowInfo.SetAsChild(winId) settings = {} 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(windowInfo, url="https://www.baidu.com") port = int(sys.argv[2]) conn = rpyc.connect('localhost', port) while True: url = conn.root.loadUrl() if url and url != browser.GetUrl(): browser.LoadUrl(url) elif conn.root.resizeCall(): cef.WindowUtils.OnSize(winId, 0, 0, 0) cef.MessageLoopWork() cef.Shutdown()
def render(self, context): cef.MessageLoopWork() if self.handler.texture_ready: self.batch.begin(context) self.batch.draw(self.handler.texture, 0, 0) return self.batch.end() return []
def onTimer(self): # The proper way of doing message loop should be: # 1. In createTimer() call self.timer.start(0) # 2. In onTimer() call MessageLoopWork() only when # QtGui.QApplication.instance()->hasPendingEvents() returns False. # But... there is a bug in Qt, hasPendingEvents() returns always true. cefpython.MessageLoopWork()
def run_message_loop(): # Run message loop for some time. # noinspection PyTypeChecker for i in range(MESSAGE_LOOP_RANGE): cef.MessageLoopWork() time.sleep(0.01) subtest_message("cef.MessageLoopWork() ok")
def message_loop(self): self.cefstream.get_logger().info("Calling message loop") while self.running: cef.MessageLoopWork() self.shutdown_cef()
def _cef_message_loop(self, task): cefpython.MessageLoopWork() if self.use_mouse and base.mouseWatcherNode.has_mouse(): posx, posy = self._get_mouse_pos() self.browser.SendMouseMoveEvent(posx, posy, mouseLeave=False) return task.cont
async def run_async(url, title="Pytigon", parent_win=None, x=200, y=200, width=1024, height=768): def py_function(value, js_callback): url = value[0] params = value[1] url2 = url.replace("file:///home/sch/prj/pytigon/pytigon", "http://127.0.0.2") print(url2, params) print("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA2") # print(url, url2) ret = request(url2 + "/", params) # print(ret.str()) print("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA3") # ret = "Hello world!" ret = ( """<base href="file:///home/sch/prj/pytigon/pytigon/" target="_blank">""" + ret.str()) ret = ret.replace( "window.BASE_PATH = '/'", "window.BASE_PATH = 'file:///home/sch/prj/pytigon/pytigon/'", ) js_callback.Call(ret, py_callback) def py_callback(value): print("Value sent from Javascript: " + value) browser, client_handler = create_browser(None, title, parent_win, x, y, width, height) bindings = cef.JavascriptBindings() bindings.SetFunction("py_function", py_function) bindings.SetFunction("py_callback", py_callback) browser.SetJavascriptBindings(bindings) for i in range(0, 10): cef.MessageLoopWork() await asyncio.sleep(0.01) browser.LoadUrl(url) async def loop(): nonlocal client_handler while not client_handler.close: cef.MessageLoopWork() await asyncio.sleep(0.01) await loop() del browser
def _cef_message_loop(self, task): cefpython.MessageLoopWork() self.browser.SendFocusEvent(True) if self.use_mouse and base.mouseWatcherNode.has_mouse(): mouse = base.mouseWatcherNode.getMouse() rx, ry = mouse.get_x(), mouse.get_y() x = (rx + 1.0) / 2.0 * self._cef_texture.get_x_size() y = (ry + 1.0) / 2.0 * self._cef_texture.get_y_size() y = self._cef_texture.get_y_size() - y self.browser.SendMouseMoveEvent(x, y, mouseLeave=False) return task.cont
def start(self): ret = None self.update_time = time.time() self.connect_time = time.time() while True: # NOTE 刷新延迟 官方建议要有 10ms if time.time() - self.update_time < .01: continue self.update_time = time.time() cef.MessageLoopWork() # if time.time() - self.connect_time < .1:continue # self.connect_time = time.time() try: client, addr = self.s.accept() except: continue data = client.recv(1024) # NOTE change to specfic type arg_list = [arg for arg in data.split(";")] args = self.browser_dict.get(arg_list[1]) func_name = arg_list[0] if func_name == "stop": break elif func_name == "createBrowser" and not args: url = arg_list[2] winId = int(arg_list[1]) # NOTE 创建浏览器 UUID = arg_list[3] windowInfo = cef.WindowInfo() windowInfo.SetAsChild(winId) browser = cef.CreateBrowserSync(windowInfo, self.browser_settings, url=url) self.browser_dict[UUID] = (browser, winId) elif func_name in self.callback_dict and args: browser, winId = args ret = self.callback_dict[func_name](browser, winId, *arg_list[2:]) else: continue client.send(str(ret)) client.close() self.s.close() cef.Shutdown()
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 _message_loop_work(self, *_): """Get called every frame.""" self.count += 1 # print(self.count) cef.MessageLoopWork() self.on_mouse_move_emulate() # From Kivy docs: # Clock.schedule_once(my_callback, 0) # call after the next frame # Clock.schedule_once(my_callback, -1) # call before the next frame # When scheduling "after the next frame" Kivy calls _message_loop_work # in about 13ms intervals. We use a small trick to make this 6ms # interval by scheduling it alternately before and after the next # frame. This gives better User Experience when scrolling. # See Issue #240 for more details on OSR performance. if self.count % 2 == 0: Clock.schedule_once(self._message_loop_work, 0) else: Clock.schedule_once(self._message_loop_work, -1)
def main(): url = sys.argv[1] cefpython.Initialize(settings, switches) windowInfo = cefpython.WindowInfo() windowInfo.SetAsOffscreen(0) browserSettings = { # Remove same-origin policy. "web_security_disabled": False, } browser = cefpython.CreateBrowserSync(windowInfo, browserSettings, navigateUrl=url) browser.SendFocusEvent(True) finished_cv = threading.Condition() clientHandler = ClientHandler(browser, finished_cv) browser.SetClientHandler(clientHandler) finished_cv.acquire() # Run until browser terminates us. TODO: WDT if something goes wrong when parsing? while True: finished_cv.wait(MESSAGE_LOOP_CALL_FREQUENCY_SECS) if clientHandler.okToQuit: break else: cefpython.MessageLoopWork() # Delete all browser refererences to ensure cookies flushed to disk etc. del clientHandler.browser del browser cefpython.Shutdown()
def main(): parser = argparse.ArgumentParser( description='PySDL2 / cefpython example', add_help=True ) parser.add_argument( '-v', '--verbose', help='Turn on debug info', dest='verbose', action='store_true' ) parser.add_argument( '-r', '--renderer', help='Specify hardware or software rendering', default='software', dest='renderer', choices=['software', 'hardware'] ) args = parser.parse_args() logLevel = logging.INFO if args.verbose: logLevel = logging.DEBUG logging.basicConfig( format='[%(filename)s %(levelname)s]: %(message)s', level=logLevel ) logging.info("Using PySDL2 %s" % sdl2.__version__) version = sdl2.SDL_version() sdl2.SDL_GetVersion(version) logging.info( "Using SDL2 %s.%s.%s" % (version.major, version.minor, version.patch) ) # The following variables control the dimensions of the window # and browser display area width = 800 height = 600 # headerHeight is useful for leaving space for controls # at the top of the window (future implementation?) headerHeight = 0 browserHeight = height - headerHeight browserWidth = width # Mouse wheel fudge to enhance scrolling scrollEnhance = 40 # desired frame rate frameRate = 100 # Initialise CEF for offscreen rendering sys.excepthook = cef.ExceptHook 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": "", } browser_settings = { # Tweaking OSR performance (Issue #240) "windowless_frame_rate": frameRate } cef.Initialize(settings={"windowless_rendering_enabled": True}, switches=switches) logging.debug("cef initialised") window_info = cef.WindowInfo() window_info.SetAsOffscreen(0) # Initialise SDL2 for video (add other init constants if you # require other SDL2 functionality e.g. mixer, # TTF, joystick etc. sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) logging.debug("SDL2 initialised") # Create the window window = sdl2.video.SDL_CreateWindow( 'cefpython3 SDL2 Demo', sdl2.video.SDL_WINDOWPOS_UNDEFINED, sdl2.video.SDL_WINDOWPOS_UNDEFINED, width, height, 0 ) # Define default background colour (black in this case) backgroundColour = sdl2.SDL_Color(0, 0, 0) renderer = None if args.renderer == 'hardware': # Create the renderer using hardware acceleration logging.info("Using hardware rendering") renderer = sdl2.SDL_CreateRenderer( window, -1, sdl2.render.SDL_RENDERER_ACCELERATED ) else: # Create the renderer using software acceleration logging.info("Using software rendering") renderer = sdl2.SDL_CreateRenderer( window, -1, sdl2.render.SDL_RENDERER_SOFTWARE ) # Set-up the RenderHandler, passing in the SDL2 renderer renderHandler = RenderHandler(renderer, width, height - headerHeight) # Create the browser instance browser = cef.CreateBrowserSync(window_info, url="https://www.google.com/", settings=browser_settings) browser.SetClientHandler(LoadHandler()) browser.SetClientHandler(renderHandler) # Must call WasResized at least once to let know CEF that # viewport size is available and that OnPaint may be called. browser.SendFocusEvent(True) browser.WasResized() # Begin the main rendering loop running = True # FPS debug variables frames = 0 logging.debug("beginning rendering loop") resetFpsTime = True fpsTime = 0 while running: # record when we started drawing this frame startTime = sdl2.timer.SDL_GetTicks() if resetFpsTime: fpsTime = sdl2.timer.SDL_GetTicks() resetFpsTime = False # Convert SDL2 events into CEF events (where appropriate) events = sdl2.ext.get_events() for event in events: if (event.type == sdl2.SDL_QUIT or (event.type == sdl2.SDL_KEYDOWN and event.key.keysym.sym == sdl2.SDLK_ESCAPE)): running = False logging.debug("SDL2 QUIT event") break if event.type == sdl2.SDL_MOUSEBUTTONDOWN: if event.button.button == sdl2.SDL_BUTTON_LEFT: if event.button.y > headerHeight: logging.debug( "SDL2 MOUSEBUTTONDOWN event (left button)" ) # Mouse click triggered in browser region browser.SendMouseClickEvent( event.button.x, event.button.y - headerHeight, cef.MOUSEBUTTON_LEFT, False, 1 ) elif event.type == sdl2.SDL_MOUSEBUTTONUP: if event.button.button == sdl2.SDL_BUTTON_LEFT: if event.button.y > headerHeight: logging.debug("SDL2 MOUSEBUTTONUP event (left button)") # Mouse click triggered in browser region browser.SendMouseClickEvent( event.button.x, event.button.y - headerHeight, cef.MOUSEBUTTON_LEFT, True, 1 ) elif event.type == sdl2.SDL_MOUSEMOTION: if event.motion.y > headerHeight: # Mouse move triggered in browser region browser.SendMouseMoveEvent(event.motion.x, event.motion.y - headerHeight, False) elif event.type == sdl2.SDL_MOUSEWHEEL: logging.debug("SDL2 MOUSEWHEEL event") # Mouse wheel event x = event.wheel.x if x < 0: x -= scrollEnhance else: x += scrollEnhance y = event.wheel.y if y < 0: y -= scrollEnhance else: y += scrollEnhance browser.SendMouseWheelEvent(0, 0, x, y) elif event.type == sdl2.SDL_TEXTINPUT: # Handle text events to get actual characters typed rather # than the key pressed. logging.debug("SDL2 TEXTINPUT event: %s" % event.text.text) keycode = ord(event.text.text) key_event = { "type": cef.KEYEVENT_CHAR, "windows_key_code": keycode, "character": keycode, "unmodified_character": keycode, "modifiers": cef.EVENTFLAG_NONE } browser.SendKeyEvent(key_event) key_event = { "type": cef.KEYEVENT_KEYUP, "windows_key_code": keycode, "character": keycode, "unmodified_character": keycode, "modifiers": cef.EVENTFLAG_NONE } browser.SendKeyEvent(key_event) elif event.type == sdl2.SDL_KEYDOWN: # Handle key down events for non-text keys logging.debug("SDL2 KEYDOWN event") if event.key.keysym.sym == sdl2.SDLK_RETURN: keycode = event.key.keysym.sym key_event = { "type": cef.KEYEVENT_CHAR, "windows_key_code": keycode, "character": keycode, "unmodified_character": keycode, "modifiers": cef.EVENTFLAG_NONE } browser.SendKeyEvent(key_event) elif event.key.keysym.sym in [ sdl2.SDLK_BACKSPACE, sdl2.SDLK_DELETE, sdl2.SDLK_LEFT, sdl2.SDLK_RIGHT, sdl2.SDLK_UP, sdl2.SDLK_DOWN, sdl2.SDLK_HOME, sdl2.SDLK_END ]: keycode = get_key_code(event.key.keysym.sym) if keycode is not None: key_event = { "type": cef.KEYEVENT_RAWKEYDOWN, "windows_key_code": keycode, "character": keycode, "unmodified_character": keycode, "modifiers": cef.EVENTFLAG_NONE } browser.SendKeyEvent(key_event) elif event.type == sdl2.SDL_KEYUP: # Handle key up events for non-text keys logging.debug("SDL2 KEYUP event") if event.key.keysym.sym in [ sdl2.SDLK_RETURN, sdl2.SDLK_BACKSPACE, sdl2.SDLK_DELETE, sdl2.SDLK_LEFT, sdl2.SDLK_RIGHT, sdl2.SDLK_UP, sdl2.SDLK_DOWN, sdl2.SDLK_HOME, sdl2.SDLK_END ]: keycode = get_key_code(event.key.keysym.sym) if keycode is not None: key_event = { "type": cef.KEYEVENT_KEYUP, "windows_key_code": keycode, "character": keycode, "unmodified_character": keycode, "modifiers": cef.EVENTFLAG_NONE } browser.SendKeyEvent(key_event) # Clear the renderer sdl2.SDL_SetRenderDrawColor( renderer, backgroundColour.r, backgroundColour.g, backgroundColour.b, 255 ) sdl2.SDL_RenderClear(renderer) # Tell CEF to update which will trigger the OnPaint # method of the RenderHandler instance cef.MessageLoopWork() # Update display sdl2.SDL_RenderCopy( renderer, renderHandler.texture, None, sdl2.SDL_Rect(0, headerHeight, browserWidth, browserHeight) ) sdl2.SDL_RenderPresent(renderer) # FPS debug code frames += 1 if sdl2.timer.SDL_GetTicks() - fpsTime > 1000: logging.debug("FPS: %d" % frames) frames = 0 resetFpsTime = True # regulate frame rate if sdl2.timer.SDL_GetTicks() - startTime < 1000.0 / frameRate: sdl2.timer.SDL_Delay( (1000 / frameRate) - (sdl2.timer.SDL_GetTicks() - startTime) ) # User exited exit_app()
def OnIdle(self, event): cefpython.MessageLoopWork()
def OnTimer(self): if self.exiting: return False from cefpython3 import cefpython cefpython.MessageLoopWork() return True
def on_timer(self): if self.exiting: return False cef.MessageLoopWork() return True
def OnTimer(self, event): cefpython.MessageLoopWork()
def test_main(self): """Main entry point.""" # All this code must run inside one single test, otherwise strange # things happen. print("") print("CEF Python {ver}".format(ver=cef.__version__)) print("Python {ver}".format(ver=sys.version[:6])) # Test initialization of CEF settings = { "debug": False, "log_severity": cef.LOGSEVERITY_ERROR, "log_file": "", } if "--debug" in sys.argv: settings["debug"] = True settings["log_severity"] = cef.LOGSEVERITY_INFO cef.Initialize(settings) subtest_message("cef.Initialize() ok") # Test global handler global_handler = GlobalHandler(self) cef.SetGlobalClientCallback("OnAfterCreated", global_handler._OnAfterCreated) subtest_message("cef.SetGlobalClientCallback() ok") # Test creation of browser browser = cef.CreateBrowserSync(url=g_datauri) self.assertIsNotNone(browser, "Browser object") subtest_message("cef.CreateBrowserSync() ok") # Test other handlers: LoadHandler, DisplayHandler etc. client_handlers = [LoadHandler(self), DisplayHandler(self)] for handler in client_handlers: browser.SetClientHandler(handler) subtest_message("browser.SetClientHandler() ok") # Test javascript bindings external = External(self) bindings = cef.JavascriptBindings(bindToFrames=False, bindToPopups=False) bindings.SetFunction("test_function", external.test_function) bindings.SetProperty("test_property1", external.test_property1) bindings.SetProperty("test_property2", external.test_property2) # Property with a function value can also be bound. CEF Python # supports passing functions as callbacks when called from # javascript, and as a side effect any value and in this case # a property can also be a function. bindings.SetProperty("test_property3_function", external.test_property3_function) bindings.SetProperty("cefpython_version", cef.GetVersion()) bindings.SetObject("external", external) browser.SetJavascriptBindings(bindings) subtest_message("browser.SetJavascriptBindings() ok") # Run message loop for some time. # noinspection PyTypeChecker for i in range(MESSAGE_LOOP_RANGE): cef.MessageLoopWork() time.sleep(0.01) subtest_message("cef.MessageLoopWork() ok") # Test browser closing. Remember to clean reference. browser.CloseBrowser(True) del browser subtest_message("browser.CloseBrowser() ok") # Give it some time to close before calling shutdown. # noinspection PyTypeChecker for i in range(25): cef.MessageLoopWork() time.sleep(0.01) # Automatic check of asserts in handlers and in external for obj in [] + client_handlers + [global_handler, external]: test_for_True = False # Test whether asserts are working correctly for key, value in obj.__dict__.items(): if key == "test_for_True": test_for_True = True continue if "_True" in key: self.assertTrue( value, "Check assert: " + obj.__class__.__name__ + "." + key) subtest_message(obj.__class__.__name__ + "." + key.replace("_True", "") + " ok") elif "_False" in key: self.assertFalse( value, "Check assert: " + obj.__class__.__name__ + "." + key) subtest_message(obj.__class__.__name__ + "." + key.replace("_False", "") + " ok") self.assertTrue(test_for_True) # Test shutdown of CEF cef.Shutdown() subtest_message("cef.Shutdown() ok") # Display real number of tests there were run print("\nRan " + str(g_subtests_ran) + " sub-tests in test_main") sys.stdout.flush()
def on_timer(self, _): if MAC: cef.MessageLoop() else: cef.MessageLoopWork()
def message_loop_work(self): cef.MessageLoopWork() self.after(10, self.message_loop_work)
def onTimer(self): try: cefpython.MessageLoopWork() except: None
def do_message_loop_work(work_loops): # noinspection PyTypeChecker for i in range(work_loops): cef.MessageLoopWork() time.sleep(0.01)
def on_timer(self): cef.MessageLoopWork() return True
def MessageLoopTimer(event): cefpython.MessageLoopWork()
def OnIdle(self, event): """Service CEF message loop when useTimer is False""" cefpython.MessageLoopWork() event.Skip()
def onTimer(self): cef.MessageLoopWork()
def OnTimer(self): if self.exiting: return False cefpython.MessageLoopWork() return True
def on_timer(self, event): cef.MessageLoopWork()
def on_timer(self, _): cef.MessageLoopWork()
def cef_loop(*largs): try: cefpython.MessageLoopWork() except Exception as e: print("EXCEPTION IN CEF LOOP", e)