🎨 Optimize hotkey service

This commit is contained in:
2025-11-06 00:08:26 +08:00
parent df79267e16
commit e0179b5838
25 changed files with 1642 additions and 1113 deletions

View File

@@ -0,0 +1,181 @@
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
// Package hotkey provides the basic facility to register a system-level
// global hotkey shortcut so that an application can be notified if a user
// triggers the desired hotkey. A hotkey must be a combination of modifiers
// and a single key.
//
// Note platform specific details:
//
// - On macOS, due to the OS restriction (other platforms does not have
// this restriction), hotkey events must be handled on the "main thread".
// Therefore, in order to use this package properly, one must start an
// OS main event loop on the main thread, For self-contained applications,
// using [mainthread] package.
// is possible. It is uncessary or applications based on other GUI frameworks,
// such as fyne, ebiten, or Gio. See the "[examples]" for more examples.
//
// - On Linux (X11), when AutoRepeat is enabled in the X server, the
// Keyup is triggered automatically and continuously as Keydown continues.
//
// - On Linux (X11), some keys may be mapped to multiple Mod keys. To
// correctly register the key combination, one must use the correct
// underlying keycode combination. For example, a regular Ctrl+Alt+S
// might be registered as: Ctrl+Mod2+Mod4+S.
//
// - If this package did not include a desired key, one can always provide
// the keycode to the API. For example, if a key code is 0x15, then the
// corresponding key is `hotkey.Key(0x15)`.
//
// THe following is a minimum example:
//
// package main
//
// import (
// "log"
//
// "golang.design/x/hotkey"
// "golang.design/x/hotkey/mainthread"
// )
//
// func main() { mainthread.Init(fn) } // Not necessary when use in Fyne, Ebiten or Gio.
// func fn() {
// hk := hotkey.New([]hotkey.Modifier{hotkey.ModCtrl, hotkey.ModShift}, hotkey.KeyS)
// err := hk.Register()
// if err != nil {
// log.Fatalf("hotkey: failed to register hotkey: %v", err)
// }
//
// log.Printf("hotkey: %v is registered\n", hk)
// <-hk.Keydown()
// log.Printf("hotkey: %v is down\n", hk)
// <-hk.Keyup()
// log.Printf("hotkey: %v is up\n", hk)
// hk.Unregister()
// log.Printf("hotkey: %v is unregistered\n", hk)
// }
//
// [mainthread]: https://pkg.go.dev/golang.design/x/hotkey/mainthread
// [examples]: https://github.com/golang-design/hotkey/tree/main/examples
package hotkey
import (
"fmt"
"runtime"
)
// Event represents a hotkey event
type Event struct{}
// Hotkey is a combination of modifiers and key to trigger an event
type Hotkey struct {
platformHotkey
mods []Modifier
key Key
keydownIn chan<- Event
keydownOut <-chan Event
keyupIn chan<- Event
keyupOut <-chan Event
}
// New creates a new hotkey for the given modifiers and keycode.
func New(mods []Modifier, key Key) *Hotkey {
keydownIn, keydownOut := newEventChan()
keyupIn, keyupOut := newEventChan()
hk := &Hotkey{
mods: mods,
key: key,
keydownIn: keydownIn,
keydownOut: keydownOut,
keyupIn: keyupIn,
keyupOut: keyupOut,
}
// Make sure the hotkey is unregistered when the created
// hotkey is garbage collected.
runtime.SetFinalizer(hk, func(x interface{}) {
hk := x.(*Hotkey)
hk.unregister()
close(hk.keydownIn)
close(hk.keyupIn)
})
return hk
}
// Register registers a combination of hotkeys. If the hotkey has
// registered. This function will invalidates the old registration
// and overwrites its callback.
func (hk *Hotkey) Register() error { return hk.register() }
// Keydown returns a channel that receives a signal when the hotkey is triggered.
func (hk *Hotkey) Keydown() <-chan Event { return hk.keydownOut }
// Keyup returns a channel that receives a signal when the hotkey is released.
func (hk *Hotkey) Keyup() <-chan Event { return hk.keyupOut }
// Unregister unregisters the hotkey.
func (hk *Hotkey) Unregister() error {
err := hk.unregister()
if err != nil {
return err
}
// Reset a new event channel.
close(hk.keydownIn)
close(hk.keyupIn)
hk.keydownIn, hk.keydownOut = newEventChan()
hk.keyupIn, hk.keyupOut = newEventChan()
return nil
}
// String returns a string representation of the hotkey.
func (hk *Hotkey) String() string {
s := fmt.Sprintf("%v", hk.key)
for _, mod := range hk.mods {
s += fmt.Sprintf("+%v", mod)
}
return s
}
// newEventChan returns a sender and a receiver of a buffered channel
// with infinite capacity.
func newEventChan() (chan<- Event, <-chan Event) {
in, out := make(chan Event), make(chan Event)
go func() {
var q []Event
for {
e, ok := <-in
if !ok {
close(out)
return
}
q = append(q, e)
for len(q) > 0 {
select {
case out <- q[0]:
q[0] = Event{}
q = q[1:]
case e, ok := <-in:
if ok {
q = append(q, e)
break
}
for _, e := range q {
out <- e
}
close(out)
return
}
}
}
}()
return in, out
}

View File

@@ -0,0 +1,176 @@
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
//go:build darwin
package hotkey
/*
#cgo CFLAGS: -x objective-c
#cgo LDFLAGS: -framework Cocoa -framework Carbon
#include <stdint.h>
#import <Cocoa/Cocoa.h>
#import <Carbon/Carbon.h>
extern void keydownCallback(uintptr_t handle);
extern void keyupCallback(uintptr_t handle);
int registerHotKey(int mod, int key, uintptr_t handle, EventHotKeyRef* ref);
int unregisterHotKey(EventHotKeyRef ref);
*/
import "C"
import (
"errors"
"runtime/cgo"
"sync"
)
// Hotkey is a combination of modifiers and key to trigger an event
type platformHotkey struct {
mu sync.Mutex
registered bool
hkref C.EventHotKeyRef
}
func (hk *Hotkey) register() error {
hk.mu.Lock()
defer hk.mu.Unlock()
if hk.registered {
return errors.New("hotkey already registered")
}
// Note: we use handle number as hotkey id in the C side.
// A cgo handle could ran out of space, but since in hotkey purpose
// we won't have that much number of hotkeys. So this should be fine.
h := cgo.NewHandle(hk)
var mod Modifier
for _, m := range hk.mods {
mod += m
}
ret := C.registerHotKey(C.int(mod), C.int(hk.key), C.uintptr_t(h), &hk.hkref)
if ret == C.int(-1) {
return errors.New("failed to register the hotkey")
}
hk.registered = true
return nil
}
func (hk *Hotkey) unregister() error {
hk.mu.Lock()
defer hk.mu.Unlock()
if !hk.registered {
return errors.New("hotkey is not registered")
}
ret := C.unregisterHotKey(hk.hkref)
if ret == C.int(-1) {
return errors.New("failed to unregister the current hotkey")
}
hk.registered = false
return nil
}
//export keydownCallback
func keydownCallback(h uintptr) {
hk := cgo.Handle(h).Value().(*Hotkey)
hk.keydownIn <- Event{}
}
//export keyupCallback
func keyupCallback(h uintptr) {
hk := cgo.Handle(h).Value().(*Hotkey)
hk.keyupIn <- Event{}
}
// Modifier represents a modifier.
// See: /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h
type Modifier uint32
// All kinds of Modifiers
const (
ModCtrl Modifier = 0x1000
ModShift Modifier = 0x200
ModOption Modifier = 0x800
ModCmd Modifier = 0x100
)
// Key represents a key.
// See: /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h
type Key uint8
// All kinds of keys
const (
KeySpace Key = 49
Key1 Key = 18
Key2 Key = 19
Key3 Key = 20
Key4 Key = 21
Key5 Key = 23
Key6 Key = 22
Key7 Key = 26
Key8 Key = 28
Key9 Key = 25
Key0 Key = 29
KeyA Key = 0
KeyB Key = 11
KeyC Key = 8
KeyD Key = 2
KeyE Key = 14
KeyF Key = 3
KeyG Key = 5
KeyH Key = 4
KeyI Key = 34
KeyJ Key = 38
KeyK Key = 40
KeyL Key = 37
KeyM Key = 46
KeyN Key = 45
KeyO Key = 31
KeyP Key = 35
KeyQ Key = 12
KeyR Key = 15
KeyS Key = 1
KeyT Key = 17
KeyU Key = 32
KeyV Key = 9
KeyW Key = 13
KeyX Key = 7
KeyY Key = 16
KeyZ Key = 6
KeyReturn Key = 0x24
KeyEscape Key = 0x35
KeyDelete Key = 0x33
KeyTab Key = 0x30
KeyLeft Key = 0x7B
KeyRight Key = 0x7C
KeyUp Key = 0x7E
KeyDown Key = 0x7D
KeyF1 Key = 0x7A
KeyF2 Key = 0x78
KeyF3 Key = 0x63
KeyF4 Key = 0x76
KeyF5 Key = 0x60
KeyF6 Key = 0x61
KeyF7 Key = 0x62
KeyF8 Key = 0x64
KeyF9 Key = 0x65
KeyF10 Key = 0x6D
KeyF11 Key = 0x67
KeyF12 Key = 0x6F
KeyF13 Key = 0x69
KeyF14 Key = 0x6B
KeyF15 Key = 0x71
KeyF16 Key = 0x6A
KeyF17 Key = 0x40
KeyF18 Key = 0x4F
KeyF19 Key = 0x50
KeyF20 Key = 0x5A
)

View File

@@ -0,0 +1,65 @@
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
//go:build darwin
#include <stdint.h>
#import <Cocoa/Cocoa.h>
#import <Carbon/Carbon.h>
extern void keydownCallback(uintptr_t handle);
extern void keyupCallback(uintptr_t handle);
static OSStatus
keydownHandler(EventHandlerCallRef nextHandler, EventRef theEvent, void *userData) {
EventHotKeyID k;
GetEventParameter(theEvent, kEventParamDirectObject, typeEventHotKeyID, NULL, sizeof(k), NULL, &k);
keydownCallback((uintptr_t)k.id); // use id as handle
return noErr;
}
static OSStatus
keyupHandler(EventHandlerCallRef nextHandler, EventRef theEvent, void *userData) {
EventHotKeyID k;
GetEventParameter(theEvent, kEventParamDirectObject, typeEventHotKeyID, NULL, sizeof(k), NULL, &k);
keyupCallback((uintptr_t)k.id); // use id as handle
return noErr;
}
// registerHotkeyWithCallback registers a global system hotkey for callbacks.
int registerHotKey(int mod, int key, uintptr_t handle, EventHotKeyRef* ref) {
__block OSStatus s;
dispatch_sync(dispatch_get_main_queue(), ^{
EventTypeSpec keydownEvent;
keydownEvent.eventClass = kEventClassKeyboard;
keydownEvent.eventKind = kEventHotKeyPressed;
EventTypeSpec keyupEvent;
keyupEvent.eventClass = kEventClassKeyboard;
keyupEvent.eventKind = kEventHotKeyReleased;
InstallApplicationEventHandler(
&keydownHandler, 1, &keydownEvent, NULL, NULL
);
InstallApplicationEventHandler(
&keyupHandler, 1, &keyupEvent, NULL, NULL
);
EventHotKeyID hkid = {.id = handle};
s = RegisterEventHotKey(
key, mod, hkid, GetApplicationEventTarget(), 0, ref
);
});
if (s != noErr) {
return -1;
}
return 0;
}
int unregisterHotKey(EventHotKeyRef ref) {
OSStatus s = UnregisterEventHotKey(ref);
if (s != noErr) {
return -1;
}
return 0;
}

View File

@@ -0,0 +1,67 @@
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
//go:build darwin && cgo
package hotkey_test
import (
"context"
"fmt"
"testing"
"time"
"voidraft/internal/common/hotkey"
)
// TestHotkey should always run success.
// This is a test to run and for manually testing the registration of multiple
// hotkeys. Registered hotkeys:
// Ctrl+Shift+S
// Ctrl+Option+S
func TestHotkey(t *testing.T) {
tt := time.Second * 5
done := make(chan struct{}, 2)
ctx, cancel := context.WithTimeout(context.Background(), tt)
go func() {
hk := hotkey.New([]hotkey.Modifier{hotkey.ModCtrl, hotkey.ModShift}, hotkey.KeyS)
if err := hk.Register(); err != nil {
t.Errorf("failed to register hotkey: %v", err)
return
}
for {
select {
case <-ctx.Done():
cancel()
done <- struct{}{}
return
case <-hk.Keydown():
fmt.Println("triggered ctrl+shift+s")
}
}
}()
go func() {
hk := hotkey.New([]hotkey.Modifier{hotkey.ModCtrl, hotkey.ModOption}, hotkey.KeyS)
if err := hk.Register(); err != nil {
t.Errorf("failed to register hotkey: %v", err)
return
}
for {
select {
case <-ctx.Done():
cancel()
done <- struct{}{}
return
case <-hk.Keydown():
fmt.Println("triggered ctrl+option+s")
}
}
}()
<-done
<-done
}

View File

@@ -0,0 +1,77 @@
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
//go:build linux
#include <stdint.h>
#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
extern void hotkeyDown(uintptr_t hkhandle);
extern void hotkeyUp(uintptr_t hkhandle);
int displayTest() {
Display* d = NULL;
for (int i = 0; i < 42; i++) {
d = XOpenDisplay(0);
if (d == NULL) continue;
break;
}
if (d == NULL) {
return -1;
}
return 0;
}
// FIXME: handle bad access properly.
// int handleErrors( Display* dpy, XErrorEvent* pErr )
// {
// printf("X Error Handler called, values: %d/%lu/%d/%d/%d\n",
// pErr->type,
// pErr->serial,
// pErr->error_code,
// pErr->request_code,
// pErr->minor_code );
// if( pErr->request_code == 33 ){ // 33 (X_GrabKey)
// if( pErr->error_code == BadAccess ){
// printf("ERROR: key combination already grabbed by another client.\n");
// return 0;
// }
// }
// return 0;
// }
// waitHotkey blocks until the hotkey is triggered.
// this function crashes the program if the hotkey already grabbed by others.
int waitHotkey(uintptr_t hkhandle, unsigned int mod, int key) {
Display* d = NULL;
for (int i = 0; i < 42; i++) {
d = XOpenDisplay(0);
if (d == NULL) continue;
break;
}
if (d == NULL) {
return -1;
}
int keycode = XKeysymToKeycode(d, key);
XGrabKey(d, keycode, mod, DefaultRootWindow(d), False, GrabModeAsync, GrabModeAsync);
XSelectInput(d, DefaultRootWindow(d), KeyPressMask);
XEvent ev;
while(1) {
XNextEvent(d, &ev);
switch(ev.type) {
case KeyPress:
hotkeyDown(hkhandle);
continue;
case KeyRelease:
hotkeyUp(hkhandle);
XUngrabKey(d, keycode, mod, DefaultRootWindow(d));
XCloseDisplay(d);
return 0;
}
}
}

View File

@@ -0,0 +1,210 @@
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
//go:build linux
package hotkey
/*
#cgo LDFLAGS: -lX11
#include <stdint.h>
int displayTest();
int waitHotkey(uintptr_t hkhandle, unsigned int mod, int key);
*/
import "C"
import (
"context"
"errors"
"runtime"
"runtime/cgo"
"sync"
)
const errmsg = `Failed to initialize the X11 display, and the clipboard package
will not work properly. Install the following dependency may help:
apt install -y libx11-dev
If the clipboard package is in an environment without a frame buffer,
such as a cloud server, it may also be necessary to install xvfb:
apt install -y xvfb
and initialize a virtual frame buffer:
Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &
export DISPLAY=:99.0
Then this package should be ready to use.
`
func init() {
if C.displayTest() != 0 {
panic(errmsg)
}
}
type platformHotkey struct {
mu sync.Mutex
registered bool
ctx context.Context
cancel context.CancelFunc
canceled chan struct{}
}
// Nothing needs to do for register
func (hk *Hotkey) register() error {
hk.mu.Lock()
if hk.registered {
hk.mu.Unlock()
return errors.New("hotkey already registered.")
}
hk.registered = true
hk.ctx, hk.cancel = context.WithCancel(context.Background())
hk.canceled = make(chan struct{})
hk.mu.Unlock()
go hk.handle()
return nil
}
// Nothing needs to do for unregister
func (hk *Hotkey) unregister() error {
hk.mu.Lock()
defer hk.mu.Unlock()
if !hk.registered {
return errors.New("hotkey is not registered.")
}
hk.cancel()
hk.registered = false
<-hk.canceled
return nil
}
// handle registers an application global hotkey to the system,
// and returns a channel that will signal if the hotkey is triggered.
func (hk *Hotkey) handle() {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
// KNOWN ISSUE: if a hotkey is grabbed by others, C side will crash the program
var mod Modifier
for _, m := range hk.mods {
mod = mod | m
}
h := cgo.NewHandle(hk)
defer h.Delete()
for {
select {
case <-hk.ctx.Done():
close(hk.canceled)
return
default:
_ = C.waitHotkey(C.uintptr_t(h), C.uint(mod), C.int(hk.key))
}
}
}
//export hotkeyDown
func hotkeyDown(h uintptr) {
hk := cgo.Handle(h).Value().(*Hotkey)
hk.keydownIn <- Event{}
}
//export hotkeyUp
func hotkeyUp(h uintptr) {
hk := cgo.Handle(h).Value().(*Hotkey)
hk.keyupIn <- Event{}
}
// Modifier represents a modifier.
type Modifier uint32
// All kinds of Modifiers
// See /usr/include/X11/X.h
const (
ModCtrl Modifier = (1 << 2)
ModShift Modifier = (1 << 0)
Mod1 Modifier = (1 << 3)
Mod2 Modifier = (1 << 4)
Mod3 Modifier = (1 << 5)
Mod4 Modifier = (1 << 6)
Mod5 Modifier = (1 << 7)
)
// Key represents a key.
// See /usr/include/X11/keysymdef.h
type Key uint16
// All kinds of keys
const (
KeySpace Key = 0x0020
Key1 Key = 0x0030
Key2 Key = 0x0031
Key3 Key = 0x0032
Key4 Key = 0x0033
Key5 Key = 0x0034
Key6 Key = 0x0035
Key7 Key = 0x0036
Key8 Key = 0x0037
Key9 Key = 0x0038
Key0 Key = 0x0039
KeyA Key = 0x0061
KeyB Key = 0x0062
KeyC Key = 0x0063
KeyD Key = 0x0064
KeyE Key = 0x0065
KeyF Key = 0x0066
KeyG Key = 0x0067
KeyH Key = 0x0068
KeyI Key = 0x0069
KeyJ Key = 0x006a
KeyK Key = 0x006b
KeyL Key = 0x006c
KeyM Key = 0x006d
KeyN Key = 0x006e
KeyO Key = 0x006f
KeyP Key = 0x0070
KeyQ Key = 0x0071
KeyR Key = 0x0072
KeyS Key = 0x0073
KeyT Key = 0x0074
KeyU Key = 0x0075
KeyV Key = 0x0076
KeyW Key = 0x0077
KeyX Key = 0x0078
KeyY Key = 0x0079
KeyZ Key = 0x007a
KeyReturn Key = 0xff0d
KeyEscape Key = 0xff1b
KeyDelete Key = 0xffff
KeyTab Key = 0xff1b
KeyLeft Key = 0xff51
KeyRight Key = 0xff53
KeyUp Key = 0xff52
KeyDown Key = 0xff54
KeyF1 Key = 0xffbe
KeyF2 Key = 0xffbf
KeyF3 Key = 0xffc0
KeyF4 Key = 0xffc1
KeyF5 Key = 0xffc2
KeyF6 Key = 0xffc3
KeyF7 Key = 0xffc4
KeyF8 Key = 0xffc5
KeyF9 Key = 0xffc6
KeyF10 Key = 0xffc7
KeyF11 Key = 0xffc8
KeyF12 Key = 0xffc9
KeyF13 Key = 0xffca
KeyF14 Key = 0xffcb
KeyF15 Key = 0xffcc
KeyF16 Key = 0xffcd
KeyF17 Key = 0xffce
KeyF18 Key = 0xffcf
KeyF19 Key = 0xffd0
KeyF20 Key = 0xffd1
)

View File

@@ -0,0 +1,41 @@
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
//go:build linux && cgo
package hotkey_test
import (
"context"
"fmt"
"testing"
"time"
"voidraft/internal/common/hotkey"
)
// TestHotkey should always run success.
// This is a test to run and for manually testing, registered combination:
// Ctrl+Alt+A (Ctrl+Mod2+Mod4+A on Linux)
func TestHotkey(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
hk := hotkey.New([]hotkey.Modifier{
hotkey.ModCtrl, hotkey.Mod2, hotkey.Mod4}, hotkey.KeyA)
if err := hk.Register(); err != nil {
t.Errorf("failed to register hotkey: %v", err)
return
}
for {
select {
case <-ctx.Done():
return
case <-hk.Keydown():
fmt.Println("triggered")
}
}
}

View File

@@ -0,0 +1,26 @@
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
//go:build !windows && !cgo
package hotkey
type platformHotkey struct{}
// Modifier represents a modifier
type Modifier uint32
// Key represents a key.
type Key uint8
func (hk *Hotkey) register() error {
panic("hotkey: cannot use when CGO_ENABLED=0")
}
// unregister deregisteres a system hotkey.
func (hk *Hotkey) unregister() error {
panic("hotkey: cannot use when CGO_ENABLED=0")
}

View File

@@ -0,0 +1,34 @@
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
//go:build (linux || darwin) && !cgo
package hotkey_test
import (
"testing"
"voidraft/internal/common/hotkey"
)
// TestHotkey should always run success.
// This is a test to run and for manually testing, registered combination:
// Ctrl+Alt+A (Ctrl+Mod2+Mod4+A on Linux)
func TestHotkey(t *testing.T) {
defer func() {
if r := recover(); r != nil {
return
}
t.Fatalf("expect to fail when CGO_ENABLED=0")
}()
hk := hotkey.New([]hotkey.Modifier{}, hotkey.Key(0))
err := hk.Register()
if err != nil {
t.Fatal(err)
}
hk.Unregister()
}

View File

@@ -0,0 +1,19 @@
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
package hotkey_test
import (
"os"
"testing"
"voidraft/internal/common/hotkey/mainthread"
)
// The test cannot be run twice since the mainthread loop may not be terminated:
// go test -v -count=1
func TestMain(m *testing.M) {
mainthread.Init(func() { os.Exit(m.Run()) })
}

View File

@@ -0,0 +1,224 @@
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
//go:build windows
package hotkey
import (
"errors"
"runtime"
"sync"
"sync/atomic"
"time"
"voidraft/internal/common/hotkey/internal/win"
)
type platformHotkey struct {
mu sync.Mutex
hotkeyId uint64
registered bool
funcs chan func()
canceled chan struct{}
}
var hotkeyId uint64 // atomic
// register registers a system hotkey. It returns an error if
// the registration is failed. This could be that the hotkey is
// conflict with other hotkeys.
func (hk *Hotkey) register() error {
hk.mu.Lock()
if hk.registered {
hk.mu.Unlock()
return errors.New("hotkey already registered")
}
mod := uint8(0)
for _, m := range hk.mods {
mod = mod | uint8(m)
}
hk.hotkeyId = atomic.AddUint64(&hotkeyId, 1)
hk.funcs = make(chan func())
hk.canceled = make(chan struct{})
go hk.handle()
var (
ok bool
err error
done = make(chan struct{})
)
hk.funcs <- func() {
ok, err = win.RegisterHotKey(0, uintptr(hk.hotkeyId), uintptr(mod), uintptr(hk.key))
done <- struct{}{}
}
<-done
if !ok {
close(hk.canceled)
hk.mu.Unlock()
return err
}
hk.registered = true
hk.mu.Unlock()
return nil
}
// unregister deregisteres a system hotkey.
func (hk *Hotkey) unregister() error {
hk.mu.Lock()
defer hk.mu.Unlock()
if !hk.registered {
return errors.New("hotkey is not registered")
}
done := make(chan struct{})
hk.funcs <- func() {
win.UnregisterHotKey(0, uintptr(hk.hotkeyId))
done <- struct{}{}
close(hk.canceled)
}
<-done
<-hk.canceled
hk.registered = false
return nil
}
const (
// wmHotkey represents hotkey message
wmHotkey uint32 = 0x0312
wmQuit uint32 = 0x0012
)
// handle handles the hotkey event loop.
func (hk *Hotkey) handle() {
// We could optimize this. So far each hotkey is served in an
// individual thread. If we have too many hotkeys, then a program
// have to create too many threads to serve them.
runtime.LockOSThread()
defer runtime.UnlockOSThread()
isKeyDown := false
tk := time.NewTicker(time.Second / 100)
for range tk.C {
msg := win.MSG{}
if !win.PeekMessage(&msg, 0, 0, 0) {
select {
case f := <-hk.funcs:
f()
case <-hk.canceled:
return
default:
// If the latest status is KeyDown, and AsyncKeyState is 0, consider key is up.
if win.GetAsyncKeyState(int(hk.key)) == 0 && isKeyDown {
hk.keyupIn <- Event{}
isKeyDown = false
}
}
continue
}
if !win.GetMessage(&msg, 0, 0, 0) {
return
}
switch msg.Message {
case wmHotkey:
hk.keydownIn <- Event{}
isKeyDown = true
case wmQuit:
return
}
}
}
// Modifier represents a modifier.
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerhotkey
type Modifier uint8
// All kinds of Modifiers
const (
ModAlt Modifier = 0x1
ModCtrl Modifier = 0x2
ModShift Modifier = 0x4
ModWin Modifier = 0x8
)
// Key represents a key.
// https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
type Key uint16
// All kinds of Keys
const (
KeySpace Key = 0x20
Key0 Key = 0x30
Key1 Key = 0x31
Key2 Key = 0x32
Key3 Key = 0x33
Key4 Key = 0x34
Key5 Key = 0x35
Key6 Key = 0x36
Key7 Key = 0x37
Key8 Key = 0x38
Key9 Key = 0x39
KeyA Key = 0x41
KeyB Key = 0x42
KeyC Key = 0x43
KeyD Key = 0x44
KeyE Key = 0x45
KeyF Key = 0x46
KeyG Key = 0x47
KeyH Key = 0x48
KeyI Key = 0x49
KeyJ Key = 0x4A
KeyK Key = 0x4B
KeyL Key = 0x4C
KeyM Key = 0x4D
KeyN Key = 0x4E
KeyO Key = 0x4F
KeyP Key = 0x50
KeyQ Key = 0x51
KeyR Key = 0x52
KeyS Key = 0x53
KeyT Key = 0x54
KeyU Key = 0x55
KeyV Key = 0x56
KeyW Key = 0x57
KeyX Key = 0x58
KeyY Key = 0x59
KeyZ Key = 0x5A
KeyReturn Key = 0x0D
KeyEscape Key = 0x1B
KeyDelete Key = 0x2E
KeyTab Key = 0x09
KeyLeft Key = 0x25
KeyRight Key = 0x27
KeyUp Key = 0x26
KeyDown Key = 0x28
KeyF1 Key = 0x70
KeyF2 Key = 0x71
KeyF3 Key = 0x72
KeyF4 Key = 0x73
KeyF5 Key = 0x74
KeyF6 Key = 0x75
KeyF7 Key = 0x76
KeyF8 Key = 0x77
KeyF9 Key = 0x78
KeyF10 Key = 0x79
KeyF11 Key = 0x7A
KeyF12 Key = 0x7B
KeyF13 Key = 0x7C
KeyF14 Key = 0x7D
KeyF15 Key = 0x7E
KeyF16 Key = 0x7F
KeyF17 Key = 0x80
KeyF18 Key = 0x81
KeyF19 Key = 0x82
KeyF20 Key = 0x83
)

View File

@@ -0,0 +1,41 @@
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
//go:build windows
package hotkey_test
import (
"context"
"fmt"
"testing"
"time"
"voidraft/internal/common/hotkey"
)
// TestHotkey should always run success.
// This is a test to run and for manually testing, registered combination:
// Ctrl+Shift+S
func TestHotkey(t *testing.T) {
tt := time.Second * 5
ctx, cancel := context.WithTimeout(context.Background(), tt)
defer cancel()
hk := hotkey.New([]hotkey.Modifier{hotkey.ModCtrl, hotkey.ModShift}, hotkey.KeyS)
if err := hk.Register(); err != nil {
t.Errorf("failed to register hotkey: %v", err)
return
}
for {
select {
case <-ctx.Done():
return
case <-hk.Keydown():
fmt.Println("triggered")
}
}
}

View File

@@ -0,0 +1,122 @@
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
//go:build windows
// +build windows
package win
import (
"syscall"
"unsafe"
)
var (
user32 = syscall.NewLazyDLL("user32")
registerHotkey = user32.NewProc("RegisterHotKey")
unregisterHotkey = user32.NewProc("UnregisterHotKey")
getMessage = user32.NewProc("GetMessageW")
peekMessage = user32.NewProc("PeekMessageA")
sendMessage = user32.NewProc("SendMessageW")
getAsyncKeyState = user32.NewProc("GetAsyncKeyState")
quitMessage = user32.NewProc("PostQuitMessage")
)
// RegisterHotKey defines a system-wide hot key.
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-registerhotkey
func RegisterHotKey(hwnd, id uintptr, mod uintptr, k uintptr) (bool, error) {
ret, _, err := registerHotkey.Call(
hwnd, id, mod, k,
)
return ret != 0, err
}
// UnregisterHotKey frees a hot key previously registered by the calling
// thread.
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-unregisterhotkey
func UnregisterHotKey(hwnd, id uintptr) (bool, error) {
ret, _, err := unregisterHotkey.Call(hwnd, id)
return ret != 0, err
}
// MSG contains message information from a thread's message queue.
//
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-msg
type MSG struct {
HWnd uintptr
Message uint32
WParam uintptr
LParam uintptr
Time uint32
Pt struct { //POINT
x, y int32
}
}
// SendMessage sends the specified message to a window or windows.
// The SendMessage function calls the window procedure for the specified
// window and does not return until the window procedure has processed
// the message.
// The return value specifies the result of the message processing;
// it depends on the message sent.
//
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendmessage
func SendMessage(hwnd uintptr, msg uint32, wParam, lParam uintptr) uintptr {
ret, _, _ := sendMessage.Call(
hwnd,
uintptr(msg),
wParam,
lParam,
)
return ret
}
// GetMessage retrieves a message from the calling thread's message
// queue. The function dispatches incoming sent messages until a posted
// message is available for retrieval.
//
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getmessage
func GetMessage(msg *MSG, hWnd uintptr, msgFilterMin, msgFilterMax uint32) bool {
ret, _, _ := getMessage.Call(
uintptr(unsafe.Pointer(msg)),
hWnd,
uintptr(msgFilterMin),
uintptr(msgFilterMax),
)
return ret != 0
}
// PeekMessage dispatches incoming sent messages, checks the thread message
// queue for a posted message, and retrieves the message (if any exist).
//
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-peekmessagea
func PeekMessage(msg *MSG, hWnd uintptr, msgFilterMin, msgFilterMax uint32) bool {
ret, _, _ := peekMessage.Call(
uintptr(unsafe.Pointer(msg)),
hWnd,
uintptr(msgFilterMin),
uintptr(msgFilterMax),
0, // PM_NOREMOVE
)
return ret != 0
}
// PostQuitMessage indicates to the system that a thread has made
// a request to terminate (quit). It is typically used in response
// to a WM_DESTROY message.
//
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-postquitmessage
func PostQuitMessage(exitCode int) {
quitMessage.Call(uintptr(exitCode))
}
func GetAsyncKeyState(keycode int) uintptr {
ret, _, _ := getAsyncKeyState.Call(uintptr(keycode))
return ret
}

View File

@@ -0,0 +1,11 @@
// Copyright 2022 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
// Package mainthread provides facilities to schedule functions
// on the main thread. It includes platform-specific implementations
// for Windows, Linux, and macOS. The macOS implementation is specially
// designed to handle main thread events for the NSApplication.
package mainthread

View File

@@ -0,0 +1,87 @@
// Copyright 2022 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
//go:build windows || linux
package mainthread
import (
"fmt"
"runtime"
"sync"
)
func init() {
runtime.LockOSThread()
}
// Call calls f on the main thread and blocks until f finishes.
func Call(f func()) {
done := donePool.Get().(chan error)
defer donePool.Put(done)
data := funcData{fn: f, done: done}
funcQ <- data
if err := <-done; err != nil {
panic(err)
}
}
// Init initializes the functionality of running arbitrary subsequent functions be called on the main system thread.
//
// Init must be called in the main.main function.
func Init(main func()) {
done := donePool.Get().(chan error)
defer donePool.Put(done)
go func() {
defer func() {
done <- nil
}()
main()
}()
for {
select {
case f := <-funcQ:
func() {
defer func() {
r := recover()
if f.done != nil {
if r != nil {
f.done <- fmt.Errorf("%v", r)
} else {
f.done <- nil
}
} else {
if r != nil {
select {
case erroQ <- fmt.Errorf("%v", r):
default:
}
}
}
}()
f.fn()
}()
case <-done:
return
}
}
}
var (
funcQ = make(chan funcData, runtime.GOMAXPROCS(0))
erroQ = make(chan error, 42)
donePool = sync.Pool{New: func() interface{} {
return make(chan error)
}}
)
type funcData struct {
fn func()
done chan error
}

View File

@@ -0,0 +1,69 @@
// Copyright 2022 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
//go:build darwin
package mainthread
/*
#cgo CFLAGS: -x objective-c
#cgo LDFLAGS: -framework Cocoa
#import <Cocoa/Cocoa.h>
#import <Dispatch/Dispatch.h>
extern void os_main(void);
extern void wakeupMainThread(void);
static bool isMainThread() {
return [NSThread isMainThread];
}
*/
import "C"
import (
"os"
"runtime"
)
func init() {
runtime.LockOSThread()
}
// Call calls f on the main thread and blocks until f finishes.
func Call(f func()) {
if C.isMainThread() {
f()
return
}
go func() {
mainFuncs <- f
C.wakeupMainThread()
}()
}
// Init initializes the functionality of running arbitrary subsequent functions be called on the main system thread.
//
// Init must be called in the main.main function.
func Init(f func()) {
go func() {
f()
os.Exit(0)
}()
C.os_main()
}
var mainFuncs = make(chan func(), 1)
//export dispatchMainFuncs
func dispatchMainFuncs() {
for {
select {
case f := <-mainFuncs:
f()
default:
return
}
}
}

View File

@@ -0,0 +1,28 @@
// Copyright 2022 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
//go:build darwin
#include <stdint.h>
#import <Cocoa/Cocoa.h>
extern void dispatchMainFuncs();
void wakeupMainThread(void) {
dispatch_async(dispatch_get_main_queue(), ^{
dispatchMainFuncs();
});
}
// The following three lines of code must run on the main thread.
// It must handle it using golang.design/x/mainthread.
//
// inspired from here: https://github.com/cehoffman/dotfiles/blob/4be8e893517e970d40746a9bdc67fe5832dd1c33/os/mac/iTerm2HotKey.m
void os_main(void) {
[NSApplication sharedApplication];
[NSApp disableRelaunchOnLogin];
[NSApp run];
}

View File

@@ -1,58 +0,0 @@
#include "hotkey_windows.h"
#include <windows.h>
// 上次检测到热键按下的时间
static DWORD lastHotkeyTime = 0;
// 防抖间隔(毫秒)
static const DWORD DEBOUNCE_INTERVAL = 300;
// 检查指定虚拟键码是否被按下
// vkCode: Windows 虚拟键码
// 返回值: 1-按下状态, 0-未按下状态
int isKeyPressed(int vkCode) {
SHORT keyState = GetAsyncKeyState(vkCode);
// 检查最高位是否为1表示按下状态
return (keyState & 0x8000) ? 1 : 0;
}
// 检查热键组合是否被按下
// ctrl, shift, alt, win: 修饰键状态 (1-需要按下, 0-不需要按下)
// mainKey: 主键的虚拟键码
// 返回值: 1-热键组合被按下, 0-未按下
int isHotkeyPressed(int ctrl, int shift, int alt, int win, int mainKey) {
// 获取当前时间
DWORD currentTime = GetTickCount();
// 防抖检查如果距离上次触发时间太短直接返回0
if (currentTime - lastHotkeyTime < DEBOUNCE_INTERVAL) {
return 0;
}
// 检查修饰键状态
int ctrlPressed = isKeyPressed(VK_CONTROL) || isKeyPressed(VK_LCONTROL) || isKeyPressed(VK_RCONTROL);
int shiftPressed = isKeyPressed(VK_SHIFT) || isKeyPressed(VK_LSHIFT) || isKeyPressed(VK_RSHIFT);
int altPressed = isKeyPressed(VK_MENU) || isKeyPressed(VK_LMENU) || isKeyPressed(VK_RMENU);
int winPressed = isKeyPressed(VK_LWIN) || isKeyPressed(VK_RWIN);
// 检查主键状态
int mainKeyPressed = isKeyPressed(mainKey);
// 所有条件都必须匹配
if (ctrl && !ctrlPressed) return 0;
if (!ctrl && ctrlPressed) return 0;
if (shift && !shiftPressed) return 0;
if (!shift && shiftPressed) return 0;
if (alt && !altPressed) return 0;
if (!alt && altPressed) return 0;
if (win && !winPressed) return 0;
if (!win && winPressed) return 0;
if (!mainKeyPressed) return 0;
// 所有条件匹配,更新最后触发时间
lastHotkeyTime = currentTime;
return 1;
}

View File

@@ -1,25 +0,0 @@
#ifndef HOTKEY_WINDOWS_H
#define HOTKEY_WINDOWS_H
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
// 检查指定虚拟键码是否被按下
// vkCode: Windows 虚拟键码
// 返回值: 1-按下状态, 0-未按下状态
int isKeyPressed(int vkCode);
// 检查热键组合是否被按下
// ctrl, shift, alt, win: 修饰键状态 (1-需要按下, 0-不需要按下)
// mainKey: 主键的虚拟键码
// 返回值: 1-热键组合被按下, 0-未按下
int isHotkeyPressed(int ctrl, int shift, int alt, int win, int mainKey);
#ifdef __cplusplus
}
#endif
#endif // HOTKEY_WINDOWS_H

View File

@@ -1,112 +1,65 @@
//go:build windows
package services
/*
#cgo CFLAGS: -I../lib
#cgo LDFLAGS: -luser32
#include "../lib/hotkey_windows.c"
#include "../lib/hotkey_windows.h"
*/
import "C"
import (
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
"voidraft/internal/common/hotkey"
"voidraft/internal/common/hotkey/mainthread"
"voidraft/internal/models"
"github.com/wailsapp/wails/v3/pkg/application"
"github.com/wailsapp/wails/v3/pkg/services/log"
)
// HotkeyService Windows全局热键服务
// HotkeyService 全局热键服务
type HotkeyService struct {
logger *log.LogService
configService *ConfigService
windowService *WindowService
windowHelper *WindowHelper
mu sync.RWMutex
currentHotkey *models.HotkeyCombo
isRegistered atomic.Bool
app *application.App
registered atomic.Bool
ctx context.Context
cancelFunc atomic.Value // 使用atomic.Value存储cancel函数避免竞态条件
wg sync.WaitGroup
}
// HotkeyError 热键错误
type HotkeyError struct {
Operation string
Err error
}
func (e *HotkeyError) Error() string {
return fmt.Sprintf("hotkey %s: %v", e.Operation, e.Err)
}
func (e *HotkeyError) Unwrap() error {
return e.Err
}
// setCancelFunc 原子地设置cancel函数
func (hs *HotkeyService) setCancelFunc(cancel context.CancelFunc) {
hs.cancelFunc.Store(cancel)
}
// getCancelFunc 原子地获取cancel函数
func (hs *HotkeyService) getCancelFunc() context.CancelFunc {
if cancel := hs.cancelFunc.Load(); cancel != nil {
if cancelFunc, ok := cancel.(context.CancelFunc); ok {
return cancelFunc
}
}
return nil
}
// clearCancelFunc 原子地清除cancel函数
func (hs *HotkeyService) clearCancelFunc() {
hs.cancelFunc.Store((context.CancelFunc)(nil))
hk *hotkey.Hotkey
stopChan chan struct{}
wg sync.WaitGroup
}
// NewHotkeyService 创建热键服务实例
func NewHotkeyService(configService *ConfigService, windowService *WindowService, logger *log.LogService) *HotkeyService {
func NewHotkeyService(configService *ConfigService, logger *log.LogService) *HotkeyService {
if logger == nil {
logger = log.New()
}
ctx, cancel := context.WithCancel(context.Background())
service := &HotkeyService{
return &HotkeyService{
logger: logger,
configService: configService,
windowService: windowService,
windowHelper: NewWindowHelper(),
ctx: ctx,
stopChan: make(chan struct{}),
}
// 初始化时设置cancel函数
service.setCancelFunc(cancel)
return service
}
// ServiceStartup initializes the service when the application starts
func (ds *HotkeyService) ServiceStartup(ctx context.Context, options application.ServiceOptions) error {
ds.ctx = ctx
return ds.Initialize()
// ServiceStartup 服务启动时初始化
func (hs *HotkeyService) ServiceStartup(ctx context.Context, options application.ServiceOptions) error {
hs.app = application.Get()
return hs.Initialize()
}
// Initialize 初始化热键服务
func (hs *HotkeyService) Initialize() error {
config, err := hs.configService.GetConfig()
if err != nil {
return &HotkeyError{"load_config", err}
return fmt.Errorf("load config: %w", err)
}
if config.General.EnableGlobalHotkey {
if err := hs.RegisterHotkey(&config.General.GlobalHotkey); err != nil {
hs.logger.Error("failed to register startup hotkey", "error", err)
return err
}
}
@@ -114,41 +67,42 @@ func (hs *HotkeyService) Initialize() error {
}
// RegisterHotkey 注册全局热键
func (hs *HotkeyService) RegisterHotkey(hotkey *models.HotkeyCombo) error {
if !hs.isValidHotkey(hotkey) {
return &HotkeyError{"validate", fmt.Errorf("invalid hotkey combination")}
func (hs *HotkeyService) RegisterHotkey(combo *models.HotkeyCombo) error {
if !hs.isValidHotkey(combo) {
return errors.New("invalid hotkey combination")
}
hs.mu.Lock()
defer hs.mu.Unlock()
// 取消现有热键
if hs.isRegistered.Load() {
// 如果已注册,先取消
if hs.registered.Load() {
hs.unregisterInternal()
}
// 启动监听器
ctx, cancel := context.WithCancel(hs.ctx)
hs.wg.Add(1)
ready := make(chan error, 1)
go hs.hotkeyListener(ctx, hotkey, ready)
// 等待启动完成
select {
case err := <-ready:
if err != nil {
cancel()
return &HotkeyError{"register", err}
}
case <-time.After(time.Second):
cancel()
return &HotkeyError{"register", fmt.Errorf("timeout")}
// 转换为 hotkey 库的格式
key, mods, err := hs.convertHotkey(combo)
if err != nil {
return fmt.Errorf("convert hotkey: %w", err)
}
hs.currentHotkey = hotkey
hs.isRegistered.Store(true)
hs.setCancelFunc(cancel)
// 在主线程中创建热键
var regErr error
mainthread.Init(func() {
hs.hk = hotkey.New(mods, key)
regErr = hs.hk.Register()
})
if regErr != nil {
return fmt.Errorf("register hotkey: %w", regErr)
}
hs.registered.Store(true)
hs.currentHotkey = combo
// 启动监听 goroutine
hs.wg.Add(1)
go hs.listenHotkey()
return nil
}
@@ -160,151 +114,177 @@ func (hs *HotkeyService) UnregisterHotkey() error {
return hs.unregisterInternal()
}
// unregisterInternal 内部取消注册(无锁)
// unregisterInternal 内部取消注册
func (hs *HotkeyService) unregisterInternal() error {
if !hs.isRegistered.Load() {
if !hs.registered.Load() {
return nil
}
// 原子地获取并调用cancel函数
if cancel := hs.getCancelFunc(); cancel != nil {
cancel()
hs.wg.Wait()
// 停止监听
close(hs.stopChan)
// 取消注册热键
if hs.hk != nil {
if err := hs.hk.Unregister(); err != nil {
hs.logger.Error("failed to unregister hotkey", "error", err)
}
hs.hk = nil
}
// 等待 goroutine 结束
hs.wg.Wait()
hs.currentHotkey = nil
hs.isRegistered.Store(false)
hs.clearCancelFunc()
hs.registered.Store(false)
// 重新创建 stopChan
hs.stopChan = make(chan struct{})
return nil
}
// UpdateHotkey 更新热键配置
func (hs *HotkeyService) UpdateHotkey(enable bool, hotkey *models.HotkeyCombo) error {
func (hs *HotkeyService) UpdateHotkey(enable bool, combo *models.HotkeyCombo) error {
if enable {
return hs.RegisterHotkey(hotkey)
return hs.RegisterHotkey(combo)
}
return hs.UnregisterHotkey()
}
// hotkeyListener 热键监听器
func (hs *HotkeyService) hotkeyListener(ctx context.Context, hotkey *models.HotkeyCombo, ready chan<- error) {
// listenHotkey 监听热键事件
func (hs *HotkeyService) listenHotkey() {
defer hs.wg.Done()
mainKeyVK := hs.keyToVirtualKeyCode(hotkey.Key)
if mainKeyVK == 0 {
ready <- fmt.Errorf("invalid key: %s", hotkey.Key)
return
}
ticker := time.NewTicker(50 * time.Millisecond)
defer ticker.Stop()
var wasPressed bool
ready <- nil // 标记准备就绪
for {
select {
case <-ctx.Done():
case <-hs.stopChan:
return
case <-ticker.C:
ctrl := cBool(hotkey.Ctrl)
shift := cBool(hotkey.Shift)
alt := cBool(hotkey.Alt)
win := cBool(hotkey.Win)
isPressed := C.isHotkeyPressed(ctrl, shift, alt, win, C.int(mainKeyVK)) == 1
if isPressed && !wasPressed {
hs.toggleWindow()
}
wasPressed = isPressed
case <-hs.hk.Keydown():
hs.toggleWindow()
}
}
}
// cBool 转换Go bool为C int
func cBool(b bool) C.int {
if b {
return 1
// convertHotkey 转换热键格式
func (hs *HotkeyService) convertHotkey(combo *models.HotkeyCombo) (hotkey.Key, []hotkey.Modifier, error) {
// 转换主键
key, err := hs.convertKey(combo.Key)
if err != nil {
return 0, nil, err
}
return 0
// 转换修饰键
var mods []hotkey.Modifier
if combo.Ctrl {
mods = append(mods, hotkey.ModCtrl)
}
if combo.Shift {
mods = append(mods, hotkey.ModShift)
}
if combo.Alt {
mods = append(mods, hotkey.ModAlt)
}
if combo.Win {
mods = append(mods, hotkey.ModWin) // Win/Cmd 键
}
return key, mods, nil
}
// convertKey 转换键码
func (hs *HotkeyService) convertKey(keyStr string) (hotkey.Key, error) {
// 字母键
keyMap := map[string]hotkey.Key{
"A": hotkey.KeyA, "B": hotkey.KeyB, "C": hotkey.KeyC, "D": hotkey.KeyD,
"E": hotkey.KeyE, "F": hotkey.KeyF, "G": hotkey.KeyG, "H": hotkey.KeyH,
"I": hotkey.KeyI, "J": hotkey.KeyJ, "K": hotkey.KeyK, "L": hotkey.KeyL,
"M": hotkey.KeyM, "N": hotkey.KeyN, "O": hotkey.KeyO, "P": hotkey.KeyP,
"Q": hotkey.KeyQ, "R": hotkey.KeyR, "S": hotkey.KeyS, "T": hotkey.KeyT,
"U": hotkey.KeyU, "V": hotkey.KeyV, "W": hotkey.KeyW, "X": hotkey.KeyX,
"Y": hotkey.KeyY, "Z": hotkey.KeyZ,
// 数字键
"0": hotkey.Key0, "1": hotkey.Key1, "2": hotkey.Key2, "3": hotkey.Key3,
"4": hotkey.Key4, "5": hotkey.Key5, "6": hotkey.Key6, "7": hotkey.Key7,
"8": hotkey.Key8, "9": hotkey.Key9,
// 功能键
"F1": hotkey.KeyF1, "F2": hotkey.KeyF2, "F3": hotkey.KeyF3, "F4": hotkey.KeyF4,
"F5": hotkey.KeyF5, "F6": hotkey.KeyF6, "F7": hotkey.KeyF7, "F8": hotkey.KeyF8,
"F9": hotkey.KeyF9, "F10": hotkey.KeyF10, "F11": hotkey.KeyF11, "F12": hotkey.KeyF12,
// 特殊键
"Space": hotkey.KeySpace,
"Tab": hotkey.KeyTab,
"Enter": hotkey.KeyReturn,
"Escape": hotkey.KeyEscape,
"Delete": hotkey.KeyDelete,
"ArrowUp": hotkey.KeyUp,
"ArrowDown": hotkey.KeyDown,
"ArrowLeft": hotkey.KeyLeft,
"ArrowRight": hotkey.KeyRight,
}
if key, ok := keyMap[keyStr]; ok {
return key, nil
}
return 0, fmt.Errorf("unsupported key: %s", keyStr)
}
// toggleWindow 切换窗口显示状态
func (hs *HotkeyService) toggleWindow() {
mainWindow := hs.windowHelper.MustGetMainWindow()
if mainWindow == nil {
hs.logger.Error("main window not found")
return
}
// 检查主窗口是否可见
if mainWindow.IsVisible() {
// 如果主窗口可见,隐藏所有窗口
// 隐藏所有窗口
hs.hideAllWindows()
} else {
// 如果主窗口不可见,显示所有窗口
// 显示所有窗口
hs.showAllWindows()
}
}
// isWindowVisible 检查窗口是否可见
func (hs *HotkeyService) isWindowVisible(window *application.WebviewWindow) bool {
return window.IsVisible()
}
// hideAllWindows 隐藏所有窗口
func (hs *HotkeyService) hideAllWindows() {
// 隐藏所有子窗口
if hs.windowService != nil {
openWindows := hs.windowService.GetOpenWindows()
for _, windowInfo := range openWindows {
windowInfo.Hide()
}
if hs.app == nil {
return
}
openWindows := hs.app.Window.GetAll()
for _, window := range openWindows {
window.Hide()
}
}
// showAllWindows 显示所有窗口
func (hs *HotkeyService) showAllWindows() {
// 显示所有子窗口
if hs.windowService != nil {
openWindows := hs.windowService.GetOpenWindows()
for _, windowInfo := range openWindows {
windowInfo.Show()
windowInfo.Restore()
}
if hs.app == nil {
return
}
}
// keyToVirtualKeyCode 键名转虚拟键码
func (hs *HotkeyService) keyToVirtualKeyCode(key string) int {
keyMap := map[string]int{
// 字母键
"A": 0x41, "B": 0x42, "C": 0x43, "D": 0x44, "E": 0x45, "F": 0x46, "G": 0x47, "H": 0x48,
"I": 0x49, "J": 0x4A, "K": 0x4B, "L": 0x4C, "M": 0x4D, "N": 0x4E, "O": 0x4F, "P": 0x50,
"Q": 0x51, "R": 0x52, "S": 0x53, "T": 0x54, "U": 0x55, "V": 0x56, "W": 0x57, "X": 0x58,
"Y": 0x59, "Z": 0x5A,
// 数字键
"0": 0x30, "1": 0x31, "2": 0x32, "3": 0x33, "4": 0x34,
"5": 0x35, "6": 0x36, "7": 0x37, "8": 0x38, "9": 0x39,
// 功能键
"F1": 0x70, "F2": 0x71, "F3": 0x72, "F4": 0x73, "F5": 0x74, "F6": 0x75,
"F7": 0x76, "F8": 0x77, "F9": 0x78, "F10": 0x79, "F11": 0x7A, "F12": 0x7B,
openWindows := hs.app.Window.GetAll()
for _, window := range openWindows {
window.Show()
window.Restore()
window.Focus()
}
return keyMap[key]
}
// isValidHotkey 验证热键组合
func (hs *HotkeyService) isValidHotkey(hotkey *models.HotkeyCombo) bool {
if hotkey == nil || hotkey.Key == "" {
func (hs *HotkeyService) isValidHotkey(combo *models.HotkeyCombo) bool {
if combo == nil || combo.Key == "" {
return false
}
// 至少需要一个修饰键
if !hotkey.Ctrl && !hotkey.Shift && !hotkey.Alt && !hotkey.Win {
if !combo.Ctrl && !combo.Shift && !combo.Alt && !combo.Win {
return false
}
return hs.keyToVirtualKeyCode(hotkey.Key) != 0
return true
}
// GetCurrentHotkey 获取当前热键
@@ -327,15 +307,10 @@ func (hs *HotkeyService) GetCurrentHotkey() *models.HotkeyCombo {
// IsRegistered 检查是否已注册
func (hs *HotkeyService) IsRegistered() bool {
return hs.isRegistered.Load()
return hs.registered.Load()
}
// ServiceShutdown 关闭服务
func (hs *HotkeyService) ServiceShutdown() error {
// 原子地获取并调用cancel函数
if cancel := hs.getCancelFunc(); cancel != nil {
cancel()
}
hs.wg.Wait()
return nil
return hs.UnregisterHotkey()
}

View File

@@ -1,373 +0,0 @@
//go:build darwin
package services
/*
#cgo CFLAGS: -x objective-c
#cgo LDFLAGS: -framework Cocoa -framework Carbon
#include <ApplicationServices/ApplicationServices.h>
#include <Carbon/Carbon.h>
// 全局变量用于存储热键ID和回调
static EventHotKeyRef g_hotKeyRef = NULL;
static int g_hotkeyRegistered = 0;
// 热键事件处理函数
OSStatus hotKeyHandler(EventHandlerCallRef nextHandler, EventRef theEvent, void *userData) {
// 通知Go代码热键被触发
extern void hotkeyTriggered();
hotkeyTriggered();
return noErr;
}
// 注册全局热键
int registerGlobalHotkey(int keyCode, int modifiers) {
if (g_hotkeyRegistered) {
// 先取消注册现有热键
UnregisterEventHotKey(g_hotKeyRef);
g_hotkeyRegistered = 0;
}
EventHotKeyID hotKeyID;
hotKeyID.signature = 'htk1';
hotKeyID.id = 1;
EventTypeSpec eventType;
eventType.eventClass = kEventClassKeyboard;
eventType.eventKind = kEventHotKeyPressed;
InstallApplicationEventHandler(&hotKeyHandler, 1, &eventType, NULL, NULL);
OSStatus status = RegisterEventHotKey(keyCode, modifiers, hotKeyID, GetApplicationEventTarget(), 0, &g_hotKeyRef);
if (status == noErr) {
g_hotkeyRegistered = 1;
return 1;
}
return 0;
}
// 取消注册全局热键
int unregisterGlobalHotkey() {
if (g_hotkeyRegistered && g_hotKeyRef != NULL) {
OSStatus status = UnregisterEventHotKey(g_hotKeyRef);
g_hotkeyRegistered = 0;
g_hotKeyRef = NULL;
return (status == noErr) ? 1 : 0;
}
return 1;
}
// 检查是否已注册热键
int isHotkeyRegistered() {
return g_hotkeyRegistered;
}
*/
import "C"
import (
"context"
"fmt"
"sync"
"sync/atomic"
"voidraft/internal/models"
"github.com/wailsapp/wails/v3/pkg/application"
"github.com/wailsapp/wails/v3/pkg/services/log"
)
// 全局服务实例用于C回调
var globalHotkeyService *HotkeyService
// HotkeyService macOS全局热键服务
type HotkeyService struct {
logger *log.LogService
configService *ConfigService
windowService *WindowService
windowHelper *WindowHelper
mu sync.RWMutex
isRegistered atomic.Bool
currentHotkey *models.HotkeyCombo
cancelFunc atomic.Value // 使用atomic.Value存储cancel函数避免竞态条件
ctx context.Context
}
// HotkeyError 热键错误
type HotkeyError struct {
Operation string
Err error
}
// Error 实现error接口
func (e *HotkeyError) Error() string {
return fmt.Sprintf("hotkey %s: %v", e.Operation, e.Err)
}
// Unwrap 获取原始错误
func (e *HotkeyError) Unwrap() error {
return e.Err
}
// setCancelFunc 原子地设置cancel函数
func (hs *HotkeyService) setCancelFunc(cancel context.CancelFunc) {
hs.cancelFunc.Store(cancel)
}
// getCancelFunc 原子地获取cancel函数
func (hs *HotkeyService) getCancelFunc() context.CancelFunc {
if cancel := hs.cancelFunc.Load(); cancel != nil {
if cancelFunc, ok := cancel.(context.CancelFunc); ok {
return cancelFunc
}
}
return nil
}
// clearCancelFunc 原子地清除cancel函数
func (hs *HotkeyService) clearCancelFunc() {
hs.cancelFunc.Store((context.CancelFunc)(nil))
}
// NewHotkeyService 创建新的热键服务实例
func NewHotkeyService(configService *ConfigService, windowService *WindowService, logger *log.LogService) *HotkeyService {
if logger == nil {
logger = log.New()
}
service := &HotkeyService{
logger: logger,
configService: configService,
windowService: windowService,
windowHelper: NewWindowHelper(),
}
// 设置全局实例
globalHotkeyService = service
return service
}
// ServiceStartup initializes the service when the application starts
func (ds *HotkeyService) ServiceStartup(ctx context.Context, options application.ServiceOptions) error {
ds.ctx = ctx
return ds.Initialize()
}
// Initialize 初始化热键服务
func (hs *HotkeyService) Initialize() error {
config, err := hs.configService.GetConfig()
if err != nil {
return &HotkeyError{"load_config", err}
}
if config.General.EnableGlobalHotkey {
if err := hs.RegisterHotkey(&config.General.GlobalHotkey); err != nil {
hs.logger.Error("failed to register startup hotkey", "error", err)
}
}
return nil
}
// RegisterHotkey 注册全局热键
func (hs *HotkeyService) RegisterHotkey(hotkey *models.HotkeyCombo) error {
if !hs.isValidHotkey(hotkey) {
return &HotkeyError{"validate", fmt.Errorf("invalid hotkey combination")}
}
hs.mu.Lock()
defer hs.mu.Unlock()
// 转换键码和修饰符
keyCode := hs.keyToMacKeyCode(hotkey.Key)
if keyCode == 0 {
return &HotkeyError{"convert_key", fmt.Errorf("unsupported key: %s", hotkey.Key)}
}
modifiers := hs.buildMacModifiers(hotkey)
// 调用C函数注册热键
result := int(C.registerGlobalHotkey(C.int(keyCode), C.int(modifiers)))
if result == 0 {
return &HotkeyError{"register", fmt.Errorf("failed to register hotkey")}
}
hs.currentHotkey = hotkey
hs.isRegistered.Store(true)
return nil
}
// UnregisterHotkey 取消注册全局热键
func (hs *HotkeyService) UnregisterHotkey() error {
hs.mu.Lock()
defer hs.mu.Unlock()
if !hs.isRegistered.Load() {
return nil
}
// 调用C函数取消注册热键
result := int(C.unregisterGlobalHotkey())
if result == 0 {
return &HotkeyError{"unregister", fmt.Errorf("failed to unregister hotkey")}
}
hs.currentHotkey = nil
hs.isRegistered.Store(false)
return nil
}
// UpdateHotkey 更新热键配置
func (hs *HotkeyService) UpdateHotkey(enable bool, hotkey *models.HotkeyCombo) error {
if enable {
return hs.RegisterHotkey(hotkey)
}
return hs.UnregisterHotkey()
}
// keyToMacKeyCode 将键名转换为macOS虚拟键码
func (hs *HotkeyService) keyToMacKeyCode(key string) int {
keyMap := map[string]int{
// 字母键
"A": 0, "S": 1, "D": 2, "F": 3, "H": 4, "G": 5, "Z": 6, "X": 7,
"C": 8, "V": 9, "B": 11, "Q": 12, "W": 13, "E": 14, "R": 15,
"Y": 16, "T": 17, "1": 18, "2": 19, "3": 20, "4": 21, "6": 22,
"5": 23, "9": 25, "7": 26, "8": 28, "0": 29, "O": 31, "U": 32,
"I": 34, "P": 35, "L": 37, "J": 38, "K": 40, "N": 45, "M": 46,
// 功能键
"F1": 122, "F2": 120, "F3": 99, "F4": 118, "F5": 96, "F6": 97,
"F7": 98, "F8": 100, "F9": 101, "F10": 109, "F11": 103, "F12": 111,
}
if keyCode, exists := keyMap[key]; exists {
return keyCode
}
return 0
}
// buildMacModifiers 构建macOS修饰符
func (hs *HotkeyService) buildMacModifiers(hotkey *models.HotkeyCombo) int {
var modifiers int = 0
if hotkey.Ctrl {
modifiers |= 0x1000 // controlKey
}
if hotkey.Shift {
modifiers |= 0x200 // shiftKey
}
if hotkey.Alt {
modifiers |= 0x800 // optionKey
}
if hotkey.Win {
modifiers |= 0x100 // cmdKey
}
return modifiers
}
// isValidHotkey 验证热键组合是否有效
func (hs *HotkeyService) isValidHotkey(hotkey *models.HotkeyCombo) bool {
if hotkey == nil {
return false
}
// 必须有主键
if hotkey.Key == "" {
return false
}
// 必须至少有一个修饰键
if !hotkey.Ctrl && !hotkey.Shift && !hotkey.Alt && !hotkey.Win {
return false
}
// 验证主键是否在有效范围内
return hs.keyToMacKeyCode(hotkey.Key) != 0
}
// GetCurrentHotkey 获取当前注册的热键
func (hs *HotkeyService) GetCurrentHotkey() *models.HotkeyCombo {
hs.mu.RLock()
defer hs.mu.RUnlock()
if hs.currentHotkey == nil {
return nil
}
// 返回副本避免并发问题
return &models.HotkeyCombo{
Ctrl: hs.currentHotkey.Ctrl,
Shift: hs.currentHotkey.Shift,
Alt: hs.currentHotkey.Alt,
Win: hs.currentHotkey.Win,
Key: hs.currentHotkey.Key,
}
}
// IsRegistered 检查是否已注册热键
func (hs *HotkeyService) IsRegistered() bool {
return hs.isRegistered.Load()
}
// ToggleWindow 切换窗口显示状态
func (hs *HotkeyService) ToggleWindow() {
mainWindow := hs.windowHelper.MustGetMainWindow()
if mainWindow == nil {
hs.logger.Error("main window not found")
return
}
// 检查主窗口是否可见
if mainWindow.IsVisible() {
// 如果主窗口可见,隐藏所有窗口
hs.hideAllWindows()
} else {
// 如果主窗口不可见,显示所有窗口
hs.showAllWindows()
}
}
// isWindowVisible 检查窗口是否可见
func (hs *HotkeyService) isWindowVisible(window *application.WebviewWindow) bool {
return window.IsVisible()
}
// hideAllWindows 隐藏所有窗口
func (hs *HotkeyService) hideAllWindows() {
// 隐藏所有子窗口
if hs.windowService != nil {
openWindows := hs.windowService.GetOpenWindows()
for _, windowInfo := range openWindows {
windowInfo.Hide()
}
}
}
// showAllWindows 显示所有窗口
func (hs *HotkeyService) showAllWindows() {
// 显示所有子窗口
if hs.windowService != nil {
openWindows := hs.windowService.GetOpenWindows()
for _, windowInfo := range openWindows {
windowInfo.Show()
windowInfo.Restore()
}
}
}
// ServiceShutdown 关闭热键服务
func (hs *HotkeyService) ServiceShutdown() error {
return hs.UnregisterHotkey()
}
//export hotkeyTriggered
func hotkeyTriggered() {
// 通过全局实例调用ToggleWindow
if globalHotkeyService != nil {
globalHotkeyService.ToggleWindow()
}
}

View File

@@ -1,468 +0,0 @@
//go:build linux
package services
/*
#cgo pkg-config: x11
#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <X11/extensions/XTest.h>
#include <stdlib.h>
#include <string.h>
static Display *display = NULL;
static Window root_window;
static int hotkey_registered = 0;
static int registered_keycode = 0;
static unsigned int registered_modifiers = 0;
// 初始化X11显示
int initX11Display() {
display = XOpenDisplay(NULL);
if (display == NULL) {
return 0;
}
root_window = DefaultRootWindow(display);
return 1;
}
// 关闭X11显示
void closeX11Display() {
if (display != NULL) {
XCloseDisplay(display);
display = NULL;
}
}
// 注册全局热键
int registerGlobalHotkey(int keycode, unsigned int modifiers) {
if (display == NULL && !initX11Display()) {
return 0;
}
// 如果已经注册了热键,先取消注册
if (hotkey_registered) {
XUngrabKey(display, registered_keycode, registered_modifiers, root_window);
hotkey_registered = 0;
}
// 注册新热键
XGrabKey(display, keycode, modifiers, root_window, False, GrabModeAsync, GrabModeAsync);
XGrabKey(display, keycode, modifiers | LockMask, root_window, False, GrabModeAsync, GrabModeAsync);
XGrabKey(display, keycode, modifiers | Mod2Mask, root_window, False, GrabModeAsync, GrabModeAsync);
XGrabKey(display, keycode, modifiers | LockMask | Mod2Mask, root_window, False, GrabModeAsync, GrabModeAsync);
XSync(display, False);
registered_keycode = keycode;
registered_modifiers = modifiers;
hotkey_registered = 1;
return 1;
}
// 取消注册全局热键
int unregisterGlobalHotkey() {
if (display == NULL || !hotkey_registered) {
return 1;
}
XUngrabKey(display, registered_keycode, registered_modifiers, root_window);
XUngrabKey(display, registered_keycode, registered_modifiers | LockMask, root_window);
XUngrabKey(display, registered_keycode, registered_modifiers | Mod2Mask, root_window);
XUngrabKey(display, registered_keycode, registered_modifiers | LockMask | Mod2Mask, root_window);
XSync(display, False);
hotkey_registered = 0;
registered_keycode = 0;
registered_modifiers = 0;
return 1;
}
// 检查热键事件
int checkHotkeyEvent() {
if (display == NULL || !hotkey_registered) {
return 0;
}
XEvent event;
while (XPending(display)) {
XNextEvent(display, &event);
if (event.type == KeyPress) {
XKeyEvent *key_event = (XKeyEvent*)&event;
if (key_event->keycode == registered_keycode) {
// 检查修饰符匹配忽略Caps Lock和Num Lock
unsigned int clean_modifiers = key_event->state & ~(LockMask | Mod2Mask);
if (clean_modifiers == registered_modifiers) {
return 1;
}
}
}
}
return 0;
}
// 将键名转换为X11键码
int getX11Keycode(const char* keyname) {
if (display == NULL) {
return 0;
}
KeySym keysym = XStringToKeysym(keyname);
if (keysym == NoSymbol) {
return 0;
}
return XKeysymToKeycode(display, keysym);
}
// 检查是否已注册热键
int isHotkeyRegistered() {
return hotkey_registered;
}
*/
import "C"
import (
"context"
"fmt"
"sync"
"sync/atomic"
"time"
"unsafe"
"voidraft/internal/models"
"github.com/wailsapp/wails/v3/pkg/application"
"github.com/wailsapp/wails/v3/pkg/services/log"
)
// HotkeyService Linux全局热键服务
type HotkeyService struct {
logger *log.LogService
configService *ConfigService
windowService *WindowService
windowHelper *WindowHelper
mu sync.RWMutex
currentHotkey *models.HotkeyCombo
isRegistered atomic.Bool
ctx context.Context
cancelFunc atomic.Value // 使用atomic.Value存储cancel函数避免竞态条件
wg sync.WaitGroup
}
// HotkeyError 热键错误
type HotkeyError struct {
Operation string
Err error
}
// Error 实现error接口
func (e *HotkeyError) Error() string {
return fmt.Sprintf("hotkey %s: %v", e.Operation, e.Err)
}
func (e *HotkeyError) Unwrap() error {
return e.Err
}
// setCancelFunc 原子地设置cancel函数
func (hs *HotkeyService) setCancelFunc(cancel context.CancelFunc) {
hs.cancelFunc.Store(cancel)
}
// getCancelFunc 原子地获取cancel函数
func (hs *HotkeyService) getCancelFunc() context.CancelFunc {
if cancel := hs.cancelFunc.Load(); cancel != nil {
if cancelFunc, ok := cancel.(context.CancelFunc); ok {
return cancelFunc
}
}
return nil
}
// clearCancelFunc 原子地清除cancel函数
func (hs *HotkeyService) clearCancelFunc() {
hs.cancelFunc.Store((context.CancelFunc)(nil))
}
// NewHotkeyService 创建热键服务实例
func NewHotkeyService(configService *ConfigService, windowService *WindowService, logger *log.LogService) *HotkeyService {
if logger == nil {
logger = log.New()
}
ctx, cancel := context.WithCancel(context.Background())
service := &HotkeyService{
logger: logger,
configService: configService,
windowService: windowService,
windowHelper: NewWindowHelper(),
ctx: ctx,
}
// 初始化时设置cancel函数
service.setCancelFunc(cancel)
return service
}
// ServiceStartup initializes the service when the application starts
func (ds *HotkeyService) ServiceStartup(ctx context.Context, options application.ServiceOptions) error {
ds.ctx = ctx
return ds.Initialize()
}
// Initialize 初始化热键服务
func (hs *HotkeyService) Initialize() error {
if int(C.initX11Display()) == 0 {
return &HotkeyError{"init_x11", fmt.Errorf("failed to initialize X11 display")}
}
config, err := hs.configService.GetConfig()
if err != nil {
return &HotkeyError{"load_config", err}
}
if config.General.EnableGlobalHotkey {
if err := hs.RegisterHotkey(&config.General.GlobalHotkey); err != nil {
hs.logger.Error("failed to register startup hotkey", "error", err)
}
}
return nil
}
// RegisterHotkey 注册全局热键
func (hs *HotkeyService) RegisterHotkey(hotkey *models.HotkeyCombo) error {
if !hs.isValidHotkey(hotkey) {
return &HotkeyError{"validate", fmt.Errorf("invalid hotkey combination")}
}
hs.mu.Lock()
defer hs.mu.Unlock()
// 取消现有热键
if hs.isRegistered.Load() {
hs.unregisterInternal()
}
keyCode := hs.keyToX11KeyCode(hotkey.Key)
if keyCode == 0 {
return &HotkeyError{"convert_key", fmt.Errorf("unsupported key: %s", hotkey.Key)}
}
modifiers := hs.buildX11Modifiers(hotkey)
result := int(C.registerGlobalHotkey(C.int(keyCode), C.uint(modifiers)))
if result == 0 {
return &HotkeyError{"register", fmt.Errorf("failed to register hotkey")}
}
// 启动监听器
ctx, cancel := context.WithCancel(hs.ctx)
hs.wg.Add(1)
ready := make(chan error, 1)
go hs.hotkeyListener(ctx, ready)
// 等待启动完成
select {
case err := <-ready:
if err != nil {
cancel()
return &HotkeyError{"start_listener", err}
}
case <-time.After(time.Second):
cancel()
return &HotkeyError{"start_listener", fmt.Errorf("timeout")}
}
hs.currentHotkey = hotkey
hs.isRegistered.Store(true)
hs.setCancelFunc(cancel)
return nil
}
// UnregisterHotkey 取消注册全局热键
func (hs *HotkeyService) UnregisterHotkey() error {
hs.mu.Lock()
defer hs.mu.Unlock()
return hs.unregisterInternal()
}
// unregisterInternal 内部取消注册(无锁)
func (hs *HotkeyService) unregisterInternal() error {
if !hs.isRegistered.Load() {
return nil
}
// 原子地获取并调用cancel函数
if cancel := hs.getCancelFunc(); cancel != nil {
cancel()
hs.wg.Wait()
}
result := int(C.unregisterGlobalHotkey())
if result == 0 {
return &HotkeyError{"unregister", fmt.Errorf("failed to unregister hotkey")}
}
hs.currentHotkey = nil
hs.isRegistered.Store(false)
hs.clearCancelFunc()
return nil
}
// UpdateHotkey 更新热键配置
func (hs *HotkeyService) UpdateHotkey(enable bool, hotkey *models.HotkeyCombo) error {
if enable {
return hs.RegisterHotkey(hotkey)
}
return hs.UnregisterHotkey()
}
// hotkeyListener 热键监听器
func (hs *HotkeyService) hotkeyListener(ctx context.Context, ready chan<- error) {
defer hs.wg.Done()
// 优化轮询频率从100ms改为50ms提高响应性
ticker := time.NewTicker(50 * time.Millisecond)
defer ticker.Stop()
ready <- nil // 标记准备就绪
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
if int(C.checkHotkeyEvent()) == 1 {
hs.toggleWindow()
}
}
}
}
// toggleWindow 切换窗口显示状态
func (hs *HotkeyService) toggleWindow() {
mainWindow := hs.windowHelper.MustGetMainWindow()
if mainWindow == nil {
hs.logger.Error("main window not found")
return
}
// 检查主窗口是否可见
if mainWindow.IsVisible() {
// 如果主窗口可见,隐藏所有窗口
hs.hideAllWindows()
} else {
// 如果主窗口不可见,显示所有窗口
hs.showAllWindows()
}
}
// isWindowVisible 检查窗口是否可见
func (hs *HotkeyService) isWindowVisible(window *application.WebviewWindow) bool {
return window.IsVisible()
}
// hideAllWindows 隐藏所有窗口
func (hs *HotkeyService) hideAllWindows() {
// 隐藏所有子窗口
if hs.windowService != nil {
openWindows := hs.windowService.GetOpenWindows()
for _, windowInfo := range openWindows {
windowInfo.Hide()
}
}
}
// showAllWindows 显示所有窗口
func (hs *HotkeyService) showAllWindows() {
// 显示所有子窗口
if hs.windowService != nil {
openWindows := hs.windowService.GetOpenWindows()
for _, windowInfo := range openWindows {
windowInfo.Show()
windowInfo.Restore()
}
}
}
// keyToX11KeyCode 键名转X11键码
func (hs *HotkeyService) keyToX11KeyCode(key string) int {
cKey := C.CString(key)
defer C.free(unsafe.Pointer(cKey))
return int(C.getX11Keycode(cKey))
}
// buildX11Modifiers 构建X11修饰符
func (hs *HotkeyService) buildX11Modifiers(hotkey *models.HotkeyCombo) uint {
var modifiers uint = 0
if hotkey.Ctrl {
modifiers |= 0x04 // ControlMask
}
if hotkey.Shift {
modifiers |= 0x01 // ShiftMask
}
if hotkey.Alt {
modifiers |= 0x08 // Mod1Mask (Alt)
}
if hotkey.Win {
modifiers |= 0x40 // Mod4Mask (Super/Win)
}
return modifiers
}
// isValidHotkey 验证热键组合
func (hs *HotkeyService) isValidHotkey(hotkey *models.HotkeyCombo) bool {
if hotkey == nil || hotkey.Key == "" {
return false
}
// 至少需要一个修饰键
if !hotkey.Ctrl && !hotkey.Shift && !hotkey.Alt && !hotkey.Win {
return false
}
return hs.keyToX11KeyCode(hotkey.Key) != 0
}
// GetCurrentHotkey 获取当前热键
func (hs *HotkeyService) GetCurrentHotkey() *models.HotkeyCombo {
hs.mu.RLock()
defer hs.mu.RUnlock()
if hs.currentHotkey == nil {
return nil
}
return &models.HotkeyCombo{
Ctrl: hs.currentHotkey.Ctrl,
Shift: hs.currentHotkey.Shift,
Alt: hs.currentHotkey.Alt,
Win: hs.currentHotkey.Win,
Key: hs.currentHotkey.Key,
}
}
// IsRegistered 检查是否已注册
func (hs *HotkeyService) IsRegistered() bool {
return hs.isRegistered.Load()
}
// ServiceShutdown 关闭服务
func (hs *HotkeyService) ServiceShutdown() error {
// 原子地获取并调用cancel函数
if cancel := hs.getCancelFunc(); cancel != nil {
cancel()
}
hs.wg.Wait()
C.closeX11Display()
return nil
}

View File

@@ -68,7 +68,7 @@ func NewServiceManager() *ServiceManager {
systemService := NewSystemService(logger)
// 初始化热键服务
hotkeyService := NewHotkeyService(configService, windowService, logger)
hotkeyService := NewHotkeyService(configService, logger)
// 初始化对话服务
dialogService := NewDialogService(logger)

View File

@@ -80,14 +80,14 @@ func (wh *WindowHelper) AutoShowMainWindow() {
}
}
// GetDocumentWindow 根据文档ID获取窗口(利用 Wails3 的 WindowManager
// GetDocumentWindow 根据文档ID获取窗口
func (wh *WindowHelper) GetDocumentWindow(documentID int64) (application.Window, bool) {
app := application.Get()
windowName := strconv.FormatInt(documentID, 10)
return app.Window.GetByName(windowName)
}
// GetAllDocumentWindows 获取所有文档窗口(排除主窗口)
// GetAllDocumentWindows 获取所有文档窗口
func (wh *WindowHelper) GetAllDocumentWindows() []application.Window {
app := application.Get()
allWindows := app.Window.GetAll()