webview-python 1.1.0__cp310-cp310-win_amd64.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.
- webview/__init__.py +1 -0
- webview/_dummy_holder.c +3972 -0
- webview/_dummy_holder.cp310-win_amd64.pyd +0 -0
- webview/_webview_ffi.py +177 -0
- webview/webview.py +109 -0
- webview_python-1.1.0.dist-info/METADATA +413 -0
- webview_python-1.1.0.dist-info/RECORD +10 -0
- webview_python-1.1.0.dist-info/WHEEL +5 -0
- webview_python-1.1.0.dist-info/licenses/LICENSE +21 -0
- webview_python-1.1.0.dist-info/top_level.txt +1 -0
|
Binary file
|
webview/_webview_ffi.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import ctypes
|
|
2
|
+
import sys
|
|
3
|
+
import os
|
|
4
|
+
import platform
|
|
5
|
+
import urllib.request
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from ctypes import c_int, c_char_p, c_void_p, CFUNCTYPE
|
|
8
|
+
import ctypes.util
|
|
9
|
+
import shutil
|
|
10
|
+
|
|
11
|
+
def _encode_c_string(s: str) -> bytes:
|
|
12
|
+
return s.encode("utf-8")
|
|
13
|
+
|
|
14
|
+
def _get_webview_version():
|
|
15
|
+
"""Get webview version from environment variable or use default"""
|
|
16
|
+
return os.getenv("WEBVIEW_VERSION", "0.9.0")
|
|
17
|
+
|
|
18
|
+
def _get_download_base():
|
|
19
|
+
"""Get download base URL or path from environment variable or use default.
|
|
20
|
+
|
|
21
|
+
This allows users to specify a custom location (URL or file path) to download
|
|
22
|
+
libraries from, which is particularly useful for internal deployments or
|
|
23
|
+
offline environments.
|
|
24
|
+
|
|
25
|
+
Returns:
|
|
26
|
+
str: The base URL or path for downloading libraries
|
|
27
|
+
"""
|
|
28
|
+
return os.getenv(
|
|
29
|
+
"WEBVIEW_DOWNLOAD_BASE",
|
|
30
|
+
"https://github.com/webview/webview_deno/releases/download"
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
def _get_lib_names():
|
|
34
|
+
"""Get platform-specific library names."""
|
|
35
|
+
system = platform.system().lower()
|
|
36
|
+
machine = platform.machine().lower()
|
|
37
|
+
|
|
38
|
+
if system == "windows":
|
|
39
|
+
if machine == "amd64" or machine == "x86_64":
|
|
40
|
+
return ["webview.dll", "WebView2Loader.dll"]
|
|
41
|
+
elif machine == "arm64":
|
|
42
|
+
raise Exception("arm64 is not supported on Windows")
|
|
43
|
+
elif system == "darwin":
|
|
44
|
+
if machine == "arm64":
|
|
45
|
+
return ["libwebview.aarch64.dylib"]
|
|
46
|
+
else:
|
|
47
|
+
return ["libwebview.x86_64.dylib"]
|
|
48
|
+
else: # linux
|
|
49
|
+
if machine == "aarch64" or machine == "arm64":
|
|
50
|
+
return ["libwebview.aarch64.so"]
|
|
51
|
+
else:
|
|
52
|
+
return ["libwebview.x86_64.so"]
|
|
53
|
+
|
|
54
|
+
def _get_download_urls():
|
|
55
|
+
"""Get the appropriate download URLs based on the platform."""
|
|
56
|
+
version = _get_webview_version()
|
|
57
|
+
base_url = _get_download_base()
|
|
58
|
+
|
|
59
|
+
# Handle both URL and file path formats
|
|
60
|
+
if base_url.startswith(("http://", "https://", "file://")):
|
|
61
|
+
# For URLs, use / separator
|
|
62
|
+
return [f"{base_url}/{version}/{lib_name}"
|
|
63
|
+
for lib_name in _get_lib_names()]
|
|
64
|
+
else:
|
|
65
|
+
# For file paths, use OS-specific path handling
|
|
66
|
+
base_path = Path(base_url)
|
|
67
|
+
return [str(base_path / version / lib_name)
|
|
68
|
+
for lib_name in _get_lib_names()]
|
|
69
|
+
|
|
70
|
+
def _be_sure_libraries():
|
|
71
|
+
"""Ensure libraries exist and return paths."""
|
|
72
|
+
if getattr(sys, 'frozen', False):
|
|
73
|
+
if hasattr(sys, '_MEIPASS'):
|
|
74
|
+
base_dir = Path(sys._MEIPASS)
|
|
75
|
+
else:
|
|
76
|
+
base_dir = Path(sys.executable).parent / '_internal'
|
|
77
|
+
else:
|
|
78
|
+
base_dir = Path(__file__).parent
|
|
79
|
+
|
|
80
|
+
lib_dir = base_dir / "lib"
|
|
81
|
+
lib_names = _get_lib_names()
|
|
82
|
+
lib_paths = [lib_dir / lib_name for lib_name in lib_names]
|
|
83
|
+
|
|
84
|
+
# Check if any library is missing
|
|
85
|
+
missing_libs = [path for path in lib_paths if not path.exists()]
|
|
86
|
+
if not missing_libs:
|
|
87
|
+
return lib_paths
|
|
88
|
+
|
|
89
|
+
# Download or copy missing libraries
|
|
90
|
+
download_urls = _get_download_urls()
|
|
91
|
+
system = platform.system().lower()
|
|
92
|
+
|
|
93
|
+
lib_dir.mkdir(parents=True, exist_ok=True)
|
|
94
|
+
|
|
95
|
+
for url, lib_path in zip(download_urls, lib_paths):
|
|
96
|
+
if lib_path.exists():
|
|
97
|
+
continue
|
|
98
|
+
|
|
99
|
+
print(f"Getting library from {url}")
|
|
100
|
+
try:
|
|
101
|
+
# Handle different URL types
|
|
102
|
+
if url.startswith(("http://", "https://")):
|
|
103
|
+
# Web URL - download
|
|
104
|
+
req = urllib.request.Request(
|
|
105
|
+
url,
|
|
106
|
+
headers={'User-Agent': 'Mozilla/5.0'}
|
|
107
|
+
)
|
|
108
|
+
with urllib.request.urlopen(req) as response, open(lib_path, 'wb') as out_file:
|
|
109
|
+
out_file.write(response.read())
|
|
110
|
+
elif url.startswith("file://"):
|
|
111
|
+
# File URL - copy from local filesystem
|
|
112
|
+
source_path = url[7:] # Strip 'file://' prefix
|
|
113
|
+
shutil.copy2(source_path, lib_path)
|
|
114
|
+
else:
|
|
115
|
+
# Assume it's a filesystem path
|
|
116
|
+
source_path = url
|
|
117
|
+
if os.path.exists(source_path):
|
|
118
|
+
shutil.copy2(source_path, lib_path)
|
|
119
|
+
else:
|
|
120
|
+
raise FileNotFoundError(f"Could not find library at {source_path}")
|
|
121
|
+
except Exception as e:
|
|
122
|
+
raise RuntimeError(f"Failed to get library from {url}: {e}")
|
|
123
|
+
|
|
124
|
+
return lib_paths
|
|
125
|
+
|
|
126
|
+
class _WebviewLibrary:
|
|
127
|
+
def __init__(self):
|
|
128
|
+
lib_names=_get_lib_names()
|
|
129
|
+
try:
|
|
130
|
+
library_path = ctypes.util.find_library(lib_names[0])
|
|
131
|
+
if not library_path:
|
|
132
|
+
library_paths = _be_sure_libraries()
|
|
133
|
+
self.lib = ctypes.cdll.LoadLibrary(str(library_paths[0]))
|
|
134
|
+
except Exception as e:
|
|
135
|
+
print(f"Failed to load webview library: {e}")
|
|
136
|
+
raise
|
|
137
|
+
# Define FFI functions
|
|
138
|
+
self.webview_create = self.lib.webview_create
|
|
139
|
+
self.webview_create.argtypes = [c_int, c_void_p]
|
|
140
|
+
self.webview_create.restype = c_void_p
|
|
141
|
+
|
|
142
|
+
self.webview_destroy = self.lib.webview_destroy
|
|
143
|
+
self.webview_destroy.argtypes = [c_void_p]
|
|
144
|
+
|
|
145
|
+
self.webview_run = self.lib.webview_run
|
|
146
|
+
self.webview_run.argtypes = [c_void_p]
|
|
147
|
+
|
|
148
|
+
self.webview_terminate = self.lib.webview_terminate
|
|
149
|
+
self.webview_terminate.argtypes = [c_void_p]
|
|
150
|
+
|
|
151
|
+
self.webview_set_title = self.lib.webview_set_title
|
|
152
|
+
self.webview_set_title.argtypes = [c_void_p, c_char_p]
|
|
153
|
+
|
|
154
|
+
self.webview_set_size = self.lib.webview_set_size
|
|
155
|
+
self.webview_set_size.argtypes = [c_void_p, c_int, c_int, c_int]
|
|
156
|
+
|
|
157
|
+
self.webview_navigate = self.lib.webview_navigate
|
|
158
|
+
self.webview_navigate.argtypes = [c_void_p, c_char_p]
|
|
159
|
+
|
|
160
|
+
self.webview_init = self.lib.webview_init
|
|
161
|
+
self.webview_init.argtypes = [c_void_p, c_char_p]
|
|
162
|
+
|
|
163
|
+
self.webview_eval = self.lib.webview_eval
|
|
164
|
+
self.webview_eval.argtypes = [c_void_p, c_char_p]
|
|
165
|
+
|
|
166
|
+
self.webview_bind = self.lib.webview_bind
|
|
167
|
+
self.webview_bind.argtypes = [c_void_p, c_char_p, c_void_p, c_void_p]
|
|
168
|
+
|
|
169
|
+
self.webview_unbind = self.lib.webview_unbind
|
|
170
|
+
self.webview_unbind.argtypes = [c_void_p, c_char_p]
|
|
171
|
+
|
|
172
|
+
self.webview_return = self.lib.webview_return
|
|
173
|
+
self.webview_return.argtypes = [c_void_p, c_char_p, c_int, c_char_p]
|
|
174
|
+
|
|
175
|
+
self.CFUNCTYPE = CFUNCTYPE
|
|
176
|
+
|
|
177
|
+
_webview_lib = _WebviewLibrary()
|
webview/webview.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
from enum import IntEnum
|
|
2
|
+
from typing import Optional, Callable, Any
|
|
3
|
+
import json
|
|
4
|
+
import ctypes
|
|
5
|
+
import asyncio
|
|
6
|
+
import inspect
|
|
7
|
+
from ._webview_ffi import _webview_lib, _encode_c_string
|
|
8
|
+
|
|
9
|
+
class SizeHint(IntEnum):
|
|
10
|
+
NONE = 0
|
|
11
|
+
MIN = 1
|
|
12
|
+
MAX = 2
|
|
13
|
+
FIXED = 3
|
|
14
|
+
|
|
15
|
+
class Size:
|
|
16
|
+
def __init__(self, width: int, height: int, hint: SizeHint):
|
|
17
|
+
self.width = width
|
|
18
|
+
self.height = height
|
|
19
|
+
self.hint = hint
|
|
20
|
+
|
|
21
|
+
class Webview:
|
|
22
|
+
def __init__(self, debug: bool = False, size: Optional[Size] = None, window: Optional[int] = None):
|
|
23
|
+
self._handle = _webview_lib.webview_create(int(debug), window)
|
|
24
|
+
self._callbacks = {}
|
|
25
|
+
|
|
26
|
+
if size:
|
|
27
|
+
self.size = size
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def size(self) -> Size:
|
|
31
|
+
return self._size
|
|
32
|
+
|
|
33
|
+
@size.setter
|
|
34
|
+
def size(self, value: Size):
|
|
35
|
+
_webview_lib.webview_set_size(self._handle, value.width, value.height, value.hint)
|
|
36
|
+
self._size = value
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def title(self) -> str:
|
|
40
|
+
return self._title
|
|
41
|
+
|
|
42
|
+
@title.setter
|
|
43
|
+
def title(self, value: str):
|
|
44
|
+
_webview_lib.webview_set_title(self._handle, _encode_c_string(value))
|
|
45
|
+
self._title = value
|
|
46
|
+
|
|
47
|
+
def destroy(self):
|
|
48
|
+
for name in list(self._callbacks.keys()):
|
|
49
|
+
self.unbind(name)
|
|
50
|
+
_webview_lib.webview_terminate(self._handle)
|
|
51
|
+
_webview_lib.webview_destroy(self._handle)
|
|
52
|
+
self._handle = None
|
|
53
|
+
|
|
54
|
+
def navigate(self, url: str):
|
|
55
|
+
_webview_lib.webview_navigate(self._handle, _encode_c_string(url))
|
|
56
|
+
|
|
57
|
+
def run(self):
|
|
58
|
+
_webview_lib.webview_run(self._handle)
|
|
59
|
+
self.destroy()
|
|
60
|
+
|
|
61
|
+
def bind(self, name: str, callback: Callable[..., Any]):
|
|
62
|
+
def wrapper(seq: bytes, req: bytes, arg: int):
|
|
63
|
+
args = json.loads(req.decode())
|
|
64
|
+
seq_str = seq.decode()
|
|
65
|
+
|
|
66
|
+
if inspect.iscoroutinefunction(callback):
|
|
67
|
+
# Handle async function
|
|
68
|
+
async def handle_async():
|
|
69
|
+
try:
|
|
70
|
+
result = await callback(*args)
|
|
71
|
+
success = True
|
|
72
|
+
except Exception as e:
|
|
73
|
+
result = str(e)
|
|
74
|
+
success = False
|
|
75
|
+
self.return_(seq_str, 0 if success else 1, json.dumps(result))
|
|
76
|
+
# Schedule the coroutine to run
|
|
77
|
+
asyncio.ensure_future(handle_async())
|
|
78
|
+
else:
|
|
79
|
+
try:
|
|
80
|
+
result = callback(*args)
|
|
81
|
+
success = True
|
|
82
|
+
except Exception as e:
|
|
83
|
+
result = str(e)
|
|
84
|
+
success = False
|
|
85
|
+
self.return_(seq_str, 0 if success else 1, json.dumps(result))
|
|
86
|
+
|
|
87
|
+
c_callback = _webview_lib.CFUNCTYPE(None, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_void_p)(wrapper)
|
|
88
|
+
self._callbacks[name] = c_callback
|
|
89
|
+
_webview_lib.webview_bind(self._handle, _encode_c_string(name), c_callback, None)
|
|
90
|
+
|
|
91
|
+
def unbind(self, name: str):
|
|
92
|
+
if name in self._callbacks:
|
|
93
|
+
_webview_lib.webview_unbind(self._handle, _encode_c_string(name))
|
|
94
|
+
del self._callbacks[name]
|
|
95
|
+
|
|
96
|
+
def return_(self, seq: str, status: int, result: str):
|
|
97
|
+
_webview_lib.webview_return(self._handle, _encode_c_string(seq), status, _encode_c_string(result))
|
|
98
|
+
|
|
99
|
+
def eval(self, source: str):
|
|
100
|
+
_webview_lib.webview_eval(self._handle, _encode_c_string(source))
|
|
101
|
+
|
|
102
|
+
def init(self, source: str):
|
|
103
|
+
_webview_lib.webview_init(self._handle, _encode_c_string(source))
|
|
104
|
+
|
|
105
|
+
if __name__ == "__main__":
|
|
106
|
+
wv = Webview()
|
|
107
|
+
wv.title = "Hello, World!"
|
|
108
|
+
wv.navigate("https://www.google.com")
|
|
109
|
+
wv.run()
|
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: webview_python
|
|
3
|
+
Version: 1.1.0
|
|
4
|
+
Summary: Python bindings for the webview library, which completely follow deno_webview design and principles
|
|
5
|
+
License: MIT License
|
|
6
|
+
|
|
7
|
+
Copyright (c) 2024 Python Webview Contributors
|
|
8
|
+
|
|
9
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
10
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
11
|
+
in the Software without restriction, including without limitation the rights
|
|
12
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
13
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
14
|
+
furnished to do so, subject to the following conditions:
|
|
15
|
+
|
|
16
|
+
The above copyright notice and this permission notice shall be included in all
|
|
17
|
+
copies or substantial portions of the Software.
|
|
18
|
+
|
|
19
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
20
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
21
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
22
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
23
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
24
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
25
|
+
SOFTWARE.
|
|
26
|
+
|
|
27
|
+
Project-URL: Homepage, https://github.com/congzhangzh/webview_python
|
|
28
|
+
Project-URL: Repository, https://github.com/congzhangzh/webview_python.git
|
|
29
|
+
Project-URL: Bug Tracker, https://github.com/congzhangzh/webview_python/issues
|
|
30
|
+
Keywords: webview,gui,desktop,application,html,web
|
|
31
|
+
Classifier: Development Status :: 3 - Alpha
|
|
32
|
+
Classifier: Intended Audience :: Developers
|
|
33
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
34
|
+
Classifier: Operating System :: OS Independent
|
|
35
|
+
Classifier: Programming Language :: Python
|
|
36
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
37
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
38
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
39
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
40
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
41
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
42
|
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
43
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
44
|
+
Classifier: Topic :: Software Development :: User Interfaces
|
|
45
|
+
Requires-Python: >=3.10
|
|
46
|
+
Description-Content-Type: text/markdown
|
|
47
|
+
License-File: LICENSE
|
|
48
|
+
Dynamic: license-file
|
|
49
|
+
|
|
50
|
+
# Webview Python
|
|
51
|
+
|
|
52
|
+
[](https://github.com/congzhangzh/webview_python/actions/workflows/test.yml)
|
|
53
|
+
[](https://github.com/congzhangzh/webview_python/actions/workflows/test.yml)
|
|
54
|
+
[](https://github.com/congzhangzh/webview_python/actions/workflows/test.yml)
|
|
55
|
+
[](https://badge.fury.io/py/webview_python)
|
|
56
|
+
[](https://opensource.org/licenses/MIT)
|
|
57
|
+
[](https://pypi.org/project/webview_python/)
|
|
58
|
+
|
|
59
|
+
Python bindings for the webview library, allowing you to create desktop applications with web technologies.
|
|
60
|
+
|
|
61
|
+
## Installation
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
pip install webview_python
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Environment Variables
|
|
68
|
+
|
|
69
|
+
Webview Python supports the following environment variables:
|
|
70
|
+
|
|
71
|
+
- `WEBVIEW_VERSION`: Specify the version of the webview library to use (default: "0.9.0")
|
|
72
|
+
- `WEBVIEW_DOWNLOAD_BASE`: Specify the base URL or file path for downloading webview libraries (default: GitHub releases)
|
|
73
|
+
- Can be a web URL: `https://internal-server.com/webview-libs`
|
|
74
|
+
- Network share: `\\server\share\webview-libs` or `/mnt/server/webview-libs`
|
|
75
|
+
- Local path: `/path/to/libs` or `C:\path\to\libs`
|
|
76
|
+
|
|
77
|
+
Example usage:
|
|
78
|
+
```bash
|
|
79
|
+
# Using an internal HTTP server
|
|
80
|
+
export WEBVIEW_DOWNLOAD_BASE="http://internal-server.com/webview-libs"
|
|
81
|
+
|
|
82
|
+
# Using a network share on Windows
|
|
83
|
+
set WEBVIEW_DOWNLOAD_BASE=\\\\server\\share\\webview-libs
|
|
84
|
+
|
|
85
|
+
# Using a mounted path on Linux
|
|
86
|
+
export WEBVIEW_DOWNLOAD_BASE="/mnt/server/webview-libs"
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Note: When using a custom download location, you must organize the libraries in the same structure as the GitHub releases:
|
|
90
|
+
```
|
|
91
|
+
WEBVIEW_DOWNLOAD_BASE/
|
|
92
|
+
├── 0.9.0/
|
|
93
|
+
│ ├── webview.dll # Windows x64
|
|
94
|
+
│ ├── WebView2Loader.dll # Windows x64
|
|
95
|
+
│ ├── libwebview.x86_64.so # Linux x64
|
|
96
|
+
│ ├── libwebview.aarch64.so # Linux ARM64
|
|
97
|
+
│ ├── libwebview.x86_64.dylib # macOS x64
|
|
98
|
+
│ └── libwebview.aarch64.dylib # macOS ARM64
|
|
99
|
+
└── other-versions/...
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## Usage
|
|
103
|
+
|
|
104
|
+
### Display Inline HTML:
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
from webview.webview import Webview
|
|
108
|
+
from urllib.parse import quote
|
|
109
|
+
|
|
110
|
+
html = """
|
|
111
|
+
<html>
|
|
112
|
+
<body>
|
|
113
|
+
<h1>Hello from Python Webview!</h1>
|
|
114
|
+
</body>
|
|
115
|
+
</html>
|
|
116
|
+
"""
|
|
117
|
+
webview = Webview()
|
|
118
|
+
webview.navigate(f"data:text/html,{quote(html)}")
|
|
119
|
+
webview.run()
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### Load Local HTML File:
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
from webview.webview import Webview
|
|
126
|
+
import os
|
|
127
|
+
|
|
128
|
+
webview = Webview()
|
|
129
|
+
current_dir = os.path.dirname(os.path.abspath(__file__))
|
|
130
|
+
html_path = os.path.join(current_dir, 'local.html')
|
|
131
|
+
webview.navigate(f"file://{html_path}")
|
|
132
|
+
webview.run()
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### Load Remote URL:
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
from webview.webview import Webview
|
|
139
|
+
webview = Webview()
|
|
140
|
+
webview.navigate("https://www.python.org")
|
|
141
|
+
webview.run()
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
### Python-JavaScript Bindings:
|
|
145
|
+
|
|
146
|
+
```python
|
|
147
|
+
from webview.webview import Webview, Size, SizeHint
|
|
148
|
+
from urllib.parse import quote
|
|
149
|
+
|
|
150
|
+
webview = Webview(debug=True)
|
|
151
|
+
|
|
152
|
+
# Python functions that can be called from JavaScript
|
|
153
|
+
def hello():
|
|
154
|
+
webview.eval("updateFromPython('Hello from Python!')")
|
|
155
|
+
return "Hello from Python!"
|
|
156
|
+
|
|
157
|
+
def add(a, b):
|
|
158
|
+
return a + b
|
|
159
|
+
|
|
160
|
+
# Bind Python functions
|
|
161
|
+
webview.bind("hello", hello)
|
|
162
|
+
webview.bind("add", add)
|
|
163
|
+
|
|
164
|
+
# Configure window
|
|
165
|
+
webview.title = "Python-JavaScript Binding Demo"
|
|
166
|
+
webview.size = Size(640, 480, SizeHint.FIXED)
|
|
167
|
+
|
|
168
|
+
# Load HTML with JavaScript
|
|
169
|
+
html = """
|
|
170
|
+
<html>
|
|
171
|
+
<head>
|
|
172
|
+
<title>Python-JavaScript Binding Demo</title>
|
|
173
|
+
<script>
|
|
174
|
+
async function callPython() {
|
|
175
|
+
const result = await hello();
|
|
176
|
+
document.getElementById('result').innerHTML = result;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async function callPythonWithArgs() {
|
|
180
|
+
const result = await add(40, 2);
|
|
181
|
+
document.getElementById('result').innerHTML = `Result: ${result}`;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function updateFromPython(message) {
|
|
185
|
+
document.getElementById('result').innerHTML = `Python says: ${message}`;
|
|
186
|
+
}
|
|
187
|
+
</script>
|
|
188
|
+
</head>
|
|
189
|
+
<body>
|
|
190
|
+
<h1>Python-JavaScript Binding Demo</h1>
|
|
191
|
+
<button onclick="callPython()">Call Python</button>
|
|
192
|
+
<button onclick="callPythonWithArgs()">Call Python with Args</button>
|
|
193
|
+
<div id="result"></div>
|
|
194
|
+
</body>
|
|
195
|
+
</html>
|
|
196
|
+
"""
|
|
197
|
+
|
|
198
|
+
webview.navigate(f"data:text/html,{quote(html)}")
|
|
199
|
+
webview.run()
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
### Async Python Functions with JavaScript:
|
|
203
|
+
|
|
204
|
+
Webview Python supports binding asynchronous Python functions that can be called from JavaScript. This is useful for time-consuming operations that should not block the main thread.
|
|
205
|
+
|
|
206
|
+
Demo: [bind_in_local_async_by_asyncio_guest_win32_wip.py](examples/async_with_asyncio_guest_run/bind_in_local_async_by_asyncio_guest_win32_wip.py), [bind_in_local_async.html](examples/async_with_asyncio_guest_run/bind_in_local_async.html)
|
|
207
|
+
|
|
208
|
+
```python
|
|
209
|
+
import asyncio
|
|
210
|
+
from webview.webview import Webview, Size, SizeHint
|
|
211
|
+
|
|
212
|
+
webview = Webview(debug=True)
|
|
213
|
+
|
|
214
|
+
# Async Python function that can be called from JavaScript
|
|
215
|
+
async def delayed_message(message, delay=1):
|
|
216
|
+
# Simulating a time-consuming operation
|
|
217
|
+
await asyncio.sleep(delay)
|
|
218
|
+
return f"Async response after {delay}s: {message}"
|
|
219
|
+
|
|
220
|
+
# Async function with progress reporting
|
|
221
|
+
async def process_with_progress(steps=5, step_time=1):
|
|
222
|
+
results = []
|
|
223
|
+
for i in range(1, steps + 1):
|
|
224
|
+
await asyncio.sleep(step_time)
|
|
225
|
+
# Report progress to JavaScript
|
|
226
|
+
progress = (i / steps) * 100
|
|
227
|
+
webview.eval(f"updateProgress({progress}, 'Processing: Step {i}/{steps}')")
|
|
228
|
+
results.append(f"Step {i} completed")
|
|
229
|
+
|
|
230
|
+
return {
|
|
231
|
+
"status": "complete",
|
|
232
|
+
"steps": steps,
|
|
233
|
+
"results": results
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
# Bind async Python functions
|
|
237
|
+
webview.bind("delayedMessage", delayed_message)
|
|
238
|
+
webview.bind("processWithProgress", process_with_progress)
|
|
239
|
+
|
|
240
|
+
# HTML/JavaScript
|
|
241
|
+
html = """
|
|
242
|
+
<html>
|
|
243
|
+
<head>
|
|
244
|
+
<script>
|
|
245
|
+
async function callAsyncPython() {
|
|
246
|
+
try {
|
|
247
|
+
document.getElementById('result').innerHTML = "Waiting for async response...";
|
|
248
|
+
const result = await delayedMessage("Hello from async world!", 2);
|
|
249
|
+
document.getElementById('result').innerHTML = result;
|
|
250
|
+
} catch (err) {
|
|
251
|
+
document.getElementById('result').innerHTML = `Error: ${err}`;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function updateProgress(percent, message) {
|
|
256
|
+
document.getElementById('progress').style.width = percent + '%';
|
|
257
|
+
document.getElementById('progress-text').textContent = message;
|
|
258
|
+
}
|
|
259
|
+
</script>
|
|
260
|
+
</head>
|
|
261
|
+
<body>
|
|
262
|
+
<button onclick="callAsyncPython()">Call Async Python</button>
|
|
263
|
+
<div id="result"></div>
|
|
264
|
+
<div id="progress" style="background-color: #ddd; width: 100%">
|
|
265
|
+
<div id="progress-bar" style="height: 20px; background-color: #4CAF50; width: 0%"></div>
|
|
266
|
+
</div>
|
|
267
|
+
<div id="progress-text"></div>
|
|
268
|
+
</body>
|
|
269
|
+
</html>
|
|
270
|
+
"""
|
|
271
|
+
|
|
272
|
+
webview.navigate(f"data:text/html,{quote(html)}")
|
|
273
|
+
webview.run()
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
For a more complete example, see [bind_in_local_async.py](examples/bind_in_local_async.py) and [bind_in_local_async.html](examples/bind_in_local_async.html) in the examples directory.
|
|
277
|
+
|
|
278
|
+
## Features
|
|
279
|
+
|
|
280
|
+
- Create desktop applications using HTML, CSS, and JavaScript
|
|
281
|
+
- Load local HTML files or remote URLs
|
|
282
|
+
- Bidirectional Python-JavaScript communication
|
|
283
|
+
- Support for async Python functions with JavaScript promises
|
|
284
|
+
- Progress reporting for long-running tasks
|
|
285
|
+
- Window size and title customization
|
|
286
|
+
- Debug mode for development
|
|
287
|
+
- Cross-platform support (Windows, macOS, Linux)
|
|
288
|
+
|
|
289
|
+
## Development
|
|
290
|
+
|
|
291
|
+
### Setup Development Environment
|
|
292
|
+
|
|
293
|
+
```bash
|
|
294
|
+
# Install Python build tools
|
|
295
|
+
pip install --upgrade pip build twine
|
|
296
|
+
|
|
297
|
+
# Install GitHub CLI (choose one based on your OS):
|
|
298
|
+
# macOS
|
|
299
|
+
brew install gh
|
|
300
|
+
|
|
301
|
+
# Windows
|
|
302
|
+
winget install GitHub.cli
|
|
303
|
+
# or
|
|
304
|
+
choco install gh
|
|
305
|
+
|
|
306
|
+
# Linux (Debian/Ubuntu)
|
|
307
|
+
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg \
|
|
308
|
+
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null \
|
|
309
|
+
&& sudo apt update \
|
|
310
|
+
&& sudo apt install gh
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
### Running Tests
|
|
314
|
+
|
|
315
|
+
```bash
|
|
316
|
+
python -m unittest discover tests
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
### Project Structure
|
|
320
|
+
|
|
321
|
+
```
|
|
322
|
+
webview_python/
|
|
323
|
+
├── src/
|
|
324
|
+
│ ├── webview.py # Main webview implementation
|
|
325
|
+
│ └── ffi.py # Foreign Function Interface
|
|
326
|
+
├── examples/ # Example applications
|
|
327
|
+
├── tests/ # Unit tests
|
|
328
|
+
└── README.md # Documentation
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
### Release Process
|
|
332
|
+
|
|
333
|
+
For maintainers who want to release a new version:
|
|
334
|
+
1. **Test**
|
|
335
|
+
```bash
|
|
336
|
+
# Install dependencies if not installed
|
|
337
|
+
pip install -r requirements.txt
|
|
338
|
+
|
|
339
|
+
# Run tests
|
|
340
|
+
pytest
|
|
341
|
+
|
|
342
|
+
# Build wheels
|
|
343
|
+
python -m build -n -w
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
2. **Update Version**
|
|
347
|
+
```bash
|
|
348
|
+
# Ensure you have the latest code
|
|
349
|
+
git pull origin main
|
|
350
|
+
|
|
351
|
+
# Update version in pyproject.toml
|
|
352
|
+
# Edit version = "x.y.z" to new version number
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
3. **Create Release**
|
|
356
|
+
```bash
|
|
357
|
+
# Commit changes
|
|
358
|
+
old_version=1.0.1
|
|
359
|
+
new_version=1.1.0
|
|
360
|
+
git add pyproject.toml
|
|
361
|
+
git commit -m "Bump version to ${new_version}"
|
|
362
|
+
git push origin main
|
|
363
|
+
|
|
364
|
+
# Create and push tag
|
|
365
|
+
git tag v${new_version}
|
|
366
|
+
git push origin v${new_version}
|
|
367
|
+
|
|
368
|
+
# Create GitHub release
|
|
369
|
+
gh release create v${new_version} --title "${new_version}" \
|
|
370
|
+
--notes "Full Changelog: https://github.com/congzhangzh/webview_python/compare/v${old_version}...v${new_version}"
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
4. **Monitor Release**
|
|
374
|
+
- Check GitHub Actions progress in the Actions tab
|
|
375
|
+
- Verify package on PyPI after workflow completion
|
|
376
|
+
|
|
377
|
+
### First-time Release Setup
|
|
378
|
+
|
|
379
|
+
1. **PyPI Setup**
|
|
380
|
+
- Create account: https://pypi.org/account/register/
|
|
381
|
+
- Generate API token: https://pypi.org/manage/account/token/
|
|
382
|
+
|
|
383
|
+
2. **GitHub Setup**
|
|
384
|
+
- Repository Settings → Secrets and variables → Actions
|
|
385
|
+
- Add new secret: `PYPI_API_TOKEN` with PyPI token value
|
|
386
|
+
|
|
387
|
+
## Roadmap
|
|
388
|
+
|
|
389
|
+
- [x] Publish to PyPI
|
|
390
|
+
- [x] Setup GitHub Actions for CI/CD
|
|
391
|
+
- [x] Add async function support
|
|
392
|
+
- [x] Add preact example
|
|
393
|
+
- [ ] Add three.js example
|
|
394
|
+
- [ ] Add three.js fiber example
|
|
395
|
+
- [ ] Add screen saver 4 window example
|
|
396
|
+
- [ ] Add MRI principle demo example by three.js fiber
|
|
397
|
+
- [ ] Add screen saver 4 windows with MRI principle demo example by three.js fiber
|
|
398
|
+
|
|
399
|
+
## TBD
|
|
400
|
+
- [x] CTRL-C support
|
|
401
|
+
|
|
402
|
+
## References
|
|
403
|
+
|
|
404
|
+
- [Webview](https://github.com/webview/webview)
|
|
405
|
+
- [webview C API IMPL](https://github.com/webview/webview/blob/master/core/include/webview/c_api_impl.hh)
|
|
406
|
+
- [Webview C API](https://github.com/webview/webview/blob/master/src/webview.h)
|
|
407
|
+
- [webview_deno](https://github.com/eliassjogreen/webview_deno)
|
|
408
|
+
- [asyncio-guest](https://github.com/congzhangzh/asyncio-guest)
|
|
409
|
+
- [asyncio-guest win32](https://github.com/congzhangzh/asyncio-guest/blob/master/asyncio_guest/asyncio_guest_win32.py)
|
|
410
|
+
|
|
411
|
+
# License
|
|
412
|
+
|
|
413
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|