示例#1
0
    def __init__(self):
        self.mainWindow = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.mainWindow.connect('focus-in-event', self.OnFocusIn)
        self.mainWindow.connect('configure-event', self.OnConfigure)
        self.mainWindow.connect('destroy', self.OnExit)
        self.mainWindow.set_size_request(width=800, height=600)
        self.mainWindow.set_title('PyGTK CEF example')
        self.mainWindow.realize()

        self.vbox = gtk.VBox(False, 0)
        self.vbox.connect('size-allocate', self.OnVBoxSize)
        self.menubar = self.CreateMenu()
        self.menubar.connect('size-allocate', self.OnMenubarSize)
        self.vbox.pack_start(self.menubar, False, False, 0)
        self.mainWindow.add(self.vbox)

        windowInfo = cefpython.WindowInfo()
        windowInfo.SetAsChild(self.mainWindow.window.xid, [0, 0, 0, 0])
        # Linux requires adding "file://" for local files,
        # otherwise /home/some will be replaced as http://home/some
        self.browser = cefpython.CreateBrowserSync(
            windowInfo,
            browserSettings={},
            navigateUrl="file://" + GetApplicationPath("example.html"))

        self.vbox.show()
        self.mainWindow.show()
        self.vbox.get_window().focus()
        self.mainWindow.get_window().focus()
        gobject.timeout_add(10, self.OnTimer)
示例#2
0
    def __init__(self):
        wx.Frame.__init__(self,
                          parent=None,
                          id=wx.ID_ANY,
                          title='wxPython example',
                          size=(800, 600))
        self.CreateMenu()

        # Cannot attach browser to the main frame as this will cause
        # the menu not to work.
        self.mainPanel = wx.Panel(self)

        windowInfo = cefpython.WindowInfo()
        windowInfo.SetAsChild(self.mainPanel.GetGtkWidget())
        # Linux requires adding "file://" for local files,
        # otherwise /home/some will be replaced as http://home/some
        self.browser = cefpython.CreateBrowserSync(
            windowInfo,
            # Flash will crash app in CEF 1 on Linux, setting
            # plugins_disabled to True.
            browserSettings={"plugins_disabled": True},
            navigateUrl="file://" + GetApplicationPath("wxpython.html"))

        self.browser.SetClientHandler(ClientHandler())

        jsBindings = cefpython.JavascriptBindings(bindToFrames=False,
                                                  bindToPopups=False)
        jsBindings.SetObject("external", JavascriptBindings(self.browser))
        self.browser.SetJavascriptBindings(jsBindings)

        self.Bind(wx.EVT_CLOSE, self.OnClose)
        if USE_EVT_IDLE:
            # Bind EVT_IDLE only for the main application frame.
            self.Bind(wx.EVT_IDLE, self.OnIdle)
示例#3
0
    def __init__(self):
        self.mainWindow = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.mainWindow.connect('destroy', self.OnExit)
        self.mainWindow.set_size_request(width=800, height=600)
        self.mainWindow.set_title('PyGTK CEF example')
        self.mainWindow.realize()

        self.vbox = gtk.VBox(False, 0)
        self.vbox.pack_start(self.CreateMenu(), False, False, 0)
        self.mainWindow.add(self.vbox)

        m = re.search("GtkVBox at 0x(\w+)", str(self.vbox))
        hexID = m.group(1)
        windowID = int(hexID, 16)

        windowInfo = cefpython.WindowInfo()
        windowInfo.SetAsChild(windowID)
        # Linux requires adding "file://" for local files,
        # otherwise /home/some will be replaced as http://home/some
        self.browser = cefpython.CreateBrowserSync(
            windowInfo,
            browserSettings={},
            navigateUrl="file://" + GetApplicationPath("example.html"))

        self.vbox.show()
        self.mainWindow.show()
        gobject.timeout_add(10, self.OnTimer)
示例#4
0
 def __init__(self, parent=None):
     super(MainFrame, self).__init__(parent)
     windowInfo = cefpython.WindowInfo()
     windowInfo.SetAsChild(int(self.winIdFixed()))
     self.browser = cefpython.CreateBrowserSync(
         windowInfo,
         browserSettings={},
         navigateUrl=GetApplicationPath("example.html"))
     self.show()
示例#5
0
文件: cef.py 项目: Charyas/python
 def __init__(self, parent=None):
     super(MainFrame, self).__init__(parent)
     windowInfo = cefpython.WindowInfo()
     windowInfo.SetAsChild(int(self.winId()))
     # Linux requires adding "file://" for local files,
     # otherwise /home/some will be replaced as http://home/some
     self.browser = cefpython.CreateBrowserSync(windowInfo,
             browserSettings={},
             navigateUrl="http://www.3dying.com/apps")
     self.show()
示例#6
0
 def __init__(self, parent=None, url="http://www.google.fr/"):
     super(MainFrame, self).__init__(parent)
     windowInfo = cefpython.WindowInfo()
     windowInfo.SetAsChild(int(self.winIdFixed()))
     self.browser = cefpython.CreateBrowserSync(
         windowInfo,
         browserSettings={},
         navigateUrl=GetApplicationPath(url))
     self.browser.SetClientCallback('OnPreKeyEvent', self.OnKeyEvent)
     self.show()
示例#7
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()
示例#8
0
        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)
示例#9
0
 def __init__(self, parent=None):
     super(MainFrame, self).__init__(parent)
     windowInfo = cefpython.WindowInfo()
     windowInfo.SetAsChild(int(self.winId()))    
     while True:
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         result = sock.connect_ex(('127.0.0.1',8000))
         sock.close()
         if result == 0:
             break
     self.browser = cefpython.CreateBrowserSync(windowInfo,
             browserSettings={},
             navigateUrl=GetApplicationPath("http://127.0.0.1:8000"))
     self.show()
示例#10
0
    def __init__(self):
        wx.Frame.__init__(self,
                          parent=None,
                          id=wx.ID_ANY,
                          title='wxPython CEF 3 example',
                          size=(800, 600))
        self.CreateMenu()

        # Cannot attach browser to the main frame as this will cause
        # the menu not to work.
        # --
        # You also have to set the wx.WANTS_CHARS style for
        # all parent panels/controls, if it's deeply embedded.
        self.mainPanel = wx.Panel(self, style=wx.WANTS_CHARS)

        windowInfo = cefpython.WindowInfo()
        windowInfo.SetAsChild(self.mainPanel.GetGtkWidget())
        # Linux requires adding "file://" for local files,
        # otherwise /home/some will be replaced as http://home/some
        self.browser = cefpython.CreateBrowserSync(
            windowInfo,
            # If there are problems with Flash you can disable it here,
            # by disabling all plugins.
            browserSettings={"plugins_disabled": False},
            navigateUrl="file://" + GetApplicationPath("index.html"))

        clientHandler = ClientHandler()
        self.browser.SetClientHandler(clientHandler)
        cefpython.SetGlobalClientCallback("OnCertificateError",
                                          clientHandler._OnCertificateError)
        cefpython.SetGlobalClientCallback("OnBeforePluginLoad",
                                          clientHandler._OnBeforePluginLoad)

        jsBindings = cefpython.JavascriptBindings(bindToFrames=False,
                                                  bindToPopups=True)
        jsBindings.SetFunction("PyPrint", PyPrint)
        jsBindings.SetProperty("pyProperty", "This was set in Python")
        jsBindings.SetProperty("pyConfig", [
            "This was set in Python", {
                "name": "Nested dictionary",
                "isNested": True
            }, [1, "2", None]
        ])
        jsBindings.SetObject("external", JavascriptExternal(self.browser))
        self.browser.SetJavascriptBindings(jsBindings)

        self.Bind(wx.EVT_CLOSE, self.OnClose)
        if USE_EVT_IDLE:
            # Bind EVT_IDLE only for the main application frame.
            self.Bind(wx.EVT_IDLE, self.OnIdle)
示例#11
0
 def __init__(self, parent=None):
     super(MainFrame, self).__init__(parent)
     windowInfo = cefpython.WindowInfo()
     windowInfo.SetAsChild(int(self.winId()))
     self.browser = cefpython.CreateBrowserSync(
         windowInfo,
         browserSettings={},
         navigateUrl=GetApplicationPath("example.html"))
     jsBindings = cefpython.JavascriptBindings(bindToFrames=False,
                                               bindToPopups=True)
     jsBindings.SetFunction("py_multiply", funcs.multiply)
     self.browser.SetJavascriptBindings(jsBindings)
     self.browser.GetMainFrame().ExecuteJavascript(
         'alert("direct call from python")')
     self.show()
示例#12
0
    def __init__(self, my_html, parent=None):
        print 'MainFrame:', my_html

        super(MainFrame, self).__init__(parent)
        self.my_html = my_html
        windowInfo = cefpython.WindowInfo()
        windowInfo.SetAsChild(int(self.winId()))
        self.browser = cefpython.CreateBrowserSync(
            windowInfo,
            browserSettings={
                "web_security_disabled": True,
                "universal_access_from_file_urls_allowed": True
            },
            navigateUrl=GetApplicationPath(self.my_html))
        self.resize(1024, 720)
        self.show()
示例#13
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()
示例#14
0
 def CreateSecondBrowser(self):
     # Closing second window won't quit application,
     # WM_DESTROY not defined here.
     wndproc2 = {
         win32con.WM_CLOSE: CloseWindow,
         win32con.WM_SIZE: cefpython.WindowUtils.OnSize,
         win32con.WM_SETFOCUS: cefpython.WindowUtils.OnSetFocus,
         win32con.WM_ERASEBKGND: cefpython.WindowUtils.OnEraseBackground
     }
     windowHandle2 = cefwindow.CreateWindow(
             title="SecondBrowser", className="secondbrowser",
             width=800, height=600, xpos=0, ypos=0, icon="icon.ico",
             windowProc=wndproc2)
     windowInfo2 = cefpython.WindowInfo()
     windowInfo2.SetAsChild(windowHandle2)
     browser2 = cefpython.CreateBrowserSync(
             windowInfo2, browserSettings={},
             navigateUrl=GetApplicationPath("cefsimple.html"))
     browser2.SetUserData("outerWindowHandle", windowHandle2)
示例#15
0
    def __init__(self, parent, url="", size=(-1, -1), *args, **kwargs):
        wx.Window.__init__(self,
                           parent,
                           id=wx.ID_ANY,
                           size=size,
                           *args,
                           **kwargs)
        self.url = url
        windowInfo = cefpython.WindowInfo()
        windowInfo.SetAsChild(self.GetHandle())
        self.browser = cefpython.CreateBrowserSync(windowInfo,
                                                   browserSettings={},
                                                   navigateUrl=url)

        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        self.Bind(wx.EVT_SIZE, self.OnSize)

        self.timerID = 1
        self._createTimer()
示例#16
0
 def loadCustumUrl(self, url):
     self.clientHandler = ClientHandler()
     cefpython.SetGlobalClientCallback(
         "OnCertificateError", self.clientHandler._OnCertificateError)
     cefpython.SetGlobalClientCallback(
         "OnBeforePluginLoad", self.clientHandler._OnBeforePluginLoad)
     cefpython.SetGlobalClientCallback("OnAfterCreated",
                                       self.clientHandler._OnAfterCreated)
     windowInfo = cefpython.WindowInfo()
     print "WIndow Infor", windowInfo
     windowInfo.SetAsChild(self.winId())
     print "WIn Id", int(self.winId())
     self.browser = cefpython.CreateBrowserSync(windowInfo,
                                                browserSettings={},
                                                navigateUrl="about:None")
     self.browser.GetMainFrame().LoadUrl("http://www.google.com")
     self.clientHandler.mainBrowser = self.browser
     self.browser.SetClientHandler(self.clientHandler)
     # cefpython.MessageLoop()
     self.show()
示例#17
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()
示例#18
0
    def __init__(self, parent=None):
        super(MainFrame, self).__init__(parent)

        # QX11EmbedContainer provides an X11 window. The CEF
        # browser can be embedded only by providing a GtkWidget
        # pointer. So we're embedding a GtkPlug inside the X11
        # window. In latest CEF trunk it is possible to embed
        # the CEF browser by providing X11 window id. So it will
        # be possible to remove the GTK dependency from CEF
        # Python in the future.
        gtkPlugPtr = cefpython.WindowUtils.gtk_plug_new(\
                int(self.winId()))
        print("[pyqt.py] MainFrame: GDK Native Window id: " +
              str(self.winId()))
        print("[pyqt.py] MainFrame: GTK Plug ptr: " + str(gtkPlugPtr))
        """
        Embedding GtkPlug is also possible with the pygtk module.
        ---------------------------------------------------------
        self.plug = gtk.Plug(self.winId())
        import re
        m = re.search("GtkPlug at 0x(\w+)", str(self.plug))
        hexId = m.group(1)
        gtkPlugPtr = int(hexId, 16)
        ...
        plug.show()
        self.show()
        ---------------------------------------------------------
        """

        windowInfo = cefpython.WindowInfo()
        # Need to pass to CEF the GtkWidget* pointer
        windowInfo.SetAsChild(gtkPlugPtr)
        # Linux requires adding "file://" for local files,
        # otherwise /home/some will be replaced as http://home/some
        self.browser = cefpython.CreateBrowserSync(
            windowInfo,
            browserSettings={},
            navigateUrl="file://" + GetApplicationPath("example.html"))

        cefpython.WindowUtils.gtk_widget_show(gtkPlugPtr)
        self.show()
示例#19
0
    def loadCustumUrl(self, url):
        # self.layout = QtGui.QVBoxLayout()
        # self.killRef = QtGui.QPushButton()
        self.clientHandler = ClientHandler()
        cefpython.SetGlobalClientCallback(
            "OnCertificateError", self.clientHandler._OnCertificateError)
        cefpython.SetGlobalClientCallback(
            "OnBeforePluginLoad", self.clientHandler._OnBeforePluginLoad)
        cefpython.SetGlobalClientCallback("OnAfterCreated",
                                          self.clientHandler._OnAfterCreated)
        windowInfo = cefpython.WindowInfo()
        windowInfo.SetAsChild(int(self.winId()))
        self.browser = cefpython.CreateBrowserSync(windowInfo,
                                                   browserSettings={},
                                                   navigateUrl="about:None")

        self.browser.GetMainFrame().LoadUrl(url)
        self.clientHandler.mainBrowser = self.browser

        self.browser.SetClientHandler(self.clientHandler)
        self.show()
示例#20
0
    def __init__(self):

        gobject.timeout_add(10, self.OnTimer)

        self.mainWindow = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.mainWindow.connect('destroy', self.OnExit)
        self.mainWindow.set_size_request(width=600, height=400)
        self.mainWindow.set_title('PyGTK CEF example')
        self.mainWindow.realize()

        self.container = gtk.DrawingArea()
        self.container.set_property('can-focus', True)
        self.container.connect('size-allocate', self.OnSize)
        self.container.show()

        self.searchEntry = gtk.Entry()
        # By default, clicking a GTK widget doesn't grab the focus away from a native Win32 control (browser).
        self.searchEntry.connect('button-press-event', self.OnWidgetClick)
        self.searchEntry.show()

        table = gtk.Table(3, 1, homogeneous=False)
        self.mainWindow.add(table)
        table.attach(self.CreateMenu(), 0, 1, 0, 1, yoptions=gtk.SHRINK)
        table.attach(self.searchEntry, 0, 1, 1, 2, yoptions=gtk.SHRINK)
        table.attach(self.container, 0, 1, 2, 3)
        table.show()

        windowID = self.container.get_window().handle
        windowInfo = cefpython.WindowInfo()
        windowInfo.SetAsChild(windowID)
        self.browser = cefpython.CreateBrowserSync(
            windowInfo,
            browserSettings={},
            navigateUrl=GetApplicationPath("cefsimple.html"))

        self.mainWindow.show()

        # Browser took focus, we need to get it back and give to searchEntry.
        self.mainWindow.get_window().focus()
        self.searchEntry.grab_focus()
示例#21
0
    def __init__(self):
        wx.Frame.__init__(self, parent=None, id=wx.ID_ANY,
                          title='wxPython example', size=(800,600))
        self.CreateMenu()

        windowInfo = cefpython.WindowInfo()
        windowInfo.SetAsChild(self.GetHandle())
        self.browser = cefpython.CreateBrowserSync(windowInfo,
                browserSettings={},
                navigateUrl=GetApplicationPath("wxpython.html"))

        self.browser.SetClientHandler(ClientHandler())
        jsBindings = cefpython.JavascriptBindings(
            bindToFrames=False, bindToPopups=False)
        jsBindings.SetObject("external", JavascriptBindings(self.browser))
        self.browser.SetJavascriptBindings(jsBindings)

        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        if USE_EVT_IDLE:
            # Bind EVT_IDLE only for the main application frame.
            self.Bind(wx.EVT_IDLE, self.OnIdle)
示例#22
0
    def __init__(self):
        wx.Frame.__init__(self,
                          parent=None,
                          id=wx.ID_ANY,
                          title='D3Up.com Client',
                          size=(375, 460))
        # self.CreateMenu()

        windowInfo = cefpython.WindowInfo()
        windowInfo.SetAsChild(self.GetHandle())
        self.browser = cefpython.CreateBrowserSync(
            windowInfo,
            browserSettings={},
            navigateUrl=GetApplicationPath(
                "http://d3up.com/ajax/compare/?&controller=ajax&action=compare&module=default&battletag=&build=379278&name=TRIUMVIRATE&quality=Legendary&type=Source&dps=0&meta=&stats=65-348%20Dmg,%205%20FireD,%206%20LtnD,%205%20ArcD,%2079%20Str,%20201%20Int,%2013%20MaxArcP,%208.0%20Crit"
            ))

        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        if USE_EVT_IDLE:
            # Bind EVT_IDLE only for the main application frame.
            self.Bind(wx.EVT_IDLE, self.OnIdle)
示例#23
0
    def __init__(self):
        wx.Frame.__init__(self,
                          parent=None,
                          id=wx.ID_ANY,
                          title='wxPython CEF 3 example',
                          size=(800, 600))
        self.CreateMenu()

        # Cannot attach browser to the main frame as this will cause
        # the menu not to work.
        # --
        # You also have to set the wx.WANTS_CHARS style for
        # all parent panels/controls, if it's deeply embedded.
        self.mainPanel = wx.Panel(self, style=wx.WANTS_CHARS)

        windowInfo = cefpython.WindowInfo()
        windowInfo.SetAsChild(self.mainPanel.GetGtkWidget())
        # Linux requires adding "file://" for local files,
        # otherwise /home/some will be replaced as http://home/some
        self.browser = cefpython.CreateBrowserSync(
            windowInfo,
            # If there are problems with Flash you can disable it here,
            # by disabling all plugins.
            browserSettings={
                "plugins_disabled": False,
                "default_encoding": BROWSER_DEFAULT_ENCODING
            },
            navigateUrl="file://" + GetApplicationPath("example.html"))

        clientHandler = ClientHandler()
        self.browser.SetClientHandler(clientHandler)

        self.Bind(wx.EVT_CLOSE, self.OnClose)
        if USE_EVT_IDLE:
            # Bind EVT_IDLE only for the main application frame.
            self.Bind(wx.EVT_IDLE, self.OnIdle)
    def __init__(self, url=None, popup=False, params=None):
        if popup:
            title = os.path.basename(url)
        else:
            title = "Kam1n0"
        wx.Frame.__init__(self, parent=None, id=wx.ID_ANY, title=title)
        size = (800, 500)

        # icon
        #setup icon object
        #icon = wx.Icon(GetApplicationPath("www/img/favicon.ico"), wx.BITMAP_TYPE_ICO)

        #setup taskbar icon
        #tbicon = wx.TaskBarIcon()
        #tbicon.SetIcon(icon, "McGill Icon")
        loc = wx.IconLocation(GetApplicationPath("www/img/favicon.ico"), 0)
        self.SetIcon(wx.IconFromLocation(loc))

        # This is an optional code to enable High DPI support.
        if "auto_zooming" in g_applicationSettings \
                and g_applicationSettings["auto_zooming"] == "system_dpi":
            # This utility function will adjust width/height using
            # OS DPI settings. For 800/600 with Win7 DPI settings
            # being set to "Larger 150%" will return 1200/900.
            size = cefpython.DpiAware.CalculateWindowSize(size[0], size[1])

        self.SetSize(size)

        global gdata
        if gdata is None:
            gdata = GetData()

        gdp = json.loads(gdata)

        if not url:
            url = gdp['url']
            # Test hash in url.
            # url += "#test-hash"

        # self.CreateMenu()

        if TEST_EMBEDDING_IN_PANEL:
            print("Embedding in a wx.Panel!")
            # You also have to set the wx.WANTS_CHARS style for
            # all parent panels/controls, if it's deeply embedded.
            self.mainPanel = wx.Panel(self, style=wx.WANTS_CHARS)

        # Global client callbacks must be set before browser is created.
        self.clientHandler = ClientHandler()
        cefpython.SetGlobalClientCallback(
            "OnCertificateError", self.clientHandler._OnCertificateError)
        cefpython.SetGlobalClientCallback(
            "OnBeforePluginLoad", self.clientHandler._OnBeforePluginLoad)
        cefpython.SetGlobalClientCallback("OnAfterCreated",
                                          self.clientHandler._OnAfterCreated)

        windowInfo = cefpython.WindowInfo()
        windowInfo.SetAsChild(self.GetHandleForBrowser())
        self.browser = cefpython.CreateBrowserSync(
            windowInfo, browserSettings=g_browserSettings, navigateUrl=url)

        self.clientHandler.mainBrowser = self.browser
        self.browser.SetClientHandler(self.clientHandler)

        jsBindings = cefpython.JavascriptBindings(bindToFrames=False,
                                                  bindToPopups=True)

        self.javascriptExternal = JavascriptExternal(self.browser, gdata)
        jsBindings.SetObject("external", self.javascriptExternal)
        jsBindings.SetProperty("GData", gdata)
        if not params is None:
            jsBindings.SetProperty("params", params)
        self.browser.SetJavascriptBindings(jsBindings)

        if self.mainPanel:
            self.mainPanel.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
            self.mainPanel.Bind(wx.EVT_SIZE, self.OnSize)
        else:
            self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
            self.Bind(wx.EVT_SIZE, self.OnSize)

        self.Bind(wx.EVT_CLOSE, self.OnClose)
        if USE_EVT_IDLE and not popup:
            # Bind EVT_IDLE only for the main application frame.
            print("Using EVT_IDLE to execute the CEF message loop work")
            self.Bind(wx.EVT_IDLE, self.OnIdle)
示例#25
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()
示例#26
0
    def __init__(self,
                 parent,
                 title,
                 pos,
                 size,
                 style,
                 name,
                 url=None,
                 popup=True):

        wx.Frame.__init__(self,
                          parent=parent,
                          id=wx.ID_ANY,
                          title=title,
                          pos=pos,
                          size=size,
                          style=style,
                          name=name)
        size = (1000, 600)

        # This is an optional code to enable High DPI support.
        if "auto_zooming" in g_applicationSettings \
                and g_applicationSettings["auto_zooming"] == "system_dpi":
            # This utility function will adjust width/height using
            # OS DPI settings. For 800/600 with Win7 DPI settings
            # being set to "Larger 150%" will return 1200/900.
            size = cefpython.DpiAware.CalculateWindowSize(size[0], size[1])

        self.SetSize(size)
        self.panel = wx.Panel(self)
        self.panel.SetBackgroundColour(wx.WHITE)
        if not url:
            url = "file://" + GetApplicationPath("example2.html")
            # Test hash in url.
            # url += "#test-hash"

        #self.CreateMenu()

        if TEST_EMBEDDING_IN_PANEL:
            print("Embedding in a wx.Panel!")
            # You also have to set the wx.WANTS_CHARS style for
            # all parent panels/controls, if it's deeply embedded.
            self.mainPanel = wx.Panel(self.panel,
                                      size=(700, 635),
                                      pos=(600, 400))
        # Global client callbacks must be set before browser is created.
        self.clientHandler = ClientHandler()
        cefpython.SetGlobalClientCallback(
            "OnCertificateError", self.clientHandler._OnCertificateError)
        cefpython.SetGlobalClientCallback(
            "OnBeforePluginLoad", self.clientHandler._OnBeforePluginLoad)
        cefpython.SetGlobalClientCallback("OnAfterCreated",
                                          self.clientHandler._OnAfterCreated)

        windowInfo = cefpython.WindowInfo()
        windowInfo.SetAsChild(self.GetHandleForBrowser())
        self.browser = cefpython.CreateBrowserSync(
            windowInfo, browserSettings=g_browserSettings, navigateUrl=url)

        self.clientHandler.mainBrowser = self.browser
        self.browser.SetClientHandler(self.clientHandler)

        jsBindings = cefpython.JavascriptBindings(bindToFrames=True,
                                                  bindToPopups=True)
        jsBindings.SetFunction("PyPrint", PyPrint)
        jsBindings.SetProperty("pyProperty", "This was set in Python")
        jsBindings.SetProperty("pyConfig", [
            "This was set in Python", {
                "name": "Nested dictionary",
                "isNested": True
            }, [1, "2", None]
        ])
        self.javascriptExternal = JavascriptExternal(self.browser)
        jsBindings.SetObject("external", self.javascriptExternal)
        jsBindings.SetProperty("sources", GetSources())
        self.browser.SetJavascriptBindings(jsBindings)

        if self.mainPanel:
            self.mainPanel.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
            self.mainPanel.Bind(wx.EVT_SIZE, self.OnSize)
        else:
            self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
            self.Bind(wx.EVT_SIZE, self.OnSize)

        self.Bind(wx.EVT_CLOSE, self.OnClose)
        if USE_EVT_IDLE and not popup:
            # Bind EVT_IDLE only for the main application frame.
            print("Using EVT_IDLE to execute the CEF message loop work")
            self.Bind(wx.EVT_IDLE, self.OnIdle)
示例#27
0
    def __init__(self, url=None):
        wx.Frame.__init__(self, parent=None, id=wx.ID_ANY,
                title='wxPython CEF 3 example', size=(800,600))

        global g_countWindows
        g_countWindows += 1

        if not url:
            url = "file://"+GetApplicationPath("wxpython.html")
            # Test hash in url.
            # url += "#test-hash"

        self.CreateMenu()

        # Cannot attach browser to the main frame as this will cause
        # the menu not to work.
        # --
        # You also have to set the wx.WANTS_CHARS style for
        # all parent panels/controls, if it's deeply embedded.
        self.mainPanel = wx.Panel(self, style=wx.WANTS_CHARS)

        # Global client callbacks must be set before browser is created.
        self.clientHandler = ClientHandler()
        cefpython.SetGlobalClientCallback("OnCertificateError",
                self.clientHandler._OnCertificateError)
        cefpython.SetGlobalClientCallback("OnBeforePluginLoad",
                self.clientHandler._OnBeforePluginLoad)
        cefpython.SetGlobalClientCallback("OnAfterCreated",
                self.clientHandler._OnAfterCreated)

        windowInfo = cefpython.WindowInfo()
        (width, height) = self.mainPanel.GetClientSizeTuple()
        windowInfo.SetAsChild(self.mainPanel.GetHandle(),
                              [0, 0, width, height])
        # Linux requires adding "file://" for local files,
        # otherwise /home/some will be replaced as http://home/some
        self.browser = cefpython.CreateBrowserSync(
            windowInfo,
            # If there are problems with Flash you can disable it here,
            # by disabling all plugins.
            browserSettings=g_browserSettings,
            navigateUrl=url)

        self.clientHandler.mainBrowser = self.browser
        self.browser.SetClientHandler(self.clientHandler)

        jsBindings = cefpython.JavascriptBindings(
            bindToFrames=False, bindToPopups=True)
        jsBindings.SetFunction("PyPrint", PyPrint)
        jsBindings.SetProperty("pyProperty", "This was set in Python")
        jsBindings.SetProperty("pyConfig", ["This was set in Python",
                {"name": "Nested dictionary", "isNested": True},
                [1,"2", None]])
        self.javascriptExternal = JavascriptExternal(self.browser)
        jsBindings.SetObject("external", self.javascriptExternal)
        jsBindings.SetProperty("sources", GetSources())
        self.browser.SetJavascriptBindings(jsBindings)

        self.Bind(wx.EVT_CLOSE, self.OnClose)
        if USE_EVT_IDLE:
            # Bind EVT_IDLE only for the main application frame.
            self.Bind(wx.EVT_IDLE, self.OnIdle)
示例#28
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
示例#29
0
 def TransparentPopup(self):
     windowInfo = cefpython.WindowInfo()
     windowInfo.SetAsPopup(self.browser.GetWindowHandle(), "transparent")
     windowInfo.SetTransparentPainting(True)
     cefpython.CreateBrowserSync(windowInfo, browserSettings={},
             navigateUrl=GetApplicationPath("cefsimple.html"))
示例#30
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()