| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import json |
| 4 |
import logging |
| 5 |
import os |
| 6 |
import urllib |
| 7 |
import uuid |
| 8 |
import webbrowser |
| 9 |
from threading import Semaphore, Thread, main_thread |
| 10 |
|
| 11 |
import AppKit |
| 12 |
import Foundation |
| 13 |
import WebKit |
| 14 |
from objc import nil, super |
| 15 |
from PyObjCTools import AppHelper |
| 16 |
|
| 17 |
from webview import FileDialog, _state, windows |
| 18 |
from webview import settings as webview_settings |
| 19 |
from webview.dom import _dnd_state |
| 20 |
from webview.menu import Menu, MenuAction, MenuSeparator |
| 21 |
from webview.models import Request, Response |
| 22 |
from webview.screen import Screen |
| 23 |
from webview.util import ( |
| 24 |
DEFAULT_HTML, |
| 25 |
create_cookie, |
| 26 |
inject_pywebview, |
| 27 |
js_bridge_call, |
| 28 |
parse_file_type, |
| 29 |
stringify_headers, |
| 30 |
) |
| 31 |
from webview.window import FixPoint |
| 32 |
|
| 33 |
# This lines allow to load non-HTTPS resources, like a local app as: http://127.0.0.1:5000 |
| 34 |
bundle = AppKit.NSBundle.mainBundle() |
| 35 |
info = bundle.localizedInfoDictionary() or bundle.infoDictionary() |
| 36 |
info['NSAppTransportSecurity'] = {'NSAllowsArbitraryLoads': Foundation.YES} |
| 37 |
info['NSRequiresAquaSystemAppearance'] = Foundation.NO # Enable dark mode support for Mojave |
| 38 |
|
| 39 |
# Fallbacks, in case these constants are not wrapped by PyObjC |
| 40 |
try: |
| 41 |
NSFullSizeContentViewWindowMask = AppKit.NSFullSizeContentViewWindowMask |
| 42 |
except AttributeError: |
| 43 |
NSFullSizeContentViewWindowMask = 1 << 15 |
| 44 |
|
| 45 |
try: |
| 46 |
NSWindowTitleHidden = AppKit.NSWindowTitleHidden |
| 47 |
except AttributeError: |
| 48 |
NSWindowTitleHidden = 1 |
| 49 |
|
| 50 |
logger = logging.getLogger('pywebview') |
| 51 |
logger.debug('Using Cocoa') |
| 52 |
|
| 53 |
renderer = 'wkwebview' |
| 54 |
|
| 55 |
|
| 56 |
class BrowserView: |
| 57 |
instances = {} |
| 58 |
app = AppKit.NSApplication.sharedApplication() |
| 59 |
app.setActivationPolicy_(0) |
| 60 |
current_menu = None |
| 61 |
|
| 62 |
cascade_loc = Foundation.NSMakePoint(100.0, 0.0) |
| 63 |
_shared_app_delegate = None |
| 64 |
|
| 65 |
class AppDelegate(AppKit.NSObject): |
| 66 |
def applicationShouldTerminate_(self, app): |
| 67 |
should_close = True |
| 68 |
for i in BrowserView.instances.values(): |
| 69 |
should_close = should_close and BrowserView.should_close(i.pywebview_window) |
| 70 |
return Foundation.YES if should_close else Foundation.NO |
| 71 |
|
| 72 |
def applicationSupportsSecureRestorableState_(self, app): |
| 73 |
return Foundation.YES |
| 74 |
|
| 75 |
class WindowHost(AppKit.NSWindow): |
| 76 |
def canBecomeKeyWindow(self): |
| 77 |
return self.focus |
| 78 |
|
| 79 |
class WindowDelegate(AppKit.NSObject): |
| 80 |
def windowDidBecomeKey_(self, notification): |
| 81 |
i = BrowserView.get_instance('window', notification.object()) |
| 82 |
|
| 83 |
if i and i.menu and BrowserView.current_menu != i.menu: |
| 84 |
BrowserView.current_menu = i.menu |
| 85 |
new_menu = i._recreate_menus(BrowserView.current_menu) |
| 86 |
BrowserView.app.setMainMenu_(new_menu) |
| 87 |
|
| 88 |
if not i: |
| 89 |
logger.error('No BrowserView instance found for windowDidBecomeKey_') |
| 90 |
|
| 91 |
def windowShouldClose_(self, window): |
| 92 |
i = BrowserView.get_instance('window', window) |
| 93 |
return BrowserView.should_close(i.pywebview_window) |
| 94 |
|
| 95 |
def windowWillClose_(self, notification): |
| 96 |
i = BrowserView.get_instance('window', notification.object()) |
| 97 |
|
| 98 |
# Clear delegates before removing from instances dict so no |
| 99 |
# callbacks can arrive after get_instance would return None. |
| 100 |
i.webview.setNavigationDelegate_(None) |
| 101 |
i.webview.setUIDelegate_(None) |
| 102 |
|
| 103 |
del BrowserView.instances[i.uid] |
| 104 |
|
| 105 |
if i.pywebview_window in windows: |
| 106 |
windows.remove(i.pywebview_window) |
| 107 |
|
| 108 |
# this seems to be a bug in WkWebView, so we need to load blank html |
| 109 |
# see https://stackoverflow.com/questions/27410413/wkwebview-embed-video-keeps-playing-sound-after-release |
| 110 |
i.webview.loadHTMLString_baseURL_('', None) |
| 111 |
i.webview.removeFromSuperview() |
| 112 |
i.webview = None |
| 113 |
|
| 114 |
i.closed.set() |
| 115 |
if BrowserView.instances == {}: |
| 116 |
BrowserView.app.setDelegate_(None) |
| 117 |
BrowserView._shared_app_delegate = None |
| 118 |
BrowserView.app.stop_(self) |
| 119 |
BrowserView.app.abortModal() |
| 120 |
|
| 121 |
def windowDidResize_(self, notification): |
| 122 |
i = BrowserView.get_instance('window', notification.object()) |
| 123 |
|
| 124 |
if i: |
| 125 |
size = i.window.frame().size |
| 126 |
i.pywebview_window.events.resized.set(size.width, size.height) |
| 127 |
|
| 128 |
def windowDidMiniaturize_(self, notification): |
| 129 |
i = BrowserView.get_instance('window', notification.object()) |
| 130 |
|
| 131 |
if i: |
| 132 |
i.pywebview_window.events.minimized.set() |
| 133 |
|
| 134 |
def windowDidDeminiaturize_(self, notification): |
| 135 |
i = BrowserView.get_instance('window', notification.object()) |
| 136 |
|
| 137 |
if i: |
| 138 |
i.pywebview_window.events.restored.set() |
| 139 |
|
| 140 |
def windowDidEnterFullScreen_(self, notification): |
| 141 |
i = BrowserView.get_instance('window', notification.object()) |
| 142 |
if i: |
| 143 |
i.pywebview_window.events.maximized.set() |
| 144 |
|
| 145 |
def windowDidExitFullScreen_(self, notification): |
| 146 |
i = BrowserView.get_instance('window', notification.object()) |
| 147 |
if i: |
| 148 |
i.pywebview_window.events.restored.set() |
| 149 |
|
| 150 |
def windowDidMove_(self, notification): |
| 151 |
i = BrowserView.get_instance('window', notification.object()) |
| 152 |
if i: |
| 153 |
frame = i.window.frame() |
| 154 |
screen = i.window.screen().frame() |
| 155 |
flipped_y = screen.size.height - frame.size.height - frame.origin.y |
| 156 |
i.pywebview_window.events.moved.set(frame.origin.x, flipped_y) |
| 157 |
|
| 158 |
class JSBridge(AppKit.NSObject): |
| 159 |
def initWithObject_(self, window): |
| 160 |
super(BrowserView.JSBridge, self).init() |
| 161 |
self.window = window |
| 162 |
return self |
| 163 |
|
| 164 |
def userContentController_didReceiveScriptMessage_(self, controller, message): |
| 165 |
body = json.loads(message.body()) |
| 166 |
if body['params'] is WebKit.WebUndefined.undefined(): |
| 167 |
body['params'] = None |
| 168 |
js_bridge_call(self.window, body['funcName'], body['params'], body['id']) |
| 169 |
|
| 170 |
class DownloadDelegate(AppKit.NSObject): |
| 171 |
# Download delegate to handle links with download attribute set |
| 172 |
def download_decideDestinationUsingResponse_suggestedFilename_completionHandler_( |
| 173 |
self, download, decideDestinationUsingResponse, suggestedFilename, completionHandler |
| 174 |
): |
| 175 |
save_dlg = AppKit.NSSavePanel.savePanel() |
| 176 |
directory = Foundation.NSSearchPathForDirectoriesInDomains( |
| 177 |
Foundation.NSDownloadsDirectory, Foundation.NSUserDomainMask, True |
| 178 |
)[0] |
| 179 |
save_dlg.setDirectoryURL_(Foundation.NSURL.fileURLWithPath_(directory)) |
| 180 |
save_dlg.setNameFieldStringValue_(suggestedFilename) |
| 181 |
if save_dlg.runModal() == AppKit.NSFileHandlingPanelOKButton: |
| 182 |
filename = save_dlg.filename() |
| 183 |
url = Foundation.NSURL.fileURLWithPath_(filename) |
| 184 |
completionHandler(url) |
| 185 |
else: |
| 186 |
completionHandler(None) |
| 187 |
|
| 188 |
class BrowserDelegate(AppKit.NSObject): |
| 189 |
# Display a JavaScript alert panel containing the specified message |
| 190 |
def webView_runJavaScriptAlertPanelWithMessage_initiatedByFrame_completionHandler_( |
| 191 |
self, webview, message, frame, handler |
| 192 |
): |
| 193 |
AppKit.NSRunningApplication.currentApplication().activateWithOptions_( |
| 194 |
AppKit.NSApplicationActivateIgnoringOtherApps |
| 195 |
) |
| 196 |
alert = AppKit.NSAlert.alloc().init() |
| 197 |
alert.setInformativeText_(str(message)) |
| 198 |
alert.runModal() |
| 199 |
|
| 200 |
handler() |
| 201 |
|
| 202 |
def webView_didReceiveAuthenticationChallenge_completionHandler_( |
| 203 |
self, webview, challenge, handler |
| 204 |
): |
| 205 |
# Prevent `ObjCPointerWarning: PyObjCPointer created: ... type ^{__SecTrust=}` |
| 206 |
|
| 207 |
# this allows any server cert |
| 208 |
if webview_settings['IGNORE_SSL_ERRORS'] or _state['ssl']: |
| 209 |
credential = AppKit.NSURLCredential.credentialForTrust_( |
| 210 |
challenge.protectionSpace().serverTrust() |
| 211 |
) |
| 212 |
handler(AppKit.NSURLSessionAuthChallengeUseCredential, credential) |
| 213 |
else: |
| 214 |
handler(AppKit.NSURLSessionAuthChallengePerformDefaultHandling, nil) |
| 215 |
|
| 216 |
# Display a JavaScript confirm panel containing the specified message |
| 217 |
def webView_runJavaScriptConfirmPanelWithMessage_initiatedByFrame_completionHandler_( |
| 218 |
self, webview, message, frame, handler |
| 219 |
): |
| 220 |
i = BrowserView.get_instance('webview', webview) |
| 221 |
ok = i.localization['global.ok'] |
| 222 |
cancel = i.localization['global.cancel'] |
| 223 |
|
| 224 |
result = BrowserView.display_confirmation_dialog(ok, cancel, message) |
| 225 |
handler(result) |
| 226 |
|
| 227 |
# Display a Javascript input panel |
| 228 |
def webView_runJavaScriptTextInputPanelWithPrompt_defaultText_initiatedByFrame_completionHandler_( |
| 229 |
self, webview, prompt, default_text, frame, handler |
| 230 |
): |
| 231 |
i = BrowserView.get_instance('webview', webview) |
| 232 |
ok = i.localization['global.ok'] |
| 233 |
cancel = i.localization['global.cancel'] |
| 234 |
|
| 235 |
result = BrowserView.display_input_dialog(ok, cancel, prompt, default_text) |
| 236 |
handler(result) |
| 237 |
|
| 238 |
# Display an open panel for <input type="file"> element |
| 239 |
def webView_runOpenPanelWithParameters_initiatedByFrame_completionHandler_( |
| 240 |
self, webview, param, frame, handler |
| 241 |
): |
| 242 |
i = list(BrowserView.instances.values())[0] |
| 243 |
file_filter = param._acceptedMIMETypes() |
| 244 |
|
| 245 |
files = i.create_file_dialog( |
| 246 |
FileDialog.OPEN, |
| 247 |
'', |
| 248 |
param.allowsMultipleSelection(), |
| 249 |
'', |
| 250 |
file_filter, |
| 251 |
main_thread=True, |
| 252 |
) |
| 253 |
|
| 254 |
if files: |
| 255 |
urls = [Foundation.NSURL.fileURLWithPath_(i) for i in files] |
| 256 |
handler(urls) |
| 257 |
else: |
| 258 |
handler(nil) |
| 259 |
|
| 260 |
# Open target="_blank" links in external browser |
| 261 |
def webView_createWebViewWithConfiguration_forNavigationAction_windowFeatures_( |
| 262 |
self, webview, config, action, features |
| 263 |
): |
| 264 |
if action.navigationType() == getattr(WebKit, 'WKNavigationTypeLinkActivated', 0): |
| 265 |
if webview_settings['OPEN_EXTERNAL_LINKS_IN_BROWSER']: |
| 266 |
webbrowser.open(action.request().URL().absoluteString(), 2, True) |
| 267 |
else: |
| 268 |
webview.loadRequest_(action.request()) |
| 269 |
return nil |
| 270 |
|
| 271 |
# WKNavigationDelegate method, invoked when a navigation decision needs to be made |
| 272 |
def webView_decidePolicyForNavigationAction_decisionHandler_( |
| 273 |
self, webview, action, handler |
| 274 |
): |
| 275 |
# The event that might have triggered the navigation |
| 276 |
event = AppKit.NSApp.currentEvent() |
| 277 |
|
| 278 |
# Handle links with the download attribute set to recommend a file name |
| 279 |
if action.shouldPerformDownload() and webview_settings['ALLOW_DOWNLOADS']: |
| 280 |
handler(getattr(WebKit, 'WKNavigationActionPolicyDownload', 2)) |
| 281 |
return |
| 282 |
|
| 283 |
""" Disable back navigation on pressing the Delete key: """ |
| 284 |
# Check if the requested navigation action is Back/Forward |
| 285 |
if action.navigationType() == getattr(WebKit, 'WKNavigationTypeBackForward', 2): |
| 286 |
# Check if the event is a Delete key press (keyCode = 51) |
| 287 |
if event and event.type() == AppKit.NSKeyDown and event.keyCode() == 51: |
| 288 |
# If so, ignore the request and return |
| 289 |
handler(getattr(WebKit, 'WKNavigationActionPolicyCancel', 0)) |
| 290 |
return |
| 291 |
|
| 292 |
request = action.request() |
| 293 |
url = request.URL() |
| 294 |
|
| 295 |
original_headers = dict(request.allHTTPHeaderFields()) |
| 296 |
i = BrowserView.get_instance('webview', webview) |
| 297 |
|
| 298 |
if ( |
| 299 |
len(i.pywebview_window.events.request_sent) > 0 |
| 300 |
and 'X-Handled' not in original_headers |
| 301 |
and str(url) != 'about:blank' |
| 302 |
): |
| 303 |
request_ = Request(str(url), request.HTTPMethod(), original_headers) |
| 304 |
i.pywebview_window.events.request_sent.set(request_) |
| 305 |
request_.headers['X-Handled'] = 'true' |
| 306 |
|
| 307 |
new_request = Foundation.NSMutableURLRequest.requestWithURL_(url) |
| 308 |
new_request.setHTTPMethod_(request.HTTPMethod()) |
| 309 |
new_request.setAllHTTPHeaderFields_( |
| 310 |
AppKit.NSDictionary(stringify_headers(request_.headers)) |
| 311 |
) |
| 312 |
new_request.setHTTPBody_(request.HTTPBody()) |
| 313 |
new_request.setHTTPBodyStream_(request.HTTPBodyStream()) |
| 314 |
new_request.setHTTPShouldHandleCookies_(request.HTTPShouldHandleCookies()) |
| 315 |
new_request.setHTTPShouldUsePipelining_(request.HTTPShouldUsePipelining()) |
| 316 |
new_request.setMainDocumentURL_(request.mainDocumentURL()) |
| 317 |
new_request.setNetworkServiceType_(request.networkServiceType()) |
| 318 |
webview.loadRequest_(new_request) |
| 319 |
handler(getattr(WebKit, 'WKNavigationActionPolicyCancel', 1)) |
| 320 |
else: |
| 321 |
# Normal navigation, allow |
| 322 |
handler(getattr(WebKit, 'WKNavigationActionPolicyAllow', 1)) |
| 323 |
|
| 324 |
def webView_navigationAction_didBecomeDownload_(self, webview, navigationAction, download): |
| 325 |
download.setDelegate_(BrowserView.DownloadDelegate.alloc().init().retain()) |
| 326 |
|
| 327 |
def webView_decidePolicyForNavigationResponse_decisionHandler_( |
| 328 |
self, webview, navigationResponse, decisionHandler |
| 329 |
): |
| 330 |
if navigationResponse.canShowMIMEType(): |
| 331 |
response_ = navigationResponse.response() |
| 332 |
headers = dict(response_.allHeaderFields()) |
| 333 |
response = Response( |
| 334 |
response_.URL().absoluteString(), response_.statusCode(), headers |
| 335 |
) |
| 336 |
webview.pywebview_window.events.response_received.set(response) |
| 337 |
|
| 338 |
decisionHandler(WebKit.WKNavigationResponsePolicyAllow) |
| 339 |
elif webview_settings['ALLOW_DOWNLOADS']: |
| 340 |
decisionHandler(WebKit.WKNavigationResponsePolicyCancel) |
| 341 |
|
| 342 |
save_filename = navigationResponse.response().suggestedFilename() |
| 343 |
|
| 344 |
save_dlg = AppKit.NSSavePanel.savePanel() |
| 345 |
save_dlg.setTitle_(webview.pywebview_window.localization['global.saveFile']) |
| 346 |
directory = Foundation.NSSearchPathForDirectoriesInDomains( |
| 347 |
Foundation.NSDownloadsDirectory, Foundation.NSUserDomainMask, True |
| 348 |
)[0] |
| 349 |
save_dlg.setDirectoryURL_(Foundation.NSURL.fileURLWithPath_(directory)) |
| 350 |
|
| 351 |
if save_filename: # set file name |
| 352 |
save_dlg.setNameFieldStringValue_(save_filename) |
| 353 |
|
| 354 |
if save_dlg.runModal() == AppKit.NSFileHandlingPanelOKButton: |
| 355 |
self._file_name = save_dlg.filename() |
| 356 |
dataTask = Foundation.NSURLSession.sharedSession().downloadTaskWithURL_completionHandler_( |
| 357 |
navigationResponse.response().URL(), self.download_completionHandler_error_ |
| 358 |
) |
| 359 |
dataTask.resume() |
| 360 |
else: |
| 361 |
self._file_name = None |
| 362 |
else: |
| 363 |
decisionHandler(WebKit.WKNavigationResponsePolicyCancel) |
| 364 |
|
| 365 |
def download_completionHandler_error_(self, temporaryLocation, response, error): |
| 366 |
if error is not None: |
| 367 |
logger.error('Download error:', error) |
| 368 |
else: |
| 369 |
if temporaryLocation is not None: |
| 370 |
destinationURL = Foundation.NSURL.fileURLWithPath_(self._file_name) |
| 371 |
fileManager = Foundation.NSFileManager.defaultManager() |
| 372 |
try: |
| 373 |
fileManager.moveItemAtURL_toURL_error_( |
| 374 |
temporaryLocation, destinationURL, None |
| 375 |
) |
| 376 |
except Foundation.NSError as moveError: |
| 377 |
logger.exception(moveError) |
| 378 |
|
| 379 |
# Show the webview when it finishes loading |
| 380 |
def webView_didFinishNavigation_(self, webview, nav): |
| 381 |
# Add the webview to the window if it's not yet the contentView |
| 382 |
i = BrowserView.get_instance('webview', webview) |
| 383 |
|
| 384 |
if i: |
| 385 |
if not webview.window(): |
| 386 |
i.window.setContentView_(webview) |
| 387 |
i.window.makeFirstResponder_(webview) |
| 388 |
|
| 389 |
inject_pywebview('cocoa', i.js_bridge.window) |
| 390 |
|
| 391 |
if _state['debug'] and webview_settings['OPEN_DEVTOOLS_IN_DEBUG']: |
| 392 |
BrowserView._open_web_inspector(webview) |
| 393 |
|
| 394 |
# Handle JavaScript window.print() |
| 395 |
def userContentController_didReceiveScriptMessage_(self, controller, message): |
| 396 |
if message.body() == 'print': |
| 397 |
i = BrowserView.get_instance('_browserDelegate', self) |
| 398 |
BrowserView.print_webview(i.webview) |
| 399 |
|
| 400 |
class FileFilterChooser(AppKit.NSPopUpButton): |
| 401 |
def initWithFilter_(self, file_filter): |
| 402 |
super(BrowserView.FileFilterChooser, self).init() |
| 403 |
self.filter = file_filter |
| 404 |
|
| 405 |
self.addItemsWithTitles_([i[0] for i in self.filter]) |
| 406 |
self.setAction_('onChange:') |
| 407 |
self.setTarget_(self) |
| 408 |
return self |
| 409 |
|
| 410 |
def setFileDialog_(self, file_dlg): |
| 411 |
self.file_dlg = file_dlg |
| 412 |
|
| 413 |
def onChange_(self, sender): |
| 414 |
option = sender.indexOfSelectedItem() |
| 415 |
self.file_dlg.setAllowedFileTypes_(self.filter[option][1]) |
| 416 |
|
| 417 |
class WebKitHost(WebKit.WKWebView): |
| 418 |
def performDragOperation_(self, sender): |
| 419 |
if sender.draggingSource() is None and _dnd_state['num_listeners'] > 0: |
| 420 |
pboard = sender.draggingPasteboard() |
| 421 |
classes = [AppKit.NSURL] |
| 422 |
options = { |
| 423 |
AppKit.NSPasteboardURLReadingFileURLsOnlyKey: AppKit.NSNumber.numberWithBool_( |
| 424 |
True |
| 425 |
) |
| 426 |
} |
| 427 |
urls = pboard.readObjectsForClasses_options_(classes, options) or [] |
| 428 |
files = [ |
| 429 |
( |
| 430 |
os.path.basename(os.path.dirname(file_path)) |
| 431 |
if os.path.isdir(file_path) |
| 432 |
else os.path.basename(file_path), |
| 433 |
file_path, |
| 434 |
) |
| 435 |
for url in urls |
| 436 |
for file_path in [ |
| 437 |
urllib.parse.unquote( |
| 438 |
url.filePathURL().absoluteString().replace('file://', '') |
| 439 |
) |
| 440 |
] |
| 441 |
if os.path.isdir(file_path) or os.path.isfile(file_path) |
| 442 |
] |
| 443 |
|
| 444 |
_dnd_state['paths'] += files |
| 445 |
|
| 446 |
return super(BrowserView.WebKitHost, self).performDragOperation_(sender) |
| 447 |
|
| 448 |
def addSubview_(self, event): |
| 449 |
# translate the event from the web coordinate space into the window coordinate space |
| 450 |
# basically flip the y axis since the WKWebView/WebKitHost implements a flipped view |
| 451 |
# (but seems to miss this flip back when adding a subview) |
| 452 |
event_frame = event.frame() |
| 453 |
flipped_y = self.frame().size.height - (event_frame.origin.y + event_frame.size.height) |
| 454 |
event.setFrameOrigin_(AppKit.NSPoint(event_frame.origin.x, flipped_y)) |
| 455 |
|
| 456 |
super(BrowserView.WebKitHost, self).addSubview_(event) |
| 457 |
|
| 458 |
def mouseDown_(self, event): |
| 459 |
i = BrowserView.get_instance('webview', self) |
| 460 |
window = self.window() |
| 461 |
|
| 462 |
if i.frameless and i.easy_drag: |
| 463 |
windowFrame = window.frame() |
| 464 |
if windowFrame is None: |
| 465 |
raise RuntimeError('Failed to obtain screen') |
| 466 |
|
| 467 |
self.initialLocation = window.convertBaseToScreen_(event.locationInWindow()) |
| 468 |
self.initialLocation.x -= windowFrame.origin.x |
| 469 |
self.initialLocation.y -= windowFrame.origin.y |
| 470 |
|
| 471 |
super(BrowserView.WebKitHost, self).mouseDown_(event) |
| 472 |
|
| 473 |
def mouseDragged_(self, event): |
| 474 |
i = BrowserView.get_instance('webview', self) |
| 475 |
window = self.window() |
| 476 |
|
| 477 |
if i.frameless and i.easy_drag: |
| 478 |
screenFrame = i.screen |
| 479 |
if screenFrame is None: |
| 480 |
raise RuntimeError('Failed to obtain screen') |
| 481 |
|
| 482 |
windowFrame = window.frame() |
| 483 |
if windowFrame is None: |
| 484 |
raise RuntimeError('Failed to obtain frame') |
| 485 |
|
| 486 |
currentLocation = window.convertBaseToScreen_( |
| 487 |
window.mouseLocationOutsideOfEventStream() |
| 488 |
) |
| 489 |
newOrigin = AppKit.NSMakePoint( |
| 490 |
(currentLocation.x - self.initialLocation.x), |
| 491 |
(currentLocation.y - self.initialLocation.y), |
| 492 |
) |
| 493 |
if (newOrigin.y + windowFrame.size.height) > ( |
| 494 |
screenFrame.origin.y + screenFrame.size.height |
| 495 |
): |
| 496 |
newOrigin.y = screenFrame.origin.y + ( |
| 497 |
screenFrame.size.height + windowFrame.size.height |
| 498 |
) |
| 499 |
window.setFrameOrigin_(newOrigin) |
| 500 |
|
| 501 |
if event.modifierFlags() & getattr(AppKit, 'NSEventModifierFlagControl', 1 << 18): |
| 502 |
i = BrowserView.get_instance('webview', self) |
| 503 |
if not _state['debug']: |
| 504 |
return |
| 505 |
|
| 506 |
super(BrowserView.WebKitHost, self).mouseDragged_(event) |
| 507 |
|
| 508 |
def willOpenMenu_withEvent_(self, menu, event): |
| 509 |
if not _state['debug']: |
| 510 |
menu.removeAllItems() |
| 511 |
|
| 512 |
def keyDown_(self, event): |
| 513 |
if event.modifierFlags() & AppKit.NSCommandKeyMask: |
| 514 |
responder = self.window().firstResponder() |
| 515 |
if responder is not None: |
| 516 |
range_ = responder.selectedRange() |
| 517 |
hasSelectedText = len(range_) > 0 |
| 518 |
|
| 519 |
char = event.characters() |
| 520 |
|
| 521 |
if char == 'x' and hasSelectedText: # cut |
| 522 |
responder.cut_(self) |
| 523 |
return |
| 524 |
elif char == 'c' and hasSelectedText: # copy |
| 525 |
responder.copy_(self) |
| 526 |
return |
| 527 |
elif char == 'v': # paste |
| 528 |
responder.paste_(self) |
| 529 |
return |
| 530 |
elif char == 'a': # select all |
| 531 |
responder.selectAll_(self) |
| 532 |
return |
| 533 |
elif char == 'z': # undo |
| 534 |
if responder.undoManager().canUndo(): |
| 535 |
responder.undoManager().undo() |
| 536 |
return |
| 537 |
elif char == 'q': # quit |
| 538 |
BrowserView.app.stop_(self) |
| 539 |
return |
| 540 |
elif char == 'w': # close |
| 541 |
self.window().performClose_(event) |
| 542 |
return |
| 543 |
|
| 544 |
super(BrowserView.WebKitHost, self).keyDown_(event) |
| 545 |
|
| 546 |
def __init__(self, window): |
| 547 |
BrowserView.instances[window.uid] = self |
| 548 |
self.uid = window.uid |
| 549 |
self.pywebview_window = window |
| 550 |
|
| 551 |
self.js_bridge = None |
| 552 |
self._file_name = None |
| 553 |
self._file_name_semaphore = Semaphore(0) |
| 554 |
self._current_url_semaphore = Semaphore(0) |
| 555 |
self.closed = window.events.closed |
| 556 |
self.closing = window.events.closing |
| 557 |
self.shown = window.events.shown |
| 558 |
self.loaded = window.events.loaded |
| 559 |
self.confirm_close = window.confirm_close |
| 560 |
self.title = window.title |
| 561 |
self.is_fullscreen = False |
| 562 |
self.hidden = window.hidden |
| 563 |
self.minimized = window.minimized |
| 564 |
self.maximized = window.maximized |
| 565 |
self.localization = window.localization |
| 566 |
|
| 567 |
if window.screen: |
| 568 |
self.screen = window.screen.frame |
| 569 |
else: |
| 570 |
self.screen = AppKit.NSScreen.mainScreen().frame() |
| 571 |
|
| 572 |
rect = AppKit.NSMakeRect(0.0, 0.0, window.initial_width, window.initial_height) |
| 573 |
window_mask = ( |
| 574 |
AppKit.NSTitledWindowMask |
| 575 |
| AppKit.NSClosableWindowMask |
| 576 |
| AppKit.NSMiniaturizableWindowMask |
| 577 |
) |
| 578 |
|
| 579 |
if window.resizable: |
| 580 |
window_mask = window_mask | AppKit.NSResizableWindowMask |
| 581 |
|
| 582 |
if window.frameless: |
| 583 |
window_mask = ( |
| 584 |
window_mask |
| 585 |
| NSFullSizeContentViewWindowMask |
| 586 |
| AppKit.NSTexturedBackgroundWindowMask |
| 587 |
) |
| 588 |
|
| 589 |
self.menu = window.menu or _state['menu'] |
| 590 |
|
| 591 |
self.window = BrowserView.WindowHost.alloc().initWithContentRect_styleMask_backing_defer_( |
| 592 |
rect, window_mask, AppKit.NSBackingStoreBuffered, False |
| 593 |
) |
| 594 |
self.window.setReleasedWhenClosed_(False) |
| 595 |
self.pywebview_window.native = self.window |
| 596 |
|
| 597 |
self.window.focus = window.focus |
| 598 |
self.window.setTitle_(window.title) |
| 599 |
self.window.setMinSize_(AppKit.NSSize(window.min_size[0], window.min_size[1])) |
| 600 |
self.window.setAnimationBehavior_(AppKit.NSWindowAnimationBehaviorDocumentWindow) |
| 601 |
BrowserView.cascade_loc = self.window.cascadeTopLeftFromPoint_(BrowserView.cascade_loc) |
| 602 |
|
| 603 |
frame = self.window.frame() |
| 604 |
frame.size.width = window.initial_width |
| 605 |
frame.size.height = window.initial_height |
| 606 |
self.window.setFrame_display_(frame, True) |
| 607 |
|
| 608 |
config = WebKit.WKWebViewConfiguration.alloc().init() |
| 609 |
self.webview = BrowserView.WebKitHost.alloc().initWithFrame_configuration_(rect, config) |
| 610 |
self.webview.pywebview_window = window |
| 611 |
|
| 612 |
self._browserDelegate = BrowserView.BrowserDelegate.alloc().init() |
| 613 |
self._windowDelegate = BrowserView.WindowDelegate.alloc().init() |
| 614 |
|
| 615 |
if BrowserView._shared_app_delegate is None: |
| 616 |
BrowserView._shared_app_delegate = BrowserView.AppDelegate.alloc().init() |
| 617 |
BrowserView.app.setDelegate_(BrowserView._shared_app_delegate) |
| 618 |
self.webview.setUIDelegate_(self._browserDelegate) |
| 619 |
self.webview.setNavigationDelegate_(self._browserDelegate) |
| 620 |
self.window.setDelegate_(self._windowDelegate) |
| 621 |
|
| 622 |
config.userContentController().addScriptMessageHandler_name_( |
| 623 |
self._browserDelegate, 'browserDelegate' |
| 624 |
) |
| 625 |
|
| 626 |
self.datastore = WebKit.WKWebsiteDataStore.defaultDataStore() |
| 627 |
|
| 628 |
if _state['icon'] and os.path.isfile(_state['icon']): |
| 629 |
ns_image = AppKit.NSImage.alloc().initByReferencingFile_(_state['icon']) |
| 630 |
BrowserView.app.setApplicationIconImage_(ns_image) |
| 631 |
|
| 632 |
if _state['private_mode']: |
| 633 |
# nonPersisentDataStore preserves cookies for some unknown reason. For this reason we use default datastore |
| 634 |
# and clear all the cookies beforehand |
| 635 |
|
| 636 |
def dummy_completion_handler(): |
| 637 |
pass |
| 638 |
|
| 639 |
data_types = WebKit.WKWebsiteDataStore.allWebsiteDataTypes() |
| 640 |
from_start = WebKit.NSDate.dateWithTimeIntervalSince1970_(0) |
| 641 |
config.setWebsiteDataStore_(self.datastore) |
| 642 |
self.datastore.removeDataOfTypes_modifiedSince_completionHandler_( |
| 643 |
data_types, from_start, dummy_completion_handler |
| 644 |
) |
| 645 |
else: |
| 646 |
config.setWebsiteDataStore_(self.datastore) |
| 647 |
|
| 648 |
try: |
| 649 |
config.preferences().setValue_forKey_(False, 'backspaceKeyNavigationEnabled') |
| 650 |
except KeyError: |
| 651 |
pass # backspaceKeyNavigationEnabled does not exist prior to macOS Mojave |
| 652 |
|
| 653 |
config.preferences().setValue_forKey_( |
| 654 |
webview_settings['ALLOW_FILE_URLS'], 'allowFileAccessFromFileURLs' |
| 655 |
) |
| 656 |
|
| 657 |
if _state['debug']: |
| 658 |
config.preferences().setValue_forKey_(True, 'developerExtrasEnabled') |
| 659 |
|
| 660 |
self.js_bridge = BrowserView.JSBridge.alloc().initWithObject_(window) |
| 661 |
config.userContentController().addScriptMessageHandler_name_(self.js_bridge, 'jsBridge') |
| 662 |
|
| 663 |
user_agent = webview_settings.get('user_agent') or _state['user_agent'] |
| 664 |
if user_agent: |
| 665 |
self.webview.setCustomUserAgent_(user_agent) |
| 666 |
|
| 667 |
self.window.setFrameOrigin_(self.screen.origin) |
| 668 |
|
| 669 |
if window.initial_x is not None and window.initial_y is not None: |
| 670 |
self.move(window.initial_x, window.initial_y) |
| 671 |
else: |
| 672 |
self.center() |
| 673 |
|
| 674 |
if window.transparent: |
| 675 |
self.window.setOpaque_(False) |
| 676 |
self.window.setHasShadow_(False) |
| 677 |
self.window.setBackgroundColor_( |
| 678 |
BrowserView.nscolor_from_hex(window.background_color, 0) |
| 679 |
) |
| 680 |
self.webview.setValue_forKey_(True, 'drawsTransparentBackground') |
| 681 |
else: |
| 682 |
self.window.setBackgroundColor_(BrowserView.nscolor_from_hex(window.background_color)) |
| 683 |
|
| 684 |
if window.vibrancy: |
| 685 |
frame_vibrancy = AppKit.NSMakeRect(0, 0, frame.size.width, frame.size.height) |
| 686 |
visualEffectView = AppKit.NSVisualEffectView.new() |
| 687 |
visualEffectView.setAutoresizingMask_( |
| 688 |
AppKit.NSViewWidthSizable | AppKit.NSViewHeightSizable |
| 689 |
) |
| 690 |
visualEffectView.setWantsLayer_(True) |
| 691 |
visualEffectView.setFrame_(frame_vibrancy) |
| 692 |
visualEffectView.setState_(AppKit.NSVisualEffectStateActive) |
| 693 |
visualEffectView.setBlendingMode_(AppKit.NSVisualEffectBlendingModeBehindWindow) |
| 694 |
self.webview.addSubview_positioned_relativeTo_( |
| 695 |
visualEffectView, AppKit.NSWindowBelow, self.webview |
| 696 |
) |
| 697 |
|
| 698 |
self.frameless = window.frameless |
| 699 |
self.easy_drag = window.easy_drag |
| 700 |
|
| 701 |
if window.frameless: |
| 702 |
# Make content full size and titlebar transparent |
| 703 |
self.window.setTitlebarAppearsTransparent_(True) |
| 704 |
self.window.setTitleVisibility_(NSWindowTitleHidden) |
| 705 |
self.window.standardWindowButton_(AppKit.NSWindowCloseButton).setHidden_(True) |
| 706 |
self.window.standardWindowButton_(AppKit.NSWindowMiniaturizeButton).setHidden_(True) |
| 707 |
self.window.standardWindowButton_(AppKit.NSWindowZoomButton).setHidden_(True) |
| 708 |
else: |
| 709 |
# Set the titlebar color (so that it does not change with the window color) |
| 710 |
self.window.contentView().superview().subviews().lastObject().setBackgroundColor_( |
| 711 |
AppKit.NSColor.windowBackgroundColor() |
| 712 |
) |
| 713 |
|
| 714 |
if window.on_top: |
| 715 |
self.window.setLevel_(AppKit.NSStatusWindowLevel) |
| 716 |
|
| 717 |
self.pywebview_window.events.before_show.set() |
| 718 |
|
| 719 |
if window.real_url: |
| 720 |
self.url = window.real_url |
| 721 |
self.load_url(window.real_url) |
| 722 |
elif window.html: |
| 723 |
self.load_html(window.html, '') |
| 724 |
else: |
| 725 |
self.load_html(DEFAULT_HTML, '') |
| 726 |
if window.fullscreen: |
| 727 |
self.toggle_fullscreen() |
| 728 |
|
| 729 |
def first_show(self): |
| 730 |
if not self.hidden: |
| 731 |
self.window.makeKeyAndOrderFront_(self.window) |
| 732 |
|
| 733 |
if self.maximized: |
| 734 |
self.maximize() |
| 735 |
elif self.minimized: |
| 736 |
self.minimize() |
| 737 |
|
| 738 |
self.shown.set() |
| 739 |
|
| 740 |
if not BrowserView.app.isRunning(): |
| 741 |
new_menu = self._recreate_menus(self.menu) |
| 742 |
BrowserView.app.setMainMenu_(new_menu) |
| 743 |
|
| 744 |
BrowserView.app.activateIgnoringOtherApps_(Foundation.YES) |
| 745 |
AppHelper.installMachInterrupt() |
| 746 |
BrowserView.app.run() |
| 747 |
|
| 748 |
def show(self): |
| 749 |
def _show(): |
| 750 |
self.window.makeKeyAndOrderFront_(self.window) |
| 751 |
BrowserView.app.activateIgnoringOtherApps_(Foundation.YES) |
| 752 |
|
| 753 |
AppHelper.callAfter(_show) |
| 754 |
|
| 755 |
def hide(self): |
| 756 |
AppHelper.callAfter(self.window.orderOut_, self.window) |
| 757 |
|
| 758 |
def destroy(self): |
| 759 |
AppHelper.callAfter(self.window.close) |
| 760 |
|
| 761 |
def set_title(self, title): |
| 762 |
AppHelper.callAfter(self.window.setTitle_, title) |
| 763 |
|
| 764 |
def toggle_fullscreen(self): |
| 765 |
def toggle(): |
| 766 |
if self.is_fullscreen: |
| 767 |
window_behaviour = 1 << 2 # NSWindowCollectionBehaviorManaged |
| 768 |
else: |
| 769 |
window_behaviour = 1 << 7 # NSWindowCollectionBehaviorFullScreenPrimary |
| 770 |
|
| 771 |
self.window.setCollectionBehavior_(window_behaviour) |
| 772 |
self.window.toggleFullScreen_(None) |
| 773 |
|
| 774 |
AppHelper.callAfter(toggle) |
| 775 |
self.is_fullscreen = not self.is_fullscreen |
| 776 |
|
| 777 |
def resize(self, width, height, fix_point): |
| 778 |
def _resize(): |
| 779 |
frame = self.window.frame() |
| 780 |
|
| 781 |
if fix_point and fix_point & FixPoint.EAST: |
| 782 |
# Keep the right of the window in the same place |
| 783 |
frame.origin.x += frame.size.width - width |
| 784 |
|
| 785 |
if fix_point and fix_point & FixPoint.NORTH: |
| 786 |
# Keep the top of the window in the same place |
| 787 |
frame.origin.y += frame.size.height - height |
| 788 |
|
| 789 |
frame.size.width = width |
| 790 |
frame.size.height = height |
| 791 |
|
| 792 |
if not fix_point: # used in maximized |
| 793 |
frame.origin.x = 0 |
| 794 |
frame.origin.y = 0 |
| 795 |
|
| 796 |
self.window.setFrame_display_(frame, True) |
| 797 |
|
| 798 |
AppHelper.callAfter(_resize) |
| 799 |
|
| 800 |
def maximize(self): |
| 801 |
width = self.screen.size.width |
| 802 |
height = self.screen.size.height |
| 803 |
self.resize(width, height, None) |
| 804 |
|
| 805 |
def minimize(self): |
| 806 |
AppHelper.callAfter(self.window.miniaturize_, self) |
| 807 |
|
| 808 |
def restore(self): |
| 809 |
AppHelper.callAfter(self.window.deminiaturize_, self) |
| 810 |
|
| 811 |
def move(self, x, y): |
| 812 |
flipped_y = self.screen.size.height - y |
| 813 |
self.window.setFrameTopLeftPoint_( |
| 814 |
AppKit.NSPoint(self.screen.origin.x + x, self.screen.origin.y + flipped_y) |
| 815 |
) |
| 816 |
|
| 817 |
def center(self): |
| 818 |
window_frame = self.window.frame() |
| 819 |
|
| 820 |
window_frame.origin.x = ( |
| 821 |
self.screen.origin.x + (self.screen.size.width - window_frame.size.width) / 2 |
| 822 |
) |
| 823 |
window_frame.origin.y = ( |
| 824 |
self.screen.origin.y + (self.screen.size.height - window_frame.size.height) / 2 |
| 825 |
) |
| 826 |
|
| 827 |
self.window.setFrameOrigin_(window_frame.origin) |
| 828 |
|
| 829 |
def clear_cookies(self): |
| 830 |
def clear(): |
| 831 |
self.datastore.removeDataOfTypes_modifiedSince_completionHandler_( |
| 832 |
WebKit.WKWebsiteDataStore.allWebsiteDataTypes(), |
| 833 |
Foundation.NSDate.dateWithTimeIntervalSince1970_(0), |
| 834 |
lambda: None, |
| 835 |
) |
| 836 |
|
| 837 |
AppHelper.callAfter(clear) |
| 838 |
|
| 839 |
def get_cookies(self): |
| 840 |
def handler(cookies): |
| 841 |
for c in cookies: |
| 842 |
domain = c.domain()[1:] if c.domain().startswith('.') else c.domain() |
| 843 |
if domain not in self.url: |
| 844 |
continue |
| 845 |
|
| 846 |
data = { |
| 847 |
'name': c.name(), |
| 848 |
'value': c.value(), |
| 849 |
'path': c.path(), |
| 850 |
'domain': c.domain(), |
| 851 |
'expires': c.expiresDate(), |
| 852 |
'secure': c.isSecure(), |
| 853 |
'httponly': c.isHTTPOnly(), |
| 854 |
'samesite': c.SameSitePolicy(), |
| 855 |
} |
| 856 |
|
| 857 |
cookie = create_cookie(data) |
| 858 |
_cookies.append(cookie) |
| 859 |
|
| 860 |
cookie_semaphore.release() |
| 861 |
|
| 862 |
_cookies = [] |
| 863 |
AppHelper.callAfter(self.datastore.httpCookieStore().getAllCookies_, handler) |
| 864 |
cookie_semaphore = Semaphore(0) |
| 865 |
cookie_semaphore.acquire() |
| 866 |
|
| 867 |
return _cookies |
| 868 |
|
| 869 |
def get_current_url(self): |
| 870 |
def get(): |
| 871 |
self._current_url = str(self.webview.URL()) |
| 872 |
self._current_url_semaphore.release() |
| 873 |
|
| 874 |
AppHelper.callAfter(get) |
| 875 |
|
| 876 |
self._current_url_semaphore.acquire() |
| 877 |
return None if self._current_url == 'about:blank' else self._current_url |
| 878 |
|
| 879 |
def load_url(self, url): |
| 880 |
def load(url): |
| 881 |
page_url = Foundation.NSURL.URLWithString_(BrowserView.quote(url)) |
| 882 |
req = Foundation.NSURLRequest.requestWithURL_(page_url) |
| 883 |
self.webview.loadRequest_(req) |
| 884 |
|
| 885 |
self.url = url |
| 886 |
AppHelper.callAfter(load, url) |
| 887 |
|
| 888 |
def load_html(self, content, base_uri): |
| 889 |
def load(content, url): |
| 890 |
url = Foundation.NSURL.URLWithString_(BrowserView.quote(url)) |
| 891 |
self.webview.loadHTMLString_baseURL_(content, url) |
| 892 |
|
| 893 |
AppHelper.callAfter(load, content, base_uri) |
| 894 |
|
| 895 |
def evaluate_js(self, script, parse_json): |
| 896 |
def eval(): |
| 897 |
self.webview.evaluateJavaScript_completionHandler_(script, handler) |
| 898 |
|
| 899 |
def handler(result, error): |
| 900 |
if parse_json and result: |
| 901 |
try: |
| 902 |
JSResult.result = json.loads(result) |
| 903 |
except Exception: |
| 904 |
logger.exception('Failed to parse JSON: ' + result) |
| 905 |
JSResult.result = result |
| 906 |
else: |
| 907 |
JSResult.result = result |
| 908 |
|
| 909 |
JSResult.result_semaphore.release() |
| 910 |
|
| 911 |
class JSResult: |
| 912 |
result = None |
| 913 |
result_semaphore = Semaphore(0) |
| 914 |
|
| 915 |
AppHelper.callAfter(eval) |
| 916 |
JSResult.result_semaphore.acquire() |
| 917 |
return JSResult.result |
| 918 |
|
| 919 |
def create_file_dialog( |
| 920 |
self, dialog_type, directory, allow_multiple, save_filename, file_filter, main_thread=False |
| 921 |
): |
| 922 |
def create_dialog(*args): |
| 923 |
dialog_type = args[0] |
| 924 |
|
| 925 |
if dialog_type == FileDialog.SAVE: |
| 926 |
save_filename = args[2] |
| 927 |
|
| 928 |
save_dlg = AppKit.NSSavePanel.savePanel() |
| 929 |
save_dlg.setTitle_(self.localization['global.saveFile']) |
| 930 |
|
| 931 |
if directory: # set initial directory |
| 932 |
save_dlg.setDirectoryURL_(Foundation.NSURL.fileURLWithPath_(directory)) |
| 933 |
|
| 934 |
if save_filename: # set file name |
| 935 |
save_dlg.setNameFieldStringValue_(save_filename) |
| 936 |
|
| 937 |
if save_dlg.runModal() == AppKit.NSFileHandlingPanelOKButton: |
| 938 |
self._file_name = save_dlg.filename() |
| 939 |
else: |
| 940 |
self._file_name = None |
| 941 |
else: |
| 942 |
allow_multiple = args[1] |
| 943 |
|
| 944 |
open_dlg = AppKit.NSOpenPanel.openPanel() |
| 945 |
|
| 946 |
# Enable the selection of files in the dialog. |
| 947 |
open_dlg.setCanChooseFiles_(dialog_type != FileDialog.FOLDER) |
| 948 |
|
| 949 |
# Enable the selection of directories in the dialog. |
| 950 |
open_dlg.setCanChooseDirectories_(dialog_type == FileDialog.FOLDER) |
| 951 |
|
| 952 |
# Enable creating new folders in folder dialogs (macOS) |
| 953 |
if dialog_type == FileDialog.FOLDER: |
| 954 |
open_dlg.setCanCreateDirectories_(True) |
| 955 |
|
| 956 |
# Enable / disable multiple selection |
| 957 |
open_dlg.setAllowsMultipleSelection_(allow_multiple) |
| 958 |
|
| 959 |
# Set allowed file extensions |
| 960 |
if file_filter: |
| 961 |
if isinstance(file_filter, Foundation.WKNSArray): |
| 962 |
try: |
| 963 |
import UniformTypeIdentifiers |
| 964 |
|
| 965 |
UTType = UniformTypeIdentifiers.UTType |
| 966 |
except ImportError: |
| 967 |
UTType = None # Fallback if UTType is not available |
| 968 |
|
| 969 |
if UTType is not None: |
| 970 |
# Map wildcard MIME types to supertype UTIs because |
| 971 |
# typeWithMIMEType_ returns unusable dynamic types for them. |
| 972 |
_wildcard_uti = { |
| 973 |
'image/*': 'public.image', |
| 974 |
'video/*': 'public.movie', |
| 975 |
'audio/*': 'public.audio', |
| 976 |
'text/*': 'public.text', |
| 977 |
} |
| 978 |
content_types = [] |
| 979 |
for mime in file_filter: |
| 980 |
mime_str = str(mime) |
| 981 |
uti_id = _wildcard_uti.get(mime_str) |
| 982 |
if uti_id: |
| 983 |
ut = UTType.typeWithIdentifier_(uti_id) |
| 984 |
else: |
| 985 |
ut = UTType.typeWithMIMEType_(mime_str) |
| 986 |
if ut is not None and not str(ut).startswith('dyn.'): |
| 987 |
content_types.append(ut) |
| 988 |
if content_types: |
| 989 |
open_dlg.setAllowedContentTypes_(content_types) |
| 990 |
else: |
| 991 |
open_dlg.setAllowedFileTypes_(file_filter[0][1]) |
| 992 |
|
| 993 |
if len(file_filter) > 1: |
| 994 |
filter_chooser = BrowserView.FileFilterChooser.alloc().initWithFilter_( |
| 995 |
file_filter |
| 996 |
) |
| 997 |
filter_chooser.setFileDialog_(open_dlg) |
| 998 |
open_dlg.setAccessoryView_(filter_chooser) |
| 999 |
open_dlg.setAccessoryViewDisclosed_(True) |
| 1000 |
|
| 1001 |
if directory: # set initial directory |
| 1002 |
open_dlg.setDirectoryURL_(Foundation.NSURL.fileURLWithPath_(directory)) |
| 1003 |
|
| 1004 |
if open_dlg.runModal() == AppKit.NSFileHandlingPanelOKButton: |
| 1005 |
files = open_dlg.filenames() |
| 1006 |
self._file_name = tuple(files) |
| 1007 |
else: |
| 1008 |
self._file_name = None |
| 1009 |
|
| 1010 |
if not main_thread: |
| 1011 |
self._file_name_semaphore.release() |
| 1012 |
|
| 1013 |
if main_thread: |
| 1014 |
create_dialog(dialog_type, allow_multiple, save_filename) |
| 1015 |
else: |
| 1016 |
AppHelper.callAfter(create_dialog, dialog_type, allow_multiple, save_filename) |
| 1017 |
self._file_name_semaphore.acquire() |
| 1018 |
|
| 1019 |
return self._file_name |
| 1020 |
|
| 1021 |
def _recreate_menus(self, user_menu): |
| 1022 |
main_menu = self._clear_main_menu() |
| 1023 |
|
| 1024 |
# Filter out app menu items (menus with title '__app__') |
| 1025 |
app_menu_items = None |
| 1026 |
regular_menus = None |
| 1027 |
|
| 1028 |
if user_menu: |
| 1029 |
app_menu_items = [] |
| 1030 |
regular_menus = [] |
| 1031 |
|
| 1032 |
for menu in user_menu: |
| 1033 |
if isinstance(menu, Menu) and menu.title == '__app__': |
| 1034 |
# This is an app menu - extract its items |
| 1035 |
app_menu_items.extend(menu.items) |
| 1036 |
else: |
| 1037 |
# Regular menu |
| 1038 |
regular_menus.append(menu) |
| 1039 |
|
| 1040 |
# If no app menu items were found, set to None |
| 1041 |
if not app_menu_items: |
| 1042 |
app_menu_items = None |
| 1043 |
|
| 1044 |
# If no regular menus, set to None |
| 1045 |
if not regular_menus: |
| 1046 |
regular_menus = None |
| 1047 |
|
| 1048 |
self._add_app_menu(main_menu, app_menu_items) |
| 1049 |
|
| 1050 |
if webview_settings['SHOW_DEFAULT_MENUS']: |
| 1051 |
self._add_view_menu(main_menu) |
| 1052 |
self._add_edit_menu(main_menu) |
| 1053 |
|
| 1054 |
self._add_custom_menu(main_menu, regular_menus) |
| 1055 |
|
| 1056 |
return main_menu |
| 1057 |
|
| 1058 |
def _clear_main_menu(self): |
| 1059 |
""" |
| 1060 |
Remove all items from the main menu or create a new one if it doesn't exist. |
| 1061 |
""" |
| 1062 |
mainMenu = BrowserView.app.mainMenu() |
| 1063 |
if mainMenu: |
| 1064 |
mainMenu.removeAllItems() |
| 1065 |
|
| 1066 |
mainMenu = AppKit.NSMenu.alloc().init() |
| 1067 |
|
| 1068 |
return mainMenu |
| 1069 |
|
| 1070 |
def _add_app_menu(self, mainMenu, custom_items=None): |
| 1071 |
""" |
| 1072 |
Create a default Cocoa menu that shows 'Services', 'Hide', |
| 1073 |
'Hide Others', 'Show All', and 'Quit'. Will append the application name |
| 1074 |
to some menu items if it's available. |
| 1075 |
""" |
| 1076 |
|
| 1077 |
# Create an application menu and make it a submenu of the main menu |
| 1078 |
mainAppMenuItem = AppKit.NSMenuItem.alloc().init() |
| 1079 |
# The application menu is the first item, so add this menu ast the first item |
| 1080 |
mainMenu.insertItem_atIndex_(mainAppMenuItem, 0) |
| 1081 |
appMenu = AppKit.NSMenu.alloc().init() |
| 1082 |
mainAppMenuItem.setSubmenu_(appMenu) |
| 1083 |
|
| 1084 |
appMenu.addItemWithTitle_action_keyEquivalent_( |
| 1085 |
self._append_app_name(self.localization['cocoa.menu.about']), |
| 1086 |
'orderFrontStandardAboutPanel:', |
| 1087 |
'', |
| 1088 |
) |
| 1089 |
|
| 1090 |
# Add custom app menu items if provided (between About and Services) |
| 1091 |
if custom_items: |
| 1092 |
appMenu.addItem_(AppKit.NSMenuItem.separatorItem()) |
| 1093 |
self._process_menu_items(custom_items, appMenu) |
| 1094 |
|
| 1095 |
appMenu.addItem_(AppKit.NSMenuItem.separatorItem()) |
| 1096 |
|
| 1097 |
# Set the 'Services' menu for the app and create an app menu item |
| 1098 |
appServicesMenu = AppKit.NSMenu.alloc().init() |
| 1099 |
BrowserView.app.setServicesMenu_(appServicesMenu) |
| 1100 |
servicesMenuItem = appMenu.addItemWithTitle_action_keyEquivalent_( |
| 1101 |
self.localization['cocoa.menu.services'], nil, '' |
| 1102 |
) |
| 1103 |
servicesMenuItem.setSubmenu_(appServicesMenu) |
| 1104 |
|
| 1105 |
appMenu.addItem_(AppKit.NSMenuItem.separatorItem()) |
| 1106 |
|
| 1107 |
# Append the 'Hide', 'Hide Others', and 'Show All' menu items |
| 1108 |
appMenu.addItemWithTitle_action_keyEquivalent_( |
| 1109 |
self._append_app_name(self.localization['cocoa.menu.hide']), 'hide:', 'h' |
| 1110 |
) |
| 1111 |
hideOthersMenuItem = appMenu.addItemWithTitle_action_keyEquivalent_( |
| 1112 |
self.localization['cocoa.menu.hideOthers'], 'hideOtherApplications:', 'h' |
| 1113 |
) |
| 1114 |
hideOthersMenuItem.setKeyEquivalentModifierMask_( |
| 1115 |
AppKit.NSAlternateKeyMask | AppKit.NSCommandKeyMask |
| 1116 |
) |
| 1117 |
appMenu.addItemWithTitle_action_keyEquivalent_( |
| 1118 |
self.localization['cocoa.menu.showAll'], 'unhideAllApplications:', '' |
| 1119 |
) |
| 1120 |
|
| 1121 |
appMenu.addItem_(AppKit.NSMenuItem.separatorItem()) |
| 1122 |
|
| 1123 |
# Append a 'Quit' menu item |
| 1124 |
appMenu.addItemWithTitle_action_keyEquivalent_( |
| 1125 |
self._append_app_name(self.localization['cocoa.menu.quit']), 'terminate:', 'q' |
| 1126 |
) |
| 1127 |
|
| 1128 |
def _add_view_menu(self, mainMenu): |
| 1129 |
""" |
| 1130 |
Create a default View menu that shows 'Enter Full Screen'. |
| 1131 |
""" |
| 1132 |
|
| 1133 |
# Create an View menu and make it a submenu of the main menu |
| 1134 |
viewMenu = AppKit.NSMenu.alloc().init() |
| 1135 |
viewMenu.setTitle_(self.localization['cocoa.menu.view']) |
| 1136 |
viewMenuItem = AppKit.NSMenuItem.alloc().init() |
| 1137 |
viewMenuItem.setSubmenu_(viewMenu) |
| 1138 |
# Make the view menu the first item after the application menu |
| 1139 |
mainMenu.insertItem_atIndex_(viewMenuItem, 1) |
| 1140 |
|
| 1141 |
# TODO: localization of the Enter fullscreen string has no effect |
| 1142 |
fullScreenMenuItem = viewMenu.addItemWithTitle_action_keyEquivalent_( |
| 1143 |
self.localization['cocoa.menu.fullscreen'], 'toggleFullScreen:', 'f' |
| 1144 |
) |
| 1145 |
fullScreenMenuItem.setKeyEquivalentModifierMask_( |
| 1146 |
AppKit.NSControlKeyMask | AppKit.NSCommandKeyMask |
| 1147 |
) |
| 1148 |
|
| 1149 |
def _add_edit_menu(self, mainMenu): |
| 1150 |
""" |
| 1151 |
Create a default Edit menu that shows Copy/Paste/etc. |
| 1152 |
""" |
| 1153 |
# Create an Edit menu and make it a submenu of the main menu |
| 1154 |
editMenu = AppKit.NSMenu.alloc().init() |
| 1155 |
editMenu.setTitle_(self.localization['cocoa.menu.edit']) |
| 1156 |
editMenuItem = AppKit.NSMenuItem.alloc().init() |
| 1157 |
editMenuItem.setSubmenu_(editMenu) |
| 1158 |
# Make the edit menu the first item after the application menu |
| 1159 |
mainMenu.insertItem_atIndex_(editMenuItem, 1) |
| 1160 |
|
| 1161 |
for title, action, keyEquivalent in [ |
| 1162 |
(self.localization['cocoa.menu.cut'], 'cut:', 'x'), |
| 1163 |
(self.localization['cocoa.menu.copy'], 'copy:', 'c'), |
| 1164 |
(self.localization['cocoa.menu.paste'], 'paste:', 'v'), |
| 1165 |
(self.localization['cocoa.menu.selectAll'], 'selectAll:', 'a'), |
| 1166 |
]: |
| 1167 |
editMenu.addItemWithTitle_action_keyEquivalent_(title, action, keyEquivalent) |
| 1168 |
|
| 1169 |
def _process_menu_items(self, menu_items, parent_menu): |
| 1170 |
""" |
| 1171 |
Process menu items and add them to the parent menu. |
| 1172 |
Used for both custom menus and app menu items. |
| 1173 |
""" |
| 1174 |
for item in menu_items: |
| 1175 |
if isinstance(item, MenuSeparator): |
| 1176 |
parent_menu.addItem_(AppKit.NSMenuItem.separatorItem()) |
| 1177 |
elif isinstance(item, MenuAction): |
| 1178 |
# Actions must be registered before application start. Otherwise they are disabled. |
| 1179 |
# Menu handler is a workaround to register actions after application start |
| 1180 |
random_id = str(uuid.uuid4())[:6] |
| 1181 |
# Handle functools.partial objects which don't have __name__ attribute |
| 1182 |
if hasattr(item.function, '__name__'): |
| 1183 |
func_name = item.function.__name__ |
| 1184 |
elif hasattr(item.function, 'func') and hasattr(item.function.func, '__name__'): |
| 1185 |
func_name = item.function.func.__name__ |
| 1186 |
else: |
| 1187 |
func_name = 'anonymous_function' |
| 1188 |
action_id = func_name + '.' + random_id |
| 1189 |
menu_handler.register_action(action_id, item.function) |
| 1190 |
|
| 1191 |
menu_item = AppKit.NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( |
| 1192 |
item.title, 'handleMenuAction:', '' |
| 1193 |
) |
| 1194 |
menu_item.setTarget_(menu_handler) |
| 1195 |
menu_item.setRepresentedObject_(action_id) |
| 1196 |
parent_menu.addItem_(menu_item) |
| 1197 |
elif isinstance(item, Menu): |
| 1198 |
submenu = AppKit.NSMenu.alloc().init() |
| 1199 |
submenu.setTitle_(item.title) |
| 1200 |
menu_item = AppKit.NSMenuItem.alloc().init() |
| 1201 |
menu_item.setTitle_(item.title) |
| 1202 |
menu_item.setSubmenu_(submenu) |
| 1203 |
parent_menu.addItem_(menu_item) |
| 1204 |
|
| 1205 |
self._process_menu_items(item.items, submenu) |
| 1206 |
|
| 1207 |
def _add_custom_menu(self, mainMenu, app_menu_list): |
| 1208 |
""" |
| 1209 |
Create a custom menu for the app menu (MacOS bar menu) |
| 1210 |
""" |
| 1211 |
|
| 1212 |
if app_menu_list is None: |
| 1213 |
return |
| 1214 |
|
| 1215 |
for app_menu in app_menu_list: |
| 1216 |
submenu = AppKit.NSMenu.alloc().init() |
| 1217 |
submenu.setTitle_(app_menu.title) |
| 1218 |
menu_item = AppKit.NSMenuItem.alloc().init() |
| 1219 |
menu_item.setTitle_(app_menu.title) |
| 1220 |
menu_item.setSubmenu_(submenu) |
| 1221 |
mainMenu.addItem_(menu_item) |
| 1222 |
self._process_menu_items(app_menu.items, submenu) |
| 1223 |
|
| 1224 |
def _append_app_name(self, val): |
| 1225 |
""" |
| 1226 |
Append the application name to a string if it's available. If not, the |
| 1227 |
string is returned unchanged. |
| 1228 |
|
| 1229 |
:param str val: The string to append to |
| 1230 |
:return: String with app name appended, or unchanged string |
| 1231 |
:rtype: str |
| 1232 |
""" |
| 1233 |
if 'CFBundleName' in info: |
| 1234 |
val += ' {}'.format(info['CFBundleName']) |
| 1235 |
return val |
| 1236 |
|
| 1237 |
@staticmethod |
| 1238 |
def nscolor_from_hex(hex_string, alpha=1.0): |
| 1239 |
""" |
| 1240 |
Convert given hex color to NSColor. |
| 1241 |
|
| 1242 |
:hex_string: Hex code of the color as #RGB or #RRGGBB |
| 1243 |
""" |
| 1244 |
|
| 1245 |
hex_string = hex_string[1:] # Remove leading hash |
| 1246 |
if len(hex_string) == 3: |
| 1247 |
hex_string = ''.join([c * 2 for c in hex_string]) # 3-digit to 6-digit |
| 1248 |
|
| 1249 |
hex_int = int(hex_string, 16) |
| 1250 |
rgb = ( |
| 1251 |
(hex_int >> 16) & 0xFF, # Red byte |
| 1252 |
(hex_int >> 8) & 0xFF, # Blue byte |
| 1253 |
(hex_int) & 0xFF, # Green byte |
| 1254 |
) |
| 1255 |
rgb = [i / 255.0 for i in rgb] # Normalize to range(0.0, 1.0) |
| 1256 |
|
| 1257 |
return AppKit.NSColor.colorWithSRGBRed_green_blue_alpha_(rgb[0], rgb[1], rgb[2], alpha) |
| 1258 |
|
| 1259 |
@staticmethod |
| 1260 |
def get_instance(attr, value): |
| 1261 |
""" |
| 1262 |
Return a BrowserView instance by the :value of its given :attribute, |
| 1263 |
and None if no match is found. |
| 1264 |
""" |
| 1265 |
for i in list(BrowserView.instances.values()): |
| 1266 |
try: |
| 1267 |
if getattr(i, attr) == value: |
| 1268 |
return i |
| 1269 |
except AttributeError: |
| 1270 |
break |
| 1271 |
|
| 1272 |
return None |
| 1273 |
|
| 1274 |
@staticmethod |
| 1275 |
def display_confirmation_dialog(first_button, second_button, message): |
| 1276 |
AppKit.NSApplication.sharedApplication() |
| 1277 |
AppKit.NSRunningApplication.currentApplication().activateWithOptions_( |
| 1278 |
AppKit.NSApplicationActivateIgnoringOtherApps |
| 1279 |
) |
| 1280 |
alert = AppKit.NSAlert.alloc().init() |
| 1281 |
alert.addButtonWithTitle_(first_button) |
| 1282 |
alert.addButtonWithTitle_(second_button) |
| 1283 |
alert.setMessageText_(message) |
| 1284 |
alert.setAlertStyle_(AppKit.NSWarningAlertStyle) |
| 1285 |
|
| 1286 |
return alert.runModal() == AppKit.NSAlertFirstButtonReturn |
| 1287 |
|
| 1288 |
@staticmethod |
| 1289 |
def display_input_dialog(first_button, second_button, prompt, default_text): |
| 1290 |
AppKit.NSApplication.sharedApplication() |
| 1291 |
AppKit.NSRunningApplication.currentApplication().activateWithOptions_( |
| 1292 |
AppKit.NSApplicationActivateIgnoringOtherApps |
| 1293 |
) |
| 1294 |
alert = AppKit.NSAlert.alloc().init() |
| 1295 |
text_field = AppKit.NSTextField.alloc().initWithFrame_(AppKit.NSMakeRect(0, 0, 240, 24)) |
| 1296 |
text_field.cell().setScrollable_(True) |
| 1297 |
text_field.setStringValue_(default_text) |
| 1298 |
alert.setAccessoryView_(text_field) |
| 1299 |
alert.addButtonWithTitle_(first_button) |
| 1300 |
alert.addButtonWithTitle_(second_button) |
| 1301 |
alert.setMessageText_(prompt) |
| 1302 |
alert.setAlertStyle_(AppKit.NSWarningAlertStyle) |
| 1303 |
|
| 1304 |
if alert.runModal() == AppKit.NSAlertFirstButtonReturn: |
| 1305 |
return text_field.stringValue() |
| 1306 |
else: |
| 1307 |
return None |
| 1308 |
|
| 1309 |
@staticmethod |
| 1310 |
def should_close(window): |
| 1311 |
quit = window.localization['global.quit'] |
| 1312 |
cancel = window.localization['global.cancel'] |
| 1313 |
msg = window.localization['global.quitConfirmation'] |
| 1314 |
|
| 1315 |
should_cancel = window.events.closing.set() |
| 1316 |
if should_cancel: |
| 1317 |
return Foundation.NO |
| 1318 |
if not window.confirm_close or BrowserView.display_confirmation_dialog(quit, cancel, msg): |
| 1319 |
return Foundation.YES |
| 1320 |
return Foundation.NO |
| 1321 |
|
| 1322 |
@staticmethod |
| 1323 |
def print_webview(webview): |
| 1324 |
info = AppKit.NSPrintInfo.sharedPrintInfo().copy() |
| 1325 |
|
| 1326 |
# default print settings used by Safari |
| 1327 |
info.setHorizontalPagination_(AppKit.NSFitPagination) |
| 1328 |
info.setHorizontallyCentered_(Foundation.NO) |
| 1329 |
info.setVerticallyCentered_(Foundation.NO) |
| 1330 |
|
| 1331 |
imageableBounds = info.imageablePageBounds() |
| 1332 |
paperSize = info.paperSize() |
| 1333 |
if Foundation.NSWidth(imageableBounds) > paperSize.width: |
| 1334 |
imageableBounds.origin.x = 0 |
| 1335 |
imageableBounds.size.width = paperSize.width |
| 1336 |
if Foundation.NSHeight(imageableBounds) > paperSize.height: |
| 1337 |
imageableBounds.origin.y = 0 |
| 1338 |
imageableBounds.size.height = paperSize.height |
| 1339 |
|
| 1340 |
info.setBottomMargin_(Foundation.NSMinY(imageableBounds)) |
| 1341 |
info.setTopMargin_( |
| 1342 |
paperSize.height |
| 1343 |
- Foundation.NSMinY(imageableBounds) |
| 1344 |
- Foundation.NSHeight(imageableBounds) |
| 1345 |
) |
| 1346 |
info.setLeftMargin_(Foundation.NSMinX(imageableBounds)) |
| 1347 |
info.setRightMargin_( |
| 1348 |
paperSize.width |
| 1349 |
- Foundation.NSMinX(imageableBounds) |
| 1350 |
- Foundation.NSWidth(imageableBounds) |
| 1351 |
) |
| 1352 |
|
| 1353 |
# show the print panel |
| 1354 |
print_op = webview._printOperationWithPrintInfo_(info) |
| 1355 |
print_op.runOperationModalForWindow_delegate_didRunSelector_contextInfo_( |
| 1356 |
webview.window(), nil, nil, nil |
| 1357 |
) |
| 1358 |
|
| 1359 |
@staticmethod |
| 1360 |
def _open_web_inspector(webview): |
| 1361 |
""" |
| 1362 |
Programmatically open the Web Inspector for the given WKWebView. |
| 1363 |
Uses private WebKit APIs that may not work on all macOS versions. |
| 1364 |
""" |
| 1365 |
try: |
| 1366 |
if hasattr(webview, '_inspector'): |
| 1367 |
inspector = webview._inspector() |
| 1368 |
if inspector and hasattr(inspector, 'show'): |
| 1369 |
inspector.show() |
| 1370 |
return True |
| 1371 |
|
| 1372 |
return False |
| 1373 |
|
| 1374 |
except Exception: |
| 1375 |
return False |
| 1376 |
|
| 1377 |
@staticmethod |
| 1378 |
def quote(string): |
| 1379 |
return string.replace(' ', '%20') |
| 1380 |
|
| 1381 |
|
| 1382 |
class MenuHandler: |
| 1383 |
def __init__(self): |
| 1384 |
self.actions = {} |
| 1385 |
|
| 1386 |
def handleMenuAction_(self, sender): |
| 1387 |
action_id = sender.representedObject() |
| 1388 |
if action_id in self.actions: |
| 1389 |
Thread(target=self.actions[action_id]).start() |
| 1390 |
else: |
| 1391 |
logger.warning(f'Menu cction {action_id} not found') |
| 1392 |
|
| 1393 |
def register_action(self, action_id, action_callable): |
| 1394 |
self.actions[action_id] = action_callable |
| 1395 |
|
| 1396 |
|
| 1397 |
menu_handler = MenuHandler() |
| 1398 |
|
| 1399 |
|
| 1400 |
def setup_app(): |
| 1401 |
pass |
| 1402 |
|
| 1403 |
|
| 1404 |
def get_active_window(): |
| 1405 |
active_window = BrowserView.app.keyWindow() |
| 1406 |
if active_window is None: |
| 1407 |
return None |
| 1408 |
|
| 1409 |
active_window_number = active_window.windowNumber() |
| 1410 |
|
| 1411 |
for uid, browser_view_instance in BrowserView.instances.items(): |
| 1412 |
if browser_view_instance.window.windowNumber() == active_window_number: |
| 1413 |
return browser_view_instance.pywebview_window |
| 1414 |
|
| 1415 |
return None |
| 1416 |
|
| 1417 |
|
| 1418 |
def create_window(window): |
| 1419 |
def create(): |
| 1420 |
browser = BrowserView(window) |
| 1421 |
browser.first_show() |
| 1422 |
|
| 1423 |
if window.uid == 'master': |
| 1424 |
main_thread().pydev_do_not_trace = True # vs code debugger hang fix |
| 1425 |
create() |
| 1426 |
|
| 1427 |
else: |
| 1428 |
AppHelper.callAfter(create) |
| 1429 |
|
| 1430 |
|
| 1431 |
def set_title(title, uid): |
| 1432 |
i = BrowserView.instances.get(uid) |
| 1433 |
if i: |
| 1434 |
i.set_title(title) |
| 1435 |
|
| 1436 |
|
| 1437 |
def create_confirmation_dialog(title, message, uid): |
| 1438 |
def _confirm(): |
| 1439 |
nonlocal result |
| 1440 |
|
| 1441 |
i = BrowserView.instances.get(uid) |
| 1442 |
ok = i.localization['global.ok'] |
| 1443 |
cancel = i.localization['global.cancel'] |
| 1444 |
|
| 1445 |
result = BrowserView.display_confirmation_dialog(ok, cancel, message) |
| 1446 |
semaphore.release() |
| 1447 |
|
| 1448 |
result = False |
| 1449 |
|
| 1450 |
semaphore = Semaphore(0) |
| 1451 |
AppHelper.callAfter(_confirm) |
| 1452 |
semaphore.acquire() |
| 1453 |
|
| 1454 |
return result |
| 1455 |
|
| 1456 |
|
| 1457 |
def create_file_dialog(dialog_type, directory, allow_multiple, save_filename, file_types, uid): |
| 1458 |
file_filter = [] |
| 1459 |
|
| 1460 |
# Parse file_types to obtain allowed file extensions |
| 1461 |
for s in file_types: |
| 1462 |
description, extensions = parse_file_type(s) |
| 1463 |
file_extensions = [i.lstrip('*.') for i in extensions.split(';') if i != '*.*'] |
| 1464 |
file_filter.append([description, file_extensions or []]) |
| 1465 |
|
| 1466 |
i = BrowserView.instances.get(uid) |
| 1467 |
return i.create_file_dialog(dialog_type, directory, allow_multiple, save_filename, file_filter) |
| 1468 |
|
| 1469 |
|
| 1470 |
def load_url(url, uid): |
| 1471 |
i = BrowserView.instances.get(uid) |
| 1472 |
if i: |
| 1473 |
i.load_url(url) |
| 1474 |
|
| 1475 |
|
| 1476 |
def load_html(content, base_uri, uid): |
| 1477 |
i = BrowserView.instances.get(uid) |
| 1478 |
if i: |
| 1479 |
i.load_html(content, base_uri) |
| 1480 |
|
| 1481 |
|
| 1482 |
def destroy_window(uid): |
| 1483 |
i = BrowserView.instances.get(uid) |
| 1484 |
if i: |
| 1485 |
i.destroy() |
| 1486 |
|
| 1487 |
|
| 1488 |
def hide(uid): |
| 1489 |
i = BrowserView.instances.get(uid) |
| 1490 |
if i: |
| 1491 |
i.hide() |
| 1492 |
|
| 1493 |
|
| 1494 |
def show(uid): |
| 1495 |
i = BrowserView.instances.get(uid) |
| 1496 |
if i: |
| 1497 |
i.show() |
| 1498 |
|
| 1499 |
|
| 1500 |
def toggle_fullscreen(uid): |
| 1501 |
i = BrowserView.instances.get(uid) |
| 1502 |
if i: |
| 1503 |
i.toggle_fullscreen() |
| 1504 |
|
| 1505 |
|
| 1506 |
def set_on_top(uid, top): |
| 1507 |
def _set_on_top(): |
| 1508 |
level = AppKit.NSStatusWindowLevel if top else AppKit.NSNormalWindowLevel |
| 1509 |
i.window.setLevel_(level) |
| 1510 |
|
| 1511 |
i = BrowserView.instances.get(uid) |
| 1512 |
if i: |
| 1513 |
AppHelper.callAfter(_set_on_top) |
| 1514 |
|
| 1515 |
|
| 1516 |
def resize(width, height, uid, fix_point): |
| 1517 |
i = BrowserView.instances.get(uid) |
| 1518 |
if i: |
| 1519 |
i.resize(width, height, fix_point) |
| 1520 |
|
| 1521 |
|
| 1522 |
def maximize(uid): |
| 1523 |
i = BrowserView.instances.get(uid) |
| 1524 |
if i: |
| 1525 |
i.maximize() |
| 1526 |
|
| 1527 |
|
| 1528 |
def minimize(uid): |
| 1529 |
i = BrowserView.instances.get(uid) |
| 1530 |
if i: |
| 1531 |
i.minimize() |
| 1532 |
|
| 1533 |
|
| 1534 |
def restore(uid): |
| 1535 |
i = BrowserView.instances.get(uid) |
| 1536 |
if i: |
| 1537 |
i.restore() |
| 1538 |
|
| 1539 |
|
| 1540 |
def move(x, y, uid): |
| 1541 |
i = BrowserView.instances.get(uid) |
| 1542 |
if i: |
| 1543 |
AppHelper.callAfter(i.move, x, y) |
| 1544 |
|
| 1545 |
|
| 1546 |
def get_current_url(uid): |
| 1547 |
i = BrowserView.instances.get(uid) |
| 1548 |
if i: |
| 1549 |
return i.get_current_url() |
| 1550 |
|
| 1551 |
|
| 1552 |
def clear_cookies(uid): |
| 1553 |
i = BrowserView.instances.get(uid) |
| 1554 |
if i: |
| 1555 |
i.clear_cookies() |
| 1556 |
|
| 1557 |
|
| 1558 |
def get_cookies(uid): |
| 1559 |
i = BrowserView.instances.get(uid) |
| 1560 |
if i: |
| 1561 |
return i.get_cookies() |
| 1562 |
|
| 1563 |
|
| 1564 |
def evaluate_js(script, uid, parse_json=True): |
| 1565 |
i = BrowserView.instances.get(uid) |
| 1566 |
if i: |
| 1567 |
return i.evaluate_js(script, parse_json) |
| 1568 |
|
| 1569 |
|
| 1570 |
def get_position(uid): |
| 1571 |
def _position(coordinates): |
| 1572 |
screen_frame = i.screen |
| 1573 |
|
| 1574 |
if screen_frame is None: |
| 1575 |
raise RuntimeError('Failed to obtain screen') |
| 1576 |
|
| 1577 |
window = i.window |
| 1578 |
frame = window.frame() |
| 1579 |
coordinates[0] = int(frame.origin.x) |
| 1580 |
coordinates[1] = int(screen_frame.size.height - frame.origin.y - frame.size.height) |
| 1581 |
semaphore.release() |
| 1582 |
|
| 1583 |
coordinates = [None, None] |
| 1584 |
semaphore = Semaphore(0) |
| 1585 |
|
| 1586 |
i = BrowserView.instances.get(uid) |
| 1587 |
if not i: |
| 1588 |
return None, None |
| 1589 |
|
| 1590 |
try: |
| 1591 |
_position(coordinates) |
| 1592 |
except Exception: |
| 1593 |
AppHelper.callAfter(_position, coordinates) |
| 1594 |
semaphore.acquire() |
| 1595 |
|
| 1596 |
return coordinates |
| 1597 |
|
| 1598 |
|
| 1599 |
def get_size(uid): |
| 1600 |
def _size(dimensions): |
| 1601 |
size = i.window.frame().size |
| 1602 |
dimensions[0] = size.width |
| 1603 |
dimensions[1] = size.height |
| 1604 |
semaphore.release() |
| 1605 |
|
| 1606 |
dimensions = [None, None] |
| 1607 |
semaphore = Semaphore(0) |
| 1608 |
|
| 1609 |
i = BrowserView.instances.get(uid) |
| 1610 |
if not i: |
| 1611 |
return None, None |
| 1612 |
|
| 1613 |
try: |
| 1614 |
_size(dimensions) |
| 1615 |
except Exception: |
| 1616 |
AppHelper.callAfter(_size, dimensions) |
| 1617 |
semaphore.acquire() |
| 1618 |
|
| 1619 |
return dimensions |
| 1620 |
|
| 1621 |
|
| 1622 |
def get_screens(): |
| 1623 |
screens = [ |
| 1624 |
Screen( |
| 1625 |
s.frame().origin.x, |
| 1626 |
s.frame().origin.y, |
| 1627 |
s.frame().size.width, |
| 1628 |
s.frame().size.height, |
| 1629 |
s.frame(), |
| 1630 |
s.backingScaleFactor(), |
| 1631 |
) |
| 1632 |
for s in AppKit.NSScreen.screens() |
| 1633 |
] |
| 1634 |
return screens |
| 1635 |
|
| 1636 |
|
| 1637 |
def add_tls_cert(certfile): |
| 1638 |
# does not auth against the certfile |
| 1639 |
# see webView_didReceiveAuthenticationChallenge_completionHandler_ |
| 1640 |
pass |