Debian Codegraph @

tests/android/webview/platforms/cef.py

raw
1 import json
2 import logging
3 import os
4 import shutil
5 import sys
6 import webbrowser
7 from copy import copy
8 from ctypes import windll
9 from functools import wraps
10 from threading import Event
11 from time import sleep
12
13 from cefpython3 import cefpython as cef
14
15 from webview import _state, settings
16 from webview.util import DEFAULT_HTML, create_cookie, inject_pywebview, js_bridge_call
17
18 sys.excepthook = cef.ExceptHook
19 instances = {}
20
21 logger = logging.getLogger(__name__)
22
23 browser_settings = {}
24 command_line_switches = {}
25 renderer = 'cef'
26
27
28 def _set_dpi_mode(enabled):
29 """ """
30 import winreg # Python 3
31
32 try:
33 dpi_support = winreg.OpenKey(
34 winreg.HKEY_CURRENT_USER,
35 r'Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers',
36 0,
37 winreg.KEY_ALL_ACCESS,
38 )
39 except OSError:
40 dpi_support = winreg.CreateKeyEx(
41 winreg.HKEY_CURRENT_USER,
42 r'Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers',
43 0,
44 winreg.KEY_ALL_ACCESS,
45 )
46
47 try:
48 subprocess_path = os.path.join(sys._MEIPASS, 'subprocess.exe')
49 except Exception:
50 subprocess_path = os.path.join(os.path.dirname(cef.__file__), 'subprocess.exe')
51
52 if enabled:
53 winreg.SetValueEx(dpi_support, subprocess_path, 0, winreg.REG_SZ, '~HIGHDPIAWARE')
54 else:
55 winreg.DeleteValue(dpi_support, subprocess_path)
56
57 winreg.CloseKey(dpi_support)
58
59
60 class JSBridge:
61 def __init__(self, window, eval_events):
62 self.results = {}
63 self.window = window
64 self.eval_events = eval_events
65
66 def return_result(self, result, uid):
67 self.results[uid] = json.loads(result) if result else None
68 self.eval_events[uid].set()
69
70 def call(self, func_name, param, value_id):
71 js_bridge_call(self.window, func_name, json.loads(param), value_id)
72
73
74 class CookieVisitor:
75 def Visit(self, cookie, count, total, delete_cookie_out):
76 data = {
77 'name': cookie.GetName(),
78 'value': cookie.GetValue(),
79 'path': cookie.GetPath(),
80 'domain': cookie.GetDomain(),
81 'expires': cookie.GetExpires().strftime('%a, %d %b %Y %H:%M:%S GMT'),
82 'secure': cookie.GetSecure(),
83 'httponly': cookie.GetHttpOnly(),
84 }
85
86 cookie = create_cookie(data)
87 self.cookies.append(cookie)
88
89 if count + 1 == total:
90 self.lock.set()
91
92 return True
93
94
95 class Browser:
96 def __init__(self, window, handle, browser, parent):
97 self.window = window
98 self.handle = handle
99 self.browser = browser
100 self.parent = parent
101 self.uid = window.uid
102 self.loaded = window.events.loaded
103 self.shown = window.events.shown
104 self.inner_hwnd = self.browser.GetWindowHandle()
105 self.eval_events = {}
106 self.js_bridge = JSBridge(window, self.eval_events)
107 self.initialized = False
108
109 def initialize(self):
110 if self.initialized:
111 return
112
113 self.cookie_manager = cef.CookieManager.GetGlobalManager()
114 self.cookie_visitor = CookieVisitor()
115
116 self.browser.GetJavascriptBindings().Rebind()
117 inject_pywebview('cef', self.window)
118
119 sleep(0.1) # wait for window.pywebview to load
120 self.initialized = True
121
122 def close(self):
123 self.browser.CloseBrowser(True)
124
125 def resize(self, width, height):
126 screen = self.parent.RectangleToScreen(self.parent.ClientRectangle)
127 height_diff = screen.Top - self.parent.Top + 12
128 width_diff = self.parent.Right - screen.Right + 12
129
130 windll.user32.SetWindowPos(
131 self.inner_hwnd,
132 0,
133 0,
134 0,
135 width - width_diff,
136 height - height_diff,
137 0x0002 | 0x0004 | 0x0010,
138 )
139 self.browser.NotifyMoveOrResizeStarted()
140
141 def evaluate_js(self, code, unique_id, parse_json):
142 self.eval_events[unique_id] = Event()
143
144 if unique_id:
145 eval_script = f"""
146 try {{
147 {code}
148 }} catch(e) {{
149 window.external.return_result(null, '{unique_id}');
150 }}
151 """
152
153 self.browser.ExecuteJavascript(eval_script)
154 self.eval_events[unique_id].wait() # result is obtained via JSBridge.return_result
155
156 result = copy(self.js_bridge.results[unique_id])
157
158 del self.eval_events[unique_id]
159 del self.js_bridge.results[unique_id]
160
161 return result
162 else:
163 self.browser.ExecuteJavascript(code)
164 return None
165
166 def clear_cookies(self):
167 self.cookie_manager.DeleteCookies('', '')
168 self.cookie_manager.FlushStore()
169
170 def get_cookies(self):
171 self.cookie_visitor.cookies = []
172 self.cookie_visitor.lock = Event()
173 self.cookie_manager.VisitUrlCookies(self.browser.GetUrl(), True, self.cookie_visitor)
174 self.cookie_visitor.lock.wait()
175
176 return self.cookie_visitor.cookies
177
178 def get_current_url(self):
179 return self.browser.GetUrl()
180
181 def load_url(self, url):
182 self.initialized = False
183 self.browser.LoadUrl(url)
184
185 def load_html(self, html):
186 self.initialized = False
187 self.browser.LoadUrl(f'data:text/html,{html}')
188
189 def focus(self):
190 self.browser.SendFocusEvent(True)
191
192
193 def find_instance(browser):
194 for instance in instances.values():
195 if instance.browser is browser:
196 return instance
197
198 return None
199
200
201 class LoadHandler:
202 def OnBeforePopup(self, **args):
203 url = args['target_url']
204 user_gesture = args['user_gesture']
205
206 if user_gesture:
207 webbrowser.open(url)
208
209 return True
210
211 def OnLoadingStateChange(self, browser, is_loading, **_):
212 instance = find_instance(browser)
213
214 if instance is not None:
215 if is_loading:
216 instance.initialized = False
217 else:
218 instance.initialize()
219 else:
220 logger.debug(f'CEF instance is not found {browser}')
221
222
223 def _cef_call(func):
224 @wraps(func)
225 def wrapper(*args, **kwargs):
226 uid = args[-1]
227
228 if uid not in instances:
229 logger.error(f'CEF window with uid {uid} does not exist with {func}')
230 return
231
232 return func(*args, **kwargs)
233
234 return wrapper
235
236
237 def init(_, cache_dir):
238 global _initialized
239
240 if not _initialized:
241 if sys.platform == 'win32':
242 _set_dpi_mode(True)
243
244 default_settings = {
245 'multi_threaded_message_loop': True,
246 'context_menu': {'enabled': _state['debug']},
247 }
248
249 default_command_line_switches = {
250 'enable-media-stream': '',
251 }
252
253 if not _state['debug']:
254 default_settings['remote_debugging_port'] = -1
255
256 if _state['user_agent']:
257 default_settings['user_agent'] = _state['user_agent']
258
259 if cache_dir:
260 default_settings['cache_path'] = cache_dir
261
262 if settings['ALLOW_FILE_URLS']:
263 default_command_line_switches['allow-file-access-from-files'] = ''
264
265 if settings['IGNORE_SSL_ERRORS']:
266 default_command_line_switches['ignore-certificate-errors'] = ''
267
268 resource_root = getattr(sys, '_MEIPASS', os.path.dirname(cef.__file__))
269
270 default_settings.update(
271 {
272 'resources_dir_path': resource_root,
273 'locales_dir_path': os.path.join(resource_root, 'locales'),
274 'browser_subprocess_path': os.path.join(resource_root, 'subprocess.exe'),
275 }
276 )
277
278 all_settings = dict(default_settings, **browser_settings)
279 all_command_line_switches = dict(default_command_line_switches, **command_line_switches)
280 cef.Initialize(settings=all_settings, commandLineSwitches=all_command_line_switches)
281 cef.DpiAware.EnableHighDpiSupport()
282
283 _initialized = True
284
285
286 def create_browser(window, handle, alert_func, parent):
287 def _create():
288 real_url = (
289 f'data:text/html,{window.html}'
290 if window.html
291 else window.real_url or f'data:text/html,{DEFAULT_HTML}'
292 )
293
294 default_browser_settings = {}
295 all_browser_settings = dict(default_browser_settings, **browser_settings)
296
297 cef_browser = cef.CreateBrowserSync(
298 window_info=window_info, settings=all_browser_settings, url=real_url
299 )
300 browser = Browser(window, handle, cef_browser, parent)
301
302 bindings = cef.JavascriptBindings()
303 bindings.SetObject('external', browser.js_bridge)
304 bindings.SetFunction('alert', alert_func)
305
306 cef_browser.SetJavascriptBindings(bindings)
307 cef_browser.SetClientHandler(LoadHandler())
308 instances[window.uid] = browser
309 cef_browser.SendFocusEvent(True)
310 window.events.shown.set()
311 cef_browser.SendFocusEvent(True)
312
313 if _state['debug'] and settings['OPEN_DEVTOOLS_IN_DEBUG']:
314 cef_browser.ShowDevTools()
315
316 window_info = cef.WindowInfo()
317 window_info.SetAsChild(handle)
318 cef.PostTask(cef.TID_UI, _create)
319
320
321 @_cef_call
322 def focus(uid):
323 instance = instances[uid]
324 instance.focus()
325
326
327 @_cef_call
328 def load_html(html, uid):
329 instance = instances[uid]
330 instance.load_html(html)
331
332
333 @_cef_call
334 def load_url(url, uid):
335 instance = instances[uid]
336 instance.load_url(url)
337
338
339 @_cef_call
340 def evaluate_js(code, unique_id, parse_json, uid):
341 instance = instances[uid]
342 return instance.evaluate_js(code, unique_id, parse_json)
343
344
345 @_cef_call
346 def clear_cookies(uid):
347 instance = instances[uid]
348 return instance.clear_cookies()
349
350
351 @_cef_call
352 def get_cookies(uid):
353 instance = instances[uid]
354 return instance.get_cookies()
355
356
357 @_cef_call
358 def get_current_url(uid):
359 instance = instances[uid]
360 url = instance.get_current_url()
361
362 if url.startswith('data:text/html,'):
363 return None
364 else:
365 return url
366
367
368 @_cef_call
369 def resize(width, height, uid):
370 instance = instances[uid]
371 instance.resize(width, height)
372
373
374 @_cef_call
375 def close_window(uid):
376 instance = instances[uid]
377 instance.close()
378 del instances[uid]
379
380
381 def shutdown():
382 try:
383 if os.path.exists('blob_storage'):
384 shutil.rmtree('blob_storage')
385
386 if os.path.exists('webrtc_event_logs'):
387 shutil.rmtree('webrtc_event_logs')
388
389 if os.path.exists('error.log') and not _state['debug']:
390 os.remove('error.log')
391
392 if sys.platform == 'win32':
393 _set_dpi_mode(False)
394
395 except Exception as e:
396 logger.debug(e, exc_info=True)
397
398 cef.Shutdown()
399
400
401 _initialized = False