Files
pywebview/webview/platforms/cef.py
Roman 0698b059db pywebview 3.0 (#340)
* Update change_url.md

* Update api.md

* Update installation.md

* Add Google Analytics

* Fix installation

* 2.4 info

* [Docs] add information about window.pywebview availability

* Update debuggig info about QTWebEngine

* [Docs] Add information about app architecture

* Update cef.md

* [CEF] Fix JS logic not persisting after navigating to another page

* #169 Frameless window (#313)

* Merge PR #177: [Cocoa] Implement frameless windows

* [All] Add skeleton for `frameless` parameter
* [Cocoa] Add `frameless` kwarg to remove the window frame.
  - Implement a DragBar class to enable dragging the webview
  - Make the drag bar stick to the top and autoresize to the width
    of the view.

* [WinForms] Implement frameless window + easy drag

* Merge PR #177: [Cocoa] Implement frameless windows

* [All] Add skeleton for `frameless` parameter
* [Cocoa] Add `frameless` kwarg to remove the window frame.
  - Implement a DragBar class to enable dragging the webview
  - Make the drag bar stick to the top and autoresize to the width
    of the view.

* [WinForms] Implement frameless window + easy drag

* [GTK] partial implementation of frameless window

* [QT] Partial implementation of frameless window

* [QT] implement easy drag

* [Cocoa] Hide standard buttons and make the entire window draggable

* [GTK] implement easy move

* Add frameless tests

* Remove unused parameter

* [Cocoa] Implement free drag

* Revert WebBrowserInterops

* Code cleanup

* Update interop DLLs

* Fix interop dll

* Update docs; Fix tests

* Add example

* Update examples

* [CEF]: Implement support for pyinstaller one-file mode

* [CEF] Fix typo

* [All] Change api_call timeout to 15 seconds

* Update setup.py

* [QT] Simplify QT installation

* New API
Cocoa implementation
Revamped tests and examples

* Fix web engine force setting

* Rename destroy_window to destroy

* Update documentation

* Add documentation for 2.4

* Refactor project structure

* [GTK] New API support

* Rename confirm_quit to confirm_close
Split lifecycle events to shown and loaded

* [GTK] Implement new API
Fix tests

* [QT] New API implementation

* Remove multiprocessing

* [Windows/CEF] New API implementation

* Implement CSRF token
[All] Implement get_element

* Update Flask app example

* Rename get_element to get_elements. Bug fixes.

* [GTK] Implement propert JS-Python bridge for WebKit2 >2.2

* Update documentation

* [Windows/CEF] New API implementation

* Add token test

* [Winforms] Fix js api initialization

* [Cocoa] Fix events

* Debug: print webkit version

* [GTK] Check for old webkit

* [GTK] Fix event issues

* Catch notimlementederror in tests

* Update travis conf with qt from pip

* Update .travis.yml

* Update .travis.yml

* Update .travis.yml

* Update .travis.yml

* Update .travis.yml

* [Windows] Preliminary implementation of EdgeHTML based on PR from @HeavenVolkoff

* [docs] Add information about EdgeHTML

* EdgeHTML WIP

* Remove windows.web import

* EdgeHTML improvements. Fix MSHTML evaluate_js

* [Docs] Add information about renderer limitations

* [EdgeHTML] Fix bugs and tests

* Remove window from windows list after it is destroyed

* Fix window object deletion after window is closed via GUI

* [Docs] Add information about renderer codes

* Refactor and fix JS API
Remove multiprocessing example
[MSHTML] Add console.log debug support

* [Travis] Change conf

* [WinForms] Fix fullscreen

* Fix dll installation

* [Windows] Fix DLL bundling

* Update changelog

* [CEF]: Fix JS API

* Update changelog

* Built-in HTTP server implementation

* Add http server test

* Add http server testcd

* Add http server testcd

* [EdgeHTML] allow localhost urls

* Add video example

* Bug fixing

* [Cocoa] Remove media prefs

* Update .travis.yml

* Update .travis.yml

* Update .travis.yml

* [Travis] Disable QT 5.12 builds

* Update html_load.md
2019-07-07 13:33:37 +03:00

265 lines
6.4 KiB
Python

import json
import logging
import os
import shutil
import sys
import webbrowser
from functools import wraps
from uuid import uuid1
from threading import Event
from cefpython3 import cefpython as cef
from copy import copy
from webview.js.css import disable_text_select
from webview.js import dom
from webview import _debug
from webview.util import parse_api_js, default_html, js_bridge_call
sys.excepthook = cef.ExceptHook
instances = {}
logger = logging.getLogger(__name__)
class JSBridge:
def __init__(self, window, eval_events):
self.results = {}
self.window = window
self.eval_events = eval_events
def return_result(self, result, uid):
self.results[uid] = json.loads(result) if result else None
self.eval_events[uid].set()
def call(self, func_name, param):
js_bridge_call(self.window, func_name, param)
class Browser:
def __init__(self, window, handle, browser):
self.handle = handle
self.browser = browser
self.js_api = window.js_api
self.text_select = window.text_select
self.uid = window.uid
self.loaded = window.loaded
self.shown = window.shown
self.eval_events = {}
self.js_bridge = JSBridge(window, self.eval_events)
self.initialized = False
def initialize(self):
if self.initialized:
return
self.browser.GetJavascriptBindings().Rebind()
self.browser.ExecuteJavascript(parse_api_js(self.js_api, 'cef'))
if not self.text_select:
self.browser.ExecuteJavascript(disable_text_select)
self.browser.ExecuteJavascript(dom.src)
self.initialized = True
self.loaded.set()
def close(self):
self.browser.CloseBrowser(True)
def evaluate_js(self, code):
self.loaded.wait()
eval_script = """
try {{
window.external.return_result({0}, '{1}');
}} catch(e) {{
console.error(e.stack);
window.external.return_result(null, '{1}');
}}
"""
id_ = uuid1().hex[:8]
self.eval_events[id_] = Event()
self.browser.ExecuteJavascript(eval_script.format(code, id_))
self.eval_events[id_].wait() # result is obtained via JSBridge.return_result
result = copy(self.js_bridge.results[id_])
del self.eval_events[id_]
del self.js_bridge.results[id_]
return result
def get_current_url(self):
self.loaded.wait()
return self.browser.GetUrl()
def load_url(self, url):
self.initialized = False
self.loaded.clear()
self.browser.LoadUrl(url)
def load_html(self, html):
self.initialized = False
self.loaded.clear()
self.browser.LoadUrl('data:text/html,{0}'.format(html))
def find_instance(browser):
for instance in instances.values():
if instance.browser is browser:
return instance
return None
class LoadHandler(object):
def OnBeforePopup(self, **args):
url = args['target_url']
user_gesture = args['user_gesture']
if user_gesture:
webbrowser.open(url)
return True
def OnLoadingStateChange(self, browser, is_loading, **_):
instance = find_instance(browser)
if instance is not None:
if is_loading:
instance.initialized = False
else:
instance.initialize()
else:
logger.debug('CEF instance is not found %s ' % browser)
def _cef_call(func):
@wraps(func)
def wrapper(*args, **kwargs):
uid = args[-1]
if uid not in instances:
raise Exception('CEF window with uid {0} does not exist'.format(uid))
return func(*args, **kwargs)
return wrapper
def init(window):
global _initialized
if not _initialized:
settings = {
'multi_threaded_message_loop': True,
'context_menu': {
'enabled': _debug
}
}
if not _debug:
settings['remote_debugging_port'] = -1
try: # set paths under Pyinstaller's one file mode
settings.update({
'resources_dir_path': sys._MEIPASS,
'locales_dir_path': os.path.join(sys._MEIPASS, 'locales'),
'browser_subprocess_path': os.path.join(sys._MEIPASS, 'subprocess.exe'),
})
except Exception:
pass
cef.Initialize(settings=settings)
cef.DpiAware.EnableHighDpiSupport()
_initialized = True
def create_browser(window, handle, alert_func):
def _create():
real_url = 'data:text/html,{0}'.format(window.html) if window.html else window.url or 'data:text/html,{0}'.format(default_html)
cef_browser = cef.CreateBrowserSync(window_info=window_info, url=real_url)
browser = Browser(window, handle, cef_browser)
bindings = cef.JavascriptBindings()
bindings.SetObject('external', browser.js_bridge)
bindings.SetFunction('alert', alert_func)
cef_browser.SetJavascriptBindings(bindings)
cef_browser.SetClientHandler(LoadHandler())
instances[window.uid] = browser
window.shown.set()
window_info = cef.WindowInfo()
window_info.SetAsChild(handle)
cef.PostTask(cef.TID_UI, _create)
@_cef_call
def load_html(html, uid):
instance = instances[uid]
instance.load_html(html)
@_cef_call
def load_url(url, uid):
instance = instances[uid]
instance.load_url(url)
@_cef_call
def evaluate_js(code, uid):
instance = instances[uid]
return instance.evaluate_js(code)
@_cef_call
def get_current_url(uid):
instance = instances[uid]
url = instance.get_current_url()
if url.startswith('data:text/html,'):
return None
else:
return url
@_cef_call
def resize(width, height, uid):
hwnd = instances[uid].handle
lparam = width << 16 & height
cef.WindowUtils.OnSize(hwnd, 5, 0, lparam)
@_cef_call
def close_window(uid):
instance = instances[uid]
instance.close()
del instances[uid]
def shutdown():
try:
if os.path.exists('blob_storage'):
shutil.rmtree('blob_storage')
if os.path.exists('webrtc_event_logs'):
shutil.rmtree('webrtc_event_logs')
if os.path.exists('error.log'):
os.remove('error.log')
except Exception as e:
logger.debug(e, exc_info=True)
cef.Shutdown()
_initialized = False