zebkit 0.5.0__tar.gz → 0.6.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zebkit
3
- Version: 0.5.0
3
+ Version: 0.6.0
4
4
  Summary: Chromium's engine as a library, from Python: web views, PDF, media, Playwright's API natively, and the libraries inside the engine
5
5
  Keywords: chromium,browser,webview,pdf,playwright,automation
6
6
  License-Expression: LGPL-2.1-or-later
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "zebkit"
7
- version = "0.5.0"
7
+ version = "0.6.0"
8
8
  description = "Chromium's engine as a library, from Python: web views, PDF, media, Playwright's API natively, and the libraries inside the engine"
9
9
  readme = "README.md"
10
10
  license = "LGPL-2.1-or-later"
@@ -5,7 +5,7 @@ build-backend = "uv_build"
5
5
  [project]
6
6
  name = "zebkit"
7
7
  # The engine's version (VERSION); scripts/publish-python.sh checks they agree.
8
- version = "0.5.0"
8
+ version = "0.6.0"
9
9
  description = "Chromium's engine as a library, from Python: web views, PDF, media, Playwright's API natively, and the libraries inside the engine"
10
10
  readme = "README.md"
11
11
  license = "LGPL-2.1-or-later"
@@ -37,7 +37,7 @@ __all__ = [
37
37
  "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",
38
38
  "set_cookie_storage", "set_cookie_encryption_key", "cdp_listen", "cdp_listen_async", "cdp_port", "cdp_url", "cdp_stop", "fetch", "Call", "FindResult",
39
39
  "compress", "decompress", "digest", "hmac", "random_bytes", "aes_gcm_seal", "aes_gcm_open",
40
- "url_part", "registrable_domain", "image_decode", "image_encode", "icu_init", "Error",
40
+ "url_part", "registrable_domain", "image_decode", "image_encode", "icu_init", "icu_init_from_file", "Error",
41
41
  "LOAD_STARTED", "LOAD_COMMITTED", "LOAD_FINISHED", "LOAD_FAILED",
42
42
  "ALLOW_APP", "ALLOW_FETCH", "ALLOW_FILES", "ALLOW_COMPRESS", "ALLOW_CRYPTO", "ALLOW_IMAGE",
43
43
  "ALLOW_URL", "ALLOW_PDF", "ALLOW_ALL",
@@ -768,6 +768,7 @@ _url_registrable_domain = _declare("zebkit_url_registrable_domain", _P, _S)
768
768
  _image_decode = _declare("zebkit_image_decode", _P, _P, _Z, _IP, _IP, _EP)
769
769
  _image_encode = _declare("zebkit_image_encode", _P, _I, _P, _I, _I, _I, _ZP, _EP)
770
770
  _icu_init = _declare("zebkit_icu_init", _B)
771
+ _icu_init_from_file = _declare("zebkit_icu_init_from_file", _B, _S)
771
772
  _fetch = _declare("zebkit_fetch", None, _S, _S, _S, _P, _Z, _RESPONSE, _P)
772
773
 
773
774
  # Callbacks and views that C still holds, by id: kept here so that Python
@@ -1337,6 +1338,11 @@ def icu_init():
1337
1338
  return bool(_icu_init())
1338
1339
 
1339
1340
 
1341
+ def icu_init_from_file(path):
1342
+ """ICU's data from an icudtl.dat at path, as Android needs (docs/MOBILE.md)."""
1343
+ return bool(_icu_init_from_file(os.fsencode(path)))
1344
+
1345
+
1340
1346
  # ---- PDF: <zebkit/pdf.h> ----
1341
1347
 
1342
1348
  class _RenderOptions(ctypes.Structure):
@@ -0,0 +1,329 @@
1
+ """JavaScript libraries as normal libraries (<zebkit/library.h>, docs/JS_LIBRARIES.md).
2
+
3
+ import zebkit
4
+ import zebkit.library
5
+
6
+ md = zebkit.library.load("libs/markdown") # on the engine's thread
7
+ md.call("render", "# Title").add_done_callback(lambda f: print(f.result()))
8
+ md.call("render", "# Title", function=lambda value, error: print(value, error))
9
+
10
+ A library is a folder with index.mjs, or one .mjs file, bundled (js-bundle.mjs);
11
+ it runs in a V8 isolate of its own, on a thread of its own. Values are JSON
12
+ with bytes in place: bytes, bytearray and memoryview go as parts (a Uint8Array
13
+ in the library), and the library's typed arrays come back as bytes.
14
+
15
+ load() and close() are for the engine's thread; call() and cancel() for any
16
+ thread. A call's outcome is a zebkit.automation.Future (awaitable in
17
+ zebkit.automation.run()), or function(value, error) when given, on the
18
+ engine's thread; error is a LibraryError.
19
+
20
+ The library calls the application's functions, given at load as host=, with
21
+ `await host.call(name, ...args)` (import host from 'zebkit:host'):
22
+
23
+ def progress(done):
24
+ print("progress", done)
25
+
26
+ async def ask(question): # or a function returning a Future
27
+ return await something(question)
28
+
29
+ lib = zebkit.library.load("libs/report", host={"progress": progress, "ask": ask})
30
+
31
+ Each runs on the engine's thread with the library's arguments; its value (a
32
+ coroutine's, run with zebkit.automation.run(), or a Future's, settled from any
33
+ thread) answers the library once; what it raises rejects host.call() with an
34
+ Error of the exception's class name and message.
35
+ """
36
+
37
+ import ctypes
38
+ import inspect
39
+ import itertools
40
+ import json
41
+ import threading
42
+
43
+ from . import Error, _EP, _P, _S, _Z, _declare, _guard, _require_thread, _string
44
+ from .automation import Future
45
+
46
+ __all__ = [
47
+ "Library", "LibraryError", "load", "CODES",
48
+ "OK", "THROWN", "LOAD_FAILED", "NO_FUNCTION", "BAD_ARGUMENTS", "BAD_RESULT", "TIMEOUT", "CANCELLED",
49
+ "QUEUE_FULL", "OUT_OF_MEMORY", "GONE",
50
+ ]
51
+
52
+ CODES = ("OK", "THROWN", "LOAD_FAILED", "NO_FUNCTION", "BAD_ARGUMENTS", "BAD_RESULT", "TIMEOUT", "CANCELLED",
53
+ "QUEUE_FULL", "OUT_OF_MEMORY", "GONE")
54
+ OK, THROWN, LOAD_FAILED, NO_FUNCTION, BAD_ARGUMENTS, BAD_RESULT, TIMEOUT, CANCELLED, QUEUE_FULL, \
55
+ OUT_OF_MEMORY, GONE = range(11)
56
+
57
+
58
+ class _Part(ctypes.Structure):
59
+ _fields_ = [("data", ctypes.c_void_p), ("size", ctypes.c_size_t)]
60
+
61
+
62
+ _TOLD = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(_Part),
63
+ ctypes.c_size_t, ctypes.c_void_p)
64
+ _library_load = _declare("zebkit_library_load", _P, _S, _S, _TOLD, _P, _EP)
65
+ _library_call = _declare("zebkit_library_call", ctypes.c_uint64, _P, _S, _S, ctypes.POINTER(_Part), _Z,
66
+ ctypes.c_int64, _TOLD, _P)
67
+ _library_cancel = _declare("zebkit_library_cancel", None, _P, ctypes.c_uint64)
68
+ _library_close = _declare("zebkit_library_close", None, _P)
69
+ _HOST = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_uint64, ctypes.c_char_p, ctypes.c_char_p,
70
+ ctypes.POINTER(_Part), ctypes.c_size_t, ctypes.c_void_p)
71
+ _library_set_host = _declare("zebkit_library_set_host", None, _P, _HOST, _P)
72
+ _library_answer = _declare("zebkit_library_answer", ctypes.c_int, _P, ctypes.c_uint64, ctypes.c_int, _S,
73
+ ctypes.POINTER(_Part), _Z)
74
+
75
+
76
+ class LibraryError(Error):
77
+ """A call or load that failed: code (an int, CODES[code] its name), and
78
+ what the library threw (name, stack) or what the engine says."""
79
+
80
+ def __init__(self, code, message, name="", stack=""):
81
+ super().__init__(message)
82
+ self.code, self.message, self.name, self.stack = code, message, name, stack
83
+
84
+ @property
85
+ def code_name(self):
86
+ return CODES[self.code] if 0 <= self.code < len(CODES) else str(self.code)
87
+
88
+ def __str__(self):
89
+ return "%s: %s%s" % (self.code_name, self.name + ": " if self.name else "", self.message)
90
+
91
+
92
+ # The outcomes waited for, by the key given as the callback's data.
93
+ _waiting = {}
94
+ _waiting_lock = threading.Lock()
95
+ _keys = itertools.count(1)
96
+
97
+
98
+ def _to_wire(args):
99
+ """The arguments as JSON (bytes) and parts."""
100
+ return _value_to_wire(list(args))
101
+
102
+
103
+ def _value_to_wire(value):
104
+ """A value as JSON (bytes) and parts."""
105
+ parts = []
106
+
107
+ def walk(value):
108
+ if isinstance(value, (bytes, bytearray, memoryview)):
109
+ parts.append(bytes(value))
110
+ return {"$part": len(parts) - 1}
111
+ if isinstance(value, dict):
112
+ return {key: walk(item) for key, item in value.items()}
113
+ if isinstance(value, (list, tuple)):
114
+ return [walk(item) for item in value]
115
+ return value
116
+ text = json.dumps(walk(value), ensure_ascii=False, allow_nan=False, separators=(",", ":"))
117
+ return text.encode("utf-8", "surrogatepass"), parts
118
+
119
+
120
+ def _parts_array(parts):
121
+ """A ctypes array of parts, and the buffers to keep while it is used."""
122
+ array = (_Part * len(parts))()
123
+ keep = []
124
+ for i, part in enumerate(parts):
125
+ buffer = ctypes.create_string_buffer(part, len(part)) if part else None
126
+ keep.append(buffer)
127
+ array[i].data = ctypes.cast(buffer, ctypes.c_void_p).value if buffer is not None else None
128
+ array[i].size = len(part)
129
+ return array, keep
130
+
131
+
132
+ def _from_wire(text, parts):
133
+ if not parts:
134
+ return json.loads(text)
135
+
136
+ def hook(value):
137
+ if len(value) == 1 and "$part" in value and isinstance(value["$part"], int) and \
138
+ 0 <= value["$part"] < len(parts):
139
+ return parts[value["$part"]]
140
+ return value
141
+ return json.loads(text, object_hook=hook)
142
+
143
+
144
+ def _told(library, code, text, parts, count, data):
145
+ with _waiting_lock:
146
+ handler = _waiting.pop(data or 0, None)
147
+ if handler is None:
148
+ return
149
+ text = text.decode("utf-8", "replace") if text is not None else "null"
150
+ if code == OK:
151
+ values = [ctypes.string_at(parts[i].data, parts[i].size) if parts[i].size else b"" for i in range(count)]
152
+ handler(_from_wire(text, values), None)
153
+ else:
154
+ try:
155
+ info = json.loads(text)
156
+ except ValueError:
157
+ info = {}
158
+ info = info if isinstance(info, dict) else {}
159
+ handler(None, LibraryError(code, str(info.get("message", CODES[code] if 0 <= code < len(CODES) else code)),
160
+ str(info.get("name") or ""), str(info.get("stack") or "")))
161
+
162
+
163
+ _told_callback = _TOLD(_guard(_told))
164
+
165
+ # The libraries with host functions, by the key given as their data.
166
+ _hosts = {}
167
+
168
+
169
+ def _host_called(library, request, name, text, parts, count, data):
170
+ entry = _hosts.get(data or 0)
171
+ if entry is None:
172
+ return
173
+ owner, functions = entry
174
+ values = [ctypes.string_at(parts[i].data, parts[i].size) if parts[i].size else b"" for i in range(count)]
175
+ name = name.decode("utf-8", "replace") if name else ""
176
+
177
+ def done(value=None, error=None):
178
+ owner._answer(request, value, error)
179
+
180
+ function = functions.get(name)
181
+ if function is None:
182
+ done(error=Error('the application has no function "%s"' % name))
183
+ return
184
+ try:
185
+ result = function(*_from_wire(text.decode("utf-8", "replace") if text else "[]", values))
186
+ if inspect.iscoroutine(result):
187
+ from .automation import run
188
+ result = run(result)
189
+ except BaseException as error: # noqa: BLE001: the library is told
190
+ done(error=error)
191
+ return
192
+ if callable(getattr(result, "add_done_callback", None)):
193
+ def settled(future):
194
+ try:
195
+ value = future.result()
196
+ except BaseException as error: # noqa: BLE001
197
+ done(error=error)
198
+ return
199
+ done(value)
200
+ result.add_done_callback(settled)
201
+ else:
202
+ done(result)
203
+
204
+
205
+ _host_callback = _HOST(_guard(_host_called))
206
+
207
+
208
+ def _expect(function):
209
+ """A key for the outcome, and the Future (or None) it settles."""
210
+ future = None
211
+ if function is None:
212
+ future = Future()
213
+
214
+ def function(value, error):
215
+ if error is not None:
216
+ future.set_error(error)
217
+ else:
218
+ future.set_result(value)
219
+ key = next(_keys)
220
+ with _waiting_lock:
221
+ _waiting[key] = function
222
+ return key, future
223
+
224
+
225
+ def _forget(key):
226
+ with _waiting_lock:
227
+ _waiting.pop(key, None)
228
+
229
+
230
+ class Library:
231
+ """A loaded JavaScript library (load())."""
232
+
233
+ def __init__(self, path, options=None, ready=None, host=None):
234
+ """Loads the library at path and returns at once; calls wait for the
235
+ load. options: zebkit_library_load()'s ("timeoutMs", "queue",
236
+ "heapLimitMB", "maxBytes", "network", "instances", "codeCache").
237
+ ready(value, error), if given, is told once: {"functions": [...]},
238
+ or a LibraryError. host: {name: function} the library calls as
239
+ host.call(name, ...args). Raises Error for bad options or a path that
240
+ is no library. The engine's thread."""
241
+ _require_thread("zebkit.library.load()")
242
+ self._lock = threading.RLock()
243
+ self._closed = False
244
+ self._host_key = None
245
+ if host:
246
+ if not all(callable(function) for function in host.values()):
247
+ raise Error("host is a dict of functions")
248
+ options = dict(options or {}, host=list(host))
249
+ key, self.ready = _expect(ready)
250
+ error = ctypes.c_void_p()
251
+ raw = _library_load(str(path).encode(), json.dumps(options).encode() if options else None, _told_callback,
252
+ ctypes.c_void_p(key), ctypes.byref(error))
253
+ if not raw:
254
+ _forget(key)
255
+ raise Error(_string(error.value) or "the library was not loaded")
256
+ self._raw = raw
257
+ if host:
258
+ self._host_key = next(_keys)
259
+ _hosts[self._host_key] = (self, dict(host))
260
+ _library_set_host(raw, _host_callback, ctypes.c_void_p(self._host_key))
261
+
262
+ @classmethod
263
+ def load(cls, path, options=None, ready=None, host=None):
264
+ return cls(path, options, ready, host)
265
+
266
+ def _answer(self, request, value, error):
267
+ """Answers the library's host.call() @request, once; nothing once closed."""
268
+ code = OK
269
+ try:
270
+ text, parts = _value_to_wire(value) if error is None else (None, [])
271
+ except (TypeError, ValueError) as e:
272
+ error = e
273
+ if error is not None:
274
+ code = THROWN
275
+ message = error.args[0] if len(error.args) == 1 and isinstance(error.args[0], str) else str(error)
276
+ text = json.dumps({"message": message, "name": type(error).__name__}).encode()
277
+ parts = []
278
+ array, keep = _parts_array(parts)
279
+ with self._lock:
280
+ if not self._closed:
281
+ _library_answer(self._raw, int(request), code, text, array, len(parts))
282
+ del keep
283
+
284
+ def call(self, name, *args, timeout_ms=0, function=None):
285
+ """Calls the exported function name with args (JSON values, bytes
286
+ in place). timeout_ms: 0 the library's, < 0 none. A Future of its
287
+ value; with function, function(value, error) is called instead, and
288
+ the call's number returned. Any thread; Error once closed."""
289
+ text, parts = _to_wire(args)
290
+ array, keep = _parts_array(parts)
291
+ key, future = _expect(function)
292
+ with self._lock:
293
+ number = 0 if self._closed else _library_call(self._raw, str(name).encode(), text, array, len(parts),
294
+ int(timeout_ms), _told_callback, ctypes.c_void_p(key))
295
+ if not number:
296
+ _forget(key)
297
+ raise Error("the library is closed")
298
+ if future is None:
299
+ return number
300
+ future.call_id = number
301
+ future._on_cancel = lambda: self.cancel(number)
302
+ return future
303
+
304
+ def cancel(self, call):
305
+ """The call (its number, or its Future) is told CANCELLED, unless
306
+ told already. Any thread."""
307
+ number = getattr(call, "call_id", call)
308
+ with self._lock:
309
+ if not self._closed and number:
310
+ _library_cancel(self._raw, int(number))
311
+
312
+ def close(self):
313
+ """Ends the library: calls not told yet fail with GONE. The engine's
314
+ thread."""
315
+ _require_thread("Library.close()")
316
+ with self._lock:
317
+ if not self._closed:
318
+ self._closed = True
319
+ _library_close(self._raw)
320
+ _hosts.pop(self._host_key, None)
321
+
322
+ @property
323
+ def closed(self):
324
+ return self._closed
325
+
326
+
327
+ def load(path, options=None, ready=None, host=None):
328
+ """Library(path, options, ready, host)."""
329
+ return Library(path, options, ready, host)
File without changes
File without changes
File without changes
File without changes
File without changes