Added hotkey service

This commit is contained in:
2025-06-03 13:56:45 +08:00
parent 5d7f6ec6a1
commit 5381e4ba17
20 changed files with 1895 additions and 636 deletions

View File

@@ -23,7 +23,7 @@ tasks:
BUILD_FLAGS: '{{if eq .PRODUCTION "true"}}-tags production -trimpath -buildvcs=false -ldflags="-w -s -H windowsgui"{{else}}-buildvcs=false -gcflags=all="-l"{{end}}'
env:
GOOS: windows
CGO_ENABLED: 0
CGO_ENABLED: 1
GOARCH: '{{.ARCH | default ARCH}}'
PRODUCTION: '{{.PRODUCTION | default "false"}}'

View File

@@ -1,479 +0,0 @@
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
// This file is automatically generated. DO NOT EDIT
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: Unused imports
import {Create as $Create} from "@wailsio/runtime";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: Unused imports
import * as time$0 from "../../../time/models.js";
/**
* AppConfig 应用配置 - 按照前端设置页面分类组织
*/
export class AppConfig {
/**
* 通用设置
*/
"general": GeneralConfig;
/**
* 编辑设置
*/
"editing": EditingConfig;
/**
* 外观设置
*/
"appearance": AppearanceConfig;
/**
* 快捷键设置
*/
"keyBindings": KeyBindingsConfig;
/**
* 更新设置
*/
"updates": UpdatesConfig;
/**
* 配置元数据
*/
"metadata": ConfigMetadata;
/** Creates a new AppConfig instance. */
constructor($$source: Partial<AppConfig> = {}) {
if (!("general" in $$source)) {
this["general"] = (new GeneralConfig());
}
if (!("editing" in $$source)) {
this["editing"] = (new EditingConfig());
}
if (!("appearance" in $$source)) {
this["appearance"] = (new AppearanceConfig());
}
if (!("keyBindings" in $$source)) {
this["keyBindings"] = (new KeyBindingsConfig());
}
if (!("updates" in $$source)) {
this["updates"] = (new UpdatesConfig());
}
if (!("metadata" in $$source)) {
this["metadata"] = (new ConfigMetadata());
}
Object.assign(this, $$source);
}
/**
* Creates a new AppConfig instance from a string or object.
*/
static createFrom($$source: any = {}): AppConfig {
const $$createField0_0 = $$createType0;
const $$createField1_0 = $$createType1;
const $$createField2_0 = $$createType2;
const $$createField3_0 = $$createType3;
const $$createField4_0 = $$createType4;
const $$createField5_0 = $$createType5;
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
if ("general" in $$parsedSource) {
$$parsedSource["general"] = $$createField0_0($$parsedSource["general"]);
}
if ("editing" in $$parsedSource) {
$$parsedSource["editing"] = $$createField1_0($$parsedSource["editing"]);
}
if ("appearance" in $$parsedSource) {
$$parsedSource["appearance"] = $$createField2_0($$parsedSource["appearance"]);
}
if ("keyBindings" in $$parsedSource) {
$$parsedSource["keyBindings"] = $$createField3_0($$parsedSource["keyBindings"]);
}
if ("updates" in $$parsedSource) {
$$parsedSource["updates"] = $$createField4_0($$parsedSource["updates"]);
}
if ("metadata" in $$parsedSource) {
$$parsedSource["metadata"] = $$createField5_0($$parsedSource["metadata"]);
}
return new AppConfig($$parsedSource as Partial<AppConfig>);
}
}
/**
* AppearanceConfig 外观设置配置
*/
export class AppearanceConfig {
/**
* 界面语言
*/
"language": LanguageType;
/** Creates a new AppearanceConfig instance. */
constructor($$source: Partial<AppearanceConfig> = {}) {
if (!("language" in $$source)) {
this["language"] = ("" as LanguageType);
}
Object.assign(this, $$source);
}
/**
* Creates a new AppearanceConfig instance from a string or object.
*/
static createFrom($$source: any = {}): AppearanceConfig {
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
return new AppearanceConfig($$parsedSource as Partial<AppearanceConfig>);
}
}
/**
* ConfigMetadata 配置元数据
*/
export class ConfigMetadata {
/**
* 配置版本
*/
"version": string;
/**
* 最后更新时间
*/
"lastUpdated": time$0.Time;
/** Creates a new ConfigMetadata instance. */
constructor($$source: Partial<ConfigMetadata> = {}) {
if (!("version" in $$source)) {
this["version"] = "";
}
if (!("lastUpdated" in $$source)) {
this["lastUpdated"] = null;
}
Object.assign(this, $$source);
}
/**
* Creates a new ConfigMetadata instance from a string or object.
*/
static createFrom($$source: any = {}): ConfigMetadata {
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
return new ConfigMetadata($$parsedSource as Partial<ConfigMetadata>);
}
}
/**
* Document 表示一个文档
*/
export class Document {
/**
* 元数据
*/
"meta": DocumentMeta;
/**
* 文档内容
*/
"content": string;
/** Creates a new Document instance. */
constructor($$source: Partial<Document> = {}) {
if (!("meta" in $$source)) {
this["meta"] = (new DocumentMeta());
}
if (!("content" in $$source)) {
this["content"] = "";
}
Object.assign(this, $$source);
}
/**
* Creates a new Document instance from a string or object.
*/
static createFrom($$source: any = {}): Document {
const $$createField0_0 = $$createType6;
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
if ("meta" in $$parsedSource) {
$$parsedSource["meta"] = $$createField0_0($$parsedSource["meta"]);
}
return new Document($$parsedSource as Partial<Document>);
}
}
/**
* DocumentMeta 文档元数据
*/
export class DocumentMeta {
/**
* 文档唯一标识
*/
"id": string;
/**
* 文档标题
*/
"title": string;
/**
* 最后更新时间
*/
"lastUpdated": time$0.Time;
/**
* 创建时间
*/
"createdAt": time$0.Time;
/** Creates a new DocumentMeta instance. */
constructor($$source: Partial<DocumentMeta> = {}) {
if (!("id" in $$source)) {
this["id"] = "";
}
if (!("title" in $$source)) {
this["title"] = "";
}
if (!("lastUpdated" in $$source)) {
this["lastUpdated"] = null;
}
if (!("createdAt" in $$source)) {
this["createdAt"] = null;
}
Object.assign(this, $$source);
}
/**
* Creates a new DocumentMeta instance from a string or object.
*/
static createFrom($$source: any = {}): DocumentMeta {
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
return new DocumentMeta($$parsedSource as Partial<DocumentMeta>);
}
}
/**
* EditingConfig 编辑设置配置
*/
export class EditingConfig {
/**
* 字体设置
* 字体大小
*/
"fontSize": number;
/**
* 字体族
*/
"fontFamily": string;
/**
* 字体粗细
*/
"fontWeight": string;
/**
* 行高
*/
"lineHeight": number;
/**
* Tab设置
* 是否启用Tab缩进
*/
"enableTabIndent": boolean;
/**
* Tab大小
*/
"tabSize": number;
/**
* Tab类型空格或Tab
*/
"tabType": TabType;
/**
* 保存选项
* 自动保存延迟(毫秒)
*/
"autoSaveDelay": number;
/**
* 变更字符阈值
*/
"changeThreshold": number;
/**
* 最小保存间隔(毫秒)
*/
"minSaveInterval": number;
/** Creates a new EditingConfig instance. */
constructor($$source: Partial<EditingConfig> = {}) {
if (!("fontSize" in $$source)) {
this["fontSize"] = 0;
}
if (!("fontFamily" in $$source)) {
this["fontFamily"] = "";
}
if (!("fontWeight" in $$source)) {
this["fontWeight"] = "";
}
if (!("lineHeight" in $$source)) {
this["lineHeight"] = 0;
}
if (!("enableTabIndent" in $$source)) {
this["enableTabIndent"] = false;
}
if (!("tabSize" in $$source)) {
this["tabSize"] = 0;
}
if (!("tabType" in $$source)) {
this["tabType"] = ("" as TabType);
}
if (!("autoSaveDelay" in $$source)) {
this["autoSaveDelay"] = 0;
}
if (!("changeThreshold" in $$source)) {
this["changeThreshold"] = 0;
}
if (!("minSaveInterval" in $$source)) {
this["minSaveInterval"] = 0;
}
Object.assign(this, $$source);
}
/**
* Creates a new EditingConfig instance from a string or object.
*/
static createFrom($$source: any = {}): EditingConfig {
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
return new EditingConfig($$parsedSource as Partial<EditingConfig>);
}
}
/**
* GeneralConfig 通用设置配置
*/
export class GeneralConfig {
/**
* 窗口是否置顶
*/
"alwaysOnTop": boolean;
/**
* 数据存储路径
*/
"dataPath": string;
/** Creates a new GeneralConfig instance. */
constructor($$source: Partial<GeneralConfig> = {}) {
if (!("alwaysOnTop" in $$source)) {
this["alwaysOnTop"] = false;
}
if (!("dataPath" in $$source)) {
this["dataPath"] = "";
}
Object.assign(this, $$source);
}
/**
* Creates a new GeneralConfig instance from a string or object.
*/
static createFrom($$source: any = {}): GeneralConfig {
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
return new GeneralConfig($$parsedSource as Partial<GeneralConfig>);
}
}
/**
* KeyBindingsConfig 快捷键设置配置
*/
export class KeyBindingsConfig {
/** Creates a new KeyBindingsConfig instance. */
constructor($$source: Partial<KeyBindingsConfig> = {}) {
Object.assign(this, $$source);
}
/**
* Creates a new KeyBindingsConfig instance from a string or object.
*/
static createFrom($$source: any = {}): KeyBindingsConfig {
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
return new KeyBindingsConfig($$parsedSource as Partial<KeyBindingsConfig>);
}
}
/**
* LanguageType 语言类型定义
*/
export enum LanguageType {
/**
* The Go zero value for the underlying type of the enum.
*/
$zero = "",
/**
* LangZhCN 中文简体
*/
LangZhCN = "zh-CN",
/**
* LangEnUS 英文-美国
*/
LangEnUS = "en-US",
};
/**
* TabType 定义了制表符类型
*/
export enum TabType {
/**
* The Go zero value for the underlying type of the enum.
*/
$zero = "",
/**
* TabTypeSpaces 使用空格作为制表符
*/
TabTypeSpaces = "spaces",
/**
* TabTypeTab 使用Tab作为制表符
*/
TabTypeTab = "tab",
};
/**
* UpdatesConfig 更新设置配置
*/
export class UpdatesConfig {
/** Creates a new UpdatesConfig instance. */
constructor($$source: Partial<UpdatesConfig> = {}) {
Object.assign(this, $$source);
}
/**
* Creates a new UpdatesConfig instance from a string or object.
*/
static createFrom($$source: any = {}): UpdatesConfig {
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
return new UpdatesConfig($$parsedSource as Partial<UpdatesConfig>);
}
}
// Private type creation functions
const $$createType0 = GeneralConfig.createFrom;
const $$createType1 = EditingConfig.createFrom;
const $$createType2 = AppearanceConfig.createFrom;
const $$createType3 = KeyBindingsConfig.createFrom;
const $$createType4 = UpdatesConfig.createFrom;
const $$createType5 = ConfigMetadata.createFrom;
const $$createType6 = DocumentMeta.createFrom;

View File

@@ -1,55 +0,0 @@
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
// This file is automatically generated. DO NOT EDIT
/**
* ConfigService 提供基于 Viper 的配置管理功能
* @module
*/
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: Unused imports
import {Call as $Call, Create as $Create} from "@wailsio/runtime";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: Unused imports
import * as models$0 from "../models/models.js";
/**
* Get 获取配置项
*/
export function Get(key: string): Promise<any> & { cancel(): void } {
let $resultPromise = $Call.ByID(807201772, key) as any;
return $resultPromise;
}
/**
* GetConfig 获取完整应用配置
*/
export function GetConfig(): Promise<models$0.AppConfig | null> & { cancel(): void } {
let $resultPromise = $Call.ByID(1013336538) as any;
let $typingPromise = $resultPromise.then(($result: any) => {
return $$createType1($result);
}) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
return $typingPromise;
}
/**
* ResetConfig 重置为默认配置
*/
export function ResetConfig(): Promise<void> & { cancel(): void } {
let $resultPromise = $Call.ByID(3593047389) as any;
return $resultPromise;
}
/**
* Set 设置配置项
*/
export function Set(key: string, value: any): Promise<void> & { cancel(): void } {
let $resultPromise = $Call.ByID(2921955968, key, value) as any;
return $resultPromise;
}
// Private type creation functions
const $$createType0 = models$0.AppConfig.createFrom;
const $$createType1 = $Create.Nullable($$createType0);

View File

@@ -1,13 +0,0 @@
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
// This file is automatically generated. DO NOT EDIT
import * as ConfigService from "./configservice.js";
import * as DocumentService from "./documentservice.js";
import * as SystemService from "./systemservice.js";
export {
ConfigService,
DocumentService,
SystemService
};
export * from "./models.js";

View File

@@ -1,13 +1,18 @@
import {defineStore} from 'pinia';
import {computed, reactive} from 'vue';
import {ConfigService} from '@/../bindings/voidraft/internal/services';
import {
ConfigService
} from '@/../bindings/voidraft/internal/services';
import {AppConfig, GeneralConfig, EditingConfig, AppearanceConfig, TabType, LanguageType} from '@/../bindings/voidraft/internal/models';
import { useI18n } from 'vue-i18n';
import { useErrorHandler } from '@/utils/errorHandler';
import { ConfigUtils } from '@/utils/configUtils';
AppConfig,
AppearanceConfig,
EditingConfig,
GeneralConfig,
LanguageType,
TabType
} from '@/../bindings/voidraft/internal/models';
import {useI18n} from 'vue-i18n';
import {useErrorHandler} from '@/utils/errorHandler';
import {ConfigUtils} from '@/utils/configUtils';
import {WindowController} from '@/utils/windowController';
// 国际化相关导入
export type SupportedLocaleType = 'zh-CN' | 'en-US';
@@ -41,7 +46,9 @@ type NumberConfigKey = 'fontSize' | 'tabSize' | 'lineHeight';
// 配置键映射
const GENERAL_CONFIG_KEY_MAP: GeneralConfigKeyMap = {
alwaysOnTop: 'general.always_on_top',
dataPath: 'general.data_path'
dataPath: 'general.data_path',
enableGlobalHotkey: 'general.enable_global_hotkey',
globalHotkey: 'general.global_hotkey'
} as const;
const EDITING_CONFIG_KEY_MAP: EditingConfigKeyMap = {
@@ -63,22 +70,31 @@ const APPEARANCE_CONFIG_KEY_MAP: AppearanceConfigKeyMap = {
// 配置限制
const CONFIG_LIMITS = {
fontSize: { min: 12, max: 28, default: 13 },
tabSize: { min: 2, max: 8, default: 4 },
lineHeight: { min: 1.0, max: 3.0, default: 1.5 },
tabType: { values: [TabType.TabTypeSpaces, TabType.TabTypeTab], default: TabType.TabTypeSpaces }
fontSize: {min: 12, max: 28, default: 13},
tabSize: {min: 2, max: 8, default: 4},
lineHeight: {min: 1.0, max: 3.0, default: 1.5},
tabType: {values: [TabType.TabTypeSpaces, TabType.TabTypeTab], default: TabType.TabTypeSpaces}
} as const;
// 常用字体选项
export const FONT_OPTIONS = [
{ label: '鸿蒙字体', value: '"HarmonyOS Sans SC", "HarmonyOS Sans", "Microsoft YaHei", "PingFang SC", "Helvetica Neue", Arial, sans-serif' },
{ label: '微软雅黑', value: '"Microsoft YaHei", "PingFang SC", "Helvetica Neue", Arial, sans-serif' },
{ label: '苹方字体', value: '"PingFang SC", "Microsoft YaHei", "Helvetica Neue", Arial, sans-serif' },
{ label: 'JetBrains Mono', value: '"JetBrains Mono", "Fira Code", "SF Mono", Monaco, Consolas, "Ubuntu Mono", monospace' },
{ label: 'Fira Code', value: '"Fira Code", "JetBrains Mono", "SF Mono", Monaco, Consolas, "Ubuntu Mono", monospace' },
{ label: 'Source Code Pro', value: '"Source Code Pro", "SF Mono", Monaco, Consolas, "Ubuntu Mono", monospace' },
{ label: 'Cascadia Code', value: '"Cascadia Code", "SF Mono", Monaco, Consolas, "Ubuntu Mono", monospace' },
{ label: '系统等宽字体', value: '"SF Mono", Monaco, "Cascadia Code", "Roboto Mono", Consolas, "Courier New", monospace' }
{
label: '鸿蒙字体',
value: '"HarmonyOS Sans SC", "HarmonyOS Sans", "Microsoft YaHei", "PingFang SC", "Helvetica Neue", Arial, sans-serif'
},
{label: '微软雅黑', value: '"Microsoft YaHei", "PingFang SC", "Helvetica Neue", Arial, sans-serif'},
{label: '苹方字体', value: '"PingFang SC", "Microsoft YaHei", "Helvetica Neue", Arial, sans-serif'},
{
label: 'JetBrains Mono',
value: '"JetBrains Mono", "Fira Code", "SF Mono", Monaco, Consolas, "Ubuntu Mono", monospace'
},
{label: 'Fira Code', value: '"Fira Code", "JetBrains Mono", "SF Mono", Monaco, Consolas, "Ubuntu Mono", monospace'},
{label: 'Source Code Pro', value: '"Source Code Pro", "SF Mono", Monaco, Consolas, "Ubuntu Mono", monospace'},
{label: 'Cascadia Code', value: '"Cascadia Code", "SF Mono", Monaco, Consolas, "Ubuntu Mono", monospace'},
{
label: '系统等宽字体',
value: '"SF Mono", Monaco, "Cascadia Code", "Roboto Mono", Consolas, "Courier New", monospace'
}
] as const;
// 获取浏览器的默认语言
@@ -98,7 +114,15 @@ const getBrowserLanguage = (): SupportedLocaleType => {
const DEFAULT_CONFIG: AppConfig = {
general: {
alwaysOnTop: false,
dataPath: './data'
dataPath: './data',
enableGlobalHotkey: false,
globalHotkey: {
ctrl: false,
shift: false,
alt: true,
win: false,
key: 'X'
}
},
editing: {
fontSize: CONFIG_LIMITS.fontSize.default,
@@ -123,13 +147,14 @@ const DEFAULT_CONFIG: AppConfig = {
}
};
export const useConfigStore = defineStore('config', () => {
const { locale } = useI18n();
const { safeCall } = useErrorHandler();
const {locale} = useI18n();
const {safeCall} = useErrorHandler();
// 响应式状态
const state = reactive({
config: { ...DEFAULT_CONFIG } as AppConfig,
config: {...DEFAULT_CONFIG} as AppConfig,
isLoading: false,
configLoaded: false
});
@@ -146,12 +171,12 @@ export const useConfigStore = defineStore('config', () => {
if (!state.configLoaded && !state.isLoading) {
await initConfig();
}
const backendKey = GENERAL_CONFIG_KEY_MAP[key];
if (!backendKey) {
throw new Error(`No backend key mapping found for general.${key.toString()}`);
}
await ConfigService.Set(backendKey, value);
state.config.general[key] = value;
};
@@ -161,12 +186,12 @@ export const useConfigStore = defineStore('config', () => {
if (!state.configLoaded && !state.isLoading) {
await initConfig();
}
const backendKey = EDITING_CONFIG_KEY_MAP[key];
if (!backendKey) {
throw new Error(`No backend key mapping found for editing.${key.toString()}`);
}
await ConfigService.Set(backendKey, value);
state.config.editing[key] = value;
};
@@ -176,12 +201,12 @@ export const useConfigStore = defineStore('config', () => {
if (!state.configLoaded && !state.isLoading) {
await initConfig();
}
const backendKey = APPEARANCE_CONFIG_KEY_MAP[key];
if (!backendKey) {
throw new Error(`No backend key mapping found for appearance.${key.toString()}`);
}
await ConfigService.Set(backendKey, value);
state.config.appearance[key] = value;
};
@@ -189,11 +214,11 @@ export const useConfigStore = defineStore('config', () => {
// 加载配置
const initConfig = async (): Promise<void> => {
if (state.isLoading) return;
state.isLoading = true;
try {
const appConfig = await ConfigService.GetConfig();
if (appConfig) {
// 合并配置
if (appConfig.general) Object.assign(state.config.general, appConfig.general);
@@ -203,8 +228,12 @@ export const useConfigStore = defineStore('config', () => {
if (appConfig.updates) Object.assign(state.config.updates, appConfig.updates);
if (appConfig.metadata) Object.assign(state.config.metadata, appConfig.metadata);
}
state.configLoaded = true;
// 初始化热键监听器
const windowController = WindowController.getInstance();
await windowController.initializeHotkeyListener();
} finally {
state.isLoading = false;
}
@@ -214,7 +243,7 @@ export const useConfigStore = defineStore('config', () => {
const createAdjuster = <T extends NumberConfigKey>(key: T) => {
const limit = CONFIG_LIMITS[key];
const clamp = (value: number) => ConfigUtils.clamp(value, limit.min, limit.max);
return {
increase: () => safeCall(() => updateEditingConfig(key, clamp(state.config.editing[key] + 1)), 'config.saveFailed', 'config.saveSuccess'),
decrease: () => safeCall(() => updateEditingConfig(key, clamp(state.config.editing[key] - 1)), 'config.saveFailed', 'config.saveSuccess'),
@@ -224,10 +253,10 @@ export const useConfigStore = defineStore('config', () => {
};
// 通用布尔值切换器
const createGeneralToggler = <T extends keyof GeneralConfig>(key: T) =>
const createGeneralToggler = <T extends keyof GeneralConfig>(key: T) =>
() => safeCall(() => updateGeneralConfig(key, !state.config.general[key] as GeneralConfig[T]), 'config.saveFailed', 'config.saveSuccess');
const createEditingToggler = <T extends keyof EditingConfig>(key: T) =>
const createEditingToggler = <T extends keyof EditingConfig>(key: T) =>
() => safeCall(() => updateEditingConfig(key, !state.config.editing[key] as EditingConfig[T]), 'config.saveFailed', 'config.saveSuccess');
// 枚举值切换器
@@ -241,7 +270,7 @@ export const useConfigStore = defineStore('config', () => {
// 重置配置
const resetConfig = async (): Promise<void> => {
if (state.isLoading) return;
state.isLoading = true;
try {
await safeCall(() => ConfigService.ResetConfig(), 'config.resetFailed', 'config.resetSuccess');
@@ -255,7 +284,7 @@ export const useConfigStore = defineStore('config', () => {
const setLanguage = async (language: LanguageType): Promise<void> => {
await safeCall(async () => {
await updateAppearanceConfig('language', language);
// 同步更新前端语言
const frontendLocale = ConfigUtils.backendLanguageToFrontend(language);
locale.value = frontendLocale as any;
@@ -269,7 +298,7 @@ export const useConfigStore = defineStore('config', () => {
if (!state.configLoaded) {
await initConfig();
}
// 同步前端语言设置
const frontendLocale = ConfigUtils.backendLanguageToFrontend(state.config.appearance.language);
locale.value = frontendLocale as any;
@@ -315,18 +344,18 @@ export const useConfigStore = defineStore('config', () => {
// 核心方法
initConfig: () => safeCall(() => initConfig(), 'config.loadFailed', 'config.loadSuccess'),
resetConfig,
// 语言相关方法
setLanguage,
initializeLanguage,
// 字体大小操作
...adjusters.fontSize,
increaseFontSize: adjusters.fontSize.increase,
decreaseFontSize: adjusters.fontSize.decrease,
resetFontSize: adjusters.fontSize.reset,
setFontSize: adjusters.fontSize.set,
// Tab操作
toggleTabIndent: togglers.tabIndent,
setEnableTabIndent: (value: boolean) => safeCall(() => updateEditingConfig('enableTabIndent', value), 'config.saveFailed', 'config.saveSuccess'),
@@ -335,10 +364,10 @@ export const useConfigStore = defineStore('config', () => {
decreaseTabSize: adjusters.tabSize.decrease,
setTabSize: adjusters.tabSize.set,
toggleTabType: togglers.tabType,
// 行高操作
setLineHeight: adjusters.lineHeight.set,
// 窗口操作
toggleAlwaysOnTop: togglers.alwaysOnTop,
@@ -352,6 +381,10 @@ export const useConfigStore = defineStore('config', () => {
// 保存配置相关方法
setAutoSaveDelay: setters.autoSaveDelay,
setChangeThreshold: setters.changeThreshold,
setMinSaveInterval: setters.minSaveInterval
setMinSaveInterval: setters.minSaveInterval,
// 热键配置相关方法
setEnableGlobalHotkey: (value: boolean) => safeCall(() => updateGeneralConfig('enableGlobalHotkey', value), 'config.saveFailed', 'config.saveSuccess'),
setGlobalHotkey: (hotkey: any) => safeCall(() => updateGeneralConfig('globalHotkey', hotkey), 'config.saveFailed', 'config.saveSuccess')
};
});

View File

@@ -0,0 +1,105 @@
import * as wails from '@wailsio/runtime'
// 窗口控制工具类
export class WindowController {
private static instance: WindowController;
private currentWindow = wails.Window;
private isWindowVisible: boolean = true; // 跟踪窗口可见状态
private isInitialized: boolean = false; // 跟踪是否已初始化
private isToggling: boolean = false; // 防止重复切换
private lastToggleTime: number = 0; // 上次切换时间
private readonly TOGGLE_COOLDOWN = 500; // 切换冷却时间(毫秒)
static getInstance(): WindowController {
if (!WindowController.instance) {
WindowController.instance = new WindowController();
}
return WindowController.instance;
}
async toggleWindow(): Promise<void> {
const now = Date.now();
// 防抖检查
if (this.isToggling || (now - this.lastToggleTime) < this.TOGGLE_COOLDOWN) {
return;
}
this.isToggling = true;
this.lastToggleTime = now;
try {
// 如果还没初始化,先初始化状态
if (!this.isInitialized) {
await this.syncWindowState();
}
if (!this.isWindowVisible) {
// 窗口当前隐藏,显示它
await this.currentWindow.Show();
await this.currentWindow.UnMinimise(); // 修正API名称
await this.currentWindow.Focus();
this.isWindowVisible = true;
} else {
// 窗口当前可见,隐藏它
await this.currentWindow.Hide();
this.isWindowVisible = false;
}
} catch (error) {
console.error(error);
} finally {
// 延迟重置切换状态,确保操作完成
setTimeout(() => {
this.isToggling = false;
}, 100);
}
}
// 同步窗口状态
private async syncWindowState(): Promise<void> {
try {
// 检查窗口是否最小化
const isMinimised = await this.currentWindow.IsMinimised();
// 简化状态判断:只要不是最小化状态就认为是可见的
this.isWindowVisible = !isMinimised;
this.isInitialized = true;
} catch (error) {
// 如果检查失败,保持默认状态
this.isWindowVisible = true;
this.isInitialized = true;
}
}
// 当窗口被系统事件隐藏时调用(比如点击关闭/最小化按钮)
onWindowHidden(): void {
this.isWindowVisible = false;
}
// 当窗口被系统事件显示时调用(比如点击托盘图标)
onWindowShown(): void {
this.isWindowVisible = true;
}
async initializeHotkeyListener(): Promise<void> {
// 初始化时同步窗口状态
await this.syncWindowState();
// 监听后端发送的热键事件
wails.Events.On('hotkey:toggle-window', () => {
this.toggleWindow();
});
// 监听窗口显示/隐藏事件以同步状态
wails.Events.On('window:shown', () => {
this.onWindowShown();
});
wails.Events.On('window:hidden', () => {
this.onWindowHidden();
});
}
}

View File

@@ -1,25 +1,15 @@
<script setup lang="ts">
import { useConfigStore } from '@/stores/configStore';
import { useI18n } from 'vue-i18n';
import { ref } from 'vue';
import { computed } from 'vue';
import SettingSection from '../components/SettingSection.vue';
import SettingItem from '../components/SettingItem.vue';
import ToggleSwitch from '../components/ToggleSwitch.vue';
import { useErrorHandler } from '@/utils/errorHandler';
const { t } = useI18n();
const configStore = useConfigStore();
// 选择的键盘修饰键
const selectedModifiers = ref({
ctrl: false,
shift: false,
alt: true,
altgr: false,
win: false
});
// 选择的键
const selectedKey = ref('X');
const { safeCall } = useErrorHandler();
// 可选键列表
const keyOptions = [
@@ -29,15 +19,35 @@ const keyOptions = [
'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12'
];
// 计算属性 - 启用全局热键
const enableGlobalHotkey = computed({
get: () => configStore.config.general.enableGlobalHotkey,
set: (value: boolean) => configStore.setEnableGlobalHotkey(value)
});
// 修饰键配置 - 只读计算属性
const modifierKeys = computed(() => ({
ctrl: configStore.config.general.globalHotkey.ctrl,
shift: configStore.config.general.globalHotkey.shift,
alt: configStore.config.general.globalHotkey.alt,
win: configStore.config.general.globalHotkey.win
}));
// 主键配置 - 只读计算属性
const selectedKey = computed(() => configStore.config.general.globalHotkey.key);
// 切换修饰键
const toggleModifier = (key: 'ctrl' | 'shift' | 'alt' | 'win') => {
const currentHotkey = configStore.config.general.globalHotkey;
const newHotkey = { ...currentHotkey, [key]: !currentHotkey[key] };
configStore.setGlobalHotkey(newHotkey);
};
// 更新选择的键
const updateSelectedKey = (event: Event) => {
const select = event.target as HTMLSelectElement;
selectedKey.value = select.value;
};
// 切换修饰键
const toggleModifier = (key: keyof typeof selectedModifiers.value) => {
selectedModifiers.value[key] = !selectedModifiers.value[key];
const newHotkey = { ...configStore.config.general.globalHotkey, key: select.value };
configStore.setGlobalHotkey(newHotkey);
};
// 重置设置
@@ -46,42 +56,58 @@ const resetSettings = async () => {
await configStore.resetConfig();
}
};
// 计算热键预览文本
const hotkeyPreview = computed(() => {
if (!enableGlobalHotkey.value) return '';
const hotkey = configStore.config.general.globalHotkey;
const parts: string[] = [];
if (hotkey.ctrl) parts.push('Ctrl');
if (hotkey.shift) parts.push('Shift');
if (hotkey.alt) parts.push('Alt');
if (hotkey.win) parts.push('Win');
if (hotkey.key) parts.push(hotkey.key);
return parts.join(' + ');
});
</script>
<template>
<div class="settings-page">
<SettingSection :title="t('settings.globalHotkey')">
<SettingItem :title="t('settings.enableGlobalHotkey')">
<ToggleSwitch v-model="configStore.config.general.alwaysOnTop" /> <!-- 此处使用alwaysOnTop作为示例 -->
<ToggleSwitch v-model="enableGlobalHotkey" />
</SettingItem>
<div class="hotkey-selector">
<div class="hotkey-selector" :class="{ 'disabled': !enableGlobalHotkey }">
<div class="hotkey-modifiers">
<label class="modifier-label" :class="{ active: selectedModifiers.ctrl }">
<input type="checkbox" v-model="selectedModifiers.ctrl" class="hidden-checkbox">
<label class="modifier-label" :class="{ active: modifierKeys.ctrl }" @click="toggleModifier('ctrl')">
<input type="checkbox" :checked="modifierKeys.ctrl" class="hidden-checkbox" :disabled="!enableGlobalHotkey">
<span class="modifier-key">Ctrl</span>
</label>
<label class="modifier-label" :class="{ active: selectedModifiers.shift }">
<input type="checkbox" v-model="selectedModifiers.shift" class="hidden-checkbox">
<label class="modifier-label" :class="{ active: modifierKeys.shift }" @click="toggleModifier('shift')">
<input type="checkbox" :checked="modifierKeys.shift" class="hidden-checkbox" :disabled="!enableGlobalHotkey">
<span class="modifier-key">Shift</span>
</label>
<label class="modifier-label" :class="{ active: selectedModifiers.alt }">
<input type="checkbox" v-model="selectedModifiers.alt" class="hidden-checkbox">
<label class="modifier-label" :class="{ active: modifierKeys.alt }" @click="toggleModifier('alt')">
<input type="checkbox" :checked="modifierKeys.alt" class="hidden-checkbox" :disabled="!enableGlobalHotkey">
<span class="modifier-key">Alt</span>
</label>
<label class="modifier-label" :class="{ active: selectedModifiers.altgr }">
<input type="checkbox" v-model="selectedModifiers.altgr" class="hidden-checkbox">
<span class="modifier-key">AltGr</span>
</label>
<label class="modifier-label" :class="{ active: selectedModifiers.win }">
<input type="checkbox" v-model="selectedModifiers.win" class="hidden-checkbox">
<label class="modifier-label" :class="{ active: modifierKeys.win }" @click="toggleModifier('win')">
<input type="checkbox" :checked="modifierKeys.win" class="hidden-checkbox" :disabled="!enableGlobalHotkey">
<span class="modifier-key">Win</span>
</label>
</div>
<select class="key-select" v-model="selectedKey">
<select class="key-select" :value="selectedKey" @change="updateSelectedKey" :disabled="!enableGlobalHotkey">
<option v-for="key in keyOptions" :key="key" :value="key">{{ key }}</option>
</select>
<div class="hotkey-preview" v-if="hotkeyPreview">
<span class="preview-label">预览</span>
<span class="preview-hotkey">{{ hotkeyPreview }}</span>
</div>
</div>
</SettingSection>
@@ -128,6 +154,11 @@ const resetSettings = async () => {
.hotkey-selector {
padding: 15px 0 5px 20px;
&.disabled {
opacity: 0.5;
pointer-events: none;
}
.hotkey-modifiers {
display: flex;
gap: 8px;
@@ -137,6 +168,10 @@ const resetSettings = async () => {
.modifier-label {
cursor: pointer;
&.disabled {
cursor: not-allowed;
}
.hidden-checkbox {
display: none;
}
@@ -178,16 +213,46 @@ const resetSettings = async () => {
background-position: right 8px center;
background-size: 16px;
padding-right: 30px;
margin-bottom: 12px;
&:focus {
outline: none;
border-color: #4a9eff;
}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
background-color: #2a2a2a;
}
option {
background-color: #2a2a2a;
}
}
.hotkey-preview {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
background-color: #252525;
border: 1px solid #444444;
border-radius: 4px;
margin-top: 8px;
.preview-label {
font-size: 12px;
color: #888888;
}
.preview-hotkey {
font-size: 13px;
color: #4a9eff;
font-weight: 500;
font-family: 'Consolas', 'Courier New', monospace;
}
}
}
.directory-selector {

2
go.mod
View File

@@ -54,7 +54,7 @@ require (
github.com/xanzy/ssh-agent v0.3.3 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/crypto v0.38.0 // indirect
golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0 // indirect
golang.org/x/exp v0.0.0-20250506013437-ce4c2cf36ca6 // indirect
golang.org/x/net v0.40.0 // indirect
golang.org/x/sys v0.33.0 // indirect
golang.org/x/text v0.25.0 // indirect

4
go.sum
View File

@@ -133,8 +133,8 @@ go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN8
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8=
golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw=
golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0 h1:R84qjqJb5nVJMxqWYb3np9L5ZsaDtB+a39EqjV0JSUM=
golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0/go.mod h1:S9Xr4PYopiDyqSyp5NjCrhFrqg6A5zA2E/iPHPhqnS8=
golang.org/x/exp v0.0.0-20250506013437-ce4c2cf36ca6 h1:y5zboxd6LQAqYIhHnB48p0ByQ/GnQx2BE33L8BOHQkI=
golang.org/x/exp v0.0.0-20250506013437-ce4c2cf36ca6/go.mod h1:U6Lno4MTRCDY+Ba7aCcauB9T60gsv5s4ralQzP72ZoQ=
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.40.0 h1:79Xs7wF06Gbdcg4kdCCIQArK11Z1hr5POQ6+fIYHNuY=

View File

@@ -18,16 +18,31 @@ func RegisterTrayEvents(app *application.App, systray *application.SystemTray, m
// 设置点击托盘图标显示主窗口
systray.OnClick(func() {
mainWindow.Show()
mainWindow.Restore()
mainWindow.Focus()
// 通知前端窗口已显示
app.EmitEvent("window:shown", nil)
})
// 使用关闭前的事件处理
// 处理窗口关闭事件 - 隐藏到托盘
mainWindow.RegisterHook(wailsevents.Common.WindowClosing, func(event *application.WindowEvent) {
// 取消默认关闭行为
event.Cancel()
// 隐藏窗口
// 隐藏窗口到托盘
mainWindow.Hide()
// 通知前端窗口已隐藏
app.EmitEvent("window:hidden", nil)
})
// 处理窗口最小化事件 - 也隐藏到托盘
mainWindow.RegisterHook(wailsevents.Common.WindowMinimise, func(event *application.WindowEvent) {
// 取消默认最小化行为
event.Cancel()
// 隐藏窗口到托盘
mainWindow.Hide()
// 通知前端窗口已隐藏
app.EmitEvent("window:hidden", nil)
})
}
// RegisterTrayMenuEvents 注册系统托盘菜单事件

View File

@@ -0,0 +1,58 @@
#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

@@ -0,0 +1,25 @@
#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

@@ -30,6 +30,19 @@ const (
type GeneralConfig struct {
AlwaysOnTop bool `json:"alwaysOnTop" yaml:"always_on_top" mapstructure:"always_on_top"` // 窗口是否置顶
DataPath string `json:"dataPath" yaml:"data_path" mapstructure:"data_path"` // 数据存储路径
// 全局热键设置
EnableGlobalHotkey bool `json:"enableGlobalHotkey" yaml:"enable_global_hotkey" mapstructure:"enable_global_hotkey"` // 是否启用全局热键
GlobalHotkey HotkeyCombo `json:"globalHotkey" yaml:"global_hotkey" mapstructure:"global_hotkey"` // 全局热键组合
}
// HotkeyCombo 热键组合定义
type HotkeyCombo struct {
Ctrl bool `json:"ctrl" yaml:"ctrl" mapstructure:"ctrl"` // Ctrl键
Shift bool `json:"shift" yaml:"shift" mapstructure:"shift"` // Shift键
Alt bool `json:"alt" yaml:"alt" mapstructure:"alt"` // Alt键
Win bool `json:"win" yaml:"win" mapstructure:"win"` // Win键
Key string `json:"key" yaml:"key" mapstructure:"key"` // 主键(如 'X', 'F1' 等)
}
// EditingConfig 编辑设置配置
@@ -95,8 +108,16 @@ func NewDefaultAppConfig() *AppConfig {
return &AppConfig{
General: GeneralConfig{
AlwaysOnTop: false,
DataPath: dataDir,
AlwaysOnTop: false,
DataPath: dataDir,
EnableGlobalHotkey: false,
GlobalHotkey: HotkeyCombo{
Ctrl: false,
Shift: false,
Alt: true,
Win: false,
Key: "X",
},
},
Editing: EditingConfig{
// 字体设置

View File

@@ -5,6 +5,7 @@ import (
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"voidraft/internal/models"
@@ -19,6 +20,13 @@ type ConfigService struct {
viper *viper.Viper // Viper 实例
logger *log.LoggerService // 日志服务
mu sync.RWMutex // 读写锁
// 热键配置变更回调
hotkeyChangeCallback func(enable bool, hotkey *models.HotkeyCombo) error
// 热键变更防抖
hotkeyNotificationTimer *time.Timer
hotkeyNotificationMu sync.Mutex
}
// ConfigError 配置错误
@@ -283,6 +291,12 @@ func setDefaults(v *viper.Viper) {
// 通用设置默认值
v.SetDefault("general.always_on_top", defaultConfig.General.AlwaysOnTop)
v.SetDefault("general.data_path", defaultConfig.General.DataPath)
v.SetDefault("general.enable_global_hotkey", defaultConfig.General.EnableGlobalHotkey)
v.SetDefault("general.global_hotkey.ctrl", defaultConfig.General.GlobalHotkey.Ctrl)
v.SetDefault("general.global_hotkey.shift", defaultConfig.General.GlobalHotkey.Shift)
v.SetDefault("general.global_hotkey.alt", defaultConfig.General.GlobalHotkey.Alt)
v.SetDefault("general.global_hotkey.win", defaultConfig.General.GlobalHotkey.Win)
v.SetDefault("general.global_hotkey.key", defaultConfig.General.GlobalHotkey.Key)
// 编辑设置默认值
v.SetDefault("editing.font_size", defaultConfig.Editing.FontSize)
@@ -404,6 +418,15 @@ func (cs *ConfigService) Set(key string, value interface{}) error {
cs.logger.Debug("Config: Successfully set config", "key", key, "value", value)
}
// 检查是否是热键相关配置
if cs.isHotkeyRelatedKey(key) {
cs.logger.Info("Config: Detected hotkey configuration change", "key", key, "value", value)
// 释放锁后通知,避免死锁
go func() {
cs.notifyHotkeyChange()
}()
}
return nil
}
@@ -430,3 +453,77 @@ func (cs *ConfigService) ResetConfig() error {
cs.logger.Info("Config: Successfully reset to default configuration")
return nil
}
// SetHotkeyChangeCallback 设置热键配置变更回调
func (cs *ConfigService) SetHotkeyChangeCallback(callback func(enable bool, hotkey *models.HotkeyCombo) error) {
cs.mu.Lock()
defer cs.mu.Unlock()
cs.hotkeyChangeCallback = callback
}
// notifyHotkeyChange 通知热键配置变更
func (cs *ConfigService) notifyHotkeyChange() {
if cs.hotkeyChangeCallback == nil {
return
}
cs.hotkeyNotificationMu.Lock()
defer cs.hotkeyNotificationMu.Unlock()
// 取消之前的定时器
if cs.hotkeyNotificationTimer != nil {
cs.hotkeyNotificationTimer.Stop()
}
// 设置新的防抖定时器200ms延迟
cs.hotkeyNotificationTimer = time.AfterFunc(200*time.Millisecond, func() {
cs.logger.Debug("Config: Executing hotkey change notification after debounce")
// 获取当前热键配置
config, err := cs.GetConfig()
if err != nil {
cs.logger.Error("Config: Failed to get config for hotkey notification", "error", err)
return
}
cs.logger.Debug("Config: Notifying hotkey service of configuration change",
"enable", config.General.EnableGlobalHotkey,
"ctrl", config.General.GlobalHotkey.Ctrl,
"shift", config.General.GlobalHotkey.Shift,
"alt", config.General.GlobalHotkey.Alt,
"win", config.General.GlobalHotkey.Win,
"key", config.General.GlobalHotkey.Key)
// 异步通知热键服务
go func() {
err := cs.hotkeyChangeCallback(config.General.EnableGlobalHotkey, &config.General.GlobalHotkey)
if err != nil {
cs.logger.Error("Config: Failed to notify hotkey change", "error", err)
} else {
cs.logger.Debug("Config: Successfully notified hotkey change")
}
}()
})
cs.logger.Debug("Config: Hotkey change notification scheduled with debounce")
}
// isHotkeyRelatedKey 检查是否是热键相关的配置键
func (cs *ConfigService) isHotkeyRelatedKey(key string) bool {
hotkeyKeys := []string{
"general.enable_global_hotkey",
"general.global_hotkey",
"general.global_hotkey.ctrl",
"general.global_hotkey.shift",
"general.global_hotkey.alt",
"general.global_hotkey.win",
"general.global_hotkey.key",
}
for _, hotkeyKey := range hotkeyKeys {
if strings.HasPrefix(key, hotkeyKey) || key == hotkeyKey {
return true
}
}
return false
}

View File

@@ -0,0 +1,424 @@
//go:build windows
package services
/*
#cgo CFLAGS: -I../lib
#cgo LDFLAGS: -luser32
#include "../lib/hotkey_windows.c"
#include "hotkey_windows.h"
*/
import "C"
import (
"fmt"
"sync"
"time"
"voidraft/internal/models"
"github.com/wailsapp/wails/v3/pkg/application"
"github.com/wailsapp/wails/v3/pkg/services/log"
)
// HotkeyService 全局热键服务
type HotkeyService struct {
logger *log.LoggerService
configService *ConfigService
app *application.App
mu sync.RWMutex
isRegistered bool
currentHotkey *models.HotkeyCombo
stopChan chan struct{}
wg sync.WaitGroup
running bool
}
// HotkeyError 热键错误
type HotkeyError struct {
Operation string
Err error
}
// Error 实现error接口
func (e *HotkeyError) Error() string {
return fmt.Sprintf("hotkey error during %s: %v", e.Operation, e.Err)
}
// Unwrap 获取原始错误
func (e *HotkeyError) Unwrap() error {
return e.Err
}
// NewHotkeyService 创建新的热键服务实例
func NewHotkeyService(configService *ConfigService, logger *log.LoggerService) *HotkeyService {
if logger == nil {
logger = log.New()
}
return &HotkeyService{
logger: logger,
configService: configService,
isRegistered: false,
running: false,
}
}
// Initialize 初始化热键服务
func (hs *HotkeyService) Initialize(app *application.App) error {
hs.app = app
// 加载并应用当前配置
config, err := hs.configService.GetConfig()
if err != nil {
return &HotkeyError{Operation: "load_config", Err: err}
}
if config.General.EnableGlobalHotkey {
err = hs.RegisterHotkey(&config.General.GlobalHotkey)
if err != nil {
hs.logger.Error("Hotkey: Failed to register hotkey on startup", "error", err)
}
}
hs.logger.Info("Hotkey: Service initialized")
return nil
}
// RegisterHotkey 注册全局热键
func (hs *HotkeyService) RegisterHotkey(hotkey *models.HotkeyCombo) error {
hs.mu.Lock()
defer hs.mu.Unlock()
// 先取消注册现有热键
if hs.isRegistered {
hs.logger.Info("Hotkey: Unregistering existing hotkey before registering new one")
err := hs.unregisterHotkeyInternal()
if err != nil {
return err
}
}
// 验证热键组合
if !hs.isValidHotkey(hotkey) {
return &HotkeyError{Operation: "validate_hotkey", Err: fmt.Errorf("invalid hotkey combination")}
}
hs.logger.Info("Hotkey: Registering global hotkey using Windows API",
"ctrl", hotkey.Ctrl,
"shift", hotkey.Shift,
"alt", hotkey.Alt,
"win", hotkey.Win,
"key", hotkey.Key)
// 创建ready channel等待goroutine启动完成
readyChan := make(chan struct{})
// 确保 stopChan 是新的
hs.stopChan = make(chan struct{})
hs.wg.Add(1)
go hs.hotkeyListener(hotkey, readyChan)
// 等待监听器启动完成,设置超时避免无限等待
select {
case <-readyChan:
// 监听器启动完成
case <-time.After(1 * time.Second):
// 超时处理
hs.logger.Warning("Hotkey: Timeout waiting for listener to start")
return &HotkeyError{Operation: "start_listener", Err: fmt.Errorf("timeout waiting for hotkey listener to start")}
}
hs.currentHotkey = hotkey
hs.isRegistered = true
hs.running = true
hs.logger.Info("Hotkey: Successfully registered global hotkey")
return nil
}
// UnregisterHotkey 取消注册全局热键
func (hs *HotkeyService) UnregisterHotkey() error {
hs.mu.Lock()
defer hs.mu.Unlock()
return hs.unregisterHotkeyInternal()
}
// unregisterHotkeyInternal 内部取消注册方法(无锁)
func (hs *HotkeyService) unregisterHotkeyInternal() error {
if !hs.isRegistered {
hs.logger.Debug("Hotkey: No hotkey registered, skipping unregister")
return nil
}
hs.logger.Info("Hotkey: Unregistering global hotkey")
// 停止监听
if hs.stopChan != nil {
close(hs.stopChan)
hs.logger.Debug("Hotkey: Waiting for listener goroutine to stop")
hs.wg.Wait()
hs.logger.Debug("Hotkey: Listener goroutine stopped")
}
// 重置状态
hs.currentHotkey = nil
hs.isRegistered = false
hs.running = false
hs.stopChan = nil
hs.logger.Info("Hotkey: Successfully unregistered global hotkey")
return nil
}
// UpdateHotkey 更新热键配置
func (hs *HotkeyService) UpdateHotkey(enable bool, hotkey *models.HotkeyCombo) error {
hs.logger.Info("Hotkey: === UpdateHotkey called ===",
"enable", enable,
"ctrl", hotkey.Ctrl,
"shift", hotkey.Shift,
"alt", hotkey.Alt,
"win", hotkey.Win,
"key", hotkey.Key)
// 先获取当前状态
hs.mu.RLock()
currentRegistered := hs.isRegistered
var currentHotkey *models.HotkeyCombo
if hs.currentHotkey != nil {
currentHotkey = &models.HotkeyCombo{
Ctrl: hs.currentHotkey.Ctrl,
Shift: hs.currentHotkey.Shift,
Alt: hs.currentHotkey.Alt,
Win: hs.currentHotkey.Win,
Key: hs.currentHotkey.Key,
}
}
hs.mu.RUnlock()
hs.logger.Info("Hotkey: Current state",
"currentRegistered", currentRegistered,
"currentHotkey", currentHotkey)
// 检查是否需要更新
needsUpdate := false
if enable != currentRegistered {
needsUpdate = true
hs.logger.Info("Hotkey: Enable state changed", "old", currentRegistered, "new", enable)
} else if enable && currentHotkey != nil {
// 如果启用状态,检查热键组合是否变化
if hotkey.Ctrl != currentHotkey.Ctrl ||
hotkey.Shift != currentHotkey.Shift ||
hotkey.Alt != currentHotkey.Alt ||
hotkey.Win != currentHotkey.Win ||
hotkey.Key != currentHotkey.Key {
needsUpdate = true
hs.logger.Info("Hotkey: Hotkey combination changed",
"old", fmt.Sprintf("Ctrl:%v Shift:%v Alt:%v Win:%v Key:%s",
currentHotkey.Ctrl, currentHotkey.Shift, currentHotkey.Alt, currentHotkey.Win, currentHotkey.Key),
"new", fmt.Sprintf("Ctrl:%v Shift:%v Alt:%v Win:%v Key:%s",
hotkey.Ctrl, hotkey.Shift, hotkey.Alt, hotkey.Win, hotkey.Key))
}
}
if !needsUpdate {
hs.logger.Info("Hotkey: No changes detected, skipping update")
return nil
}
hs.logger.Info("Hotkey: Proceeding with hotkey update", "needsUpdate", needsUpdate)
if enable {
// 启用热键直接注册新热键RegisterHotkey 会处理取消旧热键)
err := hs.RegisterHotkey(hotkey)
if err != nil {
hs.logger.Error("Hotkey: Failed to register new hotkey", "error", err)
return err
}
hs.logger.Info("Hotkey: Successfully updated and registered new hotkey")
return nil
} else {
// 禁用热键:取消注册
err := hs.UnregisterHotkey()
if err != nil {
hs.logger.Error("Hotkey: Failed to unregister hotkey", "error", err)
return err
}
hs.logger.Info("Hotkey: Successfully disabled hotkey")
return nil
}
}
// ToggleWindow 切换窗口显示/隐藏 - 通过事件通知前端处理
func (hs *HotkeyService) ToggleWindow() {
if hs.app == nil {
hs.logger.Warning("Hotkey: App is nil, cannot toggle")
return
}
// 发送事件到前端,让前端处理窗口切换
hs.app.EmitEvent("hotkey:toggle-window", nil)
hs.logger.Debug("Hotkey: Emitted toggle window event")
}
// hotkeyListener 热键监听器goroutine
func (hs *HotkeyService) hotkeyListener(hotkey *models.HotkeyCombo, readyChan chan struct{}) {
defer hs.wg.Done()
hs.logger.Debug("Hotkey: Starting Windows API hotkey listener")
// 将热键转换为虚拟键码
mainKeyVK := hs.keyToVirtualKeyCode(hotkey.Key)
if mainKeyVK == 0 {
hs.logger.Error("Hotkey: Invalid key", "key", hotkey.Key)
close(readyChan)
return
}
// 检查间隔100ms减少CPU使用率
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
// 添加状态跟踪
var wasPressed bool = false
// 标记是否已经发送ready信号确保只发送一次
readySent := false
for {
select {
case <-hs.stopChan:
hs.logger.Debug("Hotkey: Stopping Windows API hotkey listener")
if !readySent {
close(readyChan)
}
return
case <-ticker.C:
// 第一次循环时发送ready信号表示监听器已经准备就绪
if !readySent {
close(readyChan)
readySent = true
hs.logger.Debug("Hotkey: Listener ready signal sent")
}
// 调用 C 函数检查热键组合
ctrl := 0
if hotkey.Ctrl {
ctrl = 1
}
shift := 0
if hotkey.Shift {
shift = 1
}
alt := 0
if hotkey.Alt {
alt = 1
}
win := 0
if hotkey.Win {
win = 1
}
// 检查热键是否被按下
isPressed := int(C.isHotkeyPressed(C.int(ctrl), C.int(shift), C.int(alt), C.int(win), C.int(mainKeyVK))) == 1
// 只在按键从未按下变为按下时触发(边缘触发)
if isPressed && !wasPressed {
hs.logger.Debug("Hotkey: Global hotkey triggered via Windows API")
hs.ToggleWindow()
}
// 更新状态
wasPressed = isPressed
}
}
}
// keyToVirtualKeyCode 将键名转换为 Windows 虚拟键码
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,
}
if vk, exists := keyMap[key]; exists {
return vk
}
return 0
}
// 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.keyToVirtualKeyCode(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 {
hs.mu.RLock()
defer hs.mu.RUnlock()
return hs.isRegistered
}
// ServiceShutdown 关闭热键服务
func (hs *HotkeyService) ServiceShutdown() error {
hs.mu.Lock()
defer hs.mu.Unlock()
if hs.isRegistered {
err := hs.unregisterHotkeyInternal()
if err != nil {
hs.logger.Error("Hotkey: Failed to unregister hotkey on shutdown", "error", err)
}
}
hs.logger.Info("Hotkey: Service shutdown completed")
return nil
}

View File

@@ -0,0 +1,360 @@
//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 (
"fmt"
"sync"
"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.LoggerService
configService *ConfigService
app *application.App
mu sync.RWMutex
isRegistered bool
currentHotkey *models.HotkeyCombo
}
// HotkeyError 热键错误
type HotkeyError struct {
Operation string
Err error
}
// Error 实现error接口
func (e *HotkeyError) Error() string {
return fmt.Sprintf("hotkey error during %s: %v", e.Operation, e.Err)
}
// Unwrap 获取原始错误
func (e *HotkeyError) Unwrap() error {
return e.Err
}
// NewHotkeyService 创建新的热键服务实例
func NewHotkeyService(configService *ConfigService, logger *log.LoggerService) *HotkeyService {
if logger == nil {
logger = log.New()
}
service := &HotkeyService{
logger: logger,
configService: configService,
isRegistered: false,
}
// 设置全局实例
globalHotkeyService = service
return service
}
// Initialize 初始化热键服务
func (hs *HotkeyService) Initialize(app *application.App) error {
hs.app = app
// 加载并应用当前配置
config, err := hs.configService.GetConfig()
if err != nil {
return &HotkeyError{Operation: "load_config", Err: err}
}
if config.General.EnableGlobalHotkey {
err = hs.RegisterHotkey(&config.General.GlobalHotkey)
if err != nil {
hs.logger.Error("Hotkey: Failed to register hotkey on startup", "error", err)
}
}
hs.logger.Info("Hotkey: macOS service initialized")
return nil
}
// RegisterHotkey 注册全局热键
func (hs *HotkeyService) RegisterHotkey(hotkey *models.HotkeyCombo) error {
hs.mu.Lock()
defer hs.mu.Unlock()
// 验证热键组合
if !hs.isValidHotkey(hotkey) {
return &HotkeyError{Operation: "validate_hotkey", Err: fmt.Errorf("invalid hotkey combination")}
}
hs.logger.Info("Hotkey: Registering global hotkey on macOS",
"ctrl", hotkey.Ctrl,
"shift", hotkey.Shift,
"alt", hotkey.Alt,
"win", hotkey.Win,
"key", hotkey.Key)
// 转换键码和修饰符
keyCode := hs.keyToMacKeyCode(hotkey.Key)
if keyCode == 0 {
return &HotkeyError{Operation: "convert_key", Err: 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{Operation: "register_hotkey", Err: fmt.Errorf("failed to register hotkey")}
}
hs.currentHotkey = hotkey
hs.isRegistered = true
hs.logger.Info("Hotkey: Successfully registered global hotkey on macOS")
return nil
}
// UnregisterHotkey 取消注册全局热键
func (hs *HotkeyService) UnregisterHotkey() error {
hs.mu.Lock()
defer hs.mu.Unlock()
if !hs.isRegistered {
hs.logger.Debug("Hotkey: No hotkey registered, skipping unregister")
return nil
}
hs.logger.Info("Hotkey: Unregistering global hotkey on macOS")
// 调用C函数取消注册热键
result := int(C.unregisterGlobalHotkey())
if result == 0 {
return &HotkeyError{Operation: "unregister_hotkey", Err: fmt.Errorf("failed to unregister hotkey")}
}
hs.currentHotkey = nil
hs.isRegistered = false
hs.logger.Info("Hotkey: Successfully unregistered global hotkey on macOS")
return nil
}
// UpdateHotkey 更新热键配置
func (hs *HotkeyService) UpdateHotkey(enable bool, hotkey *models.HotkeyCombo) error {
hs.logger.Info("Hotkey: === UpdateHotkey called (macOS) ===",
"enable", enable,
"ctrl", hotkey.Ctrl,
"shift", hotkey.Shift,
"alt", hotkey.Alt,
"win", hotkey.Win,
"key", hotkey.Key)
if enable {
// 启用热键直接注册新热键RegisterHotkey 会处理取消旧热键)
err := hs.RegisterHotkey(hotkey)
if err != nil {
hs.logger.Error("Hotkey: Failed to register new hotkey", "error", err)
return err
}
hs.logger.Info("Hotkey: Successfully updated and registered new hotkey on macOS")
return nil
} else {
// 禁用热键:取消注册
err := hs.UnregisterHotkey()
if err != nil {
hs.logger.Error("Hotkey: Failed to unregister hotkey", "error", err)
return err
}
hs.logger.Info("Hotkey: Successfully disabled hotkey on macOS")
return nil
}
}
// ToggleWindow 切换窗口显示/隐藏
func (hs *HotkeyService) ToggleWindow() {
if hs.app == nil {
hs.logger.Warning("Hotkey: App is nil, cannot toggle")
return
}
// 发送事件到前端,让前端处理窗口切换
hs.app.EmitEvent("hotkey:toggle-window", nil)
hs.logger.Debug("Hotkey: Emitted toggle window event (macOS)")
}
// 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 {
hs.mu.RLock()
defer hs.mu.RUnlock()
return hs.isRegistered
}
// ServiceShutdown 关闭热键服务
func (hs *HotkeyService) ServiceShutdown() error {
hs.mu.Lock()
defer hs.mu.Unlock()
if hs.isRegistered {
err := hs.UnregisterHotkey()
if err != nil {
hs.logger.Error("Hotkey: Failed to unregister hotkey on shutdown", "error", err)
}
}
hs.logger.Info("Hotkey: macOS service shutdown completed")
return nil
}
//export hotkeyTriggered
func hotkeyTriggered() {
// 通过全局实例调用ToggleWindow
if globalHotkeyService != nil {
globalHotkeyService.ToggleWindow()
}
}

View File

@@ -0,0 +1,489 @@
//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 (
"fmt"
"sync"
"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.LoggerService
configService *ConfigService
app *application.App
mu sync.RWMutex
isRegistered bool
currentHotkey *models.HotkeyCombo
stopChan chan struct{}
wg sync.WaitGroup
running bool
}
// HotkeyError 热键错误
type HotkeyError struct {
Operation string
Err error
}
// Error 实现error接口
func (e *HotkeyError) Error() string {
return fmt.Sprintf("hotkey error during %s: %v", e.Operation, e.Err)
}
// Unwrap 获取原始错误
func (e *HotkeyError) Unwrap() error {
return e.Err
}
// NewHotkeyService 创建新的热键服务实例
func NewHotkeyService(configService *ConfigService, logger *log.LoggerService) *HotkeyService {
if logger == nil {
logger = log.New()
}
return &HotkeyService{
logger: logger,
configService: configService,
isRegistered: false,
running: false,
}
}
// Initialize 初始化热键服务
func (hs *HotkeyService) Initialize(app *application.App) error {
hs.app = app
// 初始化X11显示
if int(C.initX11Display()) == 0 {
return &HotkeyError{Operation: "init_x11", Err: fmt.Errorf("failed to initialize X11 display")}
}
// 加载并应用当前配置
config, err := hs.configService.GetConfig()
if err != nil {
return &HotkeyError{Operation: "load_config", Err: err}
}
if config.General.EnableGlobalHotkey {
err = hs.RegisterHotkey(&config.General.GlobalHotkey)
if err != nil {
hs.logger.Error("Hotkey: Failed to register hotkey on startup", "error", err)
}
}
hs.logger.Info("Hotkey: Linux service initialized")
return nil
}
// RegisterHotkey 注册全局热键
func (hs *HotkeyService) RegisterHotkey(hotkey *models.HotkeyCombo) error {
hs.mu.Lock()
defer hs.mu.Unlock()
// 先取消注册现有热键
if hs.isRegistered {
hs.logger.Info("Hotkey: Unregistering existing hotkey before registering new one")
err := hs.unregisterHotkeyInternal()
if err != nil {
return err
}
}
// 验证热键组合
if !hs.isValidHotkey(hotkey) {
return &HotkeyError{Operation: "validate_hotkey", Err: fmt.Errorf("invalid hotkey combination")}
}
hs.logger.Info("Hotkey: Registering global hotkey on Linux",
"ctrl", hotkey.Ctrl,
"shift", hotkey.Shift,
"alt", hotkey.Alt,
"win", hotkey.Win,
"key", hotkey.Key)
// 转换键码和修饰符
keyCode := hs.keyToX11KeyCode(hotkey.Key)
if keyCode == 0 {
return &HotkeyError{Operation: "convert_key", Err: fmt.Errorf("unsupported key: %s", hotkey.Key)}
}
modifiers := hs.buildX11Modifiers(hotkey)
// 调用C函数注册热键
result := int(C.registerGlobalHotkey(C.int(keyCode), C.uint(modifiers)))
if result == 0 {
return &HotkeyError{Operation: "register_hotkey", Err: fmt.Errorf("failed to register hotkey")}
}
// 创建ready channel等待goroutine启动完成
readyChan := make(chan struct{})
// 确保 stopChan 是新的
hs.stopChan = make(chan struct{})
hs.wg.Add(1)
go hs.hotkeyListener(hotkey, readyChan)
// 等待监听器启动完成,设置超时避免无限等待
select {
case <-readyChan:
// 监听器启动完成
case <-time.After(1 * time.Second):
// 超时处理
hs.logger.Warning("Hotkey: Timeout waiting for listener to start")
return &HotkeyError{Operation: "start_listener", Err: fmt.Errorf("timeout waiting for hotkey listener to start")}
}
hs.currentHotkey = hotkey
hs.isRegistered = true
hs.running = true
hs.logger.Info("Hotkey: Successfully registered global hotkey on Linux")
return nil
}
// UnregisterHotkey 取消注册全局热键
func (hs *HotkeyService) UnregisterHotkey() error {
hs.mu.Lock()
defer hs.mu.Unlock()
return hs.unregisterHotkeyInternal()
}
// unregisterHotkeyInternal 内部取消注册方法(无锁)
func (hs *HotkeyService) unregisterHotkeyInternal() error {
if !hs.isRegistered {
hs.logger.Debug("Hotkey: No hotkey registered, skipping unregister")
return nil
}
hs.logger.Info("Hotkey: Unregistering global hotkey on Linux")
// 停止监听
if hs.stopChan != nil {
close(hs.stopChan)
hs.logger.Debug("Hotkey: Waiting for listener goroutine to stop")
hs.wg.Wait()
hs.logger.Debug("Hotkey: Listener goroutine stopped")
}
// 调用C函数取消注册热键
result := int(C.unregisterGlobalHotkey())
if result == 0 {
return &HotkeyError{Operation: "unregister_hotkey", Err: fmt.Errorf("failed to unregister hotkey")}
}
// 重置状态
hs.currentHotkey = nil
hs.isRegistered = false
hs.running = false
hs.stopChan = nil
hs.logger.Info("Hotkey: Successfully unregistered global hotkey on Linux")
return nil
}
// UpdateHotkey 更新热键配置
func (hs *HotkeyService) UpdateHotkey(enable bool, hotkey *models.HotkeyCombo) error {
hs.logger.Info("Hotkey: === UpdateHotkey called (Linux) ===",
"enable", enable,
"ctrl", hotkey.Ctrl,
"shift", hotkey.Shift,
"alt", hotkey.Alt,
"win", hotkey.Win,
"key", hotkey.Key)
if enable {
// 启用热键直接注册新热键RegisterHotkey 会处理取消旧热键)
err := hs.RegisterHotkey(hotkey)
if err != nil {
hs.logger.Error("Hotkey: Failed to register new hotkey", "error", err)
return err
}
hs.logger.Info("Hotkey: Successfully updated and registered new hotkey on Linux")
return nil
} else {
// 禁用热键:取消注册
err := hs.UnregisterHotkey()
if err != nil {
hs.logger.Error("Hotkey: Failed to unregister hotkey", "error", err)
return err
}
hs.logger.Info("Hotkey: Successfully disabled hotkey on Linux")
return nil
}
}
// ToggleWindow 切换窗口显示/隐藏
func (hs *HotkeyService) ToggleWindow() {
if hs.app == nil {
hs.logger.Warning("Hotkey: App is nil, cannot toggle")
return
}
// 发送事件到前端,让前端处理窗口切换
hs.app.EmitEvent("hotkey:toggle-window", nil)
hs.logger.Debug("Hotkey: Emitted toggle window event (Linux)")
}
// hotkeyListener 热键监听器goroutine
func (hs *HotkeyService) hotkeyListener(hotkey *models.HotkeyCombo, readyChan chan struct{}) {
defer hs.wg.Done()
hs.logger.Debug("Hotkey: Starting Linux X11 hotkey listener")
// 检查间隔100ms
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
// 标记是否已经发送ready信号确保只发送一次
readySent := false
for {
select {
case <-hs.stopChan:
hs.logger.Debug("Hotkey: Stopping Linux X11 hotkey listener")
if !readySent {
close(readyChan)
}
return
case <-ticker.C:
// 第一次循环时发送ready信号表示监听器已经准备就绪
if !readySent {
close(readyChan)
readySent = true
hs.logger.Debug("Hotkey: Listener ready signal sent")
}
// 检查热键事件
if int(C.checkHotkeyEvent()) == 1 {
hs.logger.Debug("Hotkey: Global hotkey triggered via Linux X11")
hs.ToggleWindow()
}
}
}
}
// keyToX11KeyCode 将键名转换为X11键码
func (hs *HotkeyService) keyToX11KeyCode(key string) int {
// 将Go字符串转换为C字符串
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 {
return false
}
// 必须有主键
if 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 {
hs.mu.RLock()
defer hs.mu.RUnlock()
return hs.isRegistered
}
// ServiceShutdown 关闭热键服务
func (hs *HotkeyService) ServiceShutdown() error {
hs.mu.Lock()
defer hs.mu.Unlock()
if hs.isRegistered {
err := hs.unregisterHotkeyInternal()
if err != nil {
hs.logger.Error("Hotkey: Failed to unregister hotkey on shutdown", "error", err)
}
}
// 关闭X11显示
C.closeX11Display()
hs.logger.Info("Hotkey: Linux service shutdown completed")
return nil
}

View File

@@ -0,0 +1,85 @@
//go:build !windows && !darwin && !linux
package services
import (
"fmt"
"voidraft/internal/models"
"github.com/wailsapp/wails/v3/pkg/application"
"github.com/wailsapp/wails/v3/pkg/services/log"
)
// HotkeyService 全局热键服务
type HotkeyService struct {
logger *log.LoggerService
configService *ConfigService
}
// HotkeyError 热键错误
type HotkeyError struct {
Operation string
Err error
}
// Error 实现error接口
func (e *HotkeyError) Error() string {
return fmt.Sprintf("hotkey error during %s: %v", e.Operation, e.Err)
}
// Unwrap 获取原始错误
func (e *HotkeyError) Unwrap() error {
return e.Err
}
// NewHotkeyService 创建新的热键服务实例
func NewHotkeyService(configService *ConfigService, logger *log.LoggerService) *HotkeyService {
if logger == nil {
logger = log.New()
}
return &HotkeyService{
logger: logger,
configService: configService,
}
}
// Initialize 初始化热键服务
func (hs *HotkeyService) Initialize(app *application.App) error {
hs.logger.Warning("Hotkey: Global hotkey is not supported on this platform")
return nil
}
// RegisterHotkey 注册全局热键
func (hs *HotkeyService) RegisterHotkey(hotkey *models.HotkeyCombo) error {
return &HotkeyError{Operation: "register", Err: fmt.Errorf("not supported on this platform")}
}
// UnregisterHotkey 取消注册全局热键
func (hs *HotkeyService) UnregisterHotkey() error {
return &HotkeyError{Operation: "unregister", Err: fmt.Errorf("not supported on this platform")}
}
// UpdateHotkey 更新热键配置
func (hs *HotkeyService) UpdateHotkey(enable bool, hotkey *models.HotkeyCombo) error {
if enable {
return hs.RegisterHotkey(hotkey)
} else {
return hs.UnregisterHotkey()
}
}
// GetCurrentHotkey 获取当前注册的热键
func (hs *HotkeyService) GetCurrentHotkey() *models.HotkeyCombo {
return nil
}
// IsRegistered 检查是否已注册热键
func (hs *HotkeyService) IsRegistered() bool {
return false
}
// ServiceShutdown 关闭热键服务
func (hs *HotkeyService) ServiceShutdown() error {
return nil
}

View File

@@ -1,6 +1,8 @@
package services
import (
"voidraft/internal/models"
"github.com/wailsapp/wails/v3/pkg/application"
"github.com/wailsapp/wails/v3/pkg/services/log"
)
@@ -10,6 +12,7 @@ type ServiceManager struct {
configService *ConfigService
documentService *DocumentService
systemService *SystemService
hotkeyService *HotkeyService
logger *log.LoggerService
}
@@ -27,6 +30,14 @@ func NewServiceManager() *ServiceManager {
// 初始化系统服务
systemService := NewSystemService(logger)
// 初始化热键服务
hotkeyService := NewHotkeyService(configService, logger)
// 设置热键配置变更回调
configService.SetHotkeyChangeCallback(func(enable bool, hotkey *models.HotkeyCombo) error {
return hotkeyService.UpdateHotkey(enable, hotkey)
})
// 初始化文档服务
err := documentService.Initialize()
if err != nil {
@@ -38,6 +49,7 @@ func NewServiceManager() *ServiceManager {
configService: configService,
documentService: documentService,
systemService: systemService,
hotkeyService: hotkeyService,
logger: logger,
}
}
@@ -48,5 +60,11 @@ func (sm *ServiceManager) GetServices() []application.Service {
application.NewService(sm.configService),
application.NewService(sm.documentService),
application.NewService(sm.systemService),
application.NewService(sm.hotkeyService),
}
}
// GetHotkeyService 获取热键服务实例
func (sm *ServiceManager) GetHotkeyService() *HotkeyService {
return sm.hotkeyService
}

13
main.go
View File

@@ -92,6 +92,17 @@ func main() {
// 设置系统托盘
systray.SetupSystemTray(app, mainWindow, assets)
// 初始化热键服务
hotkeyService := serviceManager.GetHotkeyService()
err := hotkeyService.Initialize(app)
if err != nil {
log.Printf("Failed to initialize hotkey service: %v\n", err)
panic(err)
}
// 设置全局变量供单实例处理使用
window = mainWindow
// Create a goroutine that emits an event containing the current time every second.
// The frontend can listen to this event and update the UI accordingly.
go func() {
@@ -103,7 +114,7 @@ func main() {
}()
// Run the application. This blocks until the application has been exited.
err := app.Run()
err = app.Run()
// If an error occurred while running the application, log it and exit.
if err != nil {