This repository has been archived on 2023-09-06. You can view files and clone it, but cannot push or open issues/pull-requests.
yutent
/
py-gtk-notes
Archived
1
0
Fork 0

更新一波

master
yutent 2023-07-28 19:38:24 +08:00
parent a961b87960
commit 613d8070ed
4 changed files with 110 additions and 54 deletions

7
app.js
View File

@ -43,6 +43,13 @@ class App extends Component {
</button> </button>
<button @click=${this.createTray}>tray</button> <button @click=${this.createTray}>tray</button>
<button @click=${this.register}>screen</button> <button @click=${this.register}>screen</button>
<button
@click=${function () {
native.globalShortcut.unregisterAll(['<Ctrl>b', '<Ctrl>a'])
}}
>
unregisterall
</button>
<img style="width:100px;border:1px solid #09f;" src=${this.img} /> <img style="width:100px;border:1px solid #09f;" src=${this.img} />
<textarea @paste=${this.pasteImg}></textarea> <textarea @paste=${this.pasteImg}></textarea>
` `

View File

@ -75,6 +75,10 @@ function handler(event, data = {}, once = true) {
return _.promise return _.promise
} }
function base64(str = '') {
return btoa(str).replace(/[+=\/]/g, '')
}
class NativeImage { class NativeImage {
#origin #origin
@ -83,7 +87,6 @@ class NativeImage {
this.width = obj.width this.width = obj.width
this.height = obj.height this.height = obj.height
this.type = MIME_TYPES[obj.filepath.split('.').pop()] this.type = MIME_TYPES[obj.filepath.split('.').pop()]
console.log(obj)
} }
toPixbuf() { toPixbuf() {
@ -207,8 +210,7 @@ Object.assign(native, {
return handler('keybinder', { action: 'supported' }) return handler('keybinder', { action: 'supported' })
}, },
register(keyMap, callback) { register(keyMap, callback) {
// let shortcut_callback = base64(keyMap)
let shortcut_callback = 'blabla'
native.$off(shortcut_callback) native.$off(shortcut_callback)
native.$on(shortcut_callback, callback) native.$on(shortcut_callback, callback)
return handler('keybinder', { return handler('keybinder', {
@ -217,21 +219,52 @@ Object.assign(native, {
shortcut_callback shortcut_callback
}) })
}, },
registerAll(keyMap, callback) {
//
return handler('keybinder', { action: 'register-all', value: keyMap })
},
isRegistered(keyMap) {
//
return handler('keybinder', { action: 'is-registered', value: keyMap })
},
unregister(keyMap) { unregister(keyMap) {
// let shortcut_callback = base64(keyMap)
native.$off(shortcut_callback)
return handler('keybinder', { action: 'unregister', value: keyMap }) return handler('keybinder', { action: 'unregister', value: keyMap })
}, },
unregisterAll(keyMap) { unregisterAll(keyMaps) {
for (let it of keyMaps) {
this.unregister(it)
}
}
},
tray: {
create() {
// //
return handler('keybinder', { action: 'unregister-all', value: keyMap }) },
remove() {
//
},
/**
* 设置普通状态的tray图标, 只需要传名称, 自动会去当前主题下去找
*/
set_icon(name) {
return handler('tray', { action: 'set_icon', value: name })
},
/**
* 设置警示图标, 同上
*/
set_attention_icon(name) {
return handler('tray', { action: 'set_attention_icon', value: name })
},
/**
*
*/
set_title(title) {
return handler('tray', { action: 'set_title', value: title })
},
/**
* 修改tray图标状态
* @param status <Number> 0: 隐藏, 1: 显示, 2: 重要(对应上面的attention_icon)
*/
set_status(status) {
return handler('tray', { action: 'set_status', value: status })
} }
}, },
handler handler

74
main.py
View File

@ -90,7 +90,14 @@ class WebKitWindow(Gtk.Window):
"youtube", "youtube",
AppIndicator3.IndicatorCategory.APPLICATION_STATUS AppIndicator3.IndicatorCategory.APPLICATION_STATUS
) )
# indicator.set_title('alacritty 6666')
# indicator.set_label('alacritty 8888', '')
# indicator.set_icon_full('alacritty','alacritty')
# indicator.set_attention_icon_full('alacritty', 'alacritty')
# indicator.set_ordering_index(99)
indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE) indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)
# indicator.set_status(AppIndicator3.IndicatorStatus.ATTENTION)
else: else:
# windows 和 macos 必须传二进制图标, linux可传图标名称(自会去主题中找) # windows 和 macos 必须传二进制图标, linux可传图标名称(自会去主题中找)
indicator = Gtk.StatusIcon.new_from_pixbuf(get_logo(32)) indicator = Gtk.StatusIcon.new_from_pixbuf(get_logo(32))
@ -113,6 +120,9 @@ class WebKitWindow(Gtk.Window):
self.present() self.present()
def call_js(self, method, data = None):
scripts = 'native.$emit("' + method + '",' + json.dumps(data) + ')'
self.webview.evaluate_javascript(scripts, -1)
@ -151,17 +161,9 @@ class WebKitWindow(Gtk.Window):
# 前端传进来的值, 如果是路径的话, 直接读取 # 前端传进来的值, 如果是路径的话, 直接读取
if type(image) == str: if type(image) == str:
image = Pixbuf.new_from_file(image) image = Pixbuf.new_from_file(image)
print(pixbuf_to_dict(image, params['value']))
else: else:
image = Pixbuf.new_from_data( image = dict_to_pixbuf(image)
data = bytes(image['bytes']),
colorspace = image['colorspace'],
has_alpha = image['has_alpha'],
bits_per_sample = image['bits_per_sample'],
width = image['width'],
height = image['height'],
rowstride = image['rowstride']
)
self.clipboard.set_image(image) self.clipboard.set_image(image)
self.clipboard.store() self.clipboard.store()
@ -176,8 +178,7 @@ class WebKitWindow(Gtk.Window):
# 回调给前端 # 回调给前端
if callback: if callback:
scripts = 'native.$emit("' + callback + '",' + json.dumps(output) + ')' self.call_js(callback, output)
self.webview.evaluate_javascript(scripts, -1)
# 退出app # 退出app
case 'quit': case 'quit':
@ -189,10 +190,7 @@ class WebKitWindow(Gtk.Window):
pixbuf = Pixbuf.new_from_file(filename) pixbuf = Pixbuf.new_from_file(filename)
image = pixbuf_to_dict(pixbuf, filename) image = pixbuf_to_dict(pixbuf, filename)
scripts = 'native.$emit("' + callback + '",' + json.dumps(image) + ')' self.call_js(callback, image)
self.webview.send_message_to_page(WebKit2.UserMessage.new('blabla'))
self.webview.evaluate_javascript(scripts, -1)
case 'monitor': case 'monitor':
@ -201,24 +199,20 @@ class WebKitWindow(Gtk.Window):
monitor_num = display.get_n_monitors() monitor_num = display.get_n_monitors()
monitors = [display.get_monitor(i) for i in range(monitor_num)] monitors = [display.get_monitor(i) for i in range(monitor_num)]
monitors = [get_monitor_info(m) for m in monitors] monitors = [get_monitor_info(m) for m in monitors]
scripts = 'native.$emit("' + callback + '",' + json.dumps(monitors) + ')' self.call_js(callback, monitors)
self.webview.evaluate_javascript(scripts, -1)
elif params['action'] == 'get-primary': elif params['action'] == 'get-primary':
display = Gdk.Display.get_default() display = Gdk.Display.get_default()
monitor = display.get_primary_monitor() monitor = display.get_primary_monitor()
info = get_monitor_info(monitor) info = get_monitor_info(monitor)
scripts = 'native.$emit("' + callback + '",' + json.dumps(info) + ')' self.call_js(callback, info)
self.webview.evaluate_javascript(scripts, -1)
case 'keybinder': case 'keybinder':
output = None output = None
keymap = params.get('value') keymap = params.get('value')
shortcut_callback = params.get('shortcut_callback') or '' shortcut_callback = params.get('shortcut_callback') or ''
scripts = 'native.$emit("' + shortcut_callback + '")'
if params['action'] == 'register': if params['action'] == 'register':
# 绑定之前, 先解绑, 避免被重复绑定 # 绑定之前, 先解绑, 避免被重复绑定
@ -226,28 +220,35 @@ class WebKitWindow(Gtk.Window):
output = Keybinder.bind( output = Keybinder.bind(
keymap, keymap,
lambda km : self.webview.evaluate_javascript('native.$emit("' + shortcut_callback + '")', -1) lambda km : self.call_js(shortcut_callback)
) )
elif params['action'] == 'register': elif params['action'] == 'unregister':
pass Keybinder.unbind(keymap)
output = True
elif params['action'] == 'is-registered':
pass
elif params['action'] == 'supported': elif params['action'] == 'supported':
output = Keybinder.supported() output = Keybinder.supported()
scripts = 'native.$emit("' + callback + '",' + json.dumps(output) + ')' # 有回调则返回结果
self.webview.evaluate_javascript(scripts, -1) if callback:
self.call_js(callback, output)
case 'tray':
if params['action'] == 'create':
pass
elif params['action'] == 'remove':
pass
if callback :
self.call_js(callback, True)
case _: case _:
if callback : if callback :
res = {"foo": 123, "bar": (11,22,33)} res = {"foo": 123, "bar": (11,22,33)}
scripts = 'native.$emit("' + callback + '",' + json.dumps(res) + ')' self.call_js(callback, res)
print(scripts)
self.webview.evaluate_javascript(scripts, -1)
def all_quit(win): def all_quit(win):
@ -261,9 +262,6 @@ win.connect("destroy", all_quit)
win.show_all() win.show_all()
print(Keybinder.supported())
tray = win.create_tray() tray = win.create_tray()
Gtk.main() Gtk.main()

View File

@ -3,6 +3,8 @@
# @author yutent<yutent.io@gmail.com> # @author yutent<yutent.io@gmail.com>
# @date 2023/07/28 14:39:33 # @date 2023/07/28 14:39:33
import gi
from gi.repository.GdkPixbuf import Pixbuf
def get_monitor_info(monitor): def get_monitor_info(monitor):
return { return {
@ -30,7 +32,7 @@ def pixbuf_to_dict(pixbuf, filename = ''):
if not has_alpha: if not has_alpha:
pixbuf = pixbuf.add_alpha(False, 0, 0, 0) pixbuf = pixbuf.add_alpha(False, 0, 0, 0)
image = { data = {
"width": pixbuf.get_width(), "width": pixbuf.get_width(),
"height": pixbuf.get_height(), "height": pixbuf.get_height(),
"colorspace": pixbuf.get_colorspace(), "colorspace": pixbuf.get_colorspace(),
@ -38,9 +40,25 @@ def pixbuf_to_dict(pixbuf, filename = ''):
"bits_per_sample": pixbuf.get_bits_per_sample(), "bits_per_sample": pixbuf.get_bits_per_sample(),
"rowstride": pixbuf.get_rowstride(), "rowstride": pixbuf.get_rowstride(),
"filepath": filename, "filepath": filename,
"length": pixbuf.get_byte_length(),
"bytes": list(pixbuf.get_pixels()) "bytes": list(pixbuf.get_pixels())
} }
else:
data = None
return data
def dict_to_pixbuf(data):
if data:
image = Pixbuf.new_from_data(
data = bytes(data['bytes']),
colorspace = data['colorspace'],
has_alpha = data['has_alpha'],
bits_per_sample = data['bits_per_sample'],
width = data['width'],
height = data['height'],
rowstride = data['rowstride']
)
else: else:
image = None image = None