-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwkwebview.py
More file actions
1350 lines (1176 loc) · 51.3 KB
/
wkwebview.py
File metadata and controls
1350 lines (1176 loc) · 51.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#coding: utf-8
'''
WKWebView - modern webview for Pythonista
1.0 - https://github.com/mikaelho/pythonista-webview
1.1 - https://gist.github.com/sbbosco/1290f59d79c6963e62bb678f0f05b035
1.2 - Fixes and improvements by M4nw3l
- Improved delegate object support
- Fixed content injection methods misrendering some js
- Extended content injection methods to support reading from files
- Extended javascript argument passing to python and vice versa with full json args serialisation
- Added dispatcher queue thread to avoid deadlocks in callbacks / script message callbacks
e.g eval_js can now be called from on_[script_message_name] handlers, webview_did_finish_load,
webview_did_start_load (if targets loaded)
- Added custom schemes (WkURLSchemeHandler) support by adding a scheme_[schemeName](task) handler to a subclass.
- Added some better handling for being notified when closing
- Added some automatic cleanup on close e.g stopping the dispatcher thread
'''
__version__ = '1.2'
from objc_util import *
import ui, console, webbrowser
import queue, weakref, ctypes, functools, time, os, json, re, sys
from types import SimpleNamespace
import threading
import time
import logging
log = logging.getLogger(__name__)
# Helpers for invoking ObjC function blocks with no return value
class _block_descriptor(Structure):
_fields_ = [('reserved', c_ulong), ('size', c_ulong),
('copy_helper', c_void_p), ('dispose_helper', c_void_p),
('signature', c_char_p)]
def _block_literal_fields(*arg_types):
return [('isa', c_void_p), ('flags', c_int), ('reserved', c_int),
('invoke', ctypes.CFUNCTYPE(c_void_p, c_void_p, *arg_types)),
('descriptor', _block_descriptor)]
class WKWebView(ui.View):
# Data detector constants
NONE = 0
PHONE_NUMBER = 1
LINK = 1 << 1
ADDRESS = 1 << 2
CALENDAR_EVENT = 1 << 3
TRACKING_NUMBER = 1 << 4
FLIGHT_NUMBER = 1 << 5
LOOKUP_SUGGESTION = 1 << 6
ALL = 18446744073709551615 # NSUIntegerMax
# Global webview index for console
webviews = []
console_view = UIApplication.sharedApplication().\
keyWindow().rootViewController().\
accessoryViewController().\
consoleViewController()
def __init__(self,
swipe_navigation=False,
data_detectors=NONE,
log_js_evals=False,
respect_safe_areas=False,
inline_media=None,
airplay_media=True,
pip_media=True,
**kwargs):
self._init_webview()
WKWebView.webviews.append(self)
self.delegate = None
self.log_js_evals = log_js_evals
self.respect_safe_areas = respect_safe_areas
super().__init__(**kwargs)
self.request_url = ''
self.requested_url = ''
self.current_url = ''
self.eval_js_queue = queue.Queue()
self.dispatcher = WKWebView._webviewDispatcher()
custom_message_handler = WKWebView.CustomMessageHandler.\
new().autorelease()
retain_global(custom_message_handler)
custom_message_handler._pythonistawebview = weakref.ref(self)
self.custom_message_handler = custom_message_handler
user_content_controller = WKWebView.WKUserContentController.\
new().autorelease()
self.user_content_controller = user_content_controller
for key in dir(self):
if key.startswith('on_'):
message_name = key[3:]
user_content_controller.addScriptMessageHandler_name_(
custom_message_handler, message_name)
webview_config = WKWebView.WKWebViewConfiguration.new().autorelease()
webview_config.websiteDataStore = WKWebView.WKWebsiteDataStore.defaultDataStore(
)
webview_config.userContentController = user_content_controller
data_detectors = sum(data_detectors) if type(data_detectors) is tuple \
else data_detectors
webview_config.setDataDetectorTypes_(data_detectors)
# Must be set to True to get real js
# errors, in combination with setting a
# base directory in the case of load_html
webview_config.preferences().setValue_forKey_(
True, 'allowFileAccessFromFileURLs')
#webview_config.setValue_forKey_(True, '_allowUniversalAccessFromFileURLs')
if inline_media is not None:
webview_config.allowsInlineMediaPlayback = inline_media
else:
current_device = WKWebView.UIDevice.currentDevice()
webview_config.allowsInlineMediaPlayback = current_device.userInterfaceIdiom(
) == 1
webview_config.allowsAirPlayForMediaPlayback = airplay_media
webview_config.allowsPictureInPictureMediaPlayback = pip_media
nav_delegate = WKWebView.CustomNavigationDelegate.new()
retain_global(nav_delegate)
nav_delegate._pythonistawebview = weakref.ref(self)
ui_delegate = WKWebView.CustomUIDelegate.new()
retain_global(ui_delegate)
ui_delegate._pythonistawebview = weakref.ref(self)
url_scheme_handler = WKWebView.CustomURLSchemeHandler.new()
retain_global(url_scheme_handler)
url_scheme_handler._pythonistawebview = weakref.ref(self)
self.url_scheme_handlers = {}
for key in dir(self):
if key.startswith('scheme_'):
scheme = key[7:]
if not scheme in self.url_scheme_handlers:
if WKWebView.WKWebView.handlesURLScheme_(scheme):
raise Exception(
"WKURLSchemeHandler cannot create custom scheme for '{scheme}'"
)
self.url_scheme_handlers[scheme] = getattr(self, key)
webview_config.setURLSchemeHandler_forURLScheme_(
url_scheme_handler, scheme)
self.url_scheme_task_pool = WKWebView._urlSchemeTaskPool(
self.url_scheme_handlers)
self.init_webview_config(webview_config)
self._create_webview(webview_config, nav_delegate, ui_delegate)
self.swipe_navigation = swipe_navigation
self.add_script(WKWebView.js_logging_script,
add_to_end=False,
all_frames=True)
self.dispatcher.start()
self.init()
def init(self): # post init handler for convenience in derived instances
pass
def init_webview_config(self, webview_config):
pass
def did_load(self):
pass
def will_close(self):
self.dispatcher.stop(join=False)
@on_main_thread
def close(self):
self.will_close()
self.dispatcher.stop(join=False)
super().close()
@on_main_thread
def _create_webview(self, webview_config, nav_delegate, ui_delegate):
frame = CGRect(CGPoint(0, 0), CGSize(self.width, self.height))
self.webview = WKWebView.WKWebView.alloc(
).initWithFrame_configuration_(frame, webview_config).autorelease()
self.webview.autoresizingMask = 2 + 16 # WH
self.webview.setNavigationDelegate_(nav_delegate)
self.webview.setUIDelegate_(ui_delegate)
self.objc_instance.addSubview_(self.webview)
@on_main_thread
def _init_webview(self):
# This work around appears to prevent a pythonista app crash
# it is probably initialising some memory / handles somewhere in UIKit
# before _create_webview sets up the real WKWebView instance
frame = CGRect(CGPoint(0, 0), CGSize(self.width, self.height))
webview = WKWebView.WKWebView.alloc().initWithFrame_(
frame).autorelease()
del webview
def layout(self):
if self.respect_safe_areas:
self.update_safe_area_insets()
@on_main_thread
def load_url(self, url, no_cache=False, timeout=10, clear_cache=False):
""" Loads the contents of the given url
asynchronously.
If the url starts with `file://`, loads a local file. If the remaining
url starts with `/`, path starts from Pythonista root.
For remote (non-file) requests, there are
two additional options:
* Set `no_cache` to `True` to skip the local cache, default is `False`
* Set `timeout` to a specific timeout value, default is 10 (seconds)
"""
def _load_url():
self._load_url(url, no_cache, timeout)
if clear_cache:
self.clear_cache(_load_url)
else:
_load_url()
def _load_url(self, url, no_cache=False, timeout=10):
self.request_url = url
if url.startswith('file://'):
file_path = url[7:]
if file_path.startswith('/'):
root = os.path.expanduser('~')
if not file_path.startswith(root):
file_path = os.path.join(root, file_path[1:])
else:
current_working_directory = os.path.dirname(os.getcwd())
file_path = os.path.join(current_working_directory, file_path)
dir_only = os.path.dirname(file_path)
file_path = NSURL.fileURLWithPath_(file_path)
dir_only = NSURL.fileURLWithPath_(dir_only)
self.webview.loadFileURL_allowingReadAccessToURL_(
file_path, dir_only)
else:
cache_policy = 1 if no_cache else 0
self.webview.loadRequest_(
WKWebView.NSURLRequest.
requestWithURL_cachePolicy_timeoutInterval_(
nsurl(url), cache_policy, timeout))
@on_main_thread
def load_html(self, html):
# Need to set a base directory to get
# real js errors
self.request_url = 'html:raw'
current_working_directory = os.path.dirname(os.getcwd())
root_dir = NSURL.fileURLWithPath_(current_working_directory)
self.webview.loadHTMLString_baseURL_(html, root_dir)
@on_main_thread
def load_file(self, path, root='/'):
if root == '/':
root = __file__
elif not os.path.isabs(root):
root = os.path.join(os.path.dirname(__file__), root)
if os.path.isfile(root):
root = os.path.dirname(root)
self.load_url('file://' + os.path.join(root, path), no_cache=True)
def eval_js(self, js):
self.eval_js_async(js, self._eval_js_sync_callback)
value = self.eval_js_queue.get()
return value
evaluate_javascript = eval_js
@on_main_thread
def _eval_js_sync_callback(self, value):
self.eval_js_queue.put(value)
@ui.in_background
def eval_js_async(self, js, callback=None):
if self.log_js_evals:
self.console.message({'level': 'code', 'content': js})
handler = functools.partial(WKWebView._handle_completion, callback,
self)
block = ObjCBlock(handler,
restype=None,
argtypes=[c_void_p, c_void_p, c_void_p])
retain_global(block)
self.webview.evaluateJavaScript_completionHandler_(js, block)
@ui.in_background
def clear_cache_async(self, completion_handler=None):
store = WKWebView.WKWebsiteDataStore.defaultDataStore()
data_types = WKWebView.WKWebsiteDataStore.allWebsiteDataTypes()
from_start = WKWebView.NSDate.dateWithTimeIntervalSince1970_(0)
@ui.in_background
def _completion_handler(*args):
if completion_handler:
completion_handler()
store.removeDataOfTypes_modifiedSince_completionHandler_(
data_types, from_start, _completion_handler)
@on_main_thread
def clear_cache(self, completion_handler=None):
self.clear_cache_async(completion_handler)
def _handle_completion(callback, webview, _cmd, _obj, _err):
result = str(ObjCInstance(_obj)) if _obj else None
if webview.log_js_evals:
webview._message({'level': 'raw', 'content': str(result)})
if callback:
callback(result)
def add_script(self, js_script, add_to_end=True, all_frames=False):
location = 1 if add_to_end else 0
wk_script = WKWebView.WKUserScript.alloc().\
initWithSource_injectionTime_forMainFrameOnly_(
js_script, location, all_frames)
self.user_content_controller.addUserScript_(wk_script)
def add_style(self, css, add_to_end=True):
"""
Convenience method to add a style tag with the given css, to every
page loaded by the view.
"""
css = css.replace("'", "\'")
js = "var style = document.createElement('style');\n"
js = js + f"style.innerHTML = `{css}`;\n"
js = js + "document.getElementsByTagName('head')[0].appendChild(style);"
self.add_script(js, add_to_end)
def add_user_content_file(self, filename, root='/', add_to_end=True):
if root == '/':
root = __file__
if os.path.isfile(root):
root = os.path.dirname(root)
content = ''
with open(os.path.join(root, filename), 'r') as content_file:
content = content_file.read()
if filename.endswith(".js"):
self.add_script(content, add_to_end)
elif filename.endswith(".css"):
self.add_style(content)
def add_meta(self, name, content):
"""
Convenience method to add a meta tag with the given name and content,
to every page loaded by the view."
"""
name = name.replace("'", "\'")
content = content.replace("'", "\'")
js = "var meta = document.createElement('meta');"
js = js + f"meta.setAttribute('name', '{name}');"
js = js + f"meta.setAttribute('content', '{content}');"
js = js + "document.getElementsByTagName('head')[0].appendChild(meta);"
self.add_script(js, add_to_end=True)
@on_main_thread
def add_script_message_handler_name(self, name):
self.user_content_controller.addScriptMessageHandler_name_(
self.custom_message_handler, name)
def disable_zoom(self):
name = 'viewport'
content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no'
self.add_meta(name, content)
def disable_user_selection(self):
css = '* { -webkit-user-select: none; }'
self.add_style(css)
def disable_font_resizing(self):
css = 'body { -webkit-text-size-adjust: none; }'
self.add_style(css)
def disable_scrolling(self):
"""
Included for consistency with the other `disable_x` methods, this is
equivalent to setting `scroll_enabled` to false."
"""
self.scroll_enabled = False
def disable_all(self):
"""
Convenience method that calls all the `disable_x` methods to make the
loaded pages act more like an app."
"""
self.disable_zoom()
self.disable_scrolling()
self.disable_user_selection()
self.disable_font_resizing()
@property
def delegate(self):
return self._delegate
@delegate.setter
def delegate(self, value):
self._delegate = value
if not self._delegate is None:
for key in dir(self._delegate):
if key.startswith('webview_on_'):
message_name = key[11:]
self.add_script_message_handler_name(message_name)
@property
def user_agent(self):
"Must be called outside main thread"
return self.eval_js('navigator.userAgent')
@on_main_thread
def _get_user_agent2(self):
return str(self.webview.customUserAgent())
@user_agent.setter
def user_agent(self, value):
value = str(value)
self._set_user_agent(value)
@on_main_thread
def _set_user_agent(self, value):
self.webview.setCustomUserAgent_(value)
@on_main_thread
def go_back(self):
self.webview.goBack()
@on_main_thread
def go_forward(self):
self.webview.goForward()
@on_main_thread
def reload(self):
self.webview.reload()
@on_main_thread
def stop(self):
self.webview.stopLoading()
@property
def scales_page_to_fit(self):
raise NotImplementedError(
'Not supported on iOS. Use the "disable_" methods instead.')
@scales_page_to_fit.setter
def scales_page_to_fit(self, value):
raise NotImplementedError(
'Not supported on iOS. Use the "disable_" methods instead.')
@property
def swipe_navigation(self):
return self.webview.allowsBackForwardNavigationGestures()
@swipe_navigation.setter
def swipe_navigation(self, value):
self.webview.setAllowsBackForwardNavigationGestures_(value == True)
@property
def scroll_enabled(self):
"""
Controls whether scrolling is enabled.
Disabling scrolling is applicable for pages that need to look like an
app.
"""
return self.webview.scrollView().scrollEnabled()
@scroll_enabled.setter
def scroll_enabled(self, value):
self.webview.scrollView().setScrollEnabled_(value == True)
def update_safe_area_insets(self):
insets = self.objc_instance.safeAreaInsets()
self.frame = self.frame.inset(insets.top, insets.left, insets.bottom,
insets.right)
def _javascript_alert(self, host, message):
console.alert(host, message, 'OK', hide_cancel_button=True)
def _javascript_confirm(self, host, message):
try:
console.alert(host, message, 'OK')
return True
except KeyboardInterrupt:
return False
def _javascript_prompt(self, host, prompt, default_text):
try:
return console.input_alert(host, prompt, default_text, 'OK')
except KeyboardInterrupt:
return None
js_logging_script = '''console = new Object();
console.info = function(message) {
window.webkit.messageHandlers.javascript_console_message.postMessage(
JSON.stringify({ level: "info", content: message})
); return false; };
console.log = function(message) {
window.webkit.messageHandlers.javascript_console_message.postMessage(
JSON.stringify({ level: "log", content: message})
); return false; };
console.warn = function(message) {
window.webkit.messageHandlers.javascript_console_message.postMessage(
JSON.stringify({ level: "warn", content: message})
); return false; };
console.error = function(message) {
window.webkit.messageHandlers.javascript_console_message.postMessage(
JSON.stringify({ level: "error", content: message})
); return false; };
window.onerror = function(error, url, line, col, errorobj) {
console.error(
"" + error + " (" + url + ", line: " + line + ", column: " + col + ")"
);
};'''
def on_javascript_console_message(self, level, content):
log_message = {'level': level, 'content': content}
self._message(log_message)
def _message(self, message):
level, content = message['level'], message['content']
if level == 'code':
print('>>> ' + content)
elif level == 'raw':
print(content)
else:
#print(level.upper() + ': ' + content)
print(level.upper() + ': ' + str(content))
class Theme:
@classmethod
def get_theme(cls):
theme_dict = json.loads(cls.clean_json(cls.get_theme_data()))
theme = SimpleNamespace(**theme_dict)
theme.dict = theme_dict
return theme
@classmethod
def get_theme_data(cls):
# Name of current theme
defaults = ObjCClass("NSUserDefaults").standardUserDefaults()
name = str(defaults.objectForKey_("ThemeName"))
# Theme is user-created
if name.startswith("User:"):
home = os.getenv("CFFIXED_USER_HOME")
user_themes_path = os.path.join(
home, "Library/Application Support/Themes")
theme_path = os.path.join(user_themes_path, name[5:] + ".json")
# Theme is built-in
else:
res_path = str(
ObjCClass("NSBundle").mainBundle().resourcePath())
theme_path = os.path.join(res_path, "Themes2/%s.json" % name)
# Read theme file
with open(theme_path, "r") as f:
data = f.read()
# Return contents
return data
@classmethod
def clean_json(cls, string):
# From http://stackoverflow.com/questions/23705304
string = re.sub(r',[ \t\r\n]+}', "}", string)
string = re.sub(r',[ \t\r\n]+\]', "]", string)
return string
@classmethod
def console(cls, webview_index=0):
webview = WKWebView.webviews[webview_index]
theme = WKWebView.Theme.get_theme()
print('Welcome to WKWebView console.')
print('Evaluate javascript in any active WKWebView.')
print('Special commands: list, switch #, load <url>, quit')
console.set_color(*ui.parse_color(theme.tint)[:3])
while True:
value = input('js> ').strip()
cls.console_view.history().insertObject_atIndex_(
ns(value + '\n'), 0)
if value == 'quit':
break
if value == 'list':
for i in range(len(WKWebView.webviews)):
wv = WKWebView.webviews[i]
print(i, '-', wv.name, '-', wv.eval_js('document.title'))
elif value.startswith('switch '):
i = int(value[len('switch '):])
webview = WKWebView.webviews[i]
elif value.startswith('load '):
url = value[len('load '):]
webview.load_url(url)
else:
print(webview.eval_js(value))
console.set_color(*ui.parse_color(theme.default_text)[:3])
# MAIN OBJC SECTION
WKWebView = ObjCClass('WKWebView')
UIViewController = ObjCClass('UIViewController')
WKWebViewConfiguration = ObjCClass('WKWebViewConfiguration')
WKUserContentController = ObjCClass('WKUserContentController')
WKContentRuleListStore = ObjCClass('WKContentRuleListStore')
NSURLRequest = ObjCClass('NSURLRequest')
WKUserScript = ObjCClass('WKUserScript')
WKWebsiteDataStore = ObjCClass('WKWebsiteDataStore')
NSDate = ObjCClass('NSDate')
NSHTTPURLResponse = ObjCClass('NSHTTPURLResponse')
UIDevice = ObjCClass('UIDevice')
# Navigation delegate
class _block_decision_handler(Structure):
_fields_ = _block_literal_fields(ctypes.c_long)
#@ui.in_background
def webView_decidePolicyForNavigationAction_decisionHandler_(
_self, _cmd, _webview, _navigation_action, _decision_handler):
delegate_instance = ObjCInstance(_self)
webview = delegate_instance._pythonistawebview()
deleg = webview.delegate
nav_action = ObjCInstance(_navigation_action)
ns_url = nav_action.request().URL()
url = str(ns_url)
nav_type = int(nav_action.navigationType())
allow = True
scheme = str(ns_url.scheme())
webview.requested_url = url
if url != 'about:blank':
try:
if allow and hasattr(webview, "webview_should_start_load"):
allow = webview.webview_should_start_load(
url, scheme, nav_type)
if allow and deleg is not None:
if hasattr(deleg, 'webview_should_start_load'):
allow = deleg.webview_should_start_load(
webview, url, scheme, nav_type)
if allow and not scheme in webview.url_scheme_handlers and not WKWebView.WKWebView.handlesURLScheme_(
scheme):
allow = False
webview.current_url = url
webbrowser.open(url)
except Exception as e:
log.error(f'WKWebView exception in should_start_load handler',
e)
log.info(f'WKWebView {url} {allow}')
allow_or_cancel = 1 if allow else 0
decision_handler = ObjCInstance(_decision_handler)
retain_global(decision_handler)
blk = WKWebView._block_decision_handler.from_address(_decision_handler)
blk.invoke(_decision_handler,
1) #allow_or_cancel - dissallowing seems to break closing
if not allow:
def reload_blank(webview):
webview.stop()
webview.load_url('about:blank')
webview.dispatcher.dispatch(reload_blank, webview)
f = webView_decidePolicyForNavigationAction_decisionHandler_
f.argtypes = [c_void_p] * 3
f.restype = None
f.encoding = b'v@:@@@?'
# thread dispatcher
class _webviewDispatcher(threading.Thread):
def __init__(self):
super().__init__()
self.daemon = True
self.running = False
self.queue = []
class _dispatchMessage:
def __init__(self, func, *args, **kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
def dispatch(self, func, *args, **kwargs):
self.queue.append(self._dispatchMessage(func, *args, **kwargs))
def invoke(self, instance, name, *args, **kwargs):
def _instance_invoke(instance, name, *args, **kwargs):
func = getattr(instance, name) if hasattr(instance,
name) else None
if func:
func(*args, **kwargs)
deleg = instance.delegate if hasattr(instance,
'delegate') else None
func = getattr(
deleg, name) if deleg and hasattr(deleg, name) else None
if func:
func(instance, *args, **kwargs)
self.dispatch(_instance_invoke, instance, name, *args, **kwargs)
def run(self):
self.running = True
while self.running:
if len(self.queue) < 1:
time.sleep(0.01)
else:
while len(self.queue) > 0 and self.running:
msg = self.queue.pop(0)
func = msg.func
args = msg.args
kwargs = msg.kwargs
if func:
try:
func(*args, **kwargs)
except Exception as e:
log.error(
f"WKWebView dispatch error {e}, {func}, {args}, {kwargs}"
)
def stop(self, join=True):
self.running = False
if join:
self.join()
# https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html
def webView_didCommitNavigation_(_self, _cmd, _webview, _navigation):
delegate_instance = ObjCInstance(_self)
webview = delegate_instance._pythonistawebview()
webview.dispatcher.invoke(webview, 'webview_did_start_load',
webview.requested_url)
def webView_didFinishNavigation_(_self, _cmd, _webview, _navigation):
delegate_instance = ObjCInstance(_self)
webview = delegate_instance._pythonistawebview()
webview.current_url = webview.requested_url
webview.dispatcher.invoke(webview, 'webview_did_finish_load',
webview.current_url)
def webView_didFailNavigation_withError_(_self, _cmd, _webview,
_navigation, _error):
delegate_instance = ObjCInstance(_self)
webview = delegate_instance._pythonistawebview()
deleg = webview.delegate
err = ObjCInstance(_error)
error_code = int(err.code())
error_msg = str(err.localizedDescription())
url = webview.requested_url if not webview.requested_url is None else webview.request_url
handle = False
if hasattr(webview, 'webview_did_fail_load'):
handle = True
if deleg is not None and hasattr(deleg, 'webview_did_fail_load'):
handle = True
if handle:
webview.dispatcher.invoke(webview, 'webview_did_fail_load', url,
error_code, error_msg)
else:
log.exception(
RuntimeError(
f'WKWebView load failed to load {url} with code {error_code}: {error_msg}'
))
def webView_didFailProvisionalNavigation_withError_(
_self, _cmd, _webview, _navigation, _error):
WKWebView.webView_didFailNavigation_withError_(_self, _cmd, _webview,
_navigation, _error)
CustomNavigationDelegate = create_objc_class(
'CustomNavigationDelegate',
superclass=NSObject,
methods=[
webView_didCommitNavigation_, webView_didFinishNavigation_,
webView_didFailNavigation_withError_,
webView_didFailProvisionalNavigation_withError_,
webView_decidePolicyForNavigationAction_decisionHandler_
],
protocols=['WKNavigationDelegate'])
# Script message handler
def userContentController_didReceiveScriptMessage_(_self, _cmd,
_userContentController,
_message):
controller_instance = ObjCInstance(_self)
webview = controller_instance._pythonistawebview()
wk_message = ObjCInstance(_message)
name = str(wk_message.name())
content = str(wk_message.body())
handler = getattr(webview, 'on_' + name, None)
deleg = webview.delegate
deleg_handler = getattr(deleg, 'webview_on_' +
name, None) if deleg else None
def handle_script_message(webview, name, content, handler,
deleg_handler):
#print("script message handler ",name,content,handler,deleg_handler)
args = []
kwargs = {}
try:
data = json.loads(content)
if 'args' in data or 'kwargs' in data:
args = data['args'] if 'args' in data else args
kwargs = data['kwargs'] if 'kwargs' in data else kwargs
else:
kwargs = data
except:
args.append(content)
handled = False
if handler:
handler(*args, **kwargs)
handled = True
if deleg_handler:
deleg_handler(webview, *args, **kwargs)
handled = True
if not handled:
raise Exception(
f'Unhandled message from script - name: {name}, content: {content}'
)
webview.dispatcher.dispatch(handle_script_message, webview, name,
content, handler, deleg_handler)
CustomMessageHandler = create_objc_class(
'CustomMessageHandler',
UIViewController,
methods=[userContentController_didReceiveScriptMessage_],
protocols=['WKScriptMessageHandler'])
# UI delegate (for alerts etc.)
class _block_alert_completion(Structure):
_fields_ = _block_literal_fields()
def webView_runJavaScriptAlertPanelWithMessage_initiatedByFrame_completionHandler_(
_self, _cmd, _webview, _message, _frame, _completion_handler):
delegate_instance = ObjCInstance(_self)
webview = delegate_instance._pythonistawebview()
message = str(ObjCInstance(_message))
host = str(ObjCInstance(_frame).request().URL().host())
webview._javascript_alert(host, message)
#console.alert(host, message, 'OK', hide_cancel_button=True)
completion_handler = ObjCInstance(_completion_handler)
retain_global(completion_handler)
blk = WKWebView._block_alert_completion.from_address(
_completion_handler)
blk.invoke(_completion_handler)
f = webView_runJavaScriptAlertPanelWithMessage_initiatedByFrame_completionHandler_
f.argtypes = [c_void_p] * 4
f.restype = None
f.encoding = b'v@:@@@@?'
class _block_confirm_completion(Structure):
_fields_ = _block_literal_fields(ctypes.c_bool)
def webView_runJavaScriptConfirmPanelWithMessage_initiatedByFrame_completionHandler_(
_self, _cmd, _webview, _message, _frame, _completion_handler):
delegate_instance = ObjCInstance(_self)
webview = delegate_instance._pythonistawebview()
message = str(ObjCInstance(_message))
host = str(ObjCInstance(_frame).request().URL().host())
result = webview._javascript_confirm(host, message)
completion_handler = ObjCInstance(_completion_handler)
retain_global(completion_handler)
blk = WKWebView._block_confirm_completion.from_address(
_completion_handler)
blk.invoke(_completion_handler, result)
f = webView_runJavaScriptConfirmPanelWithMessage_initiatedByFrame_completionHandler_
f.argtypes = [c_void_p] * 4
f.restype = None
f.encoding = b'v@:@@@@?'
class _block_text_completion(Structure):
_fields_ = _block_literal_fields(c_void_p)
def webView_runJavaScriptTextInputPanelWithPrompt_defaultText_initiatedByFrame_completionHandler_(
_self, _cmd, _webview, _prompt, _default_text, _frame,
_completion_handler):
delegate_instance = ObjCInstance(_self)
webview = delegate_instance._pythonistawebview()
prompt = str(ObjCInstance(_prompt))
default_text = str(ObjCInstance(_default_text))
host = str(ObjCInstance(_frame).request().URL().host())
result = webview._javascript_prompt(host, prompt, default_text)
completion_handler = ObjCInstance(_completion_handler)
retain_global(completion_handler)
blk = WKWebView._block_text_completion.from_address(
_completion_handler)
blk.invoke(_completion_handler, ns(result))
f = webView_runJavaScriptTextInputPanelWithPrompt_defaultText_initiatedByFrame_completionHandler_
f.argtypes = [c_void_p] * 5
f.restype = None
f.encoding = b'v@:@@@@@?'
CustomUIDelegate = create_objc_class(
'CustomUIDelegate',
superclass=NSObject,
methods=[
webView_runJavaScriptAlertPanelWithMessage_initiatedByFrame_completionHandler_,
webView_runJavaScriptConfirmPanelWithMessage_initiatedByFrame_completionHandler_,
webView_runJavaScriptTextInputPanelWithPrompt_defaultText_initiatedByFrame_completionHandler_
],
protocols=['WKUIDelegate'])
class _urlSchemeTaskPool:
class _urlSchemeTask:
def __init__(self, pool, id, task, request):
self.pool = pool
self.id = id
self.task = task
self.request = request
self.method = str(request.HTTPMethod())
self.body = None # obtained later in thread
url = request.URL()
self.request_url = url
self.url = str(url.absoluteString())
self.scheme = str(url.scheme())
self.host = str(url.host())
self.port = str(url.port())
path = str(url.path())
path = str(url.relativeString()) if path == '' else path
if path.startswith(self.scheme + '://'):
path = path[len(self.scheme) + 3:]
if path != self.host and path.startswith(self.host):
path = path[len(self.host):]
self.path = path
self.query = str(url.query())
self.user = str(url.user())
self.password = str(url.password())
self.headers = {}
headers = request.allHTTPHeaderFields()
for key in headers.allKeys():
self.headers[str(key)] = str(headers[key])
self.response = None
self.receive_response = None
self.finished = False
self.handler = None
self.running = False
self.cancel = False
self.successful = False
self.started = False
self.terminated = False
self.error = None
def run(self):
self.started = True
self.running = True
try:
body = self.request.HTTPBody()
if body:
self.body = nsdata_to_bytes(body)
self.handler(self)
self.successful = True
except Exception as e:
self.error = e
log.error(
f"WKWebView WKURLSchemeTask error processing '{self.url}' {e}"
)
finally:
self.running = False
self.terminated = True
self.pool.task_cleanup(self)
def receive(self,
response=None,
data=None,
content_type=None,
status_code=200,
headers={}):
if self.cancel:
return
if self.finished:
raise Exception('Receive must not be called after finish.')
if response is None and not self.response is None and self.receive_response is None:
response = self.response
if data is None and not response is None:
data = response.get('data', None)
if response is None and data is None:
raise Exception(
'Must specify one or both of response and response data'
)
if not response is None or (not data is None
and self.receive_response is None):
if not self.receive_response is None:
raise Exception('Response header already sent')
response = {} if response is None else response
url = response.get('url', self.url)
status = response.get('status', status_code)
version = response.get('version', 'HTTP/1.1')
response_headers = response.get('headers', {})