Skip to content

Commit

Permalink
Refactor and expose webview via native
Browse files Browse the repository at this point in the history
  • Loading branch information
r0x0r committed Oct 15, 2024
1 parent 1e72206 commit 550d5a1
Show file tree
Hide file tree
Showing 6 changed files with 107 additions and 105 deletions.
2 changes: 1 addition & 1 deletion webview/platforms/android.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,6 @@ def __init__(self, window, **kwargs):
self.dialog = None
super(BrowserView, self).__init__(**kwargs)
self.window.native = self
self.window.events.before_show.set()
Clock.schedule_once(lambda dt: run_ui_thread(self.create_webview), 0)

def create_webview(self, *args):
Expand Down Expand Up @@ -178,6 +177,7 @@ def webview_callback(event, data):
self.webview.setDownloadListener(DownloadListener())

self.webview.setOnKeyListener(KeyListener(self._back_pressed))
self.window.events.before_show.set()

if self.window.real_url:
self.webview.loadUrl(self.window.real_url)
Expand Down
42 changes: 21 additions & 21 deletions webview/platforms/cocoa.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,14 +93,14 @@ def windowWillClose_(self, notification):
if i.pywebview_window in windows:
windows.remove(i.pywebview_window)

i.webkit.setNavigationDelegate_(None)
i.webkit.setUIDelegate_(None)
i.webview.setNavigationDelegate_(None)
i.webview.setUIDelegate_(None)

# this seems to be a bug in WkWebView, so we need to load blank html
# see https://stackoverflow.com/questions/27410413/wkwebview-embed-video-keeps-playing-sound-after-release
i.webkit.loadHTMLString_baseURL_('', None)
i.webkit.removeFromSuperview()
i.webkit = None
i.webview.loadHTMLString_baseURL_('', None)
i.webview.removeFromSuperview()
i.webview = None

i.closed.set()
if BrowserView.instances == {}:
Expand Down Expand Up @@ -302,14 +302,14 @@ def webView_didFinishNavigation_(self, webview, nav):
i.window.makeFirstResponder_(webview)

script = inject_pywebview(i.js_bridge.window, 'cocoa')
i.webkit.evaluateJavaScript_completionHandler_(script, lambda a, b: None)
i.webview.evaluateJavaScript_completionHandler_(script, lambda a, b: None)
i.loaded.set()

# Handle JavaScript window.print()
def userContentController_didReceiveScriptMessage_(self, controller, message):
if message.body() == 'print':
i = BrowserView.get_instance('_browserDelegate', self)
BrowserView.print_webview(i.webkit)
BrowserView.print_webview(i.webview)

class FileFilterChooser(AppKit.NSPopUpButton):
def initWithFilter_(self, file_filter):
Expand Down Expand Up @@ -501,19 +501,19 @@ def __init__(self, window):
frame.size.height = window.initial_height
self.window.setFrame_display_(frame, True)

self.webkit = BrowserView.WebKitHost.alloc().initWithFrame_(rect).retain()
self.webkit.pywebview_window = window
self.webview = BrowserView.WebKitHost.alloc().initWithFrame_(rect).retain()
self.webview.pywebview_window = window

self._browserDelegate = BrowserView.BrowserDelegate.alloc().init().retain()
self._windowDelegate = BrowserView.WindowDelegate.alloc().init().retain()
self._appDelegate = BrowserView.AppDelegate.alloc().init().retain()

BrowserView.app.setDelegate_(self._appDelegate)
self.webkit.setUIDelegate_(self._browserDelegate)
self.webkit.setNavigationDelegate_(self._browserDelegate)
self.webview.setUIDelegate_(self._browserDelegate)
self.webview.setNavigationDelegate_(self._browserDelegate)
self.window.setDelegate_(self._windowDelegate)

config = self.webkit.configuration()
config = self.webview.configuration()
config.userContentController().addScriptMessageHandler_name_(
self._browserDelegate, 'browserDelegate'
)
Expand Down Expand Up @@ -550,7 +550,7 @@ def dummy_completion_handler():

user_agent = webview_settings.get('user_agent') or _settings['user_agent']
if user_agent:
self.webkit.setCustomUserAgent_(user_agent)
self.webview.setCustomUserAgent_(user_agent)

self.window.setFrameOrigin_(self.screen.origin)

Expand All @@ -565,7 +565,7 @@ def dummy_completion_handler():
self.window.setBackgroundColor_(
BrowserView.nscolor_from_hex(window.background_color, 0)
)
self.webkit.setValue_forKey_(True, 'drawsTransparentBackground')
self.webview.setValue_forKey_(True, 'drawsTransparentBackground')
else:
self.window.setBackgroundColor_(BrowserView.nscolor_from_hex(window.background_color))

Expand All @@ -579,8 +579,8 @@ def dummy_completion_handler():
visualEffectView.setFrame_(frame_vibrancy)
visualEffectView.setState_(AppKit.NSVisualEffectStateActive)
visualEffectView.setBlendingMode_(AppKit.NSVisualEffectBlendingModeBehindWindow)
self.webkit.addSubview_positioned_relativeTo_(
visualEffectView, AppKit.NSWindowBelow, self.webkit
self.webview.addSubview_positioned_relativeTo_(
visualEffectView, AppKit.NSWindowBelow, self.webview
)

self.frameless = window.frameless
Expand All @@ -605,7 +605,7 @@ def dummy_completion_handler():
self.pywebview_window.events.before_show.set()

try:
self.webkit.evaluateJavaScript_completionHandler_('', lambda a, b: None)
self.webview.evaluateJavaScript_completionHandler_('', lambda a, b: None)
except TypeError:
registerMetaDataForSelector(
b'WKWebView', b'evaluateJavaScript:completionHandler:', _eval_js_metadata
Expand Down Expand Up @@ -765,7 +765,7 @@ def handler(cookies):

def get_current_url(self):
def get():
self._current_url = str(self.webkit.URL())
self._current_url = str(self.webview.URL())
self._current_url_semaphore.release()

AppHelper.callAfter(get)
Expand All @@ -777,7 +777,7 @@ def load_url(self, url):
def load(url):
page_url = Foundation.NSURL.URLWithString_(BrowserView.quote(url))
req = Foundation.NSURLRequest.requestWithURL_(page_url)
self.webkit.loadRequest_(req)
self.webview.loadRequest_(req)

self.loaded.clear()
self.url = url
Expand All @@ -786,14 +786,14 @@ def load(url):
def load_html(self, content, base_uri):
def load(content, url):
url = Foundation.NSURL.URLWithString_(BrowserView.quote(url))
self.webkit.loadHTMLString_baseURL_(content, url)
self.webview.loadHTMLString_baseURL_(content, url)

self.loaded.clear()
AppHelper.callAfter(load, content, base_uri)

def evaluate_js(self, script):
def eval():
self.webkit.evaluateJavaScript_completionHandler_(script, handler)
self.webview.evaluateJavaScript_completionHandler_(script, handler)

def handler(result, error):
JSResult.result = None if result is None else json.loads(result)
Expand Down
46 changes: 23 additions & 23 deletions webview/platforms/edgechromium.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
class EdgeChrome:
def __init__(self, form, window, cache_dir):
self.pywebview_window = window
self.web_view = WebView2()
self.webview = WebView2()
props = CoreWebView2CreationProperties()
props.UserDataFolder = cache_dir
props.set_IsInPrivateModeEnabled(_settings['private_mode'])
Expand All @@ -47,24 +47,24 @@ def __init__(self, form, window, cache_dir):
if webview_settings['ALLOW_FILE_URLS']:
props.AdditionalBrowserArguments += ' --allow-file-access-from-files'

self.web_view.CreationProperties = props
self.webview.CreationProperties = props

self.form = form
form.Controls.Add(self.web_view)
form.Controls.Add(self.webview)

self.js_results = {}
self.js_result_semaphore = Semaphore(0)
self.web_view.Dock = WinForms.DockStyle.Fill
self.web_view.BringToFront()
self.web_view.CoreWebView2InitializationCompleted += self.on_webview_ready
self.web_view.NavigationStarting += self.on_navigation_start
self.web_view.NavigationCompleted += self.on_navigation_completed
self.web_view.WebMessageReceived += self.on_script_notify
self.webview.Dock = WinForms.DockStyle.Fill
self.webview.BringToFront()
self.webview.CoreWebView2InitializationCompleted += self.on_webview_ready
self.webview.NavigationStarting += self.on_navigation_start
self.webview.NavigationCompleted += self.on_navigation_completed
self.webview.WebMessageReceived += self.on_script_notify
self.syncContextTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext()
self.web_view.DefaultBackgroundColor = Color.FromArgb(255, int(window.background_color.lstrip("#")[0:2], 16), int(window.background_color.lstrip("#")[2:4], 16), int(window.background_color.lstrip("#")[4:6], 16))
self.webview.DefaultBackgroundColor = Color.FromArgb(255, int(window.background_color.lstrip("#")[0:2], 16), int(window.background_color.lstrip("#")[2:4], 16), int(window.background_color.lstrip("#")[4:6], 16))

if window.transparent:
self.web_view.DefaultBackgroundColor = Color.Transparent
self.webview.DefaultBackgroundColor = Color.Transparent

self.url = None
self.ishtml = False
Expand All @@ -73,11 +73,11 @@ def __init__(self, form, window, cache_dir):
if _settings['storage_path']:
self.setup_webview2_environment()
else:
self.web_view.EnsureCoreWebView2Async(None)
self.webview.EnsureCoreWebView2Async(None)

def setup_webview2_environment(self):
def _callback(task):
self.web_view.EnsureCoreWebView2Async(task.Result)
self.webview.EnsureCoreWebView2Async(task.Result)

environment = CoreWebView2Environment.CreateAsync(
userDataFolder=_settings['storage_path']
Expand All @@ -100,7 +100,7 @@ def _callback(result):
semaphore.release()

try:
self.web_view.ExecuteScriptAsync(script).ContinueWith(
self.webview.ExecuteScriptAsync(script).ContinueWith(
Action[Task[String]](lambda task: _callback(json.loads(task.Result))),
self.syncContextTaskScheduler,
)
Expand All @@ -110,14 +110,14 @@ def _callback(result):
semaphore.release()

def clear_cookies(self):
self.web_view.CoreWebView2.CookieManager.DeleteAllCookies()
self.webview.CoreWebView2.CookieManager.DeleteAllCookies()

def get_cookies(self, cookies, semaphore):
def _callback(task):
for c in task.Result:
_cookies.append(c)

self.web_view.Invoke(Func[Type](_parse_cookies))
self.webview.Invoke(Func[Type](_parse_cookies))

def _parse_cookies():
# cookies must be accessed in the main thread, otherwise an exception is thrown
Expand All @@ -144,7 +144,7 @@ def _parse_cookies():
semaphore.release()

_cookies = []
self.web_view.CoreWebView2.CookieManager.GetCookiesAsync(self.url).ContinueWith(
self.webview.CoreWebView2.CookieManager.GetCookiesAsync(self.url).ContinueWith(
Action[Task[List[CoreWebView2Cookie]]](_callback), self.syncContextTaskScheduler
)

Expand All @@ -156,14 +156,14 @@ def load_html(self, content, _):
self.ishtml = True
self.pywebview_window.events.loaded.clear()

if self.web_view.CoreWebView2:
self.web_view.CoreWebView2.NavigateToString(self.html)
if self.webview.CoreWebView2:
self.webview.CoreWebView2.NavigateToString(self.html)
else:
self.web_view.EnsureCoreWebView2Async(None)
self.webview.EnsureCoreWebView2Async(None)

def load_url(self, url):
self.ishtml = False
self.web_view.Source = Uri(url)
self.webview.Source = Uri(url)

def on_certificate_error(self, _, args):
args.set_Action(CoreWebView2ServerCertificateErrorAction.AlwaysAllow)
Expand Down Expand Up @@ -219,7 +219,7 @@ def on_webview_ready(self, sender, args):
)
return

self.web_view.CoreWebView2.SourceChanged += self.on_source_changed
self.webview.CoreWebView2.SourceChanged += self.on_source_changed
sender.CoreWebView2.NewWindowRequested += self.on_new_window_request

if _settings['ssl']:
Expand Down Expand Up @@ -287,5 +287,5 @@ def on_navigation_completed(self, sender, _):
url = str(sender.Source)
self.url = None if self.ishtml else url

self.web_view.ExecuteScriptAsync(inject_pywebview(self.pywebview_window, renderer))
self.webview.ExecuteScriptAsync(inject_pywebview(self.pywebview_window, renderer))
self.pywebview_window.events.loaded.set()
Loading

0 comments on commit 550d5a1

Please sign in to comment.