forked from cztomczak/cefpython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchromectrl.py
More file actions
420 lines (338 loc) · 15.2 KB
/
chromectrl.py
File metadata and controls
420 lines (338 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# Additional and wx specific layer of abstraction for the cefpython
# __author__ = "Greg Kacy <[email protected]>"
#-------------------------------------------------------------------------------
from cefpython3 import cefpython
import os, sys, platform
import wx
import wx.lib.buttons as buttons
#-------------------------------------------------------------------------------
# CEF Python application settings
g_settings = None
def Debug(msg):
if g_settings and "debug" in g_settings and g_settings["debug"]:
print("[chromectrl.py] "+msg)
#-------------------------------------------------------------------------------
# Default timer interval when timer used to service CEF message loop
DEFAULT_TIMER_MILLIS = 10
# A global timer for CEF message loop processing.
g_messageLoopTimer = None
def CreateMessageLoopTimer(timerMillis):
# This function gets called multiple times for each ChromeWindow
# instance.
global g_messageLoopTimer
Debug("CreateMesageLoopTimer")
if g_messageLoopTimer:
return
g_messageLoopTimer = wx.Timer()
g_messageLoopTimer.Start(timerMillis)
Debug("g_messageLoopTimer.GetId() = "\
+str(g_messageLoopTimer.GetId()))
wx.EVT_TIMER(g_messageLoopTimer, g_messageLoopTimer.GetId(),\
MessageLoopTimer)
def MessageLoopTimer(event):
cefpython.MessageLoopWork()
def DestroyMessageLoopTimer():
global g_messageLoopTimer
Debug("DestroyMessageLoopTimer")
if g_messageLoopTimer:
g_messageLoopTimer.Stop()
g_messageLoopTimer = None
else:
# There was no browser created during session.
Debug("DestroyMessageLoopTimer: timer not started")
#-------------------------------------------------------------------------------
class NavigationBar(wx.Panel):
def __init__(self, parent, *args, **kwargs):
wx.Panel.__init__(self, parent, *args, **kwargs)
self.bitmapDir = os.path.join(os.path.dirname(
os.path.abspath(__file__)), "images")
self._InitComponents()
self._LayoutComponents()
self._InitEventHandlers()
def _InitComponents(self):
self.backBtn = buttons.GenBitmapButton(self, -1,
wx.Bitmap(os.path.join(self.bitmapDir, "back.png"),
wx.BITMAP_TYPE_PNG), style=wx.BORDER_NONE)
self.forwardBtn = buttons.GenBitmapButton(self, -1,
wx.Bitmap(os.path.join(self.bitmapDir, "forward.png"),
wx.BITMAP_TYPE_PNG), style=wx.BORDER_NONE)
self.reloadBtn = buttons.GenBitmapButton(self, -1,
wx.Bitmap(os.path.join(self.bitmapDir, "reload_page.png"),
wx.BITMAP_TYPE_PNG), style=wx.BORDER_NONE)
self.url = wx.TextCtrl(self, id=-1, style=0)
self.historyPopup = wx.Menu()
def _LayoutComponents(self):
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(self.backBtn, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL|
wx.ALL, 0)
sizer.Add(self.forwardBtn, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL|
wx.ALL, 0)
sizer.Add(self.reloadBtn, 0, wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL|
wx.ALL, 0)
sizer.Add(self.url, 1, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 12)
self.SetSizer(sizer)
self.Fit()
def _InitEventHandlers(self):
self.backBtn.Bind(wx.EVT_CONTEXT_MENU, self.OnButtonContext)
def __del__(self):
self.historyPopup.Destroy()
def GetBackButton(self):
return self.backBtn
def GetForwardButton(self):
return self.forwardBtn
def GetReloadButton(self):
return self.reloadBtn
def GetUrlCtrl(self):
return self.url
def InitHistoryPopup(self):
self.historyPopup = wx.Menu()
def AddToHistory(self, url):
self.historyPopup.Append(-1, url)
def OnButtonContext(self, event):
self.PopupMenu(self.historyPopup)
class ChromeWindow(wx.Window):
"""
Standalone CEF component. The class provides facilites for interacting
with wx message loop
"""
def __init__(self, parent, url="", useTimer=True,
timerMillis=DEFAULT_TIMER_MILLIS, browserSettings=None,
size=(-1, -1), *args, **kwargs):
wx.Window.__init__(self, parent, id=wx.ID_ANY, size=size,
*args, **kwargs)
# This timer is not used anymore, but creating it for backwards
# compatibility. In one of external projects ChromeWindow.timer.Stop()
# is being called during browser destruction.
self.timer = wx.Timer()
# On Linux absolute file urls need to start with "file://"
# otherwise a path of "/home/some" is converted to "http://home/some".
if platform.system() in ["Linux", "Darwin"]:
if url.startswith("/"):
url = "file://" + url
self.url = url
windowInfo = cefpython.WindowInfo()
if platform.system() == "Windows":
windowInfo.SetAsChild(self.GetHandle())
elif platform.system() == "Linux":
windowInfo.SetAsChild(self.GetGtkWidget())
elif platform.system() == "Darwin":
(width, height) = self.GetClientSizeTuple()
windowInfo.SetAsChild(self.GetHandle(),
[0, 0, width, height])
else:
raise Exception("Unsupported OS")
if not browserSettings:
browserSettings = {}
# Disable plugins:
# | browserSettings["plugins_disabled"] = True
self.browser = cefpython.CreateBrowserSync(windowInfo,
browserSettings=browserSettings, navigateUrl=url)
if platform.system() == "Windows":
self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
self.Bind(wx.EVT_SIZE, self.OnSize)
self._useTimer = useTimer
if useTimer:
CreateMessageLoopTimer(timerMillis)
else:
# Currently multiple EVT_IDLE events might be registered
# when creating multiple ChromeWindow instances. This will
# result in calling CEF message loop work multiple times
# simultaneously causing performance penalties and possibly
# some unwanted behavior (CEF Python Issue 129).
Debug("WARNING: Using EVT_IDLE for CEF message loop processing"\
" is not recommended")
self.Bind(wx.EVT_IDLE, self.OnIdle)
self.Bind(wx.EVT_CLOSE, self.OnClose)
def OnClose(self, event):
if not self._useTimer:
try:
self.Unbind(wx.EVT_IDLE)
except:
# Calling Unbind() may cause problems on Windows 8:
# https://groups.google.com/d/topic/cefpython/iXE7e1ekArI/discussion
# (it was causing problems in __del__, this might not
# be true anymore in OnClose, but still let's make sure)
pass
self.browser.ParentWindowWillClose()
def OnIdle(self, event):
"""Service CEF message loop when useTimer is False"""
cefpython.MessageLoopWork()
event.Skip()
def OnSetFocus(self, event):
"""OS_WIN only."""
cefpython.WindowUtils.OnSetFocus(self.GetHandle(), 0, 0, 0)
event.Skip()
def OnSize(self, event):
"""OS_WIN only. Handle the the size event"""
cefpython.WindowUtils.OnSize(self.GetHandle(), 0, 0, 0)
event.Skip()
def GetBrowser(self):
"""Returns the CEF's browser object"""
return self.browser
def LoadUrl(self, url, onLoadStart=None, onLoadEnd=None):
if onLoadStart or onLoadEnd:
self.GetBrowser().SetClientHandler(
CallbackClientHandler(onLoadStart, onLoadEnd))
browser = self.GetBrowser()
if cefpython.g_debug:
Debug("LoadUrl() self: %s" % self)
Debug("browser: %s" % browser)
Debug("browser id: %s" % browser.GetIdentifier())
Debug("mainframe: %s" % browser.GetMainFrame())
Debug("mainframe id: %s" % \
browser.GetMainFrame().GetIdentifier())
self.GetBrowser().GetMainFrame().LoadUrl(url)
#wx.CallLater(100, browser.ReloadIgnoreCache)
#wx.CallLater(200, browser.GetMainFrame().LoadUrl, url)
class ChromeCtrl(wx.Panel):
def __init__(self, parent, url="", useTimer=True,
timerMillis=DEFAULT_TIMER_MILLIS,
browserSettings=None, hasNavBar=True,
*args, **kwargs):
# You also have to set the wx.WANTS_CHARS style for
# all parent panels/controls, if it's deeply embedded.
wx.Panel.__init__(self, parent, style=wx.WANTS_CHARS, *args, **kwargs)
self.chromeWindow = ChromeWindow(self, url=str(url), useTimer=useTimer,
browserSettings=browserSettings)
sizer = wx.BoxSizer(wx.VERTICAL)
self.navigationBar = None
if hasNavBar:
self.navigationBar = self.CreateNavigationBar()
sizer.Add(self.navigationBar, 0, wx.EXPAND|wx.ALL, 0)
self._InitEventHandlers()
sizer.Add(self.chromeWindow, 1, wx.EXPAND, 0)
self.SetSizer(sizer)
self.Fit()
ch = DefaultClientHandler(self)
self.SetClientHandler(ch)
if self.navigationBar:
self.UpdateButtonsState()
def _InitEventHandlers(self):
self.navigationBar.backBtn.Bind(wx.EVT_BUTTON, self.OnLeft)
self.navigationBar.forwardBtn.Bind(wx.EVT_BUTTON, self.OnRight)
self.navigationBar.reloadBtn.Bind(wx.EVT_BUTTON, self.OnReload)
def GetNavigationBar(self):
return self.navigationBar
def SetNavigationBar(self, navigationBar):
sizer = self.GetSizer()
if self.navigationBar:
# remove previous one
sizer.Replace(self.navigationBar, navigationBar)
self.navigationBar.Hide()
del self.navigationBar
else:
sizer.Insert(0, navigationBar, 0, wx.EXPAND)
self.navigationBar = navigationBar
sizer.Fit(self)
def CreateNavigationBar(self):
np = NavigationBar(self)
return np
def SetClientHandler(self, handler):
self.chromeWindow.GetBrowser().SetClientHandler(handler)
def OnLeft(self, event):
if self.chromeWindow.GetBrowser().CanGoBack():
self.chromeWindow.GetBrowser().GoBack()
self.UpdateButtonsState()
self.chromeWindow.GetBrowser().SetFocus(True)
def OnRight(self, event):
if self.chromeWindow.GetBrowser().CanGoForward():
self.chromeWindow.GetBrowser().GoForward()
self.UpdateButtonsState()
self.chromeWindow.GetBrowser().SetFocus(True)
def OnReload(self, event):
self.chromeWindow.GetBrowser().Reload()
self.UpdateButtonsState()
self.chromeWindow.GetBrowser().SetFocus(True)
def UpdateButtonsState(self):
self.navigationBar.backBtn.Enable(
self.chromeWindow.GetBrowser().CanGoBack())
self.navigationBar.forwardBtn.Enable(
self.chromeWindow.GetBrowser().CanGoForward())
def OnLoadStart(self, browser, frame):
if self.navigationBar:
self.UpdateButtonsState()
self.navigationBar.GetUrlCtrl().SetValue(
browser.GetMainFrame().GetUrl())
self.navigationBar.AddToHistory(browser.GetMainFrame().GetUrl())
def OnLoadEnd(self, browser, frame, httpStatusCode):
if self.navigationBar:
# In CEF 3 the CanGoBack() and CanGoForward() methods
# sometimes do work, sometimes do not, when called from
# the OnLoadStart event. That's why we're calling it again
# here. This is still not perfect as OnLoadEnd() is not
# guaranteed to get called for all types of pages. See the
# cefpython documentation:
# https://code.google.com/p/cefpython/wiki/LoadHandler
# OnDomReady() would be perfect, but is still not implemented.
# Another option is to implement our own browser state
# using the OnLoadStart and OnLoadEnd callbacks.
self.UpdateButtonsState()
class DefaultClientHandler(object):
def __init__(self, parentCtrl):
self.parentCtrl = parentCtrl
def OnLoadStart(self, browser, frame):
self.parentCtrl.OnLoadStart(browser, frame)
def OnLoadEnd(self, browser, frame, httpStatusCode):
self.parentCtrl.OnLoadEnd(browser, frame, httpStatusCode)
def OnLoadError(self, browser, frame, errorCode, errorText, failedUrl):
# TODO
Debug("ERROR LOADING URL : %s" % failedUrl)
class CallbackClientHandler(object):
def __init__(self, onLoadStart=None, onLoadEnd=None):
self._onLoadStart = onLoadStart
self._onLoadEnd = onLoadEnd
def OnLoadStart(self, browser, frame):
if self._onLoadStart and frame.GetUrl() != "about:blank":
self._onLoadStart(browser, frame)
def OnLoadEnd(self, browser, frame, httpStatusCode):
if self._onLoadEnd and frame.GetUrl() != "about:blank":
self._onLoadEnd(browser, frame, httpStatusCode)
def OnLoadError(self, browser, frame, errorCode, errorText, failedUrl):
# TODO
Debug("ERROR LOADING URL : %s, %s" % (failedUrl, frame.GetUrl()))
#-------------------------------------------------------------------------------
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 Shutdown():
"""Shuts down CEF, should be called by app exiting code"""
DestroyMessageLoopTimer()
cefpython.Shutdown()