js调用python改为异步; js调用python方法异常信息改为Error对象;优化自定义桥接方法的异常处理

master 0.7.0
yutent 2024-01-24 17:37:31 +08:00
parent 3062354338
commit 64dc70b594
4 changed files with 44 additions and 12 deletions

View File

@ -3,9 +3,9 @@
# @author yutent<yutent.io@gmail.com>
# @date 2023/07/28 14:39:33
import gi
import gi, threading
gi.require_version('Gtk', '3.0')
from gi.repository import GdkPixbuf
from gi.repository import GdkPixbuf, GObject
def noop():
pass
@ -67,3 +67,33 @@ def dict_to_pixbuf(data):
image = None
return image
# 定义一个异步修饰器, 用于在子线程中运行一些会阻塞主线程的任务
def run_async(func):
def wrapper(*args, **kwargs):
thread = threading.Thread(target=func, args=args, kwargs=kwargs)
thread.daemon = True
thread.start()
return thread
return wrapper
# 类型js的settimeout的修饰器
def set_timeout(timeout = 0.5):
def decorator(callback):
def wrapper(*args):
t = threading.Timer(timeout, callback, args=args)
t.start()
return t
return wrapper
return decorator
# 定义一个修饰器, 用于将当前方法转到主线程中运行 (子线程中调用方法时)
def idle(func):
def wrapper(*args):
GObject.idle_add(func, *args)
return wrapper

View File

@ -1,4 +1,4 @@
#!/usr/bin/env python3
build = (0, 6, 1)
build = (0, 7, 0)
version = '.'.join(map(str, build))

View File

@ -38,7 +38,7 @@ from ._settings import create_setting
from ._protocal import create_protocal
from ._notify import create_notify
from ._inject import Inject
from ._utils import noop, get_monitor_info, pixbuf_to_dict, dict_to_pixbuf
from ._utils import noop, get_monitor_info, pixbuf_to_dict, dict_to_pixbuf, run_async, idle
@ -155,14 +155,14 @@ class WebEngine(WebKit2.WebView):
raise ValueError('url must starts with "/" or "app://"')
@idle
def call_js(self, method, data = None, err = None):
if err is not None:
err = str(err)
scripts = 'native.$emit("' + method + '", ' + json.dumps(err) + ', ' + json.dumps(data) + ')'
self.evaluate_javascript(scripts, -1)
@run_async
def called_by_js(self, webview, message):
data = json.loads(message.get_js_value().to_json(0))
@ -268,10 +268,12 @@ class WebEngine(WebKit2.WebView):
output = hashlib.md5(str(params.get('value'))).hexdigest()
case _:
if self.custom_bridge is None:
pass
else:
_error, output = self.custom_bridge(event, params)
if self.custom_bridge is not None:
try:
_error, output = self.custom_bridge(event, params) or (None, None)
except Exception as err:
print(err)
_error = err
# 有回调则返回结果
if callback:

View File

@ -73,7 +73,7 @@
callback = rand()
native.$once(callback, (err, res) => {
if (err) {
_.reject(err)
_.reject(new Error(err))
} else {
_.resolve(res)
}