zebkit 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
zebkit/__init__.py ADDED
@@ -0,0 +1,2672 @@
1
+ """zebkit for Python: the engine, and what is inside it, through ctypes.
2
+
3
+ import zebkit
4
+
5
+ def ready():
6
+ view = zebkit.View("https://example.com/")
7
+ view.on_load(lambda event, url: event == zebkit.LOAD_FINISHED and
8
+ view.evaluate("document.title", lambda title, error: print(title)))
9
+
10
+ zebkit.main(ready)
11
+
12
+ The services work without the engine running:
13
+
14
+ packed = zebkit.compress(b"..." * 100, "zstd")
15
+ zebkit.digest(b"abc", "sha256").hex()
16
+ zebkit.url_part("../b", "https://example.com/a/", "spec")
17
+
18
+ The library is libzebkit.so.1 (Zebkit.framework on macOS, zebkit.dll on Windows) in $ZEBKIT_DIR,
19
+ or beside this package, or in the zebkit repository's package of the slim
20
+ profile (slim-macos on macOS).
21
+
22
+ Threads: everything is for the thread that called main(), and callbacks
23
+ run on it; post() runs a function there from any thread.
24
+ """
25
+
26
+ import ctypes
27
+ import json
28
+ import os
29
+ import pathlib
30
+ import sys
31
+
32
+ __all__ = [
33
+ "View", "PermissionRequest", "NavigationRequest", "CertificateRequest", "HttpAuthRequest", "DownloadRequest", "ClientCertificateRequest", "FileChooserRequest", "MediaAccessRequest", "NetworkRequest", "NetworkStream", "main", "init", "pump", "shutdown", "set_wakeup", "quit", "post", "version", "engine_version", "is_headless", "set_engine_settings", "engine_settings",
34
+ "set_cookie_storage", "set_cookie_encryption_key", "cdp_listen", "cdp_port", "cdp_url", "cdp_stop", "fetch",
35
+ "compress", "decompress", "digest", "hmac", "random_bytes", "aes_gcm_seal", "aes_gcm_open",
36
+ "url_part", "registrable_domain", "image_decode", "image_encode", "icu_init", "Error",
37
+ "LOAD_STARTED", "LOAD_COMMITTED", "LOAD_FINISHED", "LOAD_FAILED",
38
+ "ALLOW_APP", "ALLOW_FETCH", "ALLOW_FILES", "ALLOW_COMPRESS", "ALLOW_CRYPTO", "ALLOW_IMAGE",
39
+ "ALLOW_URL", "ALLOW_PDF", "ALLOW_ALL",
40
+ "Canvas", "Font", "shape_text", "PdfHooks", "pdf_hooks", "remove_pdf_hook", "pdf_filter_input",
41
+ "Pdf", "RENDER_ANNOTATIONS", "RENDER_FORMS", "RENDER_LCD_TEXT", "RENDER_GRAYSCALE", "RENDER_PRINTING",
42
+ "RENDER_NO_SMOOTHING", "Request", "scheme_register", "scheme_handle",
43
+ "SCHEME_STANDARD", "SCHEME_SECURE", "SCHEME_FETCH", "SCHEME_BYPASS_CSP",
44
+ "app_set_menu", "app_update_menu_item", "app_menu", "app_set_badge", "app_set_progress",
45
+ "app_request_attention", "app_set_dock_menu", "app_on_open_files", "app_on_reopen", "app_on_quit_request",
46
+ ]
47
+
48
+ LOAD_STARTED, LOAD_COMMITTED, LOAD_FINISHED, LOAD_FAILED = 0, 1, 2, 3
49
+ ALLOW_APP, ALLOW_FETCH, ALLOW_FILES, ALLOW_COMPRESS = 1, 2, 4, 8
50
+ ALLOW_CRYPTO, ALLOW_IMAGE, ALLOW_URL, ALLOW_PDF, ALLOW_ALL = 16, 32, 64, 128, 0xFF
51
+
52
+ _COMPRESSION = {"gzip": 1, "zlib": 2, "deflate": 2, "deflate-raw": 3, "brotli": 4, "br": 4, "zstd": 5}
53
+ _DIGEST = {"sha1": 1, "sha256": 2, "sha384": 3, "sha512": 4}
54
+ _IMAGE = {"png": 1, "jpeg": 2, "webp": 3}
55
+ _URL_PART = {"spec": 0, "scheme": 1, "username": 2, "password": 3, "host": 4, "port": 5, "path": 6,
56
+ "query": 7, "fragment": 8, "origin": 9}
57
+
58
+
59
+ class Error(Exception):
60
+ """What the engine reports when something it was asked to do fails."""
61
+
62
+
63
+ def _find_library():
64
+ if sys.platform == "darwin":
65
+ library, profile = "Zebkit.framework/Zebkit", "slim-macos"
66
+ elif sys.platform == "win32":
67
+ # python.exe cannot be the sandbox's child (docs/WINDOWS.md): --no-sandbox.
68
+ library, profile = "zebkit.dll", "slim-windows"
69
+ else:
70
+ library, profile = "libzebkit.so.1", "slim"
71
+ names = []
72
+ if os.environ.get("ZEBKIT_DIR"):
73
+ names.append(pathlib.Path(os.environ["ZEBKIT_DIR"]) / library)
74
+ here = pathlib.Path(__file__).resolve().parent
75
+ names.append(here / library)
76
+ if sys.platform == "darwin":
77
+ names.append(here.parents[2] / "dist" / "release" / library)
78
+ names.append(here.parents[2] / "out" / "blink" / "slim-macos-native" / "package" / library)
79
+ names.append(here.parents[2] / "out" / "blink" / profile / "package" / library)
80
+ for name in names:
81
+ if name.exists():
82
+ return str(name)
83
+ raise ImportError(f"{library} not found; set ZEBKIT_DIR to the engine's directory")
84
+
85
+
86
+ _lib = ctypes.CDLL(_find_library())
87
+
88
+ _c_char_p_p = ctypes.POINTER(ctypes.c_char_p)
89
+ _TASK = ctypes.CFUNCTYPE(None, ctypes.c_void_p)
90
+ _LOAD = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_void_p)
91
+ _TITLE = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_char_p, ctypes.c_void_p)
92
+ _VIEW = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p)
93
+ _RESULT = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_void_p)
94
+ _BIND = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_void_p, ctypes.c_void_p)
95
+
96
+
97
+ class _Response(ctypes.Structure):
98
+ _fields_ = [("status", ctypes.c_int), ("url", ctypes.c_char_p), ("headers", ctypes.c_char_p),
99
+ ("body", ctypes.POINTER(ctypes.c_uint8)), ("body_size", ctypes.c_size_t),
100
+ ("error", ctypes.c_char_p)]
101
+
102
+
103
+ _RESPONSE = ctypes.CFUNCTYPE(None, ctypes.POINTER(_Response), ctypes.c_void_p)
104
+
105
+
106
+ def _declare(name, result, *args):
107
+ function = getattr(_lib, name)
108
+ function.restype = result
109
+ function.argtypes = list(args)
110
+ return function
111
+
112
+
113
+ _V, _P, _S, _I, _U, _Z, _B = ctypes.c_void_p, ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int, ctypes.c_uint, \
114
+ ctypes.c_size_t, ctypes.c_bool
115
+ _ZP = ctypes.POINTER(ctypes.c_size_t)
116
+ _IP = ctypes.POINTER(ctypes.c_int)
117
+ _EP = ctypes.POINTER(ctypes.c_void_p)
118
+
119
+ _version = _declare("zebkit_version", _S)
120
+ _engine_version = _declare("zebkit_engine_version", _S)
121
+ _free = _declare("zebkit_free", None, _P)
122
+ _main = _declare("zebkit_main", _I, _I, ctypes.POINTER(ctypes.c_char_p), _TASK, _P)
123
+ _init = _declare("zebkit_init", _I, _I, ctypes.POINTER(ctypes.c_char_p))
124
+ _init_settings = _declare("zebkit_init_with_settings", _I, _I, ctypes.POINTER(ctypes.c_char_p), _S, _EP)
125
+ _WAKEUP = ctypes.CFUNCTYPE(None, ctypes.c_int64, _P)
126
+ _set_wakeup = _declare("zebkit_set_wakeup", _B, _WAKEUP, _P)
127
+ _wakeup_callback = None
128
+ _pump = _declare("zebkit_pump", _B)
129
+ _shutdown = _declare("zebkit_shutdown", _B)
130
+ _quit = _declare("zebkit_quit", None)
131
+ _post = _declare("zebkit_post_task", None, _TASK, _P)
132
+ _post_delayed = _declare("zebkit_post_delayed_task", None, _TASK, _P, ctypes.c_uint32)
133
+ _is_headless = _declare("zebkit_is_headless", _B)
134
+ _view_new = _declare("zebkit_view_new", _V, _S, _I, _I)
135
+ _view_load_url = _declare("zebkit_view_load_url", None, _V, _S)
136
+ _view_user_agent_override = _declare("zebkit_view_set_user_agent_override", _B, _V, _S, _RESULT, _P)
137
+ _cookie_storage = _declare("zebkit_set_cookie_storage", _B, _I, _S)
138
+ _cookie_key = _declare("zebkit_set_cookie_encryption_key", _B, _P, ctypes.c_size_t)
139
+ _view_target = _declare("zebkit_view_get_target_id", _P, _V)
140
+ _view_reload = _declare("zebkit_view_reload", None, _V)
141
+ _view_go_back = _declare("zebkit_view_go_back", None, _V)
142
+ _view_go_forward = _declare("zebkit_view_go_forward", None, _V)
143
+ _view_resize = _declare("zebkit_view_resize", None, _V, _I, _I)
144
+ _view_focus = _declare("zebkit_view_focus", None, _V)
145
+ _AUTHENTICATION = ctypes.CFUNCTYPE(None, _V, _S, _P)
146
+ _view_on_authentication = _declare("zebkit_view_on_authentication", _B, _V, _AUTHENTICATION, _P)
147
+ _view_authentication_action = _declare("zebkit_view_authentication_action", _B, _V, _S)
148
+ _view_authentication_ui = _declare("zebkit_view_set_authentication_ui", _B, _V, _B)
149
+ _view_close = _declare("zebkit_view_close", None, _V)
150
+ _view_get_url = _declare("zebkit_view_get_url", _P, _V)
151
+ _view_get_title = _declare("zebkit_view_get_title", _P, _V)
152
+ _view_on_load = _declare("zebkit_view_on_load", None, _V, _LOAD, _P)
153
+ _view_on_title = _declare("zebkit_view_on_title", None, _V, _TITLE, _P)
154
+ _view_on_close = _declare("zebkit_view_on_close", None, _V, _VIEW, _P)
155
+ _POPUP_BLOCKED = ctypes.CFUNCTYPE(None, _V, _S, _P)
156
+ _WINDOW_OPEN = ctypes.CFUNCTYPE(None, _V, _V, _S, _P)
157
+ _WINDOW_OPEN_EVENT = ctypes.CFUNCTYPE(None, _V, _S, _P)
158
+ _view_on_window_open = _declare("zebkit_view_on_window_open", None, _V, _WINDOW_OPEN, _P)
159
+ _view_on_window_open_event = _declare("zebkit_view_on_window_open_event", None, _V, _WINDOW_OPEN_EVENT, _P)
160
+ _view_window_open_info = _declare("zebkit_view_get_window_open_info", _P, _V)
161
+ _CONSOLE = ctypes.CFUNCTYPE(None, _V, _S, _P)
162
+ _view_on_console = _declare("zebkit_view_on_console", None, _V, _CONSOLE, _P)
163
+
164
+ # <zebkit/window.h>
165
+ _WINDOW_STATE = ctypes.CFUNCTYPE(None, _V, _S, _P)
166
+ _view_new_with_options = _declare("zebkit_view_new_with_options", _V, _P, _S, _S, ctypes.POINTER(_P))
167
+ _view_get_window = _declare("zebkit_view_get_window", _P, _V)
168
+ _view_set_window = _declare("zebkit_view_set_window", _B, _V, _S, ctypes.POINTER(_P))
169
+ _view_window_action = _declare("zebkit_view_window_action", _B, _V, _S, ctypes.POINTER(_P))
170
+ _view_on_window_state = _declare("zebkit_view_on_window_state", None, _V, _WINDOW_STATE, _P)
171
+ _view_set_drag_regions = _declare("zebkit_view_set_drag_regions", _B, _V, _S, ctypes.POINTER(_P))
172
+ _view_set_popup_window_options = _declare("zebkit_view_set_popup_window_options", _B, _V, _S, ctypes.POINTER(_P))
173
+ _get_capabilities = _declare("zebkit_get_capabilities", _P)
174
+ _ENVIRONMENT = ctypes.CFUNCTYPE(None, _S, _P)
175
+ _JSON_EVENT = ctypes.CFUNCTYPE(None, _S, _P)
176
+ _on_notification = _declare("zebkit_on_notification", None, _JSON_EVENT, _P)
177
+ _notification_clicked = _declare("zebkit_notification_clicked", _B, _S, ctypes.c_int)
178
+ _notification_closed = _declare("zebkit_notification_closed", _B, _S, _B)
179
+ _on_power_event = _declare("zebkit_on_power_event", None, _JSON_EVENT, _P)
180
+ _get_displays = _declare("zebkit_get_displays", _P)
181
+ _on_displays_changed = _declare("zebkit_on_displays_changed", None, _JSON_EVENT, _P)
182
+ _prevent_sleep = _declare("zebkit_prevent_sleep", ctypes.c_uint64, _B, _S)
183
+ _allow_sleep = _declare("zebkit_allow_sleep", _B, ctypes.c_uint64)
184
+ _open_external = _declare("zebkit_open_external", _B, _S, ctypes.POINTER(_P))
185
+ _show_in_folder = _declare("zebkit_show_in_folder", _B, _S, ctypes.POINTER(_P))
186
+ _TRAY_CLICK = ctypes.CFUNCTYPE(None, _P)
187
+ _TRAY_MENU = ctypes.CFUNCTYPE(None, _S, _P)
188
+ _tray_new = _declare("zebkit_tray_new", _P, ctypes.c_char_p, ctypes.c_size_t, _S, ctypes.POINTER(_P))
189
+ _tray_set_icon = _declare("zebkit_tray_set_icon", _B, _P, ctypes.c_char_p, ctypes.c_size_t, ctypes.POINTER(_P))
190
+ _tray_set_tooltip = _declare("zebkit_tray_set_tooltip", None, _P, _S)
191
+ _tray_set_menu = _declare("zebkit_tray_set_menu", _B, _P, _S, _TRAY_MENU, _P, ctypes.POINTER(_P))
192
+ _tray_on_click = _declare("zebkit_tray_on_click", None, _P, _TRAY_CLICK, _P)
193
+ _tray_close = _declare("zebkit_tray_close", None, _P)
194
+ _system_callbacks = {}
195
+ _get_environment = _declare("zebkit_get_environment", _P)
196
+ _on_environment_changed = _declare("zebkit_on_environment_changed", None, _ENVIRONMENT, _P)
197
+ _environment_callback = None
198
+
199
+ _view_set_settings = _declare("zebkit_view_set_settings", _B, _V, _S, ctypes.POINTER(_P))
200
+ _view_get_settings = _declare("zebkit_view_get_settings", _P, _V)
201
+ _set_engine_settings = _declare("zebkit_set_engine_settings", _B, _S, ctypes.POINTER(_P))
202
+ _get_engine_settings = _declare("zebkit_get_engine_settings", _P)
203
+ _view_set_runtime_settings = _declare("zebkit_view_set_runtime_settings", _B, _V, _S, ctypes.POINTER(_P))
204
+ _view_get_runtime_settings = _declare("zebkit_view_get_runtime_settings", _P, _V)
205
+ _PERMISSION = ctypes.CFUNCTYPE(None, _V, _P, _S, _P)
206
+ _PERMISSION_RESULT = ctypes.CFUNCTYPE(None, _V, _S, _P)
207
+ _view_set_permission = _declare("zebkit_view_set_permission", _B, _V, _S, _S, _I, _EP)
208
+ _view_get_permission = _declare("zebkit_view_get_permission", _I, _V, _S, _S)
209
+ _view_reset_permissions = _declare("zebkit_view_reset_permissions", _B, _V, _S, _EP)
210
+ _view_permission_timeout = _declare("zebkit_view_set_permission_timeout", _B, _V, ctypes.c_uint32)
211
+ _view_on_permission = _declare("zebkit_view_on_permission", None, _V, _PERMISSION, _P)
212
+ _view_on_permission_result = _declare("zebkit_view_on_permission_result", None, _V, _PERMISSION_RESULT, _P)
213
+ _permission_info = _declare("zebkit_permission_request_info", _P, _P)
214
+ _permission_respond = _declare("zebkit_permission_respond", _B, _P, _I, _B)
215
+ _PERMISSION_STATES = {"prompt": 0, "granted": 1, "denied": 2}
216
+ _NAVIGATION = ctypes.CFUNCTYPE(None, _V, _P, _S, _P)
217
+ _NAVIGATION_RESULT = ctypes.CFUNCTYPE(None, _V, _S, _P)
218
+ _view_on_navigation = _declare("zebkit_view_on_navigation", None, _V, _NAVIGATION, _P)
219
+ _view_on_navigation_result = _declare("zebkit_view_on_navigation_result", None, _V, _NAVIGATION_RESULT, _P)
220
+ _view_navigation_timeout = _declare("zebkit_view_set_navigation_timeout", _B, _V, ctypes.c_uint32)
221
+ _view_navigation_fail_closed = _declare("zebkit_view_set_navigation_fail_closed", _B, _V, ctypes.c_bool)
222
+ _navigation_info = _declare("zebkit_navigation_request_info", _P, _P)
223
+ _navigation_respond = _declare("zebkit_navigation_respond", _B, _P, _I, _S, _EP)
224
+
225
+
226
+ _CERTIFICATE = ctypes.CFUNCTYPE(None, _V, _P, _S, _P)
227
+ _CERTIFICATE_RESULT = ctypes.CFUNCTYPE(None, _V, _S, _P)
228
+ _view_on_certificate = _declare("zebkit_view_on_certificate", None, _V, _CERTIFICATE, _P)
229
+ _view_on_certificate_result = _declare("zebkit_view_on_certificate_result", None, _V, _CERTIFICATE_RESULT, _P)
230
+ _view_certificate_timeout = _declare("zebkit_view_set_certificate_timeout", _B, _V, ctypes.c_uint32)
231
+ _certificate_info = _declare("zebkit_certificate_request_info", _P, _P)
232
+ _certificate_respond = _declare("zebkit_certificate_respond", _B, _P, _B)
233
+
234
+ _HTTP_AUTH = ctypes.CFUNCTYPE(None, _V, _P, _S, _P)
235
+ _HTTP_AUTH_RESULT = ctypes.CFUNCTYPE(None, _V, _S, _P)
236
+ _view_on_http_auth = _declare("zebkit_view_on_http_auth", None, _V, _HTTP_AUTH, _P)
237
+ _view_on_http_auth_result = _declare("zebkit_view_on_http_auth_result", None, _V, _HTTP_AUTH_RESULT, _P)
238
+ _view_http_auth_timeout = _declare("zebkit_view_set_http_auth_timeout", _B, _V, ctypes.c_uint32)
239
+ _http_auth_info = _declare("zebkit_http_auth_request_info", _P, _P)
240
+ _http_auth_respond = _declare("zebkit_http_auth_respond", _B, _P, _S, _S)
241
+
242
+
243
+ _ASKED = ctypes.CFUNCTYPE(None, _V, _P, _S, _P)
244
+ _TOLD = ctypes.CFUNCTYPE(None, _V, _S, _P)
245
+ _view_on_external_protocol = _declare("zebkit_view_on_external_protocol", None, _V, _TOLD, _P)
246
+ _view_on_download = _declare("zebkit_view_on_download", None, _V, _ASKED, _P)
247
+ _view_on_download_progress = _declare("zebkit_view_on_download_progress", None, _V, _TOLD, _P)
248
+ _view_download_timeout = _declare("zebkit_view_set_download_timeout", _B, _V, ctypes.c_uint32)
249
+ _download_info = _declare("zebkit_download_request_info", _P, _P)
250
+ _download_respond = _declare("zebkit_download_respond", _B, _P, _I, _S, _P)
251
+ _view_cancel_download = _declare("zebkit_view_cancel_download", _B, _V, _S)
252
+ _view_on_client_certificate = _declare("zebkit_view_on_client_certificate", None, _V, _ASKED, _P)
253
+ _view_on_client_certificate_result = _declare("zebkit_view_on_client_certificate_result", None, _V, _TOLD, _P)
254
+ _view_client_certificate_timeout = _declare("zebkit_view_set_client_certificate_timeout", _B, _V, ctypes.c_uint32)
255
+ _client_certificate_info = _declare("zebkit_client_certificate_request_info", _P, _P)
256
+ _client_certificate_respond = _declare("zebkit_client_certificate_respond", _B, _P, _I, _S, _S, _P)
257
+ _client_certificate_choose = _declare("zebkit_client_certificate_choose", _B, _P, ctypes.c_size_t, _P)
258
+ _view_attach_native = _declare("zebkit_view_attach_native", _B, _V, ctypes.c_size_t, _I, _I, _I, _I, _EP)
259
+ _view_detach_native = _declare("zebkit_view_detach_native", _B, _V)
260
+
261
+
262
+ class _NativeWindowInfo(ctypes.Structure):
263
+ _fields_ = [("kind", _I), ("handle", ctypes.c_size_t)]
264
+
265
+
266
+ _view_get_native_window = _declare("zebkit_view_get_native_window", _B, _V, ctypes.POINTER(_NativeWindowInfo))
267
+ _NATIVE_WINDOW_EXPORT = ctypes.CFUNCTYPE(None, _P, _S)
268
+ _view_export_native_window = _declare("zebkit_view_export_native_window", _B, _V, _NATIVE_WINDOW_EXPORT, _P)
269
+ _view_set_bounds = _declare("zebkit_view_set_bounds", None, _V, _I, _I, _I, _I)
270
+ _view_add_world_script = _declare("zebkit_view_add_world_script", _B, _V, _S, _S, _B, _P)
271
+ _view_on_file_chooser = _declare("zebkit_view_on_file_chooser", None, _V, _ASKED, _P)
272
+ _view_on_file_chooser_result = _declare("zebkit_view_on_file_chooser_result", None, _V, _TOLD, _P)
273
+ _view_file_chooser_timeout = _declare("zebkit_view_set_file_chooser_timeout", _B, _V, ctypes.c_uint32)
274
+ _file_chooser_info = _declare("zebkit_file_chooser_request_info", _P, _P)
275
+ _view_on_eye_dropper = _declare("zebkit_view_on_eye_dropper", None, _V, _ASKED, _P)
276
+ _view_on_eye_dropper_result = _declare("zebkit_view_on_eye_dropper_result", None, _V, _TOLD, _P)
277
+ _view_eye_dropper_timeout = _declare("zebkit_view_set_eye_dropper_timeout", _B, _V, ctypes.c_uint32)
278
+ _eye_dropper_info = _declare("zebkit_eye_dropper_request_info", _P, _P)
279
+ _eye_dropper_respond = _declare("zebkit_eye_dropper_respond", _B, _P, _S)
280
+ _view_on_device_chooser = _declare("zebkit_view_on_device_chooser", None, _V, _ASKED, _P)
281
+ _view_on_device_chooser_result = _declare("zebkit_view_on_device_chooser_result", None, _V, _TOLD, _P)
282
+ _view_device_chooser_timeout = _declare("zebkit_view_set_device_chooser_timeout", _B, _V, ctypes.c_uint32)
283
+ _device_chooser_info = _declare("zebkit_device_chooser_request_info", _P, _P)
284
+ _device_chooser_respond = _declare("zebkit_device_chooser_respond", _B, _P, _S)
285
+ _view_on_share = _declare("zebkit_view_on_share", None, _V, _ASKED, _P)
286
+ _view_on_share_result = _declare("zebkit_view_on_share_result", None, _V, _TOLD, _P)
287
+ _view_share_timeout = _declare("zebkit_view_set_share_timeout", _B, _V, ctypes.c_uint32)
288
+ _share_info = _declare("zebkit_share_request_info", _P, _P)
289
+ _share_respond = _declare("zebkit_share_respond", _B, _P, _B)
290
+ _file_chooser_respond = _declare("zebkit_file_chooser_respond", _B, _P, ctypes.POINTER(ctypes.c_char_p), _Z, _P)
291
+ _view_on_media_access = _declare("zebkit_view_on_media_access", None, _V, _ASKED, _P)
292
+ _view_on_media_access_result = _declare("zebkit_view_on_media_access_result", None, _V, _TOLD, _P)
293
+ _view_media_access_timeout = _declare("zebkit_view_set_media_access_timeout", _B, _V, ctypes.c_uint32)
294
+ _media_access_info = _declare("zebkit_media_access_request_info", _P, _P)
295
+ _media_access_respond = _declare("zebkit_media_access_respond", _B, _P, _B, _S, _S)
296
+ _view_set_reserved_keys = _declare("zebkit_view_set_reserved_keys", _B, _V, _S, _P)
297
+ _view_on_reserved_key = _declare("zebkit_view_on_reserved_key", None, _V, _TOLD, _P)
298
+ _view_on_context_menu = _declare("zebkit_view_on_context_menu", None, _V, _TOLD, _P)
299
+ _CONTEXT_MENU_ITEM = ctypes.CFUNCTYPE(None, _V, _S, _P)
300
+ _view_context_menu_run = _declare("zebkit_view_context_menu_run", _B, _V, ctypes.c_uint64, _S, _EP)
301
+ _view_context_menu_show = _declare("zebkit_view_context_menu_show", _B, _V, ctypes.c_uint64, _S,
302
+ _CONTEXT_MENU_ITEM, _P, _EP)
303
+ _view_set_fullscreen_policy = _declare("zebkit_view_set_fullscreen_policy", _B, _V, _I)
304
+ _view_on_fullscreen = _declare("zebkit_view_on_fullscreen", None, _V, _TOLD, _P)
305
+ _view_set_network_filter = _declare("zebkit_view_set_network_filter", _B, _V, _S, _P)
306
+ _view_on_network = _declare("zebkit_view_on_network", None, _V, _ASKED, _P)
307
+ _view_on_network_event = _declare("zebkit_view_on_network_event", None, _V, _TOLD, _P)
308
+ _view_network_timeout = _declare("zebkit_view_set_network_timeout", _B, _V, ctypes.c_uint32)
309
+ _network_info = _declare("zebkit_network_request_info", _P, _P)
310
+ _network_respond = _declare("zebkit_network_respond", _B, _P, _S, ctypes.c_char_p, _Z, _P)
311
+ _view_network_for_workers = _declare("zebkit_view_set_network_filter_for_workers", _B, _V, _B)
312
+ _NETWORK_BODY = ctypes.CFUNCTYPE(None, _V, _S, _P, _Z, _B, _B, _P)
313
+ _view_on_network_body = _declare("zebkit_view_on_network_body", None, _V, _NETWORK_BODY, _P)
314
+ _network_respond_file = _declare("zebkit_network_respond_file", _B, _P, _S, _S, _P)
315
+ _network_respond_stream = _declare("zebkit_network_respond_stream", _P, _P, _S, _P)
316
+ _network_stream_write = _declare("zebkit_network_stream_write", _B, _P, ctypes.c_char_p, _Z)
317
+ _STREAM_WRITABLE = ctypes.CFUNCTYPE(None, _P, _P)
318
+ _network_stream_on_writable = _declare("zebkit_network_stream_on_writable", None, _P, _STREAM_WRITABLE, _P)
319
+ _network_stream_is_open = _declare("zebkit_network_stream_is_open", _B, _P)
320
+ _network_stream_end = _declare("zebkit_network_stream_end", None, _P, _B)
321
+
322
+
323
+ class _Request:
324
+ """An engine-thread request with a deadline: metadata stays, info ends with it."""
325
+ _info = None
326
+
327
+ def __init__(self, handle, metadata):
328
+ self._handle = handle
329
+ self.metadata = metadata
330
+
331
+ @property
332
+ def info(self):
333
+ value = _string(type(self)._info(self._handle))
334
+ return json.loads(value) if value else None
335
+
336
+
337
+ class DownloadRequest(_Request):
338
+ _info = _download_info
339
+
340
+ def respond(self, action, path=None):
341
+ """respond('save', absolute_path) or respond('cancel'); False when stale or invalid."""
342
+ if action not in ("save", "cancel"):
343
+ raise ValueError("a download is saved or cancelled")
344
+ encoded = None if path is None else os.fsencode(path)
345
+ return bool(_download_respond(self._handle, 0 if action == "save" else 1, encoded, None))
346
+
347
+
348
+ class EyeDropperRequest(_Request):
349
+ _info = _eye_dropper_info
350
+
351
+ def respond(self, color=None):
352
+ """respond("#rrggbb") gives the page that colour; respond() cancels."""
353
+ return bool(_eye_dropper_respond(self._handle, color.encode() if color else None))
354
+
355
+
356
+ class DeviceChooserRequest(_Request):
357
+ """navigator.usb.requestDevice(), navigator.hid.requestDevice(),
358
+ navigator.serial.requestPort(): metadata["kind"], ["devices"] (info has the
359
+ list as it is now)."""
360
+ _info = _device_chooser_info
361
+
362
+ def respond(self, device_id=None):
363
+ """respond(id) gives the page that device; respond() gives none."""
364
+ return bool(_device_chooser_respond(self._handle, device_id.encode() if device_id else None))
365
+
366
+
367
+ class ShareRequest(_Request):
368
+ _info = _share_info
369
+
370
+ def respond(self, shared=True):
371
+ """respond(True): shared; respond(False): cancelled (AbortError)."""
372
+ return bool(_share_respond(self._handle, bool(shared)))
373
+
374
+
375
+ class ClientCertificateRequest(_Request):
376
+ _info = _client_certificate_info
377
+
378
+ def respond(self, action, certificate=None, key=None):
379
+ """respond('none'), respond('cancel') or respond('provide', pem_chain, pem_key)."""
380
+ actions = {"none": 0, "provide": 1, "cancel": 2}
381
+ if action not in actions:
382
+ raise ValueError("a client certificate is none, provide or cancel")
383
+ return bool(_client_certificate_respond(self._handle, actions[action],
384
+ None if certificate is None else certificate.encode(),
385
+ None if key is None else key.encode(), None))
386
+
387
+ def choose(self, index):
388
+ """One of metadata['identities'], the system store's (clientCertificateStores)."""
389
+ return bool(_client_certificate_choose(self._handle, int(index), None))
390
+
391
+
392
+ class FileChooserRequest(_Request):
393
+ _info = _file_chooser_info
394
+
395
+ def respond(self, paths=()):
396
+ """Absolute paths; none cancels. False when stale or invalid."""
397
+ if isinstance(paths, (str, bytes)):
398
+ raise TypeError("paths is a list")
399
+ encoded = [os.fsencode(path) for path in paths]
400
+ array = (ctypes.c_char_p * len(encoded))(*encoded)
401
+ return bool(_file_chooser_respond(self._handle, array, len(encoded), None))
402
+
403
+
404
+ class MediaAccessRequest(_Request):
405
+ _info = _media_access_info
406
+
407
+ def respond(self, allow, audio_device=None, video_device=None):
408
+ return bool(_media_access_respond(self._handle, bool(allow),
409
+ None if audio_device is None else audio_device.encode(),
410
+ None if video_device is None else video_device.encode()))
411
+
412
+
413
+ class NetworkRequest(_Request):
414
+ _info = _network_info
415
+
416
+ def respond(self, action, body=b"", **fields):
417
+ """respond('continue', headers=[...]), respond('block', error='failed'),
418
+ respond('redirect', url=...), respond('fulfill', body=bytes, status=200, headers=[...])."""
419
+ reply = dict(fields, action=action)
420
+ return bool(_network_respond(self._handle, json.dumps(reply).encode(), bytes(body), len(body), None))
421
+
422
+ def respond_file(self, path, **fields):
423
+ """Fulfill from an absolute path: respond_file(path, status=200, headers=[...])."""
424
+ return bool(_network_respond_file(self._handle, json.dumps(fields).encode(), os.fsencode(path), None))
425
+
426
+ def respond_stream(self, **fields):
427
+ """Fulfill with what is written: a NetworkStream, or None when invalid or stale."""
428
+ handle = _network_respond_stream(self._handle, json.dumps(fields).encode(), None)
429
+ return NetworkStream(handle) if handle else None
430
+
431
+
432
+ class NetworkStream:
433
+ """An answer written as it goes, on the engine thread; end() frees it."""
434
+ def __init__(self, handle):
435
+ self._handle = handle
436
+ self._writable = None
437
+
438
+ def write(self, data):
439
+ """False when it does not fit (at most 1 MiB waits) or nobody reads any more."""
440
+ if self._handle is None:
441
+ return False
442
+ data = bytes(data)
443
+ return bool(_network_stream_write(self._handle, data, len(data)))
444
+
445
+ def on_writable(self, function):
446
+ """function() once after a write that returned false: it fits, or is_open is false."""
447
+ if self._handle is None:
448
+ return
449
+ self._writable = _STREAM_WRITABLE(_guard(lambda stream, data: function())) if function else _STREAM_WRITABLE()
450
+ _network_stream_on_writable(self._handle, self._writable, None)
451
+
452
+ @property
453
+ def is_open(self):
454
+ return self._handle is not None and bool(_network_stream_is_open(self._handle))
455
+
456
+ def end(self, failed=False):
457
+ if self._handle is not None:
458
+ handle, self._handle = self._handle, None
459
+ _network_stream_end(handle, bool(failed))
460
+
461
+
462
+ class HttpAuthRequest:
463
+ """An expiring HTTP/proxy challenge; credentials are not kept on this object."""
464
+ def __init__(self, handle, metadata):
465
+ self._handle = handle
466
+ self.metadata = metadata
467
+
468
+ @property
469
+ def info(self):
470
+ value = _string(_http_auth_info(self._handle))
471
+ return json.loads(value) if value else None
472
+
473
+ def respond(self, username=None, password=None):
474
+ """Reply once with two strings, or cancel with two None values."""
475
+ if username is None and password is None:
476
+ return bool(_http_auth_respond(self._handle, None, None))
477
+ if not isinstance(username, str) or not isinstance(password, str):
478
+ raise TypeError("HTTP authentication needs two strings or two None values")
479
+ if '\0' in username or '\0' in password:
480
+ raise ValueError("HTTP authentication credentials cannot contain NUL")
481
+ user, secret = username.encode(), password.encode()
482
+ if len(user) > 65536 or len(secret) > 65536:
483
+ raise ValueError("each HTTP authentication credential is limited to 65536 UTF-8 bytes")
484
+ return bool(_http_auth_respond(self._handle, user, secret))
485
+
486
+
487
+ class CertificateRequest:
488
+ """A document TLS error; keeping this object does not extend its deadline."""
489
+ def __init__(self, handle, metadata):
490
+ self._handle = handle
491
+ self.metadata = metadata
492
+
493
+ @property
494
+ def info(self):
495
+ value = _string(_certificate_info(self._handle))
496
+ return json.loads(value) if value else None
497
+
498
+ def respond(self, allow=False):
499
+ """Reply once; False for stale requests or attempts to ignore strict errors."""
500
+ if not isinstance(allow, bool):
501
+ raise TypeError("certificate reply must be a boolean")
502
+ return bool(_certificate_respond(self._handle, allow))
503
+
504
+
505
+ class NavigationRequest:
506
+ """An engine-thread navigation decision; retaining it does not extend its deadline.
507
+
508
+ metadata is a snapshot; info becomes None after settlement. A reply affects
509
+ one stage of one navigation. Unanswered stages continue after their deadline.
510
+ """
511
+ def __init__(self, handle, metadata):
512
+ self._handle = handle
513
+ self.metadata = metadata
514
+
515
+ @property
516
+ def info(self):
517
+ value = _string(_navigation_info(self._handle))
518
+ return json.loads(value) if value else None
519
+
520
+ def respond(self, action='continue', replacement_url=None):
521
+ """Continue, cancel, or redirect as GET in the same frame; False if stale/invalid."""
522
+ actions = {'continue': 0, 'cancel': 1, 'redirect': 2}
523
+ if action not in actions:
524
+ raise ValueError("unknown navigation action")
525
+ if replacement_url is not None and (not isinstance(replacement_url, str) or '\0' in replacement_url):
526
+ raise ValueError("replacement URL must be a NUL-free string")
527
+ return bool(_navigation_respond(self._handle, actions[action],
528
+ replacement_url.encode() if replacement_url is not None else None, None))
529
+
530
+
531
+
532
+ def _permission_state(state):
533
+ if state not in _PERMISSION_STATES:
534
+ raise ValueError("permission state must be prompt, granted or denied")
535
+ return _PERMISSION_STATES[state]
536
+
537
+
538
+ def _permission_text(value):
539
+ if value is None:
540
+ return None
541
+ if not isinstance(value, str) or '\0' in value:
542
+ raise ValueError("permission name and origin must be NUL-free strings")
543
+ return value.encode()
544
+
545
+
546
+ class PermissionRequest:
547
+ """A permission prompt. Use only on the engine thread; post worker replies.
548
+
549
+ metadata is a snapshot. info is None after cancellation, timeout or reply;
550
+ respond returns False for stale requests, without affecting later prompts.
551
+ """
552
+
553
+ def __init__(self, handle, metadata):
554
+ self._handle = handle
555
+ self.metadata = metadata
556
+
557
+ @property
558
+ def info(self):
559
+ value = _string(_permission_info(self._handle))
560
+ return json.loads(value) if value else None
561
+
562
+ def respond(self, state, remember=False):
563
+ """Reply once; remember stores a rule for the requesting origin."""
564
+ return bool(_permission_respond(self._handle, _permission_state(state), bool(remember)))
565
+
566
+ _view_popup_policy = _declare("zebkit_view_set_popup_policy", _B, _V, _I)
567
+ _view_get_popup_policy = _declare("zebkit_view_get_popup_policy", _I, _V)
568
+ _view_on_popup_blocked = _declare("zebkit_view_on_popup_blocked", None, _V, _POPUP_BLOCKED, _P)
569
+ _view_evaluate = _declare("zebkit_view_evaluate", None, _V, _S, _RESULT, _P)
570
+ _view_grant = _declare("zebkit_view_grant", None, _V, _S, _U, _S)
571
+ _view_bind = _declare("zebkit_view_bind", None, _V, _S, _BIND, _P)
572
+ _call_resolve = _declare("zebkit_call_resolve", None, _P, _S)
573
+ _call_resolve_json = _declare("zebkit_call_resolve_json", None, _P, _S, ctypes.c_size_t)
574
+ _call_reject = _declare("zebkit_call_reject", None, _P, _S)
575
+ _cdp_listen = _declare("zebkit_cdp_listen", _U, _S, _U, _EP)
576
+ _cdp_get_port = _declare("zebkit_cdp_get_port", _U)
577
+ _cdp_get_url = _declare("zebkit_cdp_get_url", _P)
578
+ _cdp_stop = _declare("zebkit_cdp_stop", None)
579
+ _compress = _declare("zebkit_compress", _P, _I, _P, _Z, _I, _ZP, _EP)
580
+ _decompress = _declare("zebkit_decompress", _P, _I, _P, _Z, _Z, _ZP, _EP)
581
+ _digest_size = _declare("zebkit_digest_size", _Z, _I)
582
+ _digest_compute = _declare("zebkit_digest_compute", _B, _I, _P, _Z, _P)
583
+ _hmac = _declare("zebkit_hmac", _B, _I, _P, _Z, _P, _Z, _P)
584
+ _random_bytes = _declare("zebkit_random_bytes", _B, _P, _Z)
585
+ _aes_gcm_seal = _declare("zebkit_aes_gcm_seal", _P, _P, _Z, _P, _Z, _P, _Z, _P, _Z, _ZP, _EP)
586
+ _aes_gcm_open = _declare("zebkit_aes_gcm_open", _P, _P, _Z, _P, _Z, _P, _Z, _P, _Z, _ZP, _EP)
587
+ _url_get = _declare("zebkit_url_get", _P, _S, _S, _I)
588
+ _url_registrable_domain = _declare("zebkit_url_registrable_domain", _P, _S)
589
+ _image_decode = _declare("zebkit_image_decode", _P, _P, _Z, _IP, _IP, _EP)
590
+ _image_encode = _declare("zebkit_image_encode", _P, _I, _P, _I, _I, _I, _ZP, _EP)
591
+ _icu_init = _declare("zebkit_icu_init", _B)
592
+ _fetch = _declare("zebkit_fetch", None, _S, _S, _S, _P, _Z, _RESPONSE, _P)
593
+
594
+ # Callbacks and views that C still holds, by id: kept here so that Python
595
+ # does not free them. ctypes' function objects cannot be hashed.
596
+ class _Alive(dict):
597
+ def add(self, item):
598
+ self[id(item)] = item
599
+
600
+ def discard(self, item):
601
+ self.pop(id(item), None)
602
+
603
+
604
+ _alive = _Alive()
605
+
606
+
607
+ def _bytes(data):
608
+ if isinstance(data, str):
609
+ data = data.encode()
610
+ return bytes(data)
611
+
612
+
613
+ def _string(pointer):
614
+ """A string the engine returned, freed."""
615
+ if not pointer:
616
+ return None
617
+ try:
618
+ return ctypes.string_at(pointer).decode()
619
+ finally:
620
+ _free(pointer)
621
+
622
+
623
+ def _buffer(pointer, size):
624
+ """A buffer the engine returned, freed."""
625
+ try:
626
+ return ctypes.string_at(pointer, size)
627
+ finally:
628
+ _free(pointer)
629
+
630
+
631
+ def _raise(error, fallback):
632
+ message = _string(error.value) if error.value else fallback
633
+ raise Error(message)
634
+
635
+
636
+ def _guard(function):
637
+ """Exceptions do not cross into C: report them and carry on."""
638
+ def call(*args):
639
+ try:
640
+ return function(*args)
641
+ except Exception: # noqa: BLE001
642
+ sys.excepthook(*sys.exc_info())
643
+ return call
644
+
645
+
646
+ # ---- the engine ----
647
+
648
+ def version():
649
+ return _version().decode()
650
+
651
+
652
+ def engine_version():
653
+ return _engine_version().decode()
654
+
655
+
656
+ def environment():
657
+ """What the system says of how things should look: colorScheme, contrast,
658
+ forcedColors, locale, accessibility, following."""
659
+ value = _string(_get_environment())
660
+ return json.loads(value) if value else None
661
+
662
+
663
+ def on_environment_changed(function):
664
+ """function(dict) on each change of environment(); None stops."""
665
+ global _environment_callback
666
+ if function is None:
667
+ _environment_callback = None
668
+ _on_environment_changed(_ENVIRONMENT(), None)
669
+ return
670
+ _environment_callback = _ENVIRONMENT(_guard(lambda payload, d: function(json.loads(payload.decode()))))
671
+ _on_environment_changed(_environment_callback, None)
672
+
673
+
674
+ def _json_event(kind, setter, function):
675
+ if function is None:
676
+ _system_callbacks.pop(kind, None)
677
+ setter(_JSON_EVENT(), None)
678
+ return
679
+ callback = _JSON_EVENT(_guard(lambda payload, d: function(json.loads(payload.decode()))))
680
+ _system_callbacks[kind] = callback
681
+ setter(callback, None)
682
+
683
+
684
+ def on_notification(function):
685
+ """function(dict) shows web notifications: {"event": "show" | "close", ...};
686
+ None: the system shows them."""
687
+ _json_event("notification", _on_notification, function)
688
+
689
+
690
+ def notification_clicked(notification_id, action=-1):
691
+ return bool(_notification_clicked(notification_id.encode(), int(action)))
692
+
693
+
694
+ def notification_closed(notification_id, by_user=True):
695
+ return bool(_notification_closed(notification_id.encode(), bool(by_user)))
696
+
697
+
698
+ def on_power_event(function):
699
+ """function(dict): suspend, resume, power-source, lock, unlock."""
700
+ _json_event("power", _on_power_event, function)
701
+
702
+
703
+ def displays():
704
+ """The screens: [{id, bounds, workArea, scale, rotation, primary}]."""
705
+ value = _string(_get_displays())
706
+ return json.loads(value) if value else []
707
+
708
+
709
+ def on_displays_changed(function):
710
+ _json_event("displays", _on_displays_changed, function)
711
+
712
+
713
+ def prevent_sleep(reason, keep_display_on=False):
714
+ """Keeps the system awake until allow_sleep(token)."""
715
+ return int(_prevent_sleep(bool(keep_display_on), reason.encode()))
716
+
717
+
718
+ def allow_sleep(token):
719
+ return bool(_allow_sleep(int(token)))
720
+
721
+
722
+ def open_external(url):
723
+ """The system's handler for url."""
724
+ error = _P()
725
+ if not _open_external(url.encode(), ctypes.byref(error)):
726
+ _raise(error, "the URL was not opened")
727
+
728
+
729
+ def show_in_folder(path):
730
+ """The file manager, with path selected."""
731
+ error = _P()
732
+ if not _show_in_folder(os.fsencode(path), ctypes.byref(error)):
733
+ _raise(error, "the file was not shown")
734
+
735
+
736
+ class Tray:
737
+ """The application's icon in the system's tray (png: bytes of a PNG)."""
738
+
739
+ def __init__(self, png, tooltip=""):
740
+ error = _P()
741
+ self._handle = _tray_new(png, len(png), tooltip.encode(), ctypes.byref(error))
742
+ if not self._handle:
743
+ _raise(error, "the tray was not made")
744
+ self._callbacks = {}
745
+
746
+ def set_icon(self, png):
747
+ error = _P()
748
+ if not _tray_set_icon(self._handle, png, len(png), ctypes.byref(error)):
749
+ _raise(error, "the icon was refused")
750
+
751
+ def set_tooltip(self, tooltip):
752
+ _tray_set_tooltip(self._handle, tooltip.encode())
753
+
754
+ def set_menu(self, menu, function):
755
+ """Items as app_set_menu's; function(id) for one chosen."""
756
+ callback = _TRAY_MENU(_guard(lambda item, d: function(item.decode())))
757
+ error = _P()
758
+ if not _tray_set_menu(self._handle, json.dumps(menu).encode(), callback, None, ctypes.byref(error)):
759
+ _raise(error, "the menu was refused")
760
+ self._callbacks["menu"] = callback
761
+
762
+ def on_click(self, function):
763
+ callback = _TRAY_CLICK(_guard(lambda d: function())) if function else _TRAY_CLICK()
764
+ self._callbacks["click"] = callback
765
+ _tray_on_click(self._handle, callback, None)
766
+
767
+ def close(self):
768
+ if self._handle:
769
+ _tray_close(self._handle)
770
+ self._handle = None
771
+
772
+
773
+ def capabilities():
774
+ """What this build can do on this system and display (<zebkit/window.h>)."""
775
+ value = _string(_get_capabilities())
776
+ return json.loads(value) if value else None
777
+
778
+
779
+ def is_headless():
780
+ return bool(_is_headless())
781
+
782
+
783
+ def main(ready, argv=None):
784
+ """Start the engine, call ready() once views can be made, run until
785
+ quit(); returns the exit code. Chromium's switches in argv (by default
786
+ sys.argv) are honoured, such as --remote-debugging-port=9222."""
787
+ argv = list(sys.argv if argv is None else argv) or ["python"]
788
+ array = (ctypes.c_char_p * (len(argv) + 1))(*[a.encode() for a in argv], None)
789
+ callback = _TASK(_guard(lambda data: ready()))
790
+ _alive.add(callback)
791
+ try:
792
+ return _main(len(argv), array, callback, None)
793
+ finally:
794
+ _alive.discard(callback)
795
+
796
+
797
+ def init(argv=None, *, settings=None):
798
+ """Initialize on the main thread for a host-owned loop; once per process.
799
+ Returns 0 on success or Chromium's startup code. With settings (a dict or
800
+ JSON string), invalid settings/startup errors raise Error with the native
801
+ explanation. Use set_wakeup for event-driven pumping, or a toolkit timer;
802
+ call shutdown outside callbacks when the engine is no longer needed.
803
+ """
804
+ argv = list(sys.argv if argv is None else argv) or ["python"]
805
+ array = (ctypes.c_char_p * (len(argv) + 1))(*[a.encode() for a in argv], None)
806
+ if settings is None:
807
+ return _init(len(argv), array)
808
+ source = settings if isinstance(settings, str) else json.dumps(settings)
809
+ error = ctypes.c_void_p()
810
+ code = _init_settings(len(argv), array, source.encode(), ctypes.byref(error))
811
+ message = _string(error.value)
812
+ if code:
813
+ raise Error(message or f"engine startup failed: {code}")
814
+ return code
815
+
816
+
817
+ def set_engine_settings(settings):
818
+ """What zebkit decides for the whole engine (<zebkit/hooks.h>): thirdPartyCookies,
819
+ spareRenderer, dialogs, downloads, newWindows. All of it applies or none."""
820
+ source = settings if isinstance(settings, str) else json.dumps(settings)
821
+ if '\0' in source:
822
+ raise Error("runtime settings contain NUL")
823
+ error = ctypes.c_void_p()
824
+ if not _set_engine_settings(source.encode(), ctypes.byref(error)):
825
+ _raise(error, "runtime settings rejected")
826
+
827
+
828
+ def engine_settings():
829
+ """{"explicit": ..., "effective": ...}."""
830
+ return json.loads(_string(_get_engine_settings()))
831
+
832
+
833
+ def pump():
834
+ """Process ready engine/native events without waiting; False if invalid."""
835
+ return bool(_pump())
836
+
837
+
838
+ def set_wakeup(function):
839
+ """Before init, set function(delay_ms) to queue a host event/timer.
840
+ It may run on any engine thread: never call zebkit or block in it.
841
+ Keep the earliest deadline and consume it before pump(). None removes it.
842
+ """
843
+ global _wakeup_callback
844
+ callback = _WAKEUP(_guard(lambda delay, data: function(delay))) if function else _WAKEUP()
845
+ if not _set_wakeup(callback, None):
846
+ return False
847
+ _wakeup_callback = callback if function else None
848
+ return True
849
+
850
+
851
+ def shutdown():
852
+ """Close views and stop the engine on its initializing thread, outside callbacks.
853
+ Returns False if invalid. The engine cannot be restarted after shutdown.
854
+ """
855
+ global _wakeup_callback
856
+ if not _shutdown():
857
+ return False
858
+ _wakeup_callback = None
859
+ return True
860
+
861
+
862
+ def quit(): # noqa: A001
863
+ _quit()
864
+
865
+
866
+ def post(function, delay_ms=0):
867
+ """Run function() on the engine's thread; any thread may call this."""
868
+ def run(data):
869
+ _alive.discard(callback)
870
+ function()
871
+ callback = _TASK(_guard(run))
872
+ _alive.add(callback)
873
+ if delay_ms:
874
+ _post_delayed(callback, None, int(delay_ms))
875
+ else:
876
+ _post(callback, None)
877
+
878
+
879
+ class View:
880
+ """A page, in a window when the machine has a display."""
881
+
882
+ def __init__(self, url=None, width=0, height=0, options=None):
883
+ """A view loading url. options (<zebkit/window.h>): the window's, before
884
+ it is made, such as {"frame": "overlay", "show": False}; width and
885
+ height go into them."""
886
+ if options is None:
887
+ self._handle = _view_new(url.encode() if url else None, width, height)
888
+ else:
889
+ given = dict(options)
890
+ if width:
891
+ given.setdefault("width", width)
892
+ if height:
893
+ given.setdefault("height", height)
894
+ error = _P()
895
+ self._handle = _view_new_with_options(None, url.encode() if url else None,
896
+ json.dumps(given).encode(), ctypes.byref(error))
897
+ if not self._handle:
898
+ _raise(error, "cannot create a view with these window options")
899
+ if not self._handle:
900
+ raise Error("cannot create a view")
901
+ self._initialize_callbacks()
902
+
903
+ @property
904
+ def window(self):
905
+ """The window's state (<zebkit/window.h>): state, bounds, frame,
906
+ titlebarArea, controls, capabilities."""
907
+ value = _string(_view_get_window(self._check()))
908
+ return json.loads(value) if value else None
909
+
910
+ def set_window(self, options=None, **fields):
911
+ """Changes the window's runtime options, merged by key."""
912
+ given = dict(options or {}, **fields)
913
+ error = _P()
914
+ if not _view_set_window(self._check(), json.dumps(given).encode(), ctypes.byref(error)):
915
+ _raise(error, "window options rejected")
916
+
917
+ def window_action(self, action):
918
+ """show, hide, minimize, maximize, restore, fullscreen,
919
+ exit-fullscreen, close: asked of the system; the state tells."""
920
+ error = _P()
921
+ if not _view_window_action(self._check(), action.encode(), ctypes.byref(error)):
922
+ _raise(error, "window action refused")
923
+
924
+ def on_window_state(self, function):
925
+ """function(dict) for every change of the window's state; None removes it."""
926
+ if function is None:
927
+ self._callbacks.pop("window-state", None)
928
+ _view_on_window_state(self._check(), _WINDOW_STATE(), None)
929
+ return
930
+ callback = _WINDOW_STATE(_guard(lambda h, payload, d: function(json.loads(payload.decode()))))
931
+ self._set("window-state", callback, _view_on_window_state)
932
+
933
+ def set_drag_regions(self, regions):
934
+ """With dragRegions.source "host": [{"x", "y", "width", "height", "drag"}]."""
935
+ error = _P()
936
+ if not _view_set_drag_regions(self._check(), json.dumps(list(regions)).encode(), ctypes.byref(error)):
937
+ _raise(error, "drag regions rejected")
938
+
939
+ def set_popup_window_options(self, options):
940
+ """Options for the windows this view's pages open; None: the system's frame."""
941
+ error = _P()
942
+ text = json.dumps(options).encode() if options is not None else None
943
+ if not _view_set_popup_window_options(self._check(), text, ctypes.byref(error)):
944
+ _raise(error, "popup window options rejected")
945
+
946
+ @classmethod
947
+ def _adopt(cls, handle):
948
+ """Wrap a newly created native popup exactly once, from its creation callback."""
949
+ view = cls.__new__(cls)
950
+ view._handle = handle
951
+ view._initialize_callbacks()
952
+ return view
953
+
954
+ def _initialize_callbacks(self):
955
+ self._callbacks = {}
956
+ self._on_close_user = None
957
+ self._closed = False
958
+ self._set("close", _VIEW(_guard(self._closed_by_engine)), _view_on_close)
959
+ _alive.add(self)
960
+
961
+ def _set(self, kind, callback, setter):
962
+ self._callbacks[kind] = callback
963
+ setter(self._handle, callback, None)
964
+
965
+ def _closed_by_engine(self, handle, data):
966
+ self._closed = True
967
+ _alive.discard(self)
968
+ if self._on_close_user:
969
+ self._on_close_user()
970
+
971
+ def _check(self):
972
+ if self._closed:
973
+ raise Error("the view is closed")
974
+ return self._handle
975
+
976
+ def load(self, url):
977
+ _view_load_url(self._check(), url.encode())
978
+
979
+ def reload(self):
980
+ _view_reload(self._check())
981
+
982
+ def back(self):
983
+ _view_go_back(self._check())
984
+
985
+ def forward(self):
986
+ _view_go_forward(self._check())
987
+
988
+ def target_id(self):
989
+ return _string(_view_target(self._check()))
990
+
991
+ def resize(self, width, height):
992
+ _view_resize(self._check(), width, height)
993
+
994
+ def attach_native(self, parent, x, y, width, height):
995
+ """In a window of the application's: an X11 window id, or an NSView* as an int."""
996
+ error = ctypes.c_void_p()
997
+ if not _view_attach_native(self._check(), parent, x, y, width, height, ctypes.byref(error)):
998
+ _raise(error, "the window cannot be attached")
999
+
1000
+ def native_window(self):
1001
+ """Borrowed containing system window as {kind, handle}, or None.
1002
+
1003
+ kind is x11, win32 or appkit; appkit means NSWindow*, not NSView*.
1004
+ Requery after attach/detach. Never destroy or release this handle.
1005
+ """
1006
+ info = _NativeWindowInfo()
1007
+ if not _view_get_native_window(self._check(), ctypes.byref(info)):
1008
+ return None
1009
+ return {"kind": {1: "x11", 2: "win32", 3: "appkit"}[info.kind], "handle": info.handle}
1010
+
1011
+ def export_native_window(self, function):
1012
+ """function(handle) once, later: "x11:<XID>" or "wayland:<handle>" for
1013
+ the system's portals to parent a dialog to, or None when there is none
1014
+ (always on Windows and macOS, where native_window() is the handle)."""
1015
+ def done(data, handle):
1016
+ _alive.discard(callback)
1017
+ function(handle.decode() if handle else None)
1018
+ callback = _NATIVE_WINDOW_EXPORT(_guard(done))
1019
+ _alive.add(callback)
1020
+ if not _view_export_native_window(self._check(), callback, None):
1021
+ _alive.discard(callback)
1022
+ function(None)
1023
+
1024
+ def detach_native(self):
1025
+ """Back to its own window; False when it was in none of the application's."""
1026
+ return _view_detach_native(self._check())
1027
+
1028
+ def focus(self):
1029
+ """Focus to the view, as when a person clicks it; a page goes
1030
+ fullscreen only from a view with focus."""
1031
+ _view_focus(self._check())
1032
+
1033
+ def set_bounds(self, x, y, width, height):
1034
+ """Where an attached view is in its parent."""
1035
+ _view_set_bounds(self._check(), x, y, width, height)
1036
+
1037
+ def set_settings(self, settings):
1038
+ """Merge native preferences; None values reset individual keys."""
1039
+ source = settings if isinstance(settings, str) else json.dumps(settings)
1040
+ if '\0' in source:
1041
+ raise Error("view settings contain NUL")
1042
+ error = ctypes.c_void_p()
1043
+ if not _view_set_settings(self._check(), source.encode(), ctypes.byref(error)):
1044
+ _raise(error, "view settings rejected")
1045
+
1046
+ @property
1047
+ def settings(self):
1048
+ """Explicit native preferences; temporary CDP emulation is separate."""
1049
+ return json.loads(_string(_view_get_settings(self._check())))
1050
+
1051
+ def set_runtime_settings(self, settings):
1052
+ """What zebkit decides for this view (<zebkit/hooks.h>): thirdPartyCookies,
1053
+ dialogs, downloads, newWindows. All of it applies or none."""
1054
+ source = settings if isinstance(settings, str) else json.dumps(settings)
1055
+ if '\0' in source:
1056
+ raise Error("runtime settings contain NUL")
1057
+ error = ctypes.c_void_p()
1058
+ if not _view_set_runtime_settings(self._check(), source.encode(), ctypes.byref(error)):
1059
+ _raise(error, "runtime settings rejected")
1060
+
1061
+ @property
1062
+ def runtime_settings(self):
1063
+ """{"explicit": ..., "effective": ...}."""
1064
+ return json.loads(_string(_view_get_runtime_settings(self._check())))
1065
+
1066
+ def set_permission(self, permission, state, origin=None):
1067
+ """Set a view rule; None uses the current origin, '*' a default rule."""
1068
+ error = _P()
1069
+ if not _view_set_permission(self._check(), _permission_text(origin),
1070
+ _permission_text(permission), _permission_state(state), ctypes.byref(error)):
1071
+ _raise(error, "permission rule rejected")
1072
+
1073
+ def get_permission(self, permission, origin=None):
1074
+ """Effective policy for a concrete origin; document security still applies."""
1075
+ state = _view_get_permission(self._check(), _permission_text(origin), _permission_text(permission))
1076
+ if state < 0:
1077
+ raise Error("invalid permission or origin")
1078
+ return ("prompt", "granted", "denied")[state]
1079
+
1080
+ def reset_permissions(self, origin=None):
1081
+ """Remove all view rules, or only rules at the supplied origin/default."""
1082
+ error = _P()
1083
+ if not _view_reset_permissions(self._check(), _permission_text(origin), ctypes.byref(error)):
1084
+ _raise(error, "permission reset rejected")
1085
+
1086
+ def set_permission_timeout(self, milliseconds):
1087
+ """Deadline for future prompts, from 1 to 300000 milliseconds."""
1088
+ if isinstance(milliseconds, bool) or not isinstance(milliseconds, int) or not 1 <= milliseconds <= 300000:
1089
+ raise ValueError("permission timeout must be an integer from 1 to 300000")
1090
+ if not _view_permission_timeout(self._check(), milliseconds):
1091
+ raise Error("permission timeout rejected")
1092
+
1093
+ def on_permission(self, function):
1094
+ """function(PermissionRequest); None restores the default permission policy."""
1095
+ self._check()
1096
+ previous = self._callbacks.get("permission")
1097
+ callback = _PERMISSION(_guard(lambda h, request, payload, d:
1098
+ function(PermissionRequest(request, json.loads(payload))))) if function else _PERMISSION()
1099
+ self._set("permission", callback, _view_on_permission)
1100
+ if previous is not None:
1101
+ # A handler can replace itself while its trampoline is executing.
1102
+ post(lambda previous=previous: None)
1103
+
1104
+ def on_permission_result(self, function):
1105
+ """function(dict) receives asynchronous outcomes; None removes it."""
1106
+ self._check()
1107
+ previous = self._callbacks.get("permission-result")
1108
+ callback = _PERMISSION_RESULT(_guard(lambda h, payload, d: function(json.loads(payload)))) if function else _PERMISSION_RESULT()
1109
+ self._set("permission-result", callback, _view_on_permission_result)
1110
+ if previous is not None:
1111
+ post(lambda previous=previous: None)
1112
+
1113
+ def set_certificate_timeout(self, milliseconds):
1114
+ """Deadline for future certificate decisions, from 1 to 300000 milliseconds."""
1115
+ if isinstance(milliseconds, bool) or not isinstance(milliseconds, int) or not 1 <= milliseconds <= 300000:
1116
+ raise ValueError("certificate timeout must be an integer from 1 to 300000")
1117
+ if not _view_certificate_timeout(self._check(), milliseconds):
1118
+ raise Error("certificate timeout rejected")
1119
+
1120
+ def on_certificate(self, function):
1121
+ """function(CertificateRequest); None denies pending requests and removes it."""
1122
+ self._check()
1123
+ if function is not None and not callable(function):
1124
+ raise TypeError("certificate handler must be callable or None")
1125
+ previous = self._callbacks.get('certificate')
1126
+ callback = _CERTIFICATE(_guard(lambda h, request, payload, d:
1127
+ function(CertificateRequest(request, json.loads(payload))))) if function is not None else _CERTIFICATE()
1128
+ self._set('certificate', callback, _view_on_certificate)
1129
+ if previous is not None:
1130
+ post(lambda previous=previous: None)
1131
+
1132
+ def on_certificate_result(self, function):
1133
+ """function(dict) observes asynchronous outcomes; None removes it."""
1134
+ self._check()
1135
+ if function is not None and not callable(function):
1136
+ raise TypeError("certificate result observer must be callable or None")
1137
+ previous = self._callbacks.get('certificate-result')
1138
+ callback = _CERTIFICATE_RESULT(_guard(lambda h, payload, d:
1139
+ function(json.loads(payload)))) if function is not None else _CERTIFICATE_RESULT()
1140
+ self._set('certificate-result', callback, _view_on_certificate_result)
1141
+ if previous is not None:
1142
+ post(lambda previous=previous: None)
1143
+
1144
+ def set_http_auth_timeout(self, milliseconds):
1145
+ """Deadline for future HTTP challenges, from 1 to 300000 milliseconds."""
1146
+ if isinstance(milliseconds, bool) or not isinstance(milliseconds, int) or not 1 <= milliseconds <= 300000:
1147
+ raise ValueError("HTTP authentication timeout must be an integer from 1 to 300000")
1148
+ if not _view_http_auth_timeout(self._check(), milliseconds):
1149
+ raise Error("HTTP authentication timeout rejected")
1150
+
1151
+ def on_http_auth(self, function):
1152
+ """function(HttpAuthRequest); None cancels pending challenges and removes it."""
1153
+ self._check()
1154
+ if function is not None and not callable(function):
1155
+ raise TypeError("HTTP authentication handler must be callable or None")
1156
+ previous = self._callbacks.get('http-auth')
1157
+ callback = _HTTP_AUTH(_guard(lambda h, request, payload, d:
1158
+ function(HttpAuthRequest(request, json.loads(payload))))) if function is not None else _HTTP_AUTH()
1159
+ self._set('http-auth', callback, _view_on_http_auth)
1160
+ if previous is not None:
1161
+ post(lambda previous=previous: None)
1162
+
1163
+ def on_http_auth_result(self, function):
1164
+ """function(dict) observes credential provision/cancellation, not HTTP success."""
1165
+ self._check()
1166
+ if function is not None and not callable(function):
1167
+ raise TypeError("HTTP authentication result observer must be callable or None")
1168
+ previous = self._callbacks.get('http-auth-result')
1169
+ callback = _HTTP_AUTH_RESULT(_guard(lambda h, payload, d:
1170
+ function(json.loads(payload)))) if function is not None else _HTTP_AUTH_RESULT()
1171
+ self._set('http-auth-result', callback, _view_on_http_auth_result)
1172
+ if previous is not None:
1173
+ post(lambda previous=previous: None)
1174
+
1175
+ def _asked(self, kind, setter, request_type, function):
1176
+ self._check()
1177
+ if function is not None and not callable(function):
1178
+ raise TypeError(kind + " handler must be callable or None")
1179
+ previous = self._callbacks.get(kind)
1180
+ callback = _ASKED(_guard(lambda h, request, payload, d:
1181
+ function(request_type(request, json.loads(payload))))) if function is not None else _ASKED()
1182
+ self._set(kind, callback, setter)
1183
+ if previous is not None:
1184
+ post(lambda previous=previous: None)
1185
+
1186
+ def _told(self, kind, setter, function):
1187
+ self._check()
1188
+ if function is not None and not callable(function):
1189
+ raise TypeError(kind + " observer must be callable or None")
1190
+ previous = self._callbacks.get(kind)
1191
+ callback = _TOLD(_guard(lambda h, payload, d:
1192
+ function(json.loads(payload)))) if function is not None else _TOLD()
1193
+ self._set(kind, callback, setter)
1194
+ if previous is not None:
1195
+ post(lambda previous=previous: None)
1196
+
1197
+ def _deadline(self, setter, milliseconds):
1198
+ if isinstance(milliseconds, bool) or not isinstance(milliseconds, int) or not 1 <= milliseconds <= 300000:
1199
+ raise ValueError("a deadline is an integer from 1 to 300000")
1200
+ if not setter(self._check(), milliseconds):
1201
+ raise Error("deadline rejected")
1202
+
1203
+ def on_external_protocol(self, function):
1204
+ """function(dict): a link to another program. The engine opens nothing."""
1205
+ self._told('external-protocol', _view_on_external_protocol, function)
1206
+
1207
+ def on_download(self, function):
1208
+ """function(DownloadRequest); None cancels pending ones and removes it."""
1209
+ self._asked('download', _view_on_download, DownloadRequest, function)
1210
+
1211
+ def on_download_progress(self, function):
1212
+ self._told('download-progress', _view_on_download_progress, function)
1213
+
1214
+ def set_download_timeout(self, milliseconds):
1215
+ self._deadline(_view_download_timeout, milliseconds)
1216
+
1217
+ def cancel_download(self, download_id):
1218
+ return bool(_view_cancel_download(self._check(), download_id.encode()))
1219
+
1220
+ def on_client_certificate(self, function):
1221
+ """function(ClientCertificateRequest); without one no certificate is sent."""
1222
+ self._asked('client-certificate', _view_on_client_certificate, ClientCertificateRequest, function)
1223
+
1224
+ def on_client_certificate_result(self, function):
1225
+ self._told('client-certificate-result', _view_on_client_certificate_result, function)
1226
+
1227
+ def set_client_certificate_timeout(self, milliseconds):
1228
+ self._deadline(_view_client_certificate_timeout, milliseconds)
1229
+
1230
+ def add_world_script(self, source, world=None, main_frame_only=False):
1231
+ """A script before the page's, in the named isolated world or the page's."""
1232
+ if not _view_add_world_script(self._check(), None if world is None else world.encode(),
1233
+ source.encode(), bool(main_frame_only), None):
1234
+ raise Error("script or world name rejected")
1235
+
1236
+ def on_file_chooser(self, function):
1237
+ """function(FileChooserRequest); None cancels pending ones and removes it."""
1238
+ self._asked('file-chooser', _view_on_file_chooser, FileChooserRequest, function)
1239
+
1240
+ def on_eye_dropper(self, function):
1241
+ """function(EyeDropperRequest) for the page's EyeDropper.open(); without
1242
+ one it is cancelled."""
1243
+ self._asked('eye-dropper', _view_on_eye_dropper, EyeDropperRequest, function)
1244
+
1245
+ def on_device_chooser(self, function):
1246
+ """function(DeviceChooserRequest) for the page's USB, HID and serial
1247
+ choosers; without one the page gets no device."""
1248
+ self._asked('device-chooser', _view_on_device_chooser, DeviceChooserRequest, function)
1249
+
1250
+ def on_device_chooser_result(self, function):
1251
+ self._told('device-chooser-result', _view_on_device_chooser_result, function)
1252
+
1253
+ def set_device_chooser_timeout(self, milliseconds):
1254
+ self._deadline(_view_device_chooser_timeout, milliseconds)
1255
+
1256
+ def on_share(self, function):
1257
+ """function(ShareRequest) for the page's navigator.share()."""
1258
+ self._asked('share', _view_on_share, ShareRequest, function)
1259
+
1260
+ def set_share_timeout(self, milliseconds):
1261
+ self._deadline(_view_share_timeout, milliseconds)
1262
+
1263
+ def on_file_chooser_result(self, function):
1264
+ self._told('file-chooser-result', _view_on_file_chooser_result, function)
1265
+
1266
+ def set_file_chooser_timeout(self, milliseconds):
1267
+ self._deadline(_view_file_chooser_timeout, milliseconds)
1268
+
1269
+ def on_media_access(self, function):
1270
+ """function(MediaAccessRequest) for camera and microphone."""
1271
+ self._asked('media-access', _view_on_media_access, MediaAccessRequest, function)
1272
+
1273
+ def on_media_access_result(self, function):
1274
+ self._told('media-access-result', _view_on_media_access_result, function)
1275
+
1276
+ def set_media_access_timeout(self, milliseconds):
1277
+ self._deadline(_view_media_access_timeout, milliseconds)
1278
+
1279
+ def set_reserved_keys(self, keys):
1280
+ """Keys the page does not get, as ['Ctrl+Shift+KeyI']."""
1281
+ if not _view_set_reserved_keys(self._check(), json.dumps(list(keys)).encode(), None):
1282
+ raise Error("reserved keys rejected")
1283
+
1284
+ def on_reserved_key(self, function):
1285
+ self._told('reserved-key', _view_on_reserved_key, function)
1286
+
1287
+ def on_context_menu(self, function):
1288
+ """function(dict) with what was right-clicked, its menuId and the
1289
+ default items; while set, the engine shows no menu itself."""
1290
+ self._told('context-menu', _view_on_context_menu, function)
1291
+
1292
+ def context_menu_run(self, menu_id, command):
1293
+ """Runs a default item's command against what was right-clicked."""
1294
+ error = _P()
1295
+ if not _view_context_menu_run(self._check(), int(menu_id), command.encode(), ctypes.byref(error)):
1296
+ _raise(error, "the context menu's command was refused")
1297
+
1298
+ def context_menu_show(self, menu_id, items=None, function=None):
1299
+ """Shows a menu where it was asked for: the default items (None) or a
1300
+ list mixing default ids and the application's own; function(id) for
1301
+ an item of the application's ("" when none is chosen)."""
1302
+ error = _P()
1303
+ callback = _CONTEXT_MENU_ITEM(_guard(lambda h, item, d: function(item.decode()))) if function else \
1304
+ _CONTEXT_MENU_ITEM()
1305
+ self._callbacks["context-menu-item"] = callback
1306
+ text = json.dumps(items).encode() if items is not None else None
1307
+ if not _view_context_menu_show(self._check(), int(menu_id), text, callback, None, ctypes.byref(error)):
1308
+ _raise(error, "the context menu was not shown")
1309
+
1310
+ def set_fullscreen_policy(self, policy):
1311
+ if policy not in ("allow", "deny"):
1312
+ raise ValueError("fullscreen is allow or deny")
1313
+ if not _view_set_fullscreen_policy(self._check(), 0 if policy == "allow" else 1):
1314
+ raise Error("fullscreen policy rejected")
1315
+
1316
+ def on_fullscreen(self, function):
1317
+ self._told('fullscreen', _view_on_fullscreen, function)
1318
+
1319
+ def set_network_filter(self, rules):
1320
+ """A list of rules, as <zebkit/hooks.h> says; [] holds and tells nothing."""
1321
+ if not _view_set_network_filter(self._check(), json.dumps(rules).encode(), None):
1322
+ raise Error("network filter rejected")
1323
+
1324
+ def on_network(self, function):
1325
+ """function(NetworkRequest) for what a hold rule holds."""
1326
+ self._asked('network', _view_on_network, NetworkRequest, function)
1327
+
1328
+ def on_network_event(self, function):
1329
+ self._told('network-event', _view_on_network_event, function)
1330
+
1331
+ def set_network_filter_for_workers(self, on):
1332
+ """This view's filter also decides for its profile's shared and service workers."""
1333
+ return bool(_view_network_for_workers(self._check(), bool(on)))
1334
+
1335
+ def on_network_body(self, function):
1336
+ """function(request_id, bytes, end, truncated) for what a rule with body: true matches."""
1337
+ self._check()
1338
+ if function is not None and not callable(function):
1339
+ raise TypeError("network-body observer must be callable or None")
1340
+ previous = self._callbacks.get('network-body')
1341
+ callback = _NETWORK_BODY(_guard(lambda h, request_id, data, size, end, truncated, d:
1342
+ function(request_id.decode(), ctypes.string_at(data, size) if size else b"",
1343
+ bool(end), bool(truncated)))) if function is not None else _NETWORK_BODY()
1344
+ self._set('network-body', callback, _view_on_network_body)
1345
+ if previous is not None:
1346
+ post(lambda previous=previous: None)
1347
+
1348
+ def set_network_timeout(self, milliseconds):
1349
+ self._deadline(_view_network_timeout, milliseconds)
1350
+
1351
+ def set_navigation_fail_closed(self, fail_closed):
1352
+ """With True, an unanswered navigation is cancelled instead of continued."""
1353
+ if not _view_navigation_fail_closed(self._check(), bool(fail_closed)):
1354
+ raise RuntimeError("cannot set the navigation policy of this view")
1355
+
1356
+ def set_navigation_timeout(self, milliseconds):
1357
+ """Deadline for future navigation decisions, from 1 to 300000 milliseconds."""
1358
+ if isinstance(milliseconds, bool) or not isinstance(milliseconds, int) or not 1 <= milliseconds <= 300000:
1359
+ raise ValueError("navigation timeout must be an integer from 1 to 300000")
1360
+ if not _view_navigation_timeout(self._check(), milliseconds):
1361
+ raise Error("navigation timeout rejected")
1362
+
1363
+ def on_navigation(self, function):
1364
+ """function(NavigationRequest); None continues pending requests and removes policy."""
1365
+ self._check()
1366
+ previous = self._callbacks.get('navigation')
1367
+ callback = _NAVIGATION(_guard(lambda h, request, payload, d:
1368
+ function(NavigationRequest(request, json.loads(payload))))) if function else _NAVIGATION()
1369
+ self._set('navigation', callback, _view_on_navigation)
1370
+ if previous is not None:
1371
+ post(lambda previous=previous: None)
1372
+
1373
+ def on_navigation_result(self, function):
1374
+ """function(dict) observes asynchronous decisions; None removes it."""
1375
+ self._check()
1376
+ previous = self._callbacks.get('navigation-result')
1377
+ callback = _NAVIGATION_RESULT(_guard(lambda h, payload, d: function(json.loads(payload)))) if function else _NAVIGATION_RESULT()
1378
+ self._set('navigation-result', callback, _view_on_navigation_result)
1379
+ if previous is not None:
1380
+ post(lambda previous=previous: None)
1381
+
1382
+ def set_popup_policy(self, policy):
1383
+ """Set block-without-gesture, allow or block for future new windows."""
1384
+ policies = {"block-without-gesture": 0, "allow": 1, "block": 2}
1385
+ if policy not in policies:
1386
+ raise ValueError("unknown popup policy")
1387
+ return bool(_view_popup_policy(self._check(), policies[policy]))
1388
+
1389
+ @property
1390
+ def popup_policy(self):
1391
+ return ("block-without-gesture", "allow", "block")[_view_get_popup_policy(self._check())]
1392
+
1393
+ @property
1394
+ def window_open_info(self):
1395
+ """Creation snapshot for a popup; an ordinary view returns an empty dict."""
1396
+ value = _view_window_open_info(self._check())
1397
+ if not value:
1398
+ raise Error("window metadata unavailable on this thread")
1399
+ return json.loads(_string(value))
1400
+
1401
+ def on_window_open(self, function):
1402
+ """function(child_view, url) receives the original popup with its opener."""
1403
+ self._check()
1404
+ if function is not None and not callable(function):
1405
+ raise TypeError("window handler must be callable or None")
1406
+ previous = self._callbacks.get('window-open')
1407
+ callback = _WINDOW_OPEN(_guard(lambda h, child, url, d:
1408
+ function(View._adopt(child), url.decode()))) if function is not None else _WINDOW_OPEN()
1409
+ self._set('window-open', callback, _view_on_window_open)
1410
+ if previous is not None:
1411
+ post(lambda previous=previous: None)
1412
+
1413
+ def on_window_open_event(self, function):
1414
+ """function(dict) observes decision/created metadata; None removes it."""
1415
+ self._check()
1416
+ if function is not None and not callable(function):
1417
+ raise TypeError("window observer must be callable or None")
1418
+ previous = self._callbacks.get('window-open-event')
1419
+ callback = _WINDOW_OPEN_EVENT(_guard(lambda h, payload, d:
1420
+ function(json.loads(payload)))) if function is not None else _WINDOW_OPEN_EVENT()
1421
+ self._set('window-open-event', callback, _view_on_window_open_event)
1422
+ if previous is not None:
1423
+ post(lambda previous=previous: None)
1424
+
1425
+ def on_console(self, function):
1426
+ """function(dict) observes native document-console messages; None removes it."""
1427
+ self._check()
1428
+ if function is not None and not callable(function):
1429
+ raise TypeError("console observer must be callable or None")
1430
+ previous = self._callbacks.get('console')
1431
+ callback = _CONSOLE(_guard(lambda h, payload, d:
1432
+ function(json.loads(payload)))) if function is not None else _CONSOLE()
1433
+ self._set('console', callback, _view_on_console)
1434
+ if previous is not None:
1435
+ post(lambda previous=previous: None)
1436
+
1437
+ def on_popup_blocked(self, function):
1438
+ """Report a blocked popup as a dict, after the decision; None removes it."""
1439
+ self._check()
1440
+ previous = self._callbacks.get("popup-blocked")
1441
+ callback = _POPUP_BLOCKED(_guard(lambda view, event, data: function(json.loads(event)))) if function else _POPUP_BLOCKED()
1442
+ self._set("popup-blocked", callback, _view_on_popup_blocked)
1443
+ if previous is not None:
1444
+ post(lambda previous=previous: None)
1445
+
1446
+ def on_authentication(self, function):
1447
+ """Receive host-owned Passkey events as dictionaries; None restores native UI.
1448
+
1449
+ Never log/persist these events or PIN actions. Off-screen hosts must
1450
+ opt into authentication UI. See docs/PASSKEYS.md for the schema.
1451
+ """
1452
+ handle = self._check()
1453
+ _view_on_authentication(handle, _AUTHENTICATION(), None)
1454
+ previous = self._callbacks.pop("authentication", None)
1455
+ if previous is not None:
1456
+ # A handler may unregister itself; keep the ctypes trampoline
1457
+ # alive until its native invocation has returned.
1458
+ post(lambda previous=previous: None)
1459
+ if function is None:
1460
+ return True
1461
+ callback = _AUTHENTICATION(_guard(lambda h, event, data: function(json.loads(event))))
1462
+ self._callbacks["authentication"] = callback
1463
+ return bool(_view_on_authentication(handle, callback, None))
1464
+
1465
+ def authentication_action(self, action):
1466
+ """Queue a current request/revision action; True is not authentication success."""
1467
+ return bool(_view_authentication_action(self._check(), json.dumps(action).encode()))
1468
+
1469
+ def set_authentication_ui(self, enabled):
1470
+ """Allow Passkey UI for this view."""
1471
+ return bool(_view_authentication_ui(self._check(), bool(enabled)))
1472
+
1473
+ def close(self):
1474
+ if not self._closed:
1475
+ _view_close(self._handle)
1476
+
1477
+ @property
1478
+ def url(self):
1479
+ return _string(_view_get_url(self._check()))
1480
+
1481
+ @property
1482
+ def title(self):
1483
+ return _string(_view_get_title(self._check()))
1484
+
1485
+ def on_load(self, function):
1486
+ """function(event, url), event one of LOAD_STARTED, LOAD_COMMITTED,
1487
+ LOAD_FINISHED and LOAD_FAILED."""
1488
+ self._set("load", _LOAD(_guard(lambda h, e, u, d: function(e, u.decode()))), _view_on_load)
1489
+
1490
+ def on_title(self, function):
1491
+ self._set("title", _TITLE(_guard(lambda h, t, d: function(t.decode()))), _view_on_title)
1492
+
1493
+ def on_close(self, function):
1494
+ self._on_close_user = function
1495
+
1496
+ def evaluate(self, script, function=None):
1497
+ """Run script in the page; function(value, error), value as from JSON."""
1498
+ def done(handle, result, error, data):
1499
+ _alive.discard(callback)
1500
+ if function:
1501
+ if error is not None:
1502
+ function(None, error.decode())
1503
+ else:
1504
+ function(json.loads(result.decode()) if result else None, None)
1505
+ callback = _RESULT(_guard(done))
1506
+ _alive.add(callback)
1507
+ _view_evaluate(self._check(), script.encode(), callback, None)
1508
+
1509
+ def set_user_agent_override(self, options, function=None):
1510
+ """Set UA/client hints together; function(value, error) reports validation."""
1511
+ handle = self._check()
1512
+ if function is not None and not callable(function):
1513
+ raise TypeError("completion must be callable or None")
1514
+ source = options if isinstance(options, str) else json.dumps(options, ensure_ascii=False)
1515
+ encoded = source.encode('utf-8')
1516
+ if b'\0' in encoded:
1517
+ raise ValueError("user agent options must not contain a literal NUL")
1518
+ def done(handle, result, error, data):
1519
+ _alive.discard(callback)
1520
+ if function is not None:
1521
+ function(json.loads(result) if result else None, error.decode() if error else None)
1522
+ callback = _RESULT(_guard(done))
1523
+ _alive.add(callback)
1524
+ return bool(_view_user_agent_override(handle, encoded, callback, None))
1525
+
1526
+ def grant(self, origin, allow, files_root=None):
1527
+ """Give pages of origin the zebkit.* capabilities in allow (ALLOW_*)."""
1528
+ _view_grant(self._check(), origin.encode(), allow,
1529
+ str(files_root).encode() if files_root else None)
1530
+
1531
+ def bind(self, name, function):
1532
+ """Make zebkit.app.<name>(...args) in the page call
1533
+ function(*args, origin=...), whose return value (JSON-able) the
1534
+ page's promise resolves with; an exception rejects it."""
1535
+ def called(handle, origin, args, call, data):
1536
+ try:
1537
+ result = function(*json.loads(args.decode()), origin=origin.decode())
1538
+ answer = json.dumps(result).encode()
1539
+ _call_resolve_json(call, answer, len(answer))
1540
+ except Exception as e: # noqa: BLE001
1541
+ _call_reject(call, str(e).encode())
1542
+ if function is None:
1543
+ self._callbacks.pop("bind:" + name, None)
1544
+ _view_bind(self._check(), name.encode(), _BIND(), None)
1545
+ return
1546
+ callback = _BIND(called)
1547
+ self._callbacks["bind:" + name] = callback
1548
+ _view_bind(self._check(), name.encode(), callback, None)
1549
+
1550
+
1551
+ def cdp_listen(address=None, port=0):
1552
+ error = ctypes.c_void_p()
1553
+ bound = _cdp_listen(address.encode() if address else None, port, ctypes.byref(error))
1554
+ if not bound:
1555
+ _raise(error, "cannot listen")
1556
+ return bound
1557
+
1558
+
1559
+ def cdp_port():
1560
+ return _cdp_get_port()
1561
+
1562
+
1563
+ def cdp_url():
1564
+ return _string(_cdp_get_url())
1565
+
1566
+
1567
+ def cdp_stop():
1568
+ _cdp_stop()
1569
+
1570
+
1571
+ def fetch(url, function, method="GET", headers=None, body=None):
1572
+ """Request url through the engine's network stack; function(response)
1573
+ gets a dict: status, url, headers (a dict), body (bytes), error."""
1574
+ def done(response, data):
1575
+ _alive.discard(callback)
1576
+ r = response.contents
1577
+ headers_out = {}
1578
+ for line in (r.headers or b"").decode().split("\r\n"):
1579
+ if ": " in line:
1580
+ name, value = line.split(": ", 1)
1581
+ headers_out[name] = value
1582
+ function({
1583
+ "status": r.status,
1584
+ "url": (r.url or b"").decode(),
1585
+ "headers": headers_out,
1586
+ "body": ctypes.string_at(r.body, r.body_size) if r.body_size else b"",
1587
+ "error": r.error.decode() if r.error else None,
1588
+ })
1589
+ callback = _RESPONSE(_guard(done))
1590
+ _alive.add(callback)
1591
+ lines = "\r\n".join(f"{k}: {v}" for k, v in (headers or {}).items())
1592
+ data = _bytes(body) if body is not None else b""
1593
+ _fetch(method.encode(), url.encode(), lines.encode() if lines else None, data or None, len(data), callback, None)
1594
+
1595
+
1596
+ # ---- the services ----
1597
+
1598
+ def compress(data, format="gzip", level=-1):
1599
+ data = _bytes(data)
1600
+ size, error = ctypes.c_size_t(), ctypes.c_void_p()
1601
+ out = _compress(_COMPRESSION[format], data, len(data), level, ctypes.byref(size), ctypes.byref(error))
1602
+ if not out:
1603
+ _raise(error, "compression failed")
1604
+ return _buffer(out, size.value)
1605
+
1606
+
1607
+ def decompress(data, format="gzip", max_size=0):
1608
+ data = _bytes(data)
1609
+ size, error = ctypes.c_size_t(), ctypes.c_void_p()
1610
+ out = _decompress(_COMPRESSION[format], data, len(data), max_size, ctypes.byref(size), ctypes.byref(error))
1611
+ if not out:
1612
+ _raise(error, "decompression failed")
1613
+ return _buffer(out, size.value)
1614
+
1615
+
1616
+ def digest(data, algorithm="sha256"):
1617
+ data = _bytes(data)
1618
+ kind = _DIGEST[algorithm]
1619
+ out = ctypes.create_string_buffer(_digest_size(kind))
1620
+ if not _digest_compute(kind, data, len(data), out):
1621
+ raise Error("digest failed")
1622
+ return out.raw
1623
+
1624
+
1625
+ def hmac(key, data, algorithm="sha256"):
1626
+ key, data = _bytes(key), _bytes(data)
1627
+ kind = _DIGEST[algorithm]
1628
+ out = ctypes.create_string_buffer(_digest_size(kind))
1629
+ if not _hmac(kind, key, len(key), data, len(data), out):
1630
+ raise Error("hmac failed")
1631
+ return out.raw
1632
+
1633
+
1634
+ def random_bytes(count):
1635
+ out = ctypes.create_string_buffer(count)
1636
+ if not _random_bytes(out, count):
1637
+ raise Error("no random bytes")
1638
+ return out.raw
1639
+
1640
+
1641
+ def aes_gcm_seal(key, nonce, plaintext, ad=b""):
1642
+ key, nonce, plaintext, ad = _bytes(key), _bytes(nonce), _bytes(plaintext), _bytes(ad)
1643
+ size, error = ctypes.c_size_t(), ctypes.c_void_p()
1644
+ out = _aes_gcm_seal(key, len(key), nonce, len(nonce), ad or None, len(ad), plaintext, len(plaintext),
1645
+ ctypes.byref(size), ctypes.byref(error))
1646
+ if not out:
1647
+ _raise(error, "sealing failed")
1648
+ return _buffer(out, size.value)
1649
+
1650
+
1651
+ def aes_gcm_open(key, nonce, sealed, ad=b""):
1652
+ key, nonce, sealed, ad = _bytes(key), _bytes(nonce), _bytes(sealed), _bytes(ad)
1653
+ size, error = ctypes.c_size_t(), ctypes.c_void_p()
1654
+ out = _aes_gcm_open(key, len(key), nonce, len(nonce), ad or None, len(ad), sealed, len(sealed),
1655
+ ctypes.byref(size), ctypes.byref(error))
1656
+ if not out:
1657
+ _raise(error, "opening failed")
1658
+ return _buffer(out, size.value)
1659
+
1660
+
1661
+ def url_part(url, base=None, part="spec"):
1662
+ """A part of url, resolved against base, as a browser parses it; None
1663
+ when it is not a valid URL."""
1664
+ return _string(_url_get(url.encode(), base.encode() if base else None, _URL_PART[part]))
1665
+
1666
+
1667
+ def registrable_domain(host_or_url):
1668
+ return _string(_url_registrable_domain(host_or_url.encode()))
1669
+
1670
+
1671
+ def image_decode(data):
1672
+ """(width, height, RGBA bytes) of a PNG, JPEG or WebP file."""
1673
+ data = _bytes(data)
1674
+ width, height, error = ctypes.c_int(), ctypes.c_int(), ctypes.c_void_p()
1675
+ out = _image_decode(data, len(data), ctypes.byref(width), ctypes.byref(height), ctypes.byref(error))
1676
+ if not out:
1677
+ _raise(error, "decoding failed")
1678
+ return width.value, height.value, _buffer(out, width.value * height.value * 4)
1679
+
1680
+
1681
+ def image_encode(rgba, width, height, format="png", quality=-1):
1682
+ rgba = _bytes(rgba)
1683
+ if len(rgba) != width * height * 4:
1684
+ raise Error("the pixels must be width * height * 4 bytes of RGBA")
1685
+ size, error = ctypes.c_size_t(), ctypes.c_void_p()
1686
+ out = _image_encode(_IMAGE[format], rgba, width, height, quality, ctypes.byref(size), ctypes.byref(error))
1687
+ if not out:
1688
+ _raise(error, "encoding failed")
1689
+ return _buffer(out, size.value)
1690
+
1691
+
1692
+ def icu_init():
1693
+ return bool(_icu_init())
1694
+
1695
+
1696
+ # ---- PDF: <zebkit/pdf.h> ----
1697
+
1698
+ class _RenderOptions(ctypes.Structure):
1699
+ _fields_ = [("scale", ctypes.c_float), ("rotation", ctypes.c_int), ("flags", ctypes.c_uint),
1700
+ ("background", ctypes.c_uint32), ("x", ctypes.c_int), ("y", ctypes.c_int),
1701
+ ("width", ctypes.c_int), ("height", ctypes.c_int)]
1702
+
1703
+
1704
+ _pdf_open = _declare("zebkit_pdf_open", _P, _P, _Z, _S, _EP)
1705
+ _pdf_open_file = _declare("zebkit_pdf_open_file", _P, _S, _S, _EP)
1706
+ _pdf_close = _declare("zebkit_pdf_close", None, _P)
1707
+ _pdf_save = _declare("zebkit_pdf_save", _P, _P, _U, _ZP, _EP)
1708
+ _pdf_info = _declare("zebkit_pdf_info", _P, _P)
1709
+ _pdf_set_metadata = _declare("zebkit_pdf_set_metadata", _B, _P, _S, _EP)
1710
+ _pdf_page_count = _declare("zebkit_pdf_page_count", _I, _P)
1711
+ _pdf_page = _declare("zebkit_pdf_page", _P, _P, _I, _EP)
1712
+ _pdf_render = _declare("zebkit_pdf_render", _P, _P, _I, ctypes.POINTER(_RenderOptions), _IP, _IP, _EP)
1713
+ _pdf_render_annotation = _declare("zebkit_pdf_render_annotation", _P, _P, _I, _I, _I,
1714
+ ctypes.POINTER(_RenderOptions), _IP, _IP, _EP)
1715
+ _pdf_text = _declare("zebkit_pdf_text", _P, _P, _I, _EP)
1716
+ _pdf_text_layout = _declare("zebkit_pdf_text_layout", _P, _P, _I, _EP)
1717
+ _pdf_text_rects = _declare("zebkit_pdf_text_rects", _P, _P, _I, _I, _I, _EP)
1718
+ _pdf_char_at = _declare("zebkit_pdf_char_at", _I, _P, _I, ctypes.c_double, ctypes.c_double, ctypes.c_double)
1719
+ _pdf_search = _declare("zebkit_pdf_search", _P, _P, _S, _U, _I, _I, _EP)
1720
+ _pdf_set_outline = _declare("zebkit_pdf_set_outline", _B, _P, _S, _EP)
1721
+ _pdf_outline = _declare("zebkit_pdf_outline", _P, _P, _EP)
1722
+ _pdf_links = _declare("zebkit_pdf_links", _P, _P, _I, _EP)
1723
+ _pdf_annotations = _declare("zebkit_pdf_annotations", _P, _P, _I, _EP)
1724
+ _pdf_annotation_add = _declare("zebkit_pdf_annotation_add", _I, _P, _I, _S, _EP)
1725
+ _pdf_annotation_update = _declare("zebkit_pdf_annotation_update", _B, _P, _I, _I, _S, _EP)
1726
+ _pdf_annotation_remove = _declare("zebkit_pdf_annotation_remove", _B, _P, _I, _I, _EP)
1727
+ _pdf_flatten = _declare("zebkit_pdf_flatten", _B, _P, _I, _B, _EP)
1728
+ _pdf_attachments = _declare("zebkit_pdf_attachments", _P, _P, _EP)
1729
+ _pdf_attachment = _declare("zebkit_pdf_attachment", _P, _P, _I, _ZP, _EP)
1730
+ _pdf_attach = _declare("zebkit_pdf_attach", _B, _P, _S, _P, _Z, _EP)
1731
+ _pdf_detach = _declare("zebkit_pdf_detach", _B, _P, _I, _EP)
1732
+
1733
+ RENDER_ANNOTATIONS, RENDER_FORMS, RENDER_LCD_TEXT, RENDER_GRAYSCALE, RENDER_PRINTING, RENDER_NO_SMOOTHING = \
1734
+ 1, 2, 4, 8, 16, 32
1735
+
1736
+
1737
+ class Pdf:
1738
+ """A PDF document on the engine's PDFium (<zebkit/pdf.h>), from bytes or
1739
+ a path. Structured answers are Python values; coordinates are PDF page
1740
+ space. Needs no main(); any thread may use it, one at a time."""
1741
+
1742
+ def __init__(self, source, password=None):
1743
+ error = ctypes.c_void_p()
1744
+ password = password.encode() if password else None
1745
+ if isinstance(source, (bytes, bytearray, memoryview)):
1746
+ data = bytes(source)
1747
+ self._handle = _pdf_open(data, len(data), password, ctypes.byref(error))
1748
+ else:
1749
+ self._handle = _pdf_open_file(os.fspath(source).encode(), password, ctypes.byref(error))
1750
+ if not self._handle:
1751
+ _raise(error, "the document cannot be opened")
1752
+
1753
+ def __enter__(self):
1754
+ return self
1755
+
1756
+ def __exit__(self, *exc):
1757
+ self.close()
1758
+
1759
+ def __del__(self):
1760
+ self.close()
1761
+
1762
+ def close(self):
1763
+ if getattr(self, "_handle", None):
1764
+ _pdf_close(self._handle)
1765
+ self._handle = None
1766
+
1767
+ def _json(self, function, *args, fallback="failed"):
1768
+ error = ctypes.c_void_p()
1769
+ out = function(self._handle, *args, ctypes.byref(error))
1770
+ if not out:
1771
+ _raise(error, fallback)
1772
+ return json.loads(_string(out))
1773
+
1774
+ def _ok(self, function, *args, fallback="failed"):
1775
+ error = ctypes.c_void_p()
1776
+ if not function(self._handle, *args, ctypes.byref(error)):
1777
+ _raise(error, fallback)
1778
+
1779
+ def info(self):
1780
+ return json.loads(_string(_pdf_info(self._handle)))
1781
+
1782
+ def set_metadata(self, **entries):
1783
+ self._ok(_pdf_set_metadata, json.dumps(entries).encode())
1784
+
1785
+ @property
1786
+ def page_count(self):
1787
+ return _pdf_page_count(self._handle)
1788
+
1789
+ def page(self, index):
1790
+ return self._json(_pdf_page, index, fallback="no page")
1791
+
1792
+ def render(self, index, scale=1.0, rotation=0, flags=RENDER_ANNOTATIONS, background=0xFFFFFFFF,
1793
+ x=0, y=0, width=0, height=0):
1794
+ """(width, height, RGBA bytes) of a page, or of a tile of it."""
1795
+ options = _RenderOptions(scale, rotation, flags, background, x, y, width, height)
1796
+ out_width, out_height, error = ctypes.c_int(), ctypes.c_int(), ctypes.c_void_p()
1797
+ out = _pdf_render(self._handle, index, ctypes.byref(options), ctypes.byref(out_width),
1798
+ ctypes.byref(out_height), ctypes.byref(error))
1799
+ if not out:
1800
+ _raise(error, "the page cannot be rendered")
1801
+ return out_width.value, out_height.value, _buffer(out, out_width.value * out_height.value * 4)
1802
+
1803
+ def render_annotation(self, index, annotation, mode=0, scale=1.0, rotation=0, background=0):
1804
+ """(width, height, RGBA bytes) of an annotation's appearance alone (mode 0
1805
+ normal, 1 rollover, 2 down), or None when it has no such appearance."""
1806
+ options = _RenderOptions(scale, rotation, 0, background, 0, 0, 0, 0)
1807
+ out_width, out_height, error = ctypes.c_int(), ctypes.c_int(), ctypes.c_void_p()
1808
+ out = _pdf_render_annotation(self._handle, index, annotation, mode, ctypes.byref(options),
1809
+ ctypes.byref(out_width), ctypes.byref(out_height), ctypes.byref(error))
1810
+ if not out:
1811
+ message = _string(error.value) if error.value else "the annotation cannot be rendered"
1812
+ if message == "no appearance":
1813
+ return None
1814
+ raise Error(message)
1815
+ return out_width.value, out_height.value, _buffer(out, out_width.value * out_height.value * 4)
1816
+
1817
+ def text(self, index):
1818
+ error = ctypes.c_void_p()
1819
+ out = _pdf_text(self._handle, index, ctypes.byref(error))
1820
+ if not out:
1821
+ _raise(error, "no text")
1822
+ return _string(out)
1823
+
1824
+ def text_layout(self, index):
1825
+ return self._json(_pdf_text_layout, index)
1826
+
1827
+ def text_rects(self, index, start, count):
1828
+ return self._json(_pdf_text_rects, index, start, count)
1829
+
1830
+ def char_at(self, index, x, y, tolerance=2.0):
1831
+ found = _pdf_char_at(self._handle, index, x, y, tolerance)
1832
+ return None if found < 0 else found
1833
+
1834
+ def search(self, query, match_case=False, whole_word=False, first=0, limit=0):
1835
+ flags = (1 if match_case else 0) | (2 if whole_word else 0)
1836
+ return self._json(_pdf_search, query.encode(), flags, first, limit)
1837
+
1838
+ def set_outline(self, items):
1839
+ """Replace the bookmark tree; [] removes it. Validated before mutation."""
1840
+ self._ok(_pdf_set_outline, json.dumps(items).encode())
1841
+
1842
+ def outline(self):
1843
+ return self._json(_pdf_outline)
1844
+
1845
+ def links(self, index):
1846
+ return self._json(_pdf_links, index)
1847
+
1848
+ def annotations(self, index):
1849
+ return self._json(_pdf_annotations, index)
1850
+
1851
+ def add_annotation(self, index, annotation):
1852
+ error = ctypes.c_void_p()
1853
+ added = _pdf_annotation_add(self._handle, index, json.dumps(annotation).encode(), ctypes.byref(error))
1854
+ if added < 0:
1855
+ _raise(error, "the annotation cannot be made")
1856
+ return added
1857
+
1858
+ def update_annotation(self, index, annotation, changes):
1859
+ self._ok(_pdf_annotation_update, index, annotation, json.dumps(changes).encode())
1860
+
1861
+ def remove_annotation(self, index, annotation):
1862
+ self._ok(_pdf_annotation_remove, index, annotation)
1863
+
1864
+ def flatten(self, index, for_print=False):
1865
+ self._ok(_pdf_flatten, index, for_print)
1866
+
1867
+ def attachments(self):
1868
+ return self._json(_pdf_attachments)
1869
+
1870
+ def attachment(self, index):
1871
+ size, error = ctypes.c_size_t(), ctypes.c_void_p()
1872
+ out = _pdf_attachment(self._handle, index, ctypes.byref(size), ctypes.byref(error))
1873
+ if not out:
1874
+ _raise(error, "no attachment")
1875
+ return _buffer(out, size.value)
1876
+
1877
+ def attach(self, name, data):
1878
+ data = _bytes(data)
1879
+ self._ok(_pdf_attach, name.encode(), data, len(data))
1880
+
1881
+ def detach(self, index):
1882
+ self._ok(_pdf_detach, index)
1883
+
1884
+ def save(self, incremental=False, no_security=False):
1885
+ size, error = ctypes.c_size_t(), ctypes.c_void_p()
1886
+ out = _pdf_save(self._handle, (1 if incremental else 0) | (2 if no_security else 0), ctypes.byref(size),
1887
+ ctypes.byref(error))
1888
+ if not out:
1889
+ _raise(error, "the document cannot be saved")
1890
+ return _buffer(out, size.value)
1891
+
1892
+
1893
+ # ---- URL schemes of the application's own ----
1894
+
1895
+ SCHEME_STANDARD, SCHEME_SECURE, SCHEME_FETCH, SCHEME_BYPASS_CSP = 1, 2, 4, 8
1896
+
1897
+ _SCHEME = ctypes.CFUNCTYPE(None, _P, _P)
1898
+ _scheme_register = _declare("zebkit_scheme_register", _B, _S, _U)
1899
+ _scheme_handle = _declare("zebkit_scheme_handle", None, _S, _SCHEME, _P)
1900
+ _request_url = _declare("zebkit_request_url", _S, _P)
1901
+ _request_method = _declare("zebkit_request_method", _S, _P)
1902
+ _request_headers = _declare("zebkit_request_headers", _S, _P)
1903
+ _request_body = _declare("zebkit_request_body", ctypes.POINTER(ctypes.c_uint8), _P, _ZP)
1904
+ _request_respond = _declare("zebkit_request_respond", None, _P, _I, _S, _P, _Z)
1905
+ _request_respond_file = _declare("zebkit_request_respond_file", None, _P, _S, _S)
1906
+
1907
+
1908
+ class Request:
1909
+ """A request for a URL of the application's scheme. Answer it once, with
1910
+ respond() or respond_file(), from any thread."""
1911
+
1912
+ def __init__(self, handle):
1913
+ self._handle = handle
1914
+ self.url = _request_url(handle).decode()
1915
+ self.method = _request_method(handle).decode()
1916
+ self.headers = {}
1917
+ for line in _request_headers(handle).decode().split("\r\n"):
1918
+ name, _, value = line.partition(":")
1919
+ if name:
1920
+ self.headers[name.strip()] = value.strip()
1921
+ size = ctypes.c_size_t()
1922
+ body = _request_body(handle, ctypes.byref(size))
1923
+ self.body = ctypes.string_at(body, size.value) if body else None
1924
+
1925
+ def _take(self):
1926
+ handle, self._handle = self._handle, None
1927
+ if not handle:
1928
+ raise Error("the request is answered already")
1929
+ return handle
1930
+
1931
+ def respond(self, status=200, body=b"", headers=None):
1932
+ body = _bytes(body)
1933
+ lines = "\r\n".join(f"{k}: {v}" for k, v in (headers or {}).items())
1934
+ _request_respond(self._take(), status, lines.encode(), body, len(body))
1935
+
1936
+ def respond_file(self, path, headers=None):
1937
+ lines = "\r\n".join(f"{k}: {v}" for k, v in (headers or {}).items())
1938
+ _request_respond_file(self._take(), os.fspath(path).encode(), lines.encode())
1939
+
1940
+
1941
+ def scheme_register(scheme, flags=SCHEME_STANDARD | SCHEME_SECURE | SCHEME_FETCH):
1942
+ """Makes scheme one of the application's: before main()."""
1943
+ return bool(_scheme_register(scheme.encode(), flags))
1944
+
1945
+
1946
+ def scheme_handle(scheme, function):
1947
+ """function(Request) answers the scheme's requests, on the engine's thread."""
1948
+ callback = _SCHEME(_guard(lambda handle, data: function(Request(handle))))
1949
+ _alive.add(callback)
1950
+ _scheme_handle(scheme.encode(), callback, None)
1951
+
1952
+
1953
+ # ---- The application ---------------------------------------------------
1954
+
1955
+ _MENU = ctypes.CFUNCTYPE(None, ctypes.c_char_p, _P)
1956
+ _PATHS = ctypes.CFUNCTYPE(None, ctypes.c_char_p, _P)
1957
+ _APP = ctypes.CFUNCTYPE(None, _P)
1958
+ _app_set_menu = _declare("zebkit_app_set_menu", _B, _S, _MENU, _P, _EP)
1959
+ _app_update_menu_item = _declare("zebkit_app_update_menu_item", _B, _S, _S, _EP)
1960
+ _app_get_menu = _declare("zebkit_app_get_menu", _P)
1961
+ _app_on_open_files = _declare("zebkit_app_on_open_files", None, _PATHS, _P)
1962
+ _app_on_reopen = _declare("zebkit_app_on_reopen", None, _APP, _P)
1963
+ _app_on_quit_request = _declare("zebkit_app_on_quit_request", None, _APP, _P)
1964
+ _app_set_badge = _declare("zebkit_app_set_badge", _B, _S)
1965
+ _app_set_progress = _declare("zebkit_app_set_progress", _B, ctypes.c_double)
1966
+ _app_request_attention = _declare("zebkit_app_request_attention", None, _B)
1967
+ _app_set_dock_menu = _declare("zebkit_app_set_dock_menu", _B, _S, _MENU, _P, _EP)
1968
+ # The application's callbacks, one of each, as the engine holds them.
1969
+ _app_callbacks = {}
1970
+
1971
+
1972
+ def app_set_badge(text):
1973
+ """The badge on the application's icon in the Dock or on the taskbar; a
1974
+ number on Linux's launcher docks; "" or None for none."""
1975
+ return bool(_app_set_badge((text or "").encode()))
1976
+
1977
+
1978
+ def app_set_progress(progress):
1979
+ """A progress from 0 to 1 on the application's icon; None (or below 0)
1980
+ for none."""
1981
+ return bool(_app_set_progress(-1.0 if progress is None else float(progress)))
1982
+
1983
+
1984
+ def app_request_attention(critical=False):
1985
+ """The Dock's bounce (critical: until the application is active) or the
1986
+ taskbar button's flash; urgent on Linux's launcher docks."""
1987
+ _app_request_attention(bool(critical))
1988
+
1989
+
1990
+ def app_set_dock_menu(items, function):
1991
+ """The Dock's menu (macOS): items as app_set_menu's; function(id) for one
1992
+ chosen. Raises elsewhere."""
1993
+ text = items if isinstance(items, str) else json.dumps(items)
1994
+ callback = _MENU(_guard(lambda item, data: function(item.decode())))
1995
+ error = ctypes.c_void_p()
1996
+ if not _app_set_dock_menu(text.encode(), callback, None, ctypes.byref(error)):
1997
+ _raise(error, "the Dock's menu was refused")
1998
+ _app_callbacks["dock"] = callback
1999
+
2000
+
2001
+ def app_set_menu(menu, function):
2002
+ """The application's menu: a list of {"title", "items"} (or its JSON),
2003
+ where an item is {"title", "id", "key", "modifiers"}, {"role"},
2004
+ {"title", "items"} or {"separator": True}; function(id) is called when
2005
+ an item with an id is chosen. The menu bar on macOS; elsewhere the
2006
+ items' keys work in the application's windows. On the engine's thread."""
2007
+ text = menu if isinstance(menu, str) else json.dumps(menu)
2008
+ callback = _MENU(_guard(lambda item, data: function(item.decode())))
2009
+ error = ctypes.c_void_p()
2010
+ if not _app_set_menu(text.encode(), callback, None, ctypes.byref(error)):
2011
+ _raise(error, "the menu was refused")
2012
+ _app_callbacks["menu"] = callback
2013
+
2014
+
2015
+ def app_update_menu_item(item_id, **state):
2016
+ """Changes the menu item item_id without a new menu: enabled, checked,
2017
+ title; checking one of a radioGroup unchecks the others."""
2018
+ error = ctypes.c_void_p()
2019
+ if not _app_update_menu_item(item_id.encode(), json.dumps(state).encode(), ctypes.byref(error)):
2020
+ _raise(error, "the menu item was not changed")
2021
+
2022
+
2023
+ def app_menu():
2024
+ """The menu with its items' state."""
2025
+ value = _string(_app_get_menu())
2026
+ return json.loads(value) if value else []
2027
+
2028
+
2029
+ def app_on_open_files(function):
2030
+ """function(paths) for files the system asks the running application to
2031
+ open (macOS: the Finder and the Dock); elsewhere they are arguments."""
2032
+ callback = _PATHS(_guard(lambda paths, data: function(json.loads(paths.decode()))))
2033
+ _app_callbacks["open"] = callback
2034
+ _app_on_open_files(callback, None)
2035
+
2036
+
2037
+ def app_on_reopen(function):
2038
+ """function() when the application's icon in the Dock is clicked with no window shown."""
2039
+ callback = _APP(_guard(lambda data: function()))
2040
+ _app_callbacks["reopen"] = callback
2041
+ _app_on_reopen(callback, None)
2042
+
2043
+
2044
+ def app_on_quit_request(function):
2045
+ """function() when the user asks the application to quit; it calls quit() or not."""
2046
+ callback = _APP(_guard(lambda data: function()))
2047
+ _app_callbacks["quit"] = callback
2048
+ _app_on_quit_request(callback, None)
2049
+
2050
+
2051
+ def set_cookie_encryption_key(key):
2052
+ """Before run(): host-persisted 32-byte random key, or None for the OS store.
2053
+
2054
+ Never log the key. Host cookies use a separate database.
2055
+ """
2056
+ if key is None:
2057
+ return bool(_cookie_key(None, 0))
2058
+ key = bytes(key)
2059
+ if len(key) != 32:
2060
+ raise ValueError("cookie key must contain exactly 32 bytes")
2061
+ buffer = ctypes.create_string_buffer(key)
2062
+ return bool(_cookie_key(buffer, len(key)))
2063
+
2064
+
2065
+ def set_cookie_storage(storage="os", key_directory=None):
2066
+ """Select Zebkit's built-in 'os' or 'file' backend before main().
2067
+
2068
+ File mode defaults to <profile>/Secrets and needs no host key-file code.
2069
+ Startup fails if the key is lost/corrupt. The file key relies on OS file
2070
+ permissions, with less protection than the system key store.
2071
+ """
2072
+ if storage not in ("os", "file"):
2073
+ raise ValueError("cookie storage must be 'os' or 'file'")
2074
+ directory = None if key_directory is None else os.fsencode(key_directory)
2075
+ if directory is not None and b"\0" in directory:
2076
+ raise ValueError("key directory contains a zero byte")
2077
+ return bool(_cookie_storage(0 if storage == "os" else 1, directory))
2078
+
2079
+
2080
+ # ---- Canvas and text: <zebkit/canvas.h>, <zebkit/text.h> ----
2081
+
2082
+ _canvas_new = _declare("zebkit_canvas_new", _P, _I, _I, _EP)
2083
+ _canvas_wrap = _declare("zebkit_canvas_wrap", _P, _P, _I, _I, _Z, _U, _EP)
2084
+ _canvas_close = _declare("zebkit_canvas_close", None, _P)
2085
+ _canvas_width = _declare("zebkit_canvas_width", _I, _P)
2086
+ _canvas_height = _declare("zebkit_canvas_height", _I, _P)
2087
+ _canvas_pixels = _declare("zebkit_canvas_pixels", _P, _P, _EP)
2088
+ _canvas_png = _declare("zebkit_canvas_png", _P, _P, _ZP, _EP)
2089
+ _canvas_run = _declare("zebkit_canvas_run", _B, _P, _S, _EP)
2090
+ _font_new = _declare("zebkit_canvas_font_new", _P, _P, _Z, _EP)
2091
+ _font_close = _declare("zebkit_canvas_font_close", None, _P)
2092
+ _canvas_set_font = _declare("zebkit_canvas_set_font", None, _P, _P, ctypes.c_double)
2093
+ _canvas_fill_text = _declare("zebkit_canvas_fill_text", _B, _P, _S, ctypes.c_double, ctypes.c_double, _EP)
2094
+ _canvas_text_path = _declare("zebkit_canvas_text_path", _B, _P, _S, ctypes.c_double, ctypes.c_double, _EP)
2095
+ _canvas_measure_text = _declare("zebkit_canvas_measure_text", ctypes.c_double, _P, _S)
2096
+ _canvas_draw_image = _declare("zebkit_canvas_draw_image", _B, _P, _P, _I, _I, *([ctypes.c_double] * 4))
2097
+ _canvas_set_blend = _declare("zebkit_canvas_set_blend", _B, _P, _S)
2098
+ _canvas_set_dash = _declare("zebkit_canvas_set_dash", None, _P, ctypes.POINTER(ctypes.c_double), _I, ctypes.c_double)
2099
+ _canvas_linear = _declare("zebkit_canvas_set_linear_gradient", _B, _P, *([ctypes.c_double] * 4),
2100
+ ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_uint32), _I)
2101
+ _canvas_radial = _declare("zebkit_canvas_set_radial_gradient", _B, _P, *([ctypes.c_double] * 3),
2102
+ ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_uint32), _I)
2103
+ _text_shape = _declare("zebkit_text_shape", _P, _P, _Z, ctypes.c_double, _S, _S, _S, _EP)
2104
+
2105
+
2106
+ def _numbers_call(name, count):
2107
+ function = _declare(name, None, _P, *([ctypes.c_double] * count))
2108
+
2109
+ def call(self, *numbers):
2110
+ function(self._handle, *numbers)
2111
+ return call
2112
+
2113
+
2114
+ def _simple_call(name):
2115
+ function = _declare(name, None, _P)
2116
+
2117
+ def call(self):
2118
+ function(self._handle)
2119
+ return call
2120
+
2121
+
2122
+ def _color_call(name):
2123
+ function = _declare(name, None, _P, ctypes.c_uint32)
2124
+
2125
+ def call(self, rgba):
2126
+ function(self._handle, rgba)
2127
+ return call
2128
+
2129
+
2130
+ class Font:
2131
+ """A font from its bytes, for Canvas.set_font()."""
2132
+
2133
+ def __init__(self, data):
2134
+ error = ctypes.c_void_p()
2135
+ data = bytes(data)
2136
+ self._handle = _font_new(data, len(data), ctypes.byref(error))
2137
+ if not self._handle:
2138
+ _raise(error, "not a font")
2139
+
2140
+ def close(self):
2141
+ if getattr(self, "_handle", None):
2142
+ _font_close(self._handle)
2143
+ self._handle = None
2144
+
2145
+ def __del__(self):
2146
+ self.close()
2147
+
2148
+
2149
+ class Canvas:
2150
+ """2D drawing on the engine's Skia: a canvas of width by height pixels, or
2151
+ over a bytearray of RGBA with Canvas.over(). Colours are 0xRRGGBBAA."""
2152
+
2153
+ def __init__(self, width=None, height=None, _handle=None):
2154
+ if _handle is not None:
2155
+ self._handle, self._owned = _handle, False
2156
+ return
2157
+ error = ctypes.c_void_p()
2158
+ self._owned = True
2159
+ self._handle = _canvas_new(width, height, ctypes.byref(error))
2160
+ if not self._handle:
2161
+ _raise(error, "the canvas cannot be made")
2162
+
2163
+ @classmethod
2164
+ def over(cls, pixels, width, height, stride=0, unpremultiplied=False):
2165
+ """Over a bytearray, R, G, B, A, kept until close()."""
2166
+ if not isinstance(pixels, bytearray):
2167
+ raise TypeError("pixels are a bytearray")
2168
+ if stride < 0 or len(pixels) < (stride or width * 4) * height:
2169
+ raise ValueError("too few pixels")
2170
+ self = cls.__new__(cls)
2171
+ buffer = (ctypes.c_uint8 * len(pixels)).from_buffer(pixels)
2172
+ error = ctypes.c_void_p()
2173
+ self._buffer, self._owned = buffer, True
2174
+ self._handle = _canvas_wrap(ctypes.addressof(buffer), width, height, stride, 1 if unpremultiplied else 0,
2175
+ ctypes.byref(error))
2176
+ if not self._handle:
2177
+ _raise(error, "the canvas cannot be made")
2178
+ return self
2179
+
2180
+ def close(self):
2181
+ if getattr(self, "_handle", None) and self._owned:
2182
+ _canvas_close(self._handle)
2183
+ self._handle = None
2184
+ self._buffer = None
2185
+
2186
+ def __enter__(self):
2187
+ return self
2188
+
2189
+ def __exit__(self, *exc):
2190
+ self.close()
2191
+
2192
+ def __del__(self):
2193
+ self.close()
2194
+
2195
+ @property
2196
+ def width(self):
2197
+ return _canvas_width(self._handle)
2198
+
2199
+ @property
2200
+ def height(self):
2201
+ return _canvas_height(self._handle)
2202
+
2203
+ def pixels(self):
2204
+ """RGBA, not premultiplied, width * height * 4 bytes."""
2205
+ error = ctypes.c_void_p()
2206
+ out = _canvas_pixels(self._handle, ctypes.byref(error))
2207
+ if not out:
2208
+ _raise(error, "this canvas has no pixels")
2209
+ return _buffer(out, self.width * self.height * 4)
2210
+
2211
+ def png(self):
2212
+ size, error = ctypes.c_size_t(), ctypes.c_void_p()
2213
+ out = _canvas_png(self._handle, ctypes.byref(size), ctypes.byref(error))
2214
+ if not out:
2215
+ _raise(error, "the PNG cannot be made")
2216
+ return _buffer(out, size.value)
2217
+
2218
+ save = _simple_call("zebkit_canvas_save")
2219
+ restore = _simple_call("zebkit_canvas_restore")
2220
+ translate = _numbers_call("zebkit_canvas_translate", 2)
2221
+ scale = _numbers_call("zebkit_canvas_scale", 2)
2222
+ rotate = _numbers_call("zebkit_canvas_rotate", 1)
2223
+ transform = _numbers_call("zebkit_canvas_transform", 6)
2224
+ set_matrix = _numbers_call("zebkit_canvas_set_matrix", 6)
2225
+ set_fill_color = _color_call("zebkit_canvas_set_fill_color")
2226
+ set_stroke_color = _color_call("zebkit_canvas_set_stroke_color")
2227
+ set_alpha = _numbers_call("zebkit_canvas_set_alpha", 1)
2228
+ set_line_width = _numbers_call("zebkit_canvas_set_line_width", 1)
2229
+ set_miter_limit = _numbers_call("zebkit_canvas_set_miter_limit", 1)
2230
+ begin_path = _simple_call("zebkit_canvas_begin_path")
2231
+ move_to = _numbers_call("zebkit_canvas_move_to", 2)
2232
+ line_to = _numbers_call("zebkit_canvas_line_to", 2)
2233
+ quad_to = _numbers_call("zebkit_canvas_quad_to", 4)
2234
+ curve_to = _numbers_call("zebkit_canvas_curve_to", 6)
2235
+ rect = _numbers_call("zebkit_canvas_rect", 4)
2236
+ close_path = _simple_call("zebkit_canvas_close_path")
2237
+ stroke = _simple_call("zebkit_canvas_stroke")
2238
+ clear = _color_call("zebkit_canvas_clear")
2239
+
2240
+ def set_line_cap(self, cap):
2241
+ _declare("zebkit_canvas_set_line_cap", None, _P, _I)(self._handle, cap)
2242
+
2243
+ def set_line_join(self, join):
2244
+ _declare("zebkit_canvas_set_line_join", None, _P, _I)(self._handle, join)
2245
+
2246
+ def set_blend(self, mode):
2247
+ return _canvas_set_blend(self._handle, mode.encode())
2248
+
2249
+ def set_dash(self, lengths, phase=0.0):
2250
+ values = (ctypes.c_double * len(lengths))(*lengths)
2251
+ _canvas_set_dash(self._handle, values, len(lengths), phase)
2252
+
2253
+ def set_linear_gradient(self, x0, y0, x1, y1, offsets, colors):
2254
+ n = len(offsets)
2255
+ return n == len(colors) and _canvas_linear(self._handle, x0, y0, x1, y1, (ctypes.c_double * n)(*offsets),
2256
+ (ctypes.c_uint32 * n)(*colors), n)
2257
+
2258
+ def set_radial_gradient(self, x, y, radius, offsets, colors):
2259
+ n = len(offsets)
2260
+ return n == len(colors) and _canvas_radial(self._handle, x, y, radius, (ctypes.c_double * n)(*offsets),
2261
+ (ctypes.c_uint32 * n)(*colors), n)
2262
+
2263
+ def arc(self, x, y, radius, start, end, counterclockwise=False):
2264
+ _declare("zebkit_canvas_arc", None, _P, *([ctypes.c_double] * 5), _B)(
2265
+ self._handle, x, y, radius, start, end, counterclockwise)
2266
+
2267
+ def fill(self, even_odd=False):
2268
+ _declare("zebkit_canvas_fill", None, _P, _B)(self._handle, even_odd)
2269
+
2270
+ def clip(self, even_odd=False):
2271
+ _declare("zebkit_canvas_clip", None, _P, _B)(self._handle, even_odd)
2272
+
2273
+ def draw_image(self, rgba, width, height, x, y, dest_width=None, dest_height=None):
2274
+ rgba = bytes(rgba)
2275
+ if len(rgba) != width * height * 4:
2276
+ return False
2277
+ return _canvas_draw_image(self._handle, rgba, width, height, x, y,
2278
+ width if dest_width is None else dest_width,
2279
+ height if dest_height is None else dest_height)
2280
+
2281
+ def set_font(self, font, size=12.0):
2282
+ _canvas_set_font(self._handle, font._handle if font else None, size)
2283
+ self._font = font
2284
+
2285
+ def fill_text(self, text, x, y):
2286
+ error = ctypes.c_void_p()
2287
+ if not _canvas_fill_text(self._handle, text.encode(), x, y, ctypes.byref(error)):
2288
+ _raise(error, "the text cannot be drawn")
2289
+
2290
+ def text_path(self, text, x, y):
2291
+ error = ctypes.c_void_p()
2292
+ if not _canvas_text_path(self._handle, text.encode(), x, y, ctypes.byref(error)):
2293
+ _raise(error, "the text cannot be drawn")
2294
+
2295
+ def measure_text(self, text):
2296
+ width = _canvas_measure_text(self._handle, text.encode())
2297
+ return None if width < 0 else width
2298
+
2299
+ def run(self, operations):
2300
+ """A list of operations, as <zebkit/canvas.h> says."""
2301
+ error = ctypes.c_void_p()
2302
+ if not _canvas_run(self._handle, json.dumps(operations).encode(), ctypes.byref(error)):
2303
+ _raise(error, "the operations cannot be run")
2304
+
2305
+
2306
+ def shape_text(font, size, text, language=None, direction=None):
2307
+ """Shapes a line of text on the engine's HarfBuzz: {direction, script,
2308
+ unitsPerEm, advance, glyphs: [{glyph, cluster, advance, offset}]}."""
2309
+ font = bytes(font)
2310
+ error = ctypes.c_void_p()
2311
+ out = _text_shape(font, len(font), size, text.encode(), language.encode() if language else None,
2312
+ direction.encode() if direction else None, ctypes.byref(error))
2313
+ if not out:
2314
+ _raise(error, "the text cannot be shaped")
2315
+ return json.loads(_string(out))
2316
+
2317
+
2318
+ # ---- PDF, more annotations and hooks ----
2319
+
2320
+ _D = ctypes.c_double
2321
+ _pdf_string = _declare("zebkit_pdf_string", _P, _S)
2322
+ _pdf_bytes = _declare("zebkit_pdf_bytes", _P, _P, _Z)
2323
+ _pdf_hook_remove = _declare("zebkit_pdf_hook_remove", _B, _I)
2324
+ _pdf_annotation_at = _declare("zebkit_pdf_annotation_at", _I, _P, _I, _D, _D, _D, _EP)
2325
+ _pdf_annotation_move = _declare("zebkit_pdf_annotation_move", _B, _P, _I, _I, _I, _EP)
2326
+ _pdf_annotation_copy = _declare("zebkit_pdf_annotation_copy", _I, _P, _I, _I, _P, _I, _EP)
2327
+ _pdf_annotation_flatten = _declare("zebkit_pdf_annotation_flatten", _B, _P, _I, _I, _EP)
2328
+ _pdf_annotation_stamp_page = _declare("zebkit_pdf_annotation_stamp_page", _B, _P, _I, _I, _P, _I, _EP)
2329
+ _pdf_annotation_attach_file = _declare("zebkit_pdf_annotation_attach_file", _B, _P, _I, _I, _S, _P, _Z, _EP)
2330
+ _pdf_annotation_file = _declare("zebkit_pdf_annotation_file", _P, _P, _I, _I, _EP, _ZP, _EP)
2331
+ _pdf_annotation_draw = _declare("zebkit_pdf_annotation_draw", _B, _P, _I, _I, _S, _EP)
2332
+ _pdf_annotation_action = _declare("zebkit_pdf_annotation_action", _P, _P, _I, _I, _EP)
2333
+ _pdf_annotations_export = _declare("zebkit_pdf_annotations_export", _P, _P, _I, _I, _I, _ZP, _EP)
2334
+ _pdf_annotations_import = _declare("zebkit_pdf_annotations_import", _I, _P, _I, _P, _Z, _EP)
2335
+ _pdf_apply = _declare("zebkit_pdf_apply", _B, _P, _S, _EP)
2336
+ _pdf_page_data = _declare("zebkit_pdf_page_data", _P, _P, _I, _S, _EP)
2337
+ _pdf_font_add = _declare("zebkit_pdf_font_add", _B, _P, _S, _P, _Z, _EP)
2338
+ _pdf_filter_input = _declare("zebkit_pdf_filter_input", _P, _P, _S, _S, _S, _EP)
2339
+
2340
+ _HOOK_DESTROY_T = ctypes.CFUNCTYPE(None, ctypes.c_void_p)
2341
+ _BEFORE = ctypes.CFUNCTYPE(_I, _P, _S, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_void_p), _P)
2342
+ _AFTER = ctypes.CFUNCTYPE(None, _P, _S, _P)
2343
+ _APPEARANCE = ctypes.CFUNCTYPE(_B, _P, _P, _I, _I, _S, _D, _D, _P)
2344
+ _CHECK = ctypes.CFUNCTYPE(_P, _S, _P)
2345
+ _HIT = ctypes.CFUNCTYPE(_B, _P, _I, _I, _S, _D, _D, _P)
2346
+
2347
+
2348
+ class _LayerInfo(ctypes.Structure):
2349
+ _fields_ = [("width", _I), ("height", _I), ("scale", _D), ("rotation", _I), ("matrix", _D * 6)]
2350
+
2351
+
2352
+ _LAYER = ctypes.CFUNCTYPE(None, _P, _P, _I, ctypes.POINTER(_LayerInfo), _P)
2353
+ _OCR = ctypes.CFUNCTYPE(_P, _P, _I, ctypes.POINTER(ctypes.c_uint8), _I, _I, _D, _P)
2354
+ _FONT = ctypes.CFUNCTYPE(_P, _P, _S, _ZP, _P)
2355
+ _TRUST = ctypes.CFUNCTYPE(_I, _P, _S, ctypes.POINTER(ctypes.c_uint8), _Z, _P)
2356
+ _ACTION = ctypes.CFUNCTYPE(_B, _P, _S, _P)
2357
+ _INPUT = ctypes.CFUNCTYPE(_P, _P, _S, _S, _P)
2358
+
2359
+
2360
+ class _Kind(ctypes.Structure):
2361
+ _fields_ = [("name", _S), ("prefix", _S), ("subtype", _S), ("schema", _S), ("check", _CHECK),
2362
+ ("draw", _APPEARANCE), ("hit_test", _HIT), ("data", _P), ("destroy", _HOOK_DESTROY_T)]
2363
+
2364
+
2365
+ _register_before = _declare("zebkit_pdf_hook_before", _I, _P, _S, _BEFORE, _P, _HOOK_DESTROY_T)
2366
+ _register_after = _declare("zebkit_pdf_hook_after", _I, _P, _S, _AFTER, _P, _HOOK_DESTROY_T)
2367
+ _register_appearance = _declare("zebkit_pdf_hook_appearance", _I, _P, _S, _APPEARANCE, _P, _HOOK_DESTROY_T)
2368
+ _register_kind = _declare("zebkit_pdf_hook_kind", _I, _P, ctypes.POINTER(_Kind), _EP)
2369
+ _register_layer = _declare("zebkit_pdf_hook_layer", _I, _P, _I, _LAYER, _P, _HOOK_DESTROY_T)
2370
+ _register_ocr = _declare("zebkit_pdf_hook_ocr", _I, _P, _OCR, _P, _HOOK_DESTROY_T)
2371
+ _register_font = _declare("zebkit_pdf_hook_font", _I, _P, _FONT, _P, _HOOK_DESTROY_T)
2372
+ _register_trust = _declare("zebkit_pdf_hook_trust", _I, _P, _TRUST, _P, _HOOK_DESTROY_T)
2373
+ _register_action = _declare("zebkit_pdf_hook_action", _I, _P, _ACTION, _P, _HOOK_DESTROY_T)
2374
+ _register_input = _declare("zebkit_pdf_hook_input", _I, _P, _S, _INPUT, _P, _HOOK_DESTROY_T)
2375
+
2376
+ # What C holds of a hook lives here until the engine says it is done with it,
2377
+ # never while a call of it runs.
2378
+ _hook_keep = {}
2379
+ _hook_next = [1]
2380
+
2381
+
2382
+ @_HOOK_DESTROY_T
2383
+ def _hook_destroy(key):
2384
+ _hook_keep.pop(key, None)
2385
+
2386
+
2387
+ def _keep(*things):
2388
+ key = _hook_next[0]
2389
+ _hook_next[0] += 1
2390
+ _hook_keep[key] = things
2391
+ return key
2392
+
2393
+
2394
+ def _give(text):
2395
+ # What a hook says must get to the engine, whatever it holds.
2396
+ return _pdf_string(text.encode("utf-8", "replace"))
2397
+
2398
+
2399
+ def _lent(handle, draw):
2400
+ """Runs draw(canvas) over a canvas that is the engine's for this call: one
2401
+ the function keeps afterwards draws on nothing, not on what has gone."""
2402
+ canvas = Canvas(_handle=handle)
2403
+ try:
2404
+ return draw(canvas)
2405
+ finally:
2406
+ canvas._handle = None
2407
+
2408
+
2409
+ class PdfHooks:
2410
+ """Hooks of <zebkit/pdf.h> for one document (Pdf.hooks), or with no document
2411
+ for all (zebkit.pdf_hooks). Each method returns the hook's id for
2412
+ remove_pdf_hook(). Operations and annotations are Python values."""
2413
+
2414
+ def __init__(self, pdf=None):
2415
+ self._pdf = pdf
2416
+
2417
+ @property
2418
+ def _handle(self):
2419
+ # A closed document's hook must not become one for all documents.
2420
+ if self._pdf is not None and not self._pdf._handle:
2421
+ raise Error("the document is closed")
2422
+ return self._pdf._handle if self._pdf is not None else None
2423
+
2424
+ def before(self, event, function):
2425
+ """function(operation): None goes on, False or {"refuse": why} refuses,
2426
+ another operation changes what happens. An exception refuses."""
2427
+ def call(pdf, operation, change, reason, data):
2428
+ # All of it in here: what leaves this function as an exception
2429
+ # comes to C as 0, which is "go on".
2430
+ try:
2431
+ answer = function(json.loads(operation))
2432
+ if answer is False or (isinstance(answer, dict) and "refuse" in answer):
2433
+ why = answer["refuse"] if answer is not False else None
2434
+ if why:
2435
+ reason[0] = _give(str(why))
2436
+ return 1
2437
+ if isinstance(answer, dict):
2438
+ change[0] = _give(json.dumps(answer))
2439
+ return 0
2440
+ except BaseException as e: # noqa: BLE001
2441
+ reason[0] = _give(f"a hook failed: {e}")
2442
+ return 1
2443
+ thunk = _BEFORE(call)
2444
+ return _register_before(self._handle, event.encode(), thunk, _keep(thunk), _hook_destroy)
2445
+
2446
+ def after(self, event, function):
2447
+ """function(operation), with "inverse" when it can be undone."""
2448
+ thunk = _AFTER(_guard(lambda pdf, operation, data: function(json.loads(operation))))
2449
+ return _register_after(self._handle, event.encode(), thunk, _keep(thunk), _hook_destroy)
2450
+
2451
+ def appearance(self, type_name, function):
2452
+ """function(canvas, annotation, width, height) -> True when drawn. The
2453
+ canvas writes PDF operators: units are points, the origin its top left."""
2454
+ def call(canvas, pdf, page, index, annotation, width, height, data):
2455
+ try:
2456
+ return bool(_lent(canvas, lambda lent: function(lent, json.loads(annotation), width, height)))
2457
+ except Exception: # noqa: BLE001
2458
+ return False
2459
+ thunk = _APPEARANCE(call)
2460
+ return _register_appearance(self._handle, type_name.encode(), thunk, _keep(thunk), _hook_destroy)
2461
+
2462
+ def kind(self, name, prefix, subtype=None, schema=None, check=None, draw=None, hit_test=None):
2463
+ """A kind of annotation of the application's own."""
2464
+ def draw_call(canvas, pdf, page, index, annotation, width, height, data):
2465
+ try:
2466
+ return bool(_lent(canvas, lambda lent: draw(lent, json.loads(annotation), width, height)))
2467
+ except Exception: # noqa: BLE001
2468
+ return False
2469
+
2470
+ def check_call(data_json, data):
2471
+ # As for before(): nothing back is "the data is fine".
2472
+ try:
2473
+ problem = check(json.loads(data_json))
2474
+ return _give(str(problem)) if problem else None
2475
+ except BaseException as e: # noqa: BLE001
2476
+ return _give(f"a check failed: {e}")
2477
+
2478
+ def hit_call(pdf, page, index, annotation, x, y, data):
2479
+ try:
2480
+ return bool(hit_test(json.loads(annotation), x, y))
2481
+ except Exception: # noqa: BLE001
2482
+ return False
2483
+ thunks = (_CHECK(check_call) if check else _CHECK(), _APPEARANCE(draw_call) if draw else _APPEARANCE(),
2484
+ _HIT(hit_call) if hit_test else _HIT())
2485
+ kept = _keep(*thunks)
2486
+ raw = _Kind(name.encode(), prefix.encode(), subtype.encode() if subtype else None,
2487
+ json.dumps(schema).encode() if schema is not None else None, thunks[0], thunks[1], thunks[2],
2488
+ kept, _hook_destroy)
2489
+ error = ctypes.c_void_p()
2490
+ hook = _register_kind(self._handle, ctypes.byref(raw), ctypes.byref(error))
2491
+ if hook < 0:
2492
+ _hook_keep.pop(kept, None) # what fails to register is not destroyed
2493
+ _raise(error, "the kind cannot be registered")
2494
+ return hook
2495
+
2496
+ def layer(self, function, above=True):
2497
+ """function(canvas, page, info): over the page's bitmap, in page space."""
2498
+ def call(canvas, pdf, page, info, data):
2499
+ i = info.contents
2500
+ _lent(canvas, lambda lent: function(lent, page, {"width": i.width, "height": i.height, "scale": i.scale,
2501
+ "rotation": i.rotation, "matrix": list(i.matrix)}))
2502
+ thunk = _LAYER(_guard(call))
2503
+ return _register_layer(self._handle, 1 if above else 0, thunk, _keep(thunk), _hook_destroy)
2504
+
2505
+ def ocr(self, function):
2506
+ """function(page, width, height, rgba, scale) -> [{"text", "box"}] or None."""
2507
+ def call(pdf, page, rgba, width, height, scale, data):
2508
+ try:
2509
+ lines = function(page, width, height, ctypes.string_at(rgba, width * height * 4), scale)
2510
+ except Exception: # noqa: BLE001
2511
+ return None
2512
+ return _give(json.dumps(lines)) if lines else None
2513
+ thunk = _OCR(call)
2514
+ return _register_ocr(self._handle, thunk, _keep(thunk), _hook_destroy)
2515
+
2516
+ def font(self, function):
2517
+ """function(family) -> a font's bytes, or None. "" is for what the standard fonts lack."""
2518
+ def call(pdf, family, size, data):
2519
+ try:
2520
+ bytes_ = function(family.decode())
2521
+ except Exception: # noqa: BLE001
2522
+ return None
2523
+ if not bytes_:
2524
+ return None
2525
+ size[0] = len(bytes_)
2526
+ return _pdf_bytes(bytes_, len(bytes_))
2527
+ thunk = _FONT(call)
2528
+ return _register_font(self._handle, thunk, _keep(thunk), _hook_destroy)
2529
+
2530
+ def trust(self, function):
2531
+ """function(signature, pkcs7) -> True, False or None."""
2532
+ def call(pdf, signature, contents, size, data):
2533
+ try:
2534
+ answer = function(json.loads(signature), ctypes.string_at(contents, size) if contents else b"")
2535
+ except Exception: # noqa: BLE001
2536
+ return 0
2537
+ return 1 if answer is True else -1 if answer is False else 0
2538
+ thunk = _TRUST(call)
2539
+ return _register_trust(self._handle, thunk, _keep(thunk), _hook_destroy)
2540
+
2541
+ def action(self, function):
2542
+ """function(action) -> True when the application has done it."""
2543
+ def call(pdf, action, data):
2544
+ try:
2545
+ return bool(function(json.loads(action)))
2546
+ except Exception: # noqa: BLE001
2547
+ return False
2548
+ thunk = _ACTION(call)
2549
+ return _register_action(self._handle, thunk, _keep(thunk), _hook_destroy)
2550
+
2551
+ def input(self, tool, function):
2552
+ """function(points) -> new points, or None for no change."""
2553
+ def call(pdf, tool_name, points, data):
2554
+ try:
2555
+ changed = function(json.loads(points))
2556
+ except Exception: # noqa: BLE001
2557
+ return None
2558
+ return _give(json.dumps(changed)) if changed is not None else None
2559
+ thunk = _INPUT(call)
2560
+ return _register_input(self._handle, tool.encode(), thunk, _keep(thunk), _hook_destroy)
2561
+
2562
+
2563
+ pdf_hooks = PdfHooks()
2564
+
2565
+
2566
+ def remove_pdf_hook(hook):
2567
+ return _pdf_hook_remove(hook)
2568
+
2569
+
2570
+ def pdf_filter_input(points, options=None):
2571
+ """The built-in filters of a drawing tool's points, with no document."""
2572
+ error = ctypes.c_void_p()
2573
+ out = _pdf_filter_input(None, None, json.dumps(points).encode(),
2574
+ json.dumps(options).encode() if options is not None else None, ctypes.byref(error))
2575
+ if not out:
2576
+ _raise(error, "the points cannot be filtered")
2577
+ return json.loads(_string(out))
2578
+
2579
+
2580
+ def _pdf_more(cls):
2581
+ """What Pdf has beyond the first part of this file."""
2582
+ def annotation_at(self, index, x, y, tolerance=2.0):
2583
+ """The top annotation at a point, or None."""
2584
+ error = ctypes.c_void_p()
2585
+ at = _pdf_annotation_at(self._handle, index, x, y, tolerance, ctypes.byref(error))
2586
+ if at < 0 and error.value:
2587
+ _raise(error, "no page")
2588
+ return None if at < 0 else at
2589
+
2590
+ def move_annotation(self, index, annotation, to):
2591
+ self._ok(_pdf_annotation_move, index, annotation, to, fallback="the annotation cannot be moved")
2592
+
2593
+ def copy_annotation(self, index, annotation, target=None, target_page=0):
2594
+ error = ctypes.c_void_p()
2595
+ target_handle = (target or self)._handle
2596
+ at = _pdf_annotation_copy(self._handle, index, annotation, target_handle, target_page, ctypes.byref(error))
2597
+ if at < 0:
2598
+ _raise(error, "the annotation cannot be copied")
2599
+ return at
2600
+
2601
+ def flatten_annotation(self, index, annotation):
2602
+ self._ok(_pdf_annotation_flatten, index, annotation, fallback="the annotation cannot be flattened")
2603
+
2604
+ def stamp_from_page(self, index, annotation, source, source_page=0):
2605
+ self._ok(_pdf_annotation_stamp_page, index, annotation, source._handle, source_page,
2606
+ fallback="the page cannot be made a stamp")
2607
+
2608
+ def attach_file(self, index, annotation, name, data):
2609
+ data = bytes(data)
2610
+ self._ok(_pdf_annotation_attach_file, index, annotation, name.encode(), data, len(data),
2611
+ fallback="the file cannot be attached")
2612
+
2613
+ def annotation_file(self, index, annotation):
2614
+ """(name, bytes) of a file attachment annotation's file."""
2615
+ name, size, error = ctypes.c_void_p(), ctypes.c_size_t(), ctypes.c_void_p()
2616
+ out = _pdf_annotation_file(self._handle, index, annotation, ctypes.byref(name), ctypes.byref(size),
2617
+ ctypes.byref(error))
2618
+ if not out:
2619
+ _raise(error, "the annotation has no file")
2620
+ return _string(name.value), _buffer(out, size.value)
2621
+
2622
+ def draw_annotation(self, index, annotation, operations):
2623
+ """A list of canvas operations as the annotation's appearance."""
2624
+ self._ok(_pdf_annotation_draw, index, annotation, json.dumps(operations).encode(),
2625
+ fallback="the appearance cannot be drawn")
2626
+
2627
+ def annotation_action(self, index, annotation):
2628
+ return self._json(_pdf_annotation_action, index, annotation, fallback="no annotation")
2629
+
2630
+ def export_annotations(self, format="xfdf", page=-1, index=-1):
2631
+ size, error = ctypes.c_size_t(), ctypes.c_void_p()
2632
+ out = _pdf_annotations_export(self._handle, 1 if format == "fdf" else 0, page, index, ctypes.byref(size),
2633
+ ctypes.byref(error))
2634
+ if not out:
2635
+ _raise(error, "the annotations cannot be written")
2636
+ return _buffer(out, size.value)
2637
+
2638
+ def import_annotations(self, data, format="xfdf"):
2639
+ data = bytes(data)
2640
+ error = ctypes.c_void_p()
2641
+ count = _pdf_annotations_import(self._handle, 1 if format == "fdf" else 0, data, len(data), ctypes.byref(error))
2642
+ if count < 0:
2643
+ _raise(error, "the annotations cannot be read")
2644
+ return count
2645
+
2646
+ def apply(self, operation):
2647
+ """Runs an operation a hook saw, or its "inverse"."""
2648
+ self._ok(_pdf_apply, json.dumps(operation).encode(), fallback="the operation cannot be run")
2649
+
2650
+ def page_data(self, index, prefix):
2651
+ return self._json(_pdf_page_data, index, prefix.encode(), fallback="no page")
2652
+
2653
+ def add_font(self, family, font):
2654
+ font = bytes(font)
2655
+ self._ok(_pdf_font_add, family.encode(), font, len(font), fallback="the font cannot be used")
2656
+
2657
+ def filter_input(self, tool, points, options=None):
2658
+ error = ctypes.c_void_p()
2659
+ out = _pdf_filter_input(self._handle, tool.encode(), json.dumps(points).encode(),
2660
+ json.dumps(options).encode() if options is not None else None, ctypes.byref(error))
2661
+ if not out:
2662
+ _raise(error, "the points cannot be filtered")
2663
+ return json.loads(_string(out))
2664
+
2665
+ for function in (annotation_at, move_annotation, copy_annotation, flatten_annotation, stamp_from_page,
2666
+ attach_file, annotation_file, draw_annotation, annotation_action, export_annotations,
2667
+ import_annotations, apply, page_data, add_font, filter_input):
2668
+ setattr(cls, function.__name__, function)
2669
+ cls.hooks = property(lambda self: PdfHooks(self))
2670
+
2671
+
2672
+ _pdf_more(Pdf)