Compare commits

..

No commits in common. "master" and "0.5.0" have entirely different histories.

10 changed files with 474 additions and 658 deletions

View File

@ -22,7 +22,6 @@ sed -i "s/{{size}}/${_size}/" DEBIAN/control
sed -i "s/{{version}}/${version}/" DEBIAN/control
cd ..
sudo chown -R root:root unpack/
dpkg-deb -b unpack/ "python3-webengine-gtk3-${version}.deb"
sudo rm -rf unpack

2
debian/control vendored
View File

@ -4,7 +4,7 @@ Section: develop
Priority: optional
Maintainer: Yutent <yutent.io@gmail.com>
Architecture: all
Depends: python3 (>=3.10), python3-gi, gir1.2-webkit2-4.1, gir1.2-gtk-3.0, python3-pil, python3-gi-cairo, gir1.2-gdkpixbuf-2.0
Depends: python3 (>=3.10), python3-gi, gir1.2-gtk-3.0, python3-pil, python3-gi-cairo, gir1.2-gdkpixbuf-2.0
Recommends: gir1.2-ayatanaappindicator3-0.1, gir1.2-notify-0.7, gir1.2-keybinder-3.0
Installed-Size: {{size}}
Homepage: https://git.wkit.fun/appcat/python3-webengine-gtk3

View File

@ -1,10 +1,10 @@
#!/usr/bin/env python3
import gi
import gi, os, json, shutil, hashlib, time, threading
gi.require_version('Gtk', '3.0')
gi.require_version("WebKit2", "4.1")
from gi.repository import Gtk, WebKit2
from gi.repository import GObject, Gtk, Gdk, WebKit2, GLib, Gio, GdkPixbuf
def create_same_window(origin, req):
@ -37,12 +37,6 @@ def create_custom_window(origin, options):
win.set_wmclass(wmclass, 'WebEngine')
win.set_title(options.get('title') or 'WebEngine')
if options.get('icon_path'):
win.set_icon_from_file(options['icon_path'])
if options.get('icon'):
win.set_icon_name(options['icon'])
if options.get('frame') == False:
win.set_decorated(False)
@ -56,7 +50,9 @@ def create_custom_window(origin, options):
win.set_resizable(False)
web = WebEngine(win, origin, options.get('uuid'))
web = WebEngine(win, origin)
web.set_root(origin.root, True)
web.set_zoom_level(origin.get_zoom_level())
web.set_settings(origin.get_settings())

View File

@ -1,13 +0,0 @@
#!/usr/bin/env python3
import os
home_dir = os.getenv('HOME')
env = {
"HOME_DIR": home_dir,
"CONFIG_DIR": os.path.join(home_dir, '.config'),
"CACHE_DIR": os.path.join(home_dir, '.cache'),
"LANG": os.environ['LANG'] or "en_US.UTF-8"
}

View File

@ -13,18 +13,14 @@ from gi.repository import WebKit2
class Inject:
def __init__(self, webview, env = {}):
self.webview = webview
self.manager = webview.get_user_content_manager()
code = open(self.abspath('./inject.js'), 'r').read()
script_data = open(self.abspath('./inject.js'), 'r').read()
frame = WebKit2.UserContentInjectedFrames.ALL_FRAMES
time = WebKit2.UserScriptInjectionTime.START
code = code.replace("'{{env}}'", json.dumps(env))
code = code.replace("{{uuid}}", webview.uuid)
code = code.replace("{{app_name}}", webview.app_name)
code = code.replace("{{app_version}}", webview.app_version)
script = WebKit2.UserScript(code, frame, time, None, None)
time = WebKit2.UserScriptInjectionTime.END
script_data = script_data.replace("'{{env}}'", json.dumps(env))
script = WebKit2.UserScript(script_data, frame, time, None, None)
self.manager.add_script(script)

View File

@ -22,7 +22,7 @@ class Settings(WebKit2.Settings):
self.set_javascript_can_open_windows_automatically(True)
self.set_useragent_with_app('WebEngine', version)
self.set_user_agent_with_application_details('WebEngine', version)
# indexedDB 和 localStorage 和 离线缓存
@ -43,9 +43,6 @@ class Settings(WebKit2.Settings):
self.set_media_playback_allows_inline(True)
def set_useragent_with_app(self, name, ver):
self.set_user_agent_with_application_details(name, ver)
def set_useragent(self, str):
self.set_user_agent(str)
@ -78,9 +75,6 @@ def create_setting(options = None):
setting.enable_devtools()
setting.mock_devices()
if options.get('app_name') and options.get('app_version'):
setting.set_useragent_with_app(options['app_name'], options['app_version'])
if options.get('useragent'):
setting.set_useragent(options.get('useragent'))
@ -92,9 +86,6 @@ def create_setting(options = None):
def wrapper(app, extra = None):
if options is not None:
app.app_name = options.get('app_name')
app.app_version = options.get('app_version')
app.set_settings(setting)
return wrapper

View File

@ -3,12 +3,9 @@
# @author yutent<yutent.io@gmail.com>
# @date 2023/07/28 14:39:33
import gi, threading
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import GdkPixbuf, GObject
def noop():
pass
from gi.repository import GdkPixbuf
def get_monitor_info(monitor):
return {
@ -67,33 +64,3 @@ 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, 7, 0)
build = (0, 5, 0)
version = '.'.join(map(str, build))

View File

@ -3,8 +3,7 @@
# @date 2023/08/08 14:07:26
import gi, os, sys, json
import webbrowser, shutil, hashlib, random
import gi, os, json, shutil, hashlib, time, threading
gi.require_version('Gtk', '3.0')
gi.require_version("WebKit2", "4.1")
@ -32,13 +31,39 @@ try:
except:
Keybinder = None
from ._env import env
from ._version import version
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, run_async, idle
from ._utils import get_monitor_info, pixbuf_to_dict, dict_to_pixbuf
env = {
"HOME_DIR": os.getenv('HOME'),
"CONFIG_DIR": os.path.join(os.getenv('HOME'), '.config'),
"CACHE_DIR": os.path.join(os.getenv('HOME'), '.cache')
}
def noop():
pass
# 类型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
@ -47,32 +72,21 @@ class WebEngine(WebKit2.WebView):
__gsignals__ = {
'quit': (GObject.SignalFlags.RUN_FIRST, None, ())
}
app_name = 'WebEngine'
app_version = version
uuid = None
root = None
window = None
opener = None
children = set()
custom_bridge = None
def __init__(self, win, opener = None, uuid = None):
def __init__(self, win, opener = None):
WebKit2.WebView.__init__(self)
if uuid is None:
self.uuid = random.randbytes(8).hex()
else:
self.uuid = uuid
self.opener = opener
self.window = win
if opener is not None:
opener.children.add(self)
if win.get_title() is None:
win.set_title(self.app_name)
win.set_title('WebEngine')
if win.get_icon() is None and win.get_icon_name() is None:
win.set_icon_name('web-browser')
@ -95,25 +109,8 @@ class WebEngine(WebKit2.WebView):
self.connect('create', self.create_new_window)
# 允许前端 widnow.close() 关闭窗口
self.connect('close', self.close_window)
self.connect('close', lambda w: win.close())
# 通过外部关闭窗口时从父级中移除
win.connect("destroy", self.remove_from_opener)
win.connect('hide', lambda w: self.call_js('hide'))
win.connect('show', lambda w: self.call_js('show'))
def remove_from_opener(self, win = None):
if self.opener is not None:
try:
self.opener.children.remove(self)
except:
pass
def close_window(self, wv = None):
self.remove_from_opener()
self.window.close()
# 响应原生js的 window.open
@ -155,14 +152,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))
@ -175,16 +172,21 @@ class WebEngine(WebKit2.WebView):
match event:
case 'app':
_error, output = self._app_handler(params)
case 'init':
output = env
case 'fs':
_error, output = self._fs_handler(params)
_error, output = self._fs_setting(params)
case 'clipboard':
_error, output = self._clipboard_handler(params)
_error, output = self._clipboard_setting(params)
# 退出app
case 'quit':
self.window.close()
self.emit('quit')
# 读取图片, 返回图片像素数据
case 'image':
@ -204,7 +206,7 @@ class WebEngine(WebKit2.WebView):
case 'keybinder':
_error, output = self._keybinder_handler(params)
_error, output = self._keybinder_setting(params)
case 'tray':
@ -217,34 +219,15 @@ class WebEngine(WebKit2.WebView):
case 'opener':
callback = 'opener_message'
output = params.get('data')
uuid = json.dumps(self.uuid if self.opener else None)
scripts = f"native.$emit('opener_message', {json.dumps(output)}, {uuid})"
scripts = 'native.$emit("opener_message", ' + json.dumps(output) + ')'
if self.opener is None:
self.evaluate_javascript(scripts, -1)
else:
self.opener.evaluate_javascript(scripts, -1)
return
case 'children':
callback = 'opener_message'
output = params.get('data')
uuid = params.get('uuid')
scripts = f"native.$emit('opener_message', {json.dumps(output)})"
if len(self.children) == 0:
self.evaluate_javascript(scripts, -1)
else:
if uuid is None:
for child in self.children:
child.evaluate_javascript(scripts, -1)
else:
for child in self.children:
if child.uuid == uuid:
child.evaluate_javascript(scripts, -1)
break
return
case 'window':
_error, output = self._window_handler(params)
_error, output = self._window_setting(params)
case 'notify':
@ -261,61 +244,25 @@ class WebEngine(WebKit2.WebView):
case 'proxy':
_error, output = self._proxy_handler(params)
_error, output = self._proxy_setting(params)
case 'md5':
output = hashlib.md5(str(params.get('value'))).hexdigest()
case _:
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 self.custom_bridge is None:
pass
else:
_error, output = self.custom_bridge(event, params)
# 有回调则返回结果
if callback:
self.call_js(callback, output, _error)
def _app_handler(self, params = {}):
_error = None
output = None
match(params.get('action')):
# 退出app
case 'quit':
self.close_window()
self.emit('quit')
case 'relaunch':
py = sys.executable
os.execl(py, py, *sys.argv)
return (_error, output)
def _shell_handler(self, params = {}):
_error = None
output = None
path = params.get('path')
match(params.get('action')):
case 'openExternal':
webbrowser.open(params.get('url'))
case 'showItemInFolder':
os.system(f"xdg-open '{path}'")
case 'openPath':
os.system(f"xdg-open '{path}'")
case 'trashItem':
pass
def _fs_handler(self, params = {}):
def _fs_setting(self, params = {}):
_error = None
output = None
filepath = params.get('filepath')
@ -385,14 +332,11 @@ class WebEngine(WebKit2.WebView):
case 'isdir':
output = os.path.isdir(filepath)
case 'mkdir':
output = os.makedirs(filepath)
return (_error, output)
def _clipboard_handler(self, params = {}):
def _clipboard_setting(self, params = {}):
_error = None
output = None
@ -429,7 +373,7 @@ class WebEngine(WebKit2.WebView):
return (_error, output)
def _keybinder_handler(self, params = {}):
def _keybinder_setting(self, params = {}):
_error = None
output = None
keymap = params.get('value')
@ -460,7 +404,7 @@ class WebEngine(WebKit2.WebView):
def _window_handler(self, params = {}):
def _window_setting(self, params = {}):
_error = None
output = None
@ -470,7 +414,7 @@ class WebEngine(WebKit2.WebView):
self.new_window_by_custom(params.get('options'))
case 'close':
self.close_window()
self.window.close()
case 'fullscreen':
self.window.fullscreen()
@ -522,7 +466,7 @@ class WebEngine(WebKit2.WebView):
def _proxy_handler(self, params = {}):
def _proxy_setting(self, params = {}):
dm = self.get_website_data_manager()
output = True
_error = None

View File

@ -3,7 +3,7 @@
* @author yutent<yutent.io@gmail.com>
* @date 2023/07/21 17:38:11
*/
!(function () {
const MIME_TYPES = {
html: 'text/html',
json: 'application/json',
@ -48,8 +48,6 @@
const NO_CALLBACK = false
const CALL_ONCE = true
const __events__ = Symbol('events')
function defer() {
let obj = {}
obj.promise = new Promise((resolve, reject) => {
@ -73,7 +71,7 @@
callback = rand()
native.$once(callback, (err, res) => {
if (err) {
_.reject(new Error(err))
_.reject(err)
} else {
_.resolve(res)
}
@ -92,34 +90,6 @@
return btoa(str).replace(/[+=\/]/g, '')
}
function _postMessage(data = {}, uuid = null) {
let ev = new Event('message')
Object.assign(ev, {
data,
source: {
postMessage(msg) {
native.children.postMessage(msg, uuid)
}
}
})
window.dispatchEvent(ev)
}
function readonly(obj, key, value) {
Object.defineProperty(obj, key, {
get() {
return value
},
enumerable: false
})
}
function _extend(origin, options = {}) {
for (let k in options) {
readonly(origin, k, options[k])
}
}
class NativeImage {
#origin
@ -173,15 +143,15 @@
}
}
class Native {
class EventEmitter {
//
[__events__] = Object.create(null)
__events__ = Object.create(null)
$on(name, fn) {
if (this[__events__][name]) {
this[__events__][name].push(fn)
if (this.__events__[name]) {
this.__events__[name].push(fn)
} else {
this[__events__][name] = [fn]
this.__events__[name] = [fn]
}
}
@ -191,20 +161,18 @@
}
$off(name, fn) {
if (this[__events__][name]) {
if (this.__events__[name]) {
if (fn) {
this[__events__][name] = this[__events__][name].filter(
it => it !== fn
)
this.__events__[name] = this.__events__[name].filter(it => it !== fn)
} else {
this[__events__][name] = []
this.__events__[name] = []
}
}
}
$emit(name, ...args) {
if (this[__events__][name]) {
for (let fn of this[__events__][name]) {
if (this.__events__[name]) {
for (let fn of this.__events__[name]) {
try {
fn.apply(this, args)
if (fn.__once__) {
@ -218,34 +186,19 @@
}
$destroy() {
this[__events__] = Object.create(null)
this.__events__ = Object.create(null)
}
}
readonly(window, 'native', new Native())
window.native = new EventEmitter()
native.$on('opener_message', (data, uuid) => _postMessage(data, uuid))
native.$on('opener_message', data => window.postMessage(data))
_extend(native, {
Object.assign(native, {
env: '{{env}}',
app: {
name: '{{app_name}}',
version: '{{app_version}}',
quit() {
return handler('app', { action: 'quit' }, NO_CALLBACK)
},
relaunch() {
return handler('app', { action: 'relaunch' }, NO_CALLBACK)
},
getLocale() {
return native.env.LANG
}
},
shell: {
openExternal(url) {},
showItemInFolder(path) {},
openPath(path) {},
trashItem(path) {}
return handler('quit', {}, NO_CALLBACK)
},
fs: {
access(filepath, mode = 'r') {
@ -293,9 +246,6 @@
},
copy(filepath, target) {
return handler('fs', { action: 'copy', filepath, target })
},
mkdir(filepath) {
return handler('fs', { action: 'mkdir', filepath })
}
},
image(filepath) {
@ -395,21 +345,12 @@
}
},
opener: {
//
postMessage(data = {}) {
return handler('opener', { action: 'postmessage', data }, NO_CALLBACK)
}
},
children: {
postMessage(data = {}, uuid = null) {
return handler(
'children',
{ action: 'postmessage', data, uuid },
NO_CALLBACK
)
}
},
window: {
uuid: '{{uuid}}',
create(options = {}) {
return handler('window', { action: 'create', options })
},
@ -456,11 +397,7 @@
handler('window', { action: 'move', value: { x, y } }, NO_CALLBACK)
},
setOpacity(opacity = 1) {
handler(
'window',
{ action: 'set_opacity', value: opacity },
NO_CALLBACK
)
handler('window', { action: 'set_opacity', value: opacity }, NO_CALLBACK)
},
alwayOnTop(setting = true) {
handler(
@ -508,4 +445,3 @@
handler
})
})()