5 Commits

Author SHA1 Message Date
709998ff9c 🐛 Fixed hotkey crashes 2025-08-19 22:26:55 +08:00
6adeadeed4 🐛 Fixed document deadlock issue 2025-08-19 00:24:51 +08:00
7b70a39b23 🐛 Fixed hotkey service issues 2025-08-19 00:08:50 +08:00
873a3c0e60 Modify the theme storage schema 2025-08-17 19:34:35 +08:00
5b88efcfbe 🐛 Fixed the window toggle maximise issue 2025-08-17 14:51:39 +08:00
44 changed files with 1500 additions and 1087 deletions

View File

@@ -114,11 +114,6 @@ export class AppearanceConfig {
*/
"systemTheme": SystemThemeType;
/**
* 自定义主题配置
*/
"customTheme": CustomThemeConfig;
/** Creates a new AppearanceConfig instance. */
constructor($$source: Partial<AppearanceConfig> = {}) {
if (!("language" in $$source)) {
@@ -127,9 +122,6 @@ export class AppearanceConfig {
if (!("systemTheme" in $$source)) {
this["systemTheme"] = ("" as SystemThemeType);
}
if (!("customTheme" in $$source)) {
this["customTheme"] = (new CustomThemeConfig());
}
Object.assign(this, $$source);
}
@@ -138,11 +130,7 @@ export class AppearanceConfig {
* Creates a new AppearanceConfig instance from a string or object.
*/
static createFrom($$source: any = {}): AppearanceConfig {
const $$createField2_0 = $$createType6;
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
if ("customTheme" in $$parsedSource) {
$$parsedSource["customTheme"] = $$createField2_0($$parsedSource["customTheme"]);
}
return new AppearanceConfig($$parsedSource as Partial<AppearanceConfig>);
}
}
@@ -201,49 +189,6 @@ export class ConfigMetadata {
}
}
/**
* CustomThemeConfig 自定义主题配置
*/
export class CustomThemeConfig {
/**
* 深色主题配置
*/
"darkTheme": ThemeColorConfig;
/**
* 浅色主题配置
*/
"lightTheme": ThemeColorConfig;
/** Creates a new CustomThemeConfig instance. */
constructor($$source: Partial<CustomThemeConfig> = {}) {
if (!("darkTheme" in $$source)) {
this["darkTheme"] = (new ThemeColorConfig());
}
if (!("lightTheme" in $$source)) {
this["lightTheme"] = (new ThemeColorConfig());
}
Object.assign(this, $$source);
}
/**
* Creates a new CustomThemeConfig instance from a string or object.
*/
static createFrom($$source: any = {}): CustomThemeConfig {
const $$createField0_0 = $$createType7;
const $$createField1_0 = $$createType7;
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
if ("darkTheme" in $$parsedSource) {
$$parsedSource["darkTheme"] = $$createField0_0($$parsedSource["darkTheme"]);
}
if ("lightTheme" in $$parsedSource) {
$$parsedSource["lightTheme"] = $$createField1_0($$parsedSource["lightTheme"]);
}
return new CustomThemeConfig($$parsedSource as Partial<CustomThemeConfig>);
}
}
/**
* Document represents a document in the system
*/
@@ -428,7 +373,7 @@ export class Extension {
* Creates a new Extension instance from a string or object.
*/
static createFrom($$source: any = {}): Extension {
const $$createField3_0 = $$createType8;
const $$createField3_0 = $$createType6;
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
if ("config" in $$parsedSource) {
$$parsedSource["config"] = $$createField3_0($$parsedSource["config"]);
@@ -561,7 +506,7 @@ export class GeneralConfig {
* Creates a new GeneralConfig instance from a string or object.
*/
static createFrom($$source: any = {}): GeneralConfig {
const $$createField5_0 = $$createType10;
const $$createField5_0 = $$createType8;
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
if ("globalHotkey" in $$parsedSource) {
$$parsedSource["globalHotkey"] = $$createField5_0($$parsedSource["globalHotkey"]);
@@ -1171,6 +1116,58 @@ export enum TabType {
TabTypeTab = "tab",
};
/**
* Theme 主题数据库模型
*/
export class Theme {
"id": number;
"name": string;
"type": ThemeType;
"colors": ThemeColorConfig;
"isDefault": boolean;
"createdAt": time$0.Time;
"updatedAt": time$0.Time;
/** Creates a new Theme instance. */
constructor($$source: Partial<Theme> = {}) {
if (!("id" in $$source)) {
this["id"] = 0;
}
if (!("name" in $$source)) {
this["name"] = "";
}
if (!("type" in $$source)) {
this["type"] = ("" as ThemeType);
}
if (!("colors" in $$source)) {
this["colors"] = (new ThemeColorConfig());
}
if (!("isDefault" in $$source)) {
this["isDefault"] = false;
}
if (!("createdAt" in $$source)) {
this["createdAt"] = null;
}
if (!("updatedAt" in $$source)) {
this["updatedAt"] = null;
}
Object.assign(this, $$source);
}
/**
* Creates a new Theme instance from a string or object.
*/
static createFrom($$source: any = {}): Theme {
const $$createField3_0 = $$createType9;
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
if ("colors" in $$parsedSource) {
$$parsedSource["colors"] = $$createField3_0($$parsedSource["colors"]);
}
return new Theme($$parsedSource as Partial<Theme>);
}
}
/**
* ThemeColorConfig 主题颜色配置
*/
@@ -1379,6 +1376,19 @@ export class ThemeColorConfig {
}
}
/**
* ThemeType 主题类型枚举
*/
export enum ThemeType {
/**
* The Go zero value for the underlying type of the enum.
*/
$zero = "",
ThemeTypeDark = "dark",
ThemeTypeLight = "light",
};
/**
* UpdateSourceType 更新源类型
*/
@@ -1477,8 +1487,8 @@ export class UpdatesConfig {
* Creates a new UpdatesConfig instance from a string or object.
*/
static createFrom($$source: any = {}): UpdatesConfig {
const $$createField6_0 = $$createType11;
const $$createField7_0 = $$createType12;
const $$createField6_0 = $$createType10;
const $$createField7_0 = $$createType11;
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
if ("github" in $$parsedSource) {
$$parsedSource["github"] = $$createField6_0($$parsedSource["github"]);
@@ -1497,15 +1507,14 @@ const $$createType2 = AppearanceConfig.createFrom;
const $$createType3 = UpdatesConfig.createFrom;
const $$createType4 = GitBackupConfig.createFrom;
const $$createType5 = ConfigMetadata.createFrom;
const $$createType6 = CustomThemeConfig.createFrom;
const $$createType7 = ThemeColorConfig.createFrom;
var $$createType8 = (function $$initCreateType8(...args): any {
if ($$createType8 === $$initCreateType8) {
$$createType8 = $$createType9;
var $$createType6 = (function $$initCreateType6(...args): any {
if ($$createType6 === $$initCreateType6) {
$$createType6 = $$createType7;
}
return $$createType8(...args);
return $$createType6(...args);
});
const $$createType9 = $Create.Map($Create.Any, $Create.Any);
const $$createType10 = HotkeyCombo.createFrom;
const $$createType11 = GithubConfig.createFrom;
const $$createType12 = GiteaConfig.createFrom;
const $$createType7 = $Create.Map($Create.Any, $Create.Any);
const $$createType8 = HotkeyCombo.createFrom;
const $$createType9 = ThemeColorConfig.createFrom;
const $$createType10 = GithubConfig.createFrom;
const $$createType11 = GiteaConfig.createFrom;

View File

@@ -32,8 +32,8 @@ export function GetCurrentHotkey(): Promise<models$0.HotkeyCombo | null> & { can
/**
* Initialize 初始化热键服务
*/
export function Initialize(app: application$0.App | null): Promise<void> & { cancel(): void } {
let $resultPromise = $Call.ByID(3671360458, app) as any;
export function Initialize(app: application$0.App | null, mainWindow: application$0.WebviewWindow | null): Promise<void> & { cancel(): void } {
let $resultPromise = $Call.ByID(3671360458, app, mainWindow) as any;
return $resultPromise;
}

View File

@@ -13,6 +13,7 @@ import * as MigrationService from "./migrationservice.js";
import * as SelfUpdateService from "./selfupdateservice.js";
import * as StartupService from "./startupservice.js";
import * as SystemService from "./systemservice.js";
import * as ThemeService from "./themeservice.js";
import * as TranslationService from "./translationservice.js";
import * as TrayService from "./trayservice.js";
import * as WindowService from "./windowservice.js";
@@ -29,6 +30,7 @@ export {
SelfUpdateService,
StartupService,
SystemService,
ThemeService,
TranslationService,
TrayService,
WindowService

View File

@@ -0,0 +1,104 @@
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
// This file is automatically generated. DO NOT EDIT
/**
* ThemeService 主题服务
* @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 application$0 from "../../../github.com/wailsapp/wails/v3/pkg/application/models.js";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: Unused imports
import * as models$0 from "../models/models.js";
/**
* CreateTheme 创建新主题
*/
export function CreateTheme(theme: models$0.Theme | null): Promise<models$0.Theme | null> & { cancel(): void } {
let $resultPromise = $Call.ByID(3274757686, theme) as any;
let $typingPromise = $resultPromise.then(($result: any) => {
return $$createType1($result);
}) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
return $typingPromise;
}
/**
* GetAllThemes 获取所有主题
*/
export function GetAllThemes(): Promise<(models$0.Theme | null)[]> & { cancel(): void } {
let $resultPromise = $Call.ByID(2425053076) as any;
let $typingPromise = $resultPromise.then(($result: any) => {
return $$createType2($result);
}) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
return $typingPromise;
}
/**
* GetDefaultThemes 获取默认主题
*/
export function GetDefaultThemes(): Promise<{ [_: string]: models$0.Theme | null }> & { cancel(): void } {
let $resultPromise = $Call.ByID(3801788118) as any;
let $typingPromise = $resultPromise.then(($result: any) => {
return $$createType3($result);
}) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
return $typingPromise;
}
/**
* GetThemeByType 根据类型获取默认主题
*/
export function GetThemeByType(themeType: models$0.ThemeType): Promise<models$0.Theme | null> & { cancel(): void } {
let $resultPromise = $Call.ByID(1680465265, themeType) as any;
let $typingPromise = $resultPromise.then(($result: any) => {
return $$createType1($result);
}) as any;
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
return $typingPromise;
}
/**
* ResetThemeColors 重置主题颜色为默认值
*/
export function ResetThemeColors(themeType: models$0.ThemeType): Promise<void> & { cancel(): void } {
let $resultPromise = $Call.ByID(342461245, themeType) as any;
return $resultPromise;
}
/**
* ServiceShutdown 服务关闭
*/
export function ServiceShutdown(): Promise<void> & { cancel(): void } {
let $resultPromise = $Call.ByID(1676749034) as any;
return $resultPromise;
}
/**
* ServiceStartup 服务启动时初始化
*/
export function ServiceStartup(options: application$0.ServiceOptions): Promise<void> & { cancel(): void } {
let $resultPromise = $Call.ByID(2915959937, options) as any;
return $resultPromise;
}
/**
* UpdateThemeColors 更新主题颜色
*/
export function UpdateThemeColors(themeType: models$0.ThemeType, colors: models$0.ThemeColorConfig): Promise<void> & { cancel(): void } {
let $resultPromise = $Call.ByID(2750902529, themeType, colors) as any;
return $resultPromise;
}
// Private type creation functions
const $$createType0 = models$0.Theme.createFrom;
const $$createType1 = $Create.Nullable($$createType0);
const $$createType2 = $Create.Array($$createType1);
const $$createType3 = $Create.Map($Create.Any, $$createType1);

File diff suppressed because it is too large Load Diff

View File

@@ -24,18 +24,18 @@
"@codemirror/lang-json": "^6.0.2",
"@codemirror/lang-less": "^6.0.2",
"@codemirror/lang-lezer": "^6.0.2",
"@codemirror/lang-liquid": "^6.2.3",
"@codemirror/lang-markdown": "^6.3.3",
"@codemirror/lang-liquid": "^6.3.0",
"@codemirror/lang-markdown": "^6.3.4",
"@codemirror/lang-php": "^6.0.2",
"@codemirror/lang-python": "^6.2.1",
"@codemirror/lang-rust": "^6.0.2",
"@codemirror/lang-sass": "^6.0.2",
"@codemirror/lang-sql": "^6.9.0",
"@codemirror/lang-sql": "^6.9.1",
"@codemirror/lang-vue": "^0.1.3",
"@codemirror/lang-wast": "^6.0.2",
"@codemirror/lang-xml": "^6.1.0",
"@codemirror/lang-yaml": "^6.1.2",
"@codemirror/language": "^6.11.2",
"@codemirror/language": "^6.11.3",
"@codemirror/language-data": "^6.5.1",
"@codemirror/legacy-modes": "^6.5.1",
"@codemirror/lint": "^6.8.5",
@@ -52,30 +52,30 @@
"hsl-matcher": "^1.2.4",
"lezer": "^0.13.5",
"pinia": "^3.0.3",
"pinia-plugin-persistedstate": "^4.4.1",
"pinia-plugin-persistedstate": "^4.5.0",
"prettier": "^3.6.2",
"remarkable": "^2.0.1",
"sass": "^1.89.2",
"vue": "^3.5.17",
"vue-i18n": "^11.1.10",
"sass": "^1.90.0",
"vue": "^3.5.18",
"vue-i18n": "^11.1.11",
"vue-pick-colors": "^1.8.0",
"vue-router": "^4.5.1"
},
"devDependencies": {
"@eslint/js": "^9.31.0",
"@eslint/js": "^9.33.0",
"@lezer/generator": "^1.8.0",
"@types/node": "^24.0.14",
"@types/node": "^24.3.0",
"@types/remarkable": "^2.0.8",
"@vitejs/plugin-vue": "^6.0.0",
"@vitejs/plugin-vue": "^6.0.1",
"@wailsio/runtime": "latest",
"eslint": "^9.31.0",
"eslint-plugin-vue": "^10.3.0",
"eslint": "^9.33.0",
"eslint-plugin-vue": "^10.4.0",
"globals": "^16.3.0",
"typescript": "^5.8.3",
"typescript-eslint": "^8.37.0",
"unplugin-vue-components": "^28.8.0",
"vite": "^7.0.4",
"typescript": "^5.9.2",
"typescript-eslint": "^8.39.1",
"unplugin-vue-components": "^29.0.0",
"vite": "^7.1.2",
"vue-eslint-parser": "^10.2.0",
"vue-tsc": "^3.0.1"
"vue-tsc": "^3.0.5"
}
}

View File

@@ -2,26 +2,26 @@
<div class="linux-titlebar" style="--wails-draggable:drag" @contextmenu.prevent>
<div class="titlebar-content" @dblclick="toggleMaximize" @contextmenu.prevent>
<div class="titlebar-icon">
<img src="/appicon.png" alt="voidraft" />
<img src="/appicon.png" alt="voidraft"/>
</div>
<div class="titlebar-title">{{ titleText }}</div>
</div>
<div class="titlebar-controls" style="--wails-draggable:no-drag" @contextmenu.prevent>
<button
class="titlebar-button minimize-button"
@click="minimizeWindow"
:title="t('titlebar.minimize')"
<button
class="titlebar-button minimize-button"
@click="minimizeWindow"
:title="t('titlebar.minimize')"
>
<svg width="16" height="16" viewBox="0 0 16 16">
<path d="M4 8h8" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
</svg>
</button>
<button
class="titlebar-button maximize-button"
@click="toggleMaximize"
:title="isMaximized ? t('titlebar.restore') : t('titlebar.maximize')"
<button
class="titlebar-button maximize-button"
@click="toggleMaximize"
:title="isMaximized ? t('titlebar.restore') : t('titlebar.maximize')"
>
<svg width="16" height="16" viewBox="0 0 16 16" v-if="!isMaximized">
<rect x="4" y="4" width="8" height="8" fill="none" stroke="currentColor" stroke-width="2"/>
@@ -31,11 +31,11 @@
<rect x="7" y="3" width="6" height="6" fill="none" stroke="currentColor" stroke-width="1.5"/>
</svg>
</button>
<button
class="titlebar-button close-button"
@click="closeWindow"
:title="t('titlebar.close')"
<button
class="titlebar-button close-button"
@click="closeWindow"
:title="t('titlebar.close')"
>
<svg width="16" height="16" viewBox="0 0 16 16">
<path d="M4 4l8 8m0-8L4 12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
@@ -46,85 +46,56 @@
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import {computed, onMounted, ref} from 'vue';
import {useI18n} from 'vue-i18n';
import * as runtime from '@wailsio/runtime';
import { useWindowStore } from '@/stores/windowStore';
import { useDocumentStore } from '@/stores/documentStore';
import {useDocumentStore} from '@/stores/documentStore';
const { t } = useI18n();
const {t} = useI18n();
const isMaximized = ref(false);
const documentStore = useDocumentStore();
const minimizeWindow = async () => {
try {
await runtime.Window.Minimise();
} catch (error) {
// Error handling
}
};
const toggleMaximize = async () => {
try {
const newState = !isMaximized.value;
isMaximized.value = newState;
if (newState) {
await runtime.Window.Maximise();
} else {
await runtime.Window.UnMaximise();
}
setTimeout(async () => {
await checkMaximizedState();
}, 100);
} catch (error) {
isMaximized.value = !isMaximized.value;
}
};
const closeWindow = async () => {
try {
await runtime.Window.Close();
} catch (error) {
// Error handling
}
};
const checkMaximizedState = async () => {
try {
isMaximized.value = await runtime.Window.IsMaximised();
} catch (error) {
// Error handling
}
};
// 计算标题文本
const titleText = computed(() => {
const currentDoc = documentStore.currentDocument;
return currentDoc ? `voidraft - ${currentDoc.title}` : 'voidraft';
});
const minimizeWindow = async () => {
try {
await runtime.Window.Minimise();
} catch (error) {
console.error(error);
}
};
const toggleMaximize = async () => {
try {
await runtime.Window.ToggleMaximise();
await checkMaximizedState();
} catch (error) {
console.error(error);
}
};
const closeWindow = async () => {
try {
await runtime.Window.Close();
} catch (error) {
console.error(error);
}
};
const checkMaximizedState = async () => {
try {
isMaximized.value = await runtime.Window.IsMaximised();
} catch (error) {
console.error(error);
}
};
onMounted(async () => {
await checkMaximizedState();
runtime.Events.On('window:maximised', () => {
isMaximized.value = true;
});
runtime.Events.On('window:unmaximised', () => {
isMaximized.value = false;
});
runtime.Events.On('window:focus', async () => {
await checkMaximizedState();
});
});
onUnmounted(() => {
runtime.Events.Off('window:maximised');
runtime.Events.Off('window:unmaximised');
runtime.Events.Off('window:focus');
});
</script>
@@ -139,7 +110,7 @@ onUnmounted(() => {
width: 100%;
font-family: 'Ubuntu', 'Cantarell', 'DejaVu Sans', system-ui, sans-serif;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
-webkit-context-menu: none;
-moz-context-menu: none;
context-menu: none;
@@ -155,7 +126,7 @@ onUnmounted(() => {
font-size: 13px;
font-weight: 500;
cursor: default;
-webkit-context-menu: none;
-moz-context-menu: none;
context-menu: none;
@@ -164,7 +135,7 @@ onUnmounted(() => {
.titlebar-content .titlebar-icon {
width: 16px;
height: 16px;
img {
width: 100%;
height: 100%;
@@ -181,7 +152,7 @@ onUnmounted(() => {
.titlebar-controls {
display: flex;
height: 100%;
-webkit-context-menu: none;
-moz-context-menu: none;
context-menu: none;
@@ -201,22 +172,22 @@ onUnmounted(() => {
padding: 0;
margin: 0;
border-radius: 0;
svg {
width: 16px;
height: 16px;
opacity: 0.8;
transition: opacity 0.15s ease;
}
&:hover {
background: var(--toolbar-button-hover, rgba(0, 0, 0, 0.1));
svg {
opacity: 1;
}
}
&:active {
background: var(--toolbar-button-active, rgba(0, 0, 0, 0.15));
}
@@ -226,12 +197,12 @@ onUnmounted(() => {
&:hover {
background: #e74c3c;
color: #ffffff;
svg {
opacity: 1;
}
}
&:active {
background: #c0392b;
}
@@ -244,19 +215,19 @@ onUnmounted(() => {
border-bottom-color: var(--toolbar-border, #1e1e1e);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
}
.titlebar-content,
.titlebar-title {
color: var(--toolbar-text, #f0f0f0);
}
.titlebar-button {
color: var(--toolbar-text, #ccc);
&:hover {
background: var(--toolbar-button-hover, rgba(255, 255, 255, 0.1));
}
&:active {
background: var(--toolbar-button-active, rgba(255, 255, 255, 0.15));
}
@@ -267,13 +238,13 @@ onUnmounted(() => {
.linux-titlebar.gnome-style {
height: 38px;
border-radius: 12px 12px 0 0;
.titlebar-button {
height: 38px;
width: 32px;
border-radius: 6px;
margin: 3px 2px;
&:hover {
background: rgba(255, 255, 255, 0.1);
}
@@ -284,11 +255,11 @@ onUnmounted(() => {
.linux-titlebar.kde-style {
background: var(--toolbar-bg, #eff0f1);
border-bottom: 1px solid var(--toolbar-border, #bdc3c7);
.titlebar-button {
border-radius: 4px;
margin: 2px 1px;
&:hover {
background: rgba(61, 174, 233, 0.2);
}

View File

@@ -53,7 +53,6 @@
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import * as runtime from '@wailsio/runtime';
import { useWindowStore } from '@/stores/windowStore';
import { useDocumentStore } from '@/stores/documentStore';
const { t } = useI18n();
@@ -65,26 +64,16 @@ const minimizeWindow = async () => {
try {
await runtime.Window.Minimise();
} catch (error) {
// Error handling
console.error(error)
}
};
const toggleMaximize = async () => {
try {
const newState = !isMaximized.value;
isMaximized.value = newState;
if (newState) {
await runtime.Window.Maximise();
} else {
await runtime.Window.UnMaximise();
}
setTimeout(async () => {
await checkMaximizedState();
}, 100);
await runtime.Window.ToggleMaximise();
await checkMaximizedState();
} catch (error) {
isMaximized.value = !isMaximized.value;
console.error(error)
}
};
@@ -92,7 +81,7 @@ const closeWindow = async () => {
try {
await runtime.Window.Close();
} catch (error) {
// Error handling
console.error(error)
}
};
@@ -100,7 +89,7 @@ const checkMaximizedState = async () => {
try {
isMaximized.value = await runtime.Window.IsMaximised();
} catch (error) {
// Error handling
console.error(error)
}
};
@@ -112,24 +101,6 @@ const titleText = computed(() => {
onMounted(async () => {
await checkMaximizedState();
runtime.Events.On('window:maximised', () => {
isMaximized.value = true;
});
runtime.Events.On('window:unmaximised', () => {
isMaximized.value = false;
});
runtime.Events.On('window:focus', async () => {
await checkMaximizedState();
});
});
onUnmounted(() => {
runtime.Events.Off('window:maximised');
runtime.Events.Off('window:unmaximised');
runtime.Events.Off('window:focus');
});
</script>

View File

@@ -1,5 +1,5 @@
<template>
<div class="windows-titlebar" style="--wails-draggable:drag" @contextmenu.prevent>
<div class="windows-titlebar" style="--wails-draggable:drag">
<div class="titlebar-content" @dblclick="toggleMaximize" @contextmenu.prevent>
<div class="titlebar-icon">
<img src="/appicon.png" alt="voidraft"/>
@@ -36,11 +36,10 @@
</template>
<script setup lang="ts">
import {computed, onMounted, onUnmounted, ref} from 'vue';
import {computed, onMounted, ref} from 'vue';
import {useI18n} from 'vue-i18n';
import * as runtime from '@wailsio/runtime';
import { useWindowStore } from '@/stores/windowStore';
import { useDocumentStore } from '@/stores/documentStore';
import {useDocumentStore} from '@/stores/documentStore';
const {t} = useI18n();
const isMaximized = ref(false);
@@ -59,30 +58,16 @@ const minimizeWindow = async () => {
try {
await runtime.Window.Minimise();
} catch (error) {
// Error handling
console.error(error);
}
};
const toggleMaximize = async () => {
try {
// 立即更新UI状态提供即时反馈
const newState = !isMaximized.value;
isMaximized.value = newState;
// 然后执行实际操作
if (newState) {
await runtime.Window.Maximise();
} else {
await runtime.Window.UnMaximise();
}
// 操作完成后再次确认状态(防止操作失败时状态不一致)
setTimeout(async () => {
await checkMaximizedState();
}, 100);
await runtime.Window.ToggleMaximise();
await checkMaximizedState();
} catch (error) {
// 如果操作失败,恢复原状态
isMaximized.value = !isMaximized.value;
console.error(error);
}
};
@@ -90,7 +75,7 @@ const closeWindow = async () => {
try {
await runtime.Window.Close();
} catch (error) {
// Error handling
console.error(error);
}
};
@@ -98,31 +83,12 @@ const checkMaximizedState = async () => {
try {
isMaximized.value = await runtime.Window.IsMaximised();
} catch (error) {
// Error handling
console.error(error);
}
};
onMounted(async () => {
await checkMaximizedState();
runtime.Events.On('window:maximised', () => {
isMaximized.value = true;
});
runtime.Events.On('window:unmaximised', () => {
isMaximized.value = false;
});
runtime.Events.On('window:focus', async () => {
await checkMaximizedState();
});
});
onUnmounted(() => {
runtime.Events.Off('window:maximised');
runtime.Events.Off('window:unmaximised');
runtime.Events.Off('window:focus');
});
</script>

View File

@@ -107,6 +107,12 @@ const selectItem = async (item: any) => {
// 选择文档
const selectDoc = async (doc: Document) => {
try {
// 如果选择的就是当前文档,直接关闭菜单
if (documentStore.currentDocument?.id === doc.id) {
closeMenu();
return;
}
const hasOpen = await windowStore.isDocumentWindowOpen(doc.id);
if (hasOpen) {
// 设置错误状态并启动定时器
@@ -208,7 +214,7 @@ const openInNewWindow = async (doc: Document, event: Event) => {
}
};
// 处理删除 - 简化确认机制
// 处理删除
const handleDelete = async (doc: Document, event: Event) => {
event.stopPropagation();
@@ -236,9 +242,13 @@ const handleDelete = async (doc: Document, event: Event) => {
return;
}
await documentStore.deleteDocument(doc.id);
await documentStore.updateDocuments();
const deleteSuccess = await documentStore.deleteDocument(doc.id);
if (!deleteSuccess) {
return;
}
await documentStore.updateDocuments();
// 如果删除的是当前文档,切换到第一个文档
if (documentStore.currentDocument?.id === doc.id && documentStore.documentList.length > 0) {
const firstDoc = documentStore.documentList[0];

View File

@@ -16,9 +16,7 @@ import {
} from '@/../bindings/voidraft/internal/models/models';
import {useI18n} from 'vue-i18n';
import {ConfigUtils} from '@/utils/configUtils';
import {WindowController} from '@/utils/windowController';
import * as runtime from '@wailsio/runtime';
import {useBackupStore} from '@/stores/backupStore';
// 国际化相关导入
export type SupportedLocaleType = 'zh-CN' | 'en-US';
@@ -80,8 +78,7 @@ const EDITING_CONFIG_KEY_MAP: EditingConfigKeyMap = {
const APPEARANCE_CONFIG_KEY_MAP: AppearanceConfigKeyMap = {
language: 'appearance.language',
systemTheme: 'appearance.systemTheme',
customTheme: 'appearance.customTheme'
systemTheme: 'appearance.systemTheme'
} as const;
const UPDATES_CONFIG_KEY_MAP: UpdatesConfigKeyMap = {
@@ -191,80 +188,10 @@ const DEFAULT_CONFIG: AppConfig = {
tabType: CONFIG_LIMITS.tabType.default,
autoSaveDelay: 5000
},
appearance: {
language: LanguageType.LangZhCN,
systemTheme: SystemThemeType.SystemThemeAuto,
customTheme: {
darkTheme: {
// 基础色调
background: '#252B37',
backgroundSecondary: '#213644',
surface: '#474747',
foreground: '#9BB586',
foregroundSecondary: '#9c9c9c',
// 语法高亮
comment: '#6272a4',
keyword: '#ff79c6',
string: '#f1fa8c',
function: '#50fa7b',
number: '#bd93f9',
operator: '#ff79c6',
variable: '#8fbcbb',
type: '#8be9fd',
// 界面元素
cursor: '#fff',
selection: '#0865a9aa',
selectionBlur: '#225377aa',
activeLine: 'rgba(255,255,255,0.04)',
lineNumber: 'rgba(255,255,255, 0.15)',
activeLineNumber: 'rgba(255,255,255, 0.6)',
// 边框分割线
borderColor: '#1e222a',
borderLight: 'rgba(255,255,255, 0.1)',
// 搜索匹配
searchMatch: '#8fbcbb',
matchingBracket: 'rgba(255,255,255,0.1)'
},
lightTheme: {
// 基础色调
background: '#ffffff',
backgroundSecondary: '#f1faf1',
surface: '#f5f5f5',
foreground: '#444d56',
foregroundSecondary: '#6a737d',
// 语法高亮
comment: '#6a737d',
keyword: '#d73a49',
string: '#032f62',
function: '#005cc5',
number: '#005cc5',
operator: '#d73a49',
variable: '#24292e',
type: '#6f42c1',
// 界面元素
cursor: '#000',
selection: '#77baff8c',
selectionBlur: '#b2c2ca85',
activeLine: '#000000',
lineNumber: '#000000',
activeLineNumber: '#000000',
// 边框分割线
borderColor: '#dfdfdf',
borderLight: '#0000000C',
// 搜索匹配
searchMatch: '#005cc5',
matchingBracket: 'rgba(0,0,0,0.1)'
}
}
},
appearance: {
language: LanguageType.LangZhCN,
systemTheme: SystemThemeType.SystemThemeAuto
},
updates: {
version: "1.0.0",
autoUpdate: true,
@@ -416,9 +343,6 @@ export const useConfigStore = defineStore('config', () => {
state.configLoaded = true;
// 初始化热键监听器
const windowController = WindowController.getInstance();
await windowController.initializeHotkeyListener();
} finally {
state.isLoading = false;
}
@@ -483,50 +407,7 @@ export const useConfigStore = defineStore('config', () => {
await updateAppearanceConfig('systemTheme', systemTheme);
};
// 更新自定义主题方法
const updateCustomTheme = async (themeType: 'darkTheme' | 'lightTheme', colorKey: string, colorValue: string): Promise<void> => {
// 确保配置已加载
if (!state.configLoaded && !state.isLoading) {
await initConfig();
}
try {
// 深拷贝当前配置
const customTheme = JSON.parse(JSON.stringify(state.config.appearance.customTheme));
// 更新对应主题的颜色值
customTheme[themeType][colorKey] = colorValue;
// 更新整个自定义主题配置到后端
await ConfigService.Set(APPEARANCE_CONFIG_KEY_MAP.customTheme, customTheme);
// 更新前端状态
state.config.appearance.customTheme = customTheme;
} catch (error) {
throw error;
}
};
// 设置整个自定义主题配置
const setCustomTheme = async (customTheme: any): Promise<void> => {
// 确保配置已加载
if (!state.configLoaded && !state.isLoading) {
await initConfig();
}
try {
// 更新整个自定义主题配置到后端
await ConfigService.Set(APPEARANCE_CONFIG_KEY_MAP.customTheme, customTheme);
// 更新前端状态
state.config.appearance.customTheme = customTheme;
// 确保Vue能检测到变化
state.config.appearance = { ...state.config.appearance };
} catch (error) {
throw error;
}
};
// 初始化语言设置
const initializeLanguage = async (): Promise<void> => {
@@ -591,8 +472,6 @@ export const useConfigStore = defineStore('config', () => {
// 主题相关方法
setSystemTheme,
updateCustomTheme,
setCustomTheme,
// 字体大小操作
...adjusters.fontSize,

View File

@@ -1,6 +1,7 @@
import {defineStore} from 'pinia';
import {computed, reactive} from 'vue';
import {SystemThemeType} from '@/../bindings/voidraft/internal/models/models';
import {SystemThemeType, ThemeType, ThemeColorConfig} from '@/../bindings/voidraft/internal/models/models';
import {ThemeService} from '@/../bindings/voidraft/internal/services';
import {useConfigStore} from './configStore';
import {useEditorStore} from './editorStore';
import {defaultDarkColors} from '@/views/editor/theme/dark';
@@ -24,16 +25,21 @@ export const useThemeStore = defineStore('theme', () => {
configStore.config?.appearance?.systemTheme || SystemThemeType.SystemThemeAuto
);
// 初始化主题颜色 - 从配置加载
const initializeThemeColors = () => {
const customTheme = configStore.config?.appearance?.customTheme;
if (customTheme) {
if (customTheme.darkTheme) {
Object.assign(themeColors.darkTheme, customTheme.darkTheme);
// 初始化主题颜色 - 从数据库加载
const initializeThemeColors = async () => {
try {
const themes = await ThemeService.GetDefaultThemes();
if (themes.dark) {
Object.assign(themeColors.darkTheme, themes.dark.colors);
}
if (customTheme.lightTheme) {
Object.assign(themeColors.lightTheme, customTheme.lightTheme);
if (themes.light) {
Object.assign(themeColors.lightTheme, themes.light.colors);
}
} catch (error) {
console.warn('Failed to load themes from database, using defaults:', error);
// 如果数据库加载失败,使用默认主题
Object.assign(themeColors.darkTheme, defaultDarkColors);
Object.assign(themeColors.lightTheme, defaultLightColors);
}
};
@@ -46,10 +52,10 @@ export const useThemeStore = defineStore('theme', () => {
};
// 初始化主题
const initializeTheme = () => {
const initializeTheme = async () => {
const theme = configStore.config?.appearance?.systemTheme || SystemThemeType.SystemThemeAuto;
applyThemeToDOM(theme);
initializeThemeColors();
await initializeThemeColors();
};
// 设置主题
@@ -84,31 +90,35 @@ export const useThemeStore = defineStore('theme', () => {
return hasChanges;
};
// 保存主题颜色到配置
// 保存主题颜色到数据库
const saveThemeColors = async () => {
const customTheme = {
darkTheme: { ...themeColors.darkTheme },
lightTheme: { ...themeColors.lightTheme }
};
await configStore.setCustomTheme(customTheme);
try {
const darkColors = ThemeColorConfig.createFrom(themeColors.darkTheme);
const lightColors = ThemeColorConfig.createFrom(themeColors.lightTheme);
await ThemeService.UpdateThemeColors(ThemeType.ThemeTypeDark, darkColors);
await ThemeService.UpdateThemeColors(ThemeType.ThemeTypeLight, lightColors);
} catch (error) {
console.error('Failed to save theme colors:', error);
throw error;
}
};
// 重置主题颜色
const resetThemeColors = async (themeType: 'darkTheme' | 'lightTheme') => {
try {
// 1. 更新内存中的颜色状态
const dbThemeType = themeType === 'darkTheme' ? ThemeType.ThemeTypeDark : ThemeType.ThemeTypeLight;
// 1. 调用后端重置服务
await ThemeService.ResetThemeColors(dbThemeType);
// 2. 更新内存中的颜色状态
if (themeType === 'darkTheme') {
Object.assign(themeColors.darkTheme, defaultDarkColors);
}
if (themeType === 'lightTheme') {
} else {
Object.assign(themeColors.lightTheme, defaultLightColors);
}
// 2. 保存到配置
await saveThemeColors();
// 3. 刷新编辑器主题
refreshEditorTheme();

View File

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

@@ -16,8 +16,8 @@ const themeStore = useThemeStore();
// 添加临时颜色状态
const tempColors = ref({
darkTheme: { ...configStore.config.appearance.customTheme?.darkTheme || defaultDarkColors },
lightTheme: { ...configStore.config.appearance.customTheme?.lightTheme || defaultLightColors }
darkTheme: { ...defaultDarkColors },
lightTheme: { ...defaultLightColors }
});
// 标记是否有未保存的更改
@@ -71,9 +71,9 @@ const currentThemeMode = computed(() => {
return isDark ? 'dark' : 'light';
});
// 监听配置变更,更新临时颜色
// 监听主题颜色变更,更新临时颜色
watch(
() => configStore.config.appearance.customTheme,
() => themeStore.themeColors,
(newValue) => {
if (!hasUnsavedChanges.value) {
tempColors.value = {

16
go.mod
View File

@@ -11,11 +11,11 @@ require (
github.com/knadh/koanf/providers/structs v1.0.0
github.com/knadh/koanf/v2 v2.2.2
github.com/robertkrimen/otto v0.5.1
github.com/wailsapp/wails/v3 v3.0.0-alpha.12
golang.org/x/net v0.42.0
golang.org/x/sys v0.34.0
golang.org/x/text v0.27.0
modernc.org/sqlite v1.38.0
github.com/wailsapp/wails/v3 v3.0.0-alpha.25
golang.org/x/net v0.43.0
golang.org/x/sys v0.35.0
golang.org/x/text v0.28.0
modernc.org/sqlite v1.38.2
)
require (
@@ -72,15 +72,15 @@ require (
github.com/wailsapp/mimetype v1.4.1 // indirect
github.com/xanzy/go-gitlab v0.115.0 // indirect
github.com/xanzy/ssh-agent v0.3.3 // indirect
golang.org/x/crypto v0.40.0 // indirect
golang.org/x/exp v0.0.0-20250711185948-6ae5c78190dc // indirect
golang.org/x/crypto v0.41.0 // indirect
golang.org/x/exp v0.0.0-20250813145105-42675adae3e6 // indirect
golang.org/x/oauth2 v0.30.0 // indirect
golang.org/x/time v0.12.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/sourcemap.v1 v1.0.5 // indirect
gopkg.in/warnings.v0 v0.1.2 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
modernc.org/libc v1.66.3 // indirect
modernc.org/libc v1.66.7 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
)

52
go.sum
View File

@@ -164,8 +164,8 @@ github.com/wailsapp/go-webview2 v1.0.21 h1:k3dtoZU4KCoN/AEIbWiPln3P2661GtA2oEgA2
github.com/wailsapp/go-webview2 v1.0.21/go.mod h1:qJmWAmAmaniuKGZPWwne+uor3AHMB5PFhqiK0Bbj8kc=
github.com/wailsapp/mimetype v1.4.1 h1:pQN9ycO7uo4vsUUuPeHEYoUkLVkaRntMnHJxVwYhwHs=
github.com/wailsapp/mimetype v1.4.1/go.mod h1:9aV5k31bBOv5z6u+QP8TltzvNGJPmNJD4XlAL3U+j3o=
github.com/wailsapp/wails/v3 v3.0.0-alpha.12 h1:z4wYfujk5tSuZXh+59S2DdEncQHG63CW51i2mZFKLS8=
github.com/wailsapp/wails/v3 v3.0.0-alpha.12/go.mod h1:4LCCW7s9e4PuSmu7l9OTvfWIGMO8TaSiftSeR5NpBIc=
github.com/wailsapp/wails/v3 v3.0.0-alpha.25 h1:o05zUiPEvmrq2lqqCs4wqnrnAjGmhryYHRhjQmtkvk8=
github.com/wailsapp/wails/v3 v3.0.0-alpha.25/go.mod h1:UZpnhYuju4saspCJrIHAvC0H5XjtKnqd26FRxJLrQ0M=
github.com/xanzy/go-gitlab v0.115.0 h1:6DmtItNcVe+At/liXSgfE/DZNZrGfalQmBRmOcJjOn8=
github.com/xanzy/go-gitlab v0.115.0/go.mod h1:5XCDtM7AM6WMKmfDdOiEpyRWUqui2iS9ILfvCZ2gJ5M=
github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM=
@@ -174,19 +174,19 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM=
golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY=
golang.org/x/exp v0.0.0-20250711185948-6ae5c78190dc h1:TS73t7x3KarrNd5qAipmspBDS1rkMcgVG/fS1aRb4Rc=
golang.org/x/exp v0.0.0-20250711185948-6ae5c78190dc/go.mod h1:A+z0yzpGtvnG90cToK5n2tu8UJVP2XUATh+r+sfOOOc=
golang.org/x/mod v0.26.0 h1:EGMPT//Ezu+ylkCijjPc+f4Aih7sZvaAr+O3EHBxvZg=
golang.org/x/mod v0.26.0/go.mod h1:/j6NAhSk8iQ723BGAUyoAcn7SlD7s15Dp9Nd/SfeaFQ=
golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4=
golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc=
golang.org/x/exp v0.0.0-20250813145105-42675adae3e6 h1:SbTAbRFnd5kjQXbczszQ0hdk3ctwYf3qBNH9jIsGclE=
golang.org/x/exp v0.0.0-20250813145105-42675adae3e6/go.mod h1:4QTo5u+SEIbbKW1RacMZq1YEfOBqeXa19JeshGi+zc4=
golang.org/x/mod v0.27.0 h1:kb+q2PyFnEADO2IEF935ehFUXlWiNjJWtRNgBLSfbxQ=
golang.org/x/mod v0.27.0/go.mod h1:rWI627Fq0DEoudcK+MBkNkCe0EetEaDSwJJkCcjpazc=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
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.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
@@ -203,21 +203,21 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.33.0 h1:NuFncQrRcaRvVmgRkvM3j/F00gWIAlcmlB8ACEKmGIg=
golang.org/x/term v0.33.0/go.mod h1:s18+ql9tYWp1IfpV9DmCtQDDSRBUjKaw9M1eAv5UeF0=
golang.org/x/term v0.34.0 h1:O/2T7POpk0ZZ7MAzMeWFSg6S5IpWd/RXDlM9hgM3DR4=
golang.org/x/term v0.34.0/go.mod h1:5jC53AEywhIVebHgPVeg0mj8OD3VO9OzclacVrqpaAw=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE=
golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0=
golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw=
golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg=
golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
@@ -234,18 +234,18 @@ gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/cc/v4 v4.26.2 h1:991HMkLjJzYBIfha6ECZdjrIYz2/1ayr+FL8GN+CNzM=
modernc.org/cc/v4 v4.26.2/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
modernc.org/cc/v4 v4.26.3 h1:yEN8dzrkRFnn4PUUKXLYIqVf2PJYAEjMTFjO3BDGc3I=
modernc.org/cc/v4 v4.26.3/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
modernc.org/ccgo/v4 v4.28.0 h1:rjznn6WWehKq7dG4JtLRKxb52Ecv8OUGah8+Z/SfpNU=
modernc.org/ccgo/v4 v4.28.0/go.mod h1:JygV3+9AV6SmPhDasu4JgquwU81XAKLd3OKTUDNOiKE=
modernc.org/fileutil v1.3.8 h1:qtzNm7ED75pd1C7WgAGcK4edm4fvhtBsEiI/0NQ54YM=
modernc.org/fileutil v1.3.8/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=
modernc.org/fileutil v1.3.15 h1:rJAXTP6ilMW/1+kzDiqmBlHLWszheUFXIyGQIAvjJpY=
modernc.org/fileutil v1.3.15/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
modernc.org/libc v1.66.3 h1:cfCbjTUcdsKyyZZfEUKfoHcP3S0Wkvz3jgSzByEWVCQ=
modernc.org/libc v1.66.3/go.mod h1:XD9zO8kt59cANKvHPXpx7yS2ELPheAey0vjIuZOhOU8=
modernc.org/libc v1.66.7 h1:rjhZ8OSCybKWxS1CJr0hikpEi6Vg+944Ouyrd+bQsoY=
modernc.org/libc v1.66.7/go.mod h1:ln6tbWX0NH+mzApEoDRvilBvAWFt1HX7AUA4VDdVDPM=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
@@ -254,8 +254,8 @@ modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/sqlite v1.38.0 h1:+4OrfPQ8pxHKuWG4md1JpR/EYAh3Md7TdejuuzE7EUI=
modernc.org/sqlite v1.38.0/go.mod h1:1Bj+yES4SVvBZ4cBOpVZ6QgesMCKpJZDq0nxYzOpmNE=
modernc.org/sqlite v1.38.2 h1:Aclu7+tgjgcQVShZqim41Bbw9Cho0y/7WzYptXqkEek=
modernc.org/sqlite v1.38.2/go.mod h1:cPTJYSlgg3Sfg046yBShXENNtPrWrDX8bsbAQBzgQ5E=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=

View File

@@ -101,9 +101,8 @@ type EditingConfig struct {
// AppearanceConfig 外观设置配置
type AppearanceConfig struct {
Language LanguageType `json:"language"` // 界面语言
SystemTheme SystemThemeType `json:"systemTheme"` // 系统界面主题
CustomTheme CustomThemeConfig `json:"customTheme"` // 自定义主题配置
Language LanguageType `json:"language"` // 界面语言
SystemTheme SystemThemeType `json:"systemTheme"` // 系统界面主题
}
// UpdatesConfig 更新设置配置
@@ -171,7 +170,6 @@ func NewDefaultAppConfig() *AppConfig {
Appearance: AppearanceConfig{
Language: LangEnUS,
SystemTheme: SystemThemeAuto,
CustomTheme: *NewDefaultCustomThemeConfig(),
},
Updates: UpdatesConfig{
Version: "1.3.0",

View File

@@ -1,5 +1,20 @@
package models
import (
"database/sql/driver"
"encoding/json"
"fmt"
"time"
)
// ThemeType 主题类型枚举
type ThemeType string
const (
ThemeTypeDark ThemeType = "dark"
ThemeTypeLight ThemeType = "light"
)
// ThemeColorConfig 主题颜色配置
type ThemeColorConfig struct {
// 基础色调
@@ -36,15 +51,44 @@ type ThemeColorConfig struct {
MatchingBracket string `json:"matchingBracket"` // 匹配括号
}
// CustomThemeConfig 自定义主题配置
type CustomThemeConfig struct {
DarkTheme ThemeColorConfig `json:"darkTheme"` // 深色主题配置
LightTheme ThemeColorConfig `json:"lightTheme"` // 浅色主题配置
// Theme 主题数据库模型
type Theme struct {
ID int `db:"id" json:"id"`
Name string `db:"name" json:"name"`
Type ThemeType `db:"type" json:"type"`
Colors ThemeColorConfig `db:"colors" json:"colors"`
IsDefault bool `db:"is_default" json:"isDefault"`
CreatedAt time.Time `db:"created_at" json:"createdAt"`
UpdatedAt time.Time `db:"updated_at" json:"updatedAt"`
}
// Value 实现 driver.Valuer 接口,用于将 ThemeColorConfig 存储到数据库
func (tc ThemeColorConfig) Value() (driver.Value, error) {
return json.Marshal(tc)
}
// Scan 实现 sql.Scanner 接口,用于从数据库读取 ThemeColorConfig
func (tc *ThemeColorConfig) Scan(value interface{}) error {
if value == nil {
return nil
}
var bytes []byte
switch v := value.(type) {
case []byte:
bytes = v
case string:
bytes = []byte(v)
default:
return fmt.Errorf("cannot scan %T into ThemeColorConfig", value)
}
return json.Unmarshal(bytes, tc)
}
// NewDefaultDarkTheme 创建默认深色主题配置
func NewDefaultDarkTheme() ThemeColorConfig {
return ThemeColorConfig{
func NewDefaultDarkTheme() *ThemeColorConfig {
return &ThemeColorConfig{
// 基础色调
Background: "#252B37",
BackgroundSecondary: "#213644",
@@ -81,8 +125,8 @@ func NewDefaultDarkTheme() ThemeColorConfig {
}
// NewDefaultLightTheme 创建默认浅色主题配置
func NewDefaultLightTheme() ThemeColorConfig {
return ThemeColorConfig{
func NewDefaultLightTheme() *ThemeColorConfig {
return &ThemeColorConfig{
// 基础色调
Background: "#ffffff",
BackgroundSecondary: "#f1faf1",
@@ -117,11 +161,3 @@ func NewDefaultLightTheme() ThemeColorConfig {
MatchingBracket: "#00000019",
}
}
// NewDefaultCustomThemeConfig 创建默认自定义主题配置
func NewDefaultCustomThemeConfig() *CustomThemeConfig {
return &CustomThemeConfig{
DarkTheme: NewDefaultDarkTheme(),
LightTheme: NewDefaultLightTheme(),
}
}

View File

@@ -30,14 +30,14 @@ type BackupService struct {
configService *ConfigService
dbService *DatabaseService
repository *git.Repository
logger *log.Service
logger *log.LogService
isInitialized bool
autoBackupTicker *time.Ticker
autoBackupStop chan bool
}
// NewBackupService 创建新的备份服务实例
func NewBackupService(configService *ConfigService, dbService *DatabaseService, logger *log.Service) *BackupService {
func NewBackupService(configService *ConfigService, dbService *DatabaseService, logger *log.LogService) *BackupService {
return &BackupService{
configService: configService,
dbService: dbService,

View File

@@ -38,7 +38,7 @@ type Migratable interface {
// ConfigMigrationService 配置迁移服务
type ConfigMigrationService[T Migratable] struct {
logger *log.Service
logger *log.LogService
configDir string
configName string
targetVersion string
@@ -54,7 +54,7 @@ type MigrationResult struct {
// NewConfigMigrationService 创建配置迁移服务
func NewConfigMigrationService[T Migratable](
logger *log.Service,
logger *log.LogService,
configDir string,
configName, targetVersion, configPath string,
) *ConfigMigrationService[T] {
@@ -312,7 +312,7 @@ func chainLoad(k *koanf.Koanf, loaders ...func() error) error {
}
// 工厂函数
func NewAppConfigMigrationService(logger *log.Service, configDir, settingsPath string) *ConfigMigrationService[*models.AppConfig] {
func NewAppConfigMigrationService(logger *log.LogService, configDir, settingsPath string) *ConfigMigrationService[*models.AppConfig] {
return NewConfigMigrationService[*models.AppConfig](
logger, configDir, "settings", CurrentAppConfigVersion, settingsPath)
}

View File

@@ -51,7 +51,7 @@ type ConfigListener struct {
type ConfigNotificationService struct {
listeners map[ConfigChangeType][]*ConfigListener // 支持多监听器的map
mu sync.RWMutex // 监听器map的读写锁
logger *log.Service // 日志服务
logger *log.LogService // 日志服务
koanf *koanf.Koanf // koanf实例
ctx context.Context
cancel context.CancelFunc
@@ -59,7 +59,7 @@ type ConfigNotificationService struct {
}
// NewConfigNotificationService 创建配置通知服务
func NewConfigNotificationService(k *koanf.Koanf, logger *log.Service) *ConfigNotificationService {
func NewConfigNotificationService(k *koanf.Koanf, logger *log.LogService) *ConfigNotificationService {
ctx, cancel := context.WithCancel(context.Background())
return &ConfigNotificationService{
listeners: make(map[ConfigChangeType][]*ConfigListener),

View File

@@ -18,12 +18,12 @@ import (
// ConfigService 应用配置服务
type ConfigService struct {
koanf *koanf.Koanf // koanf 实例
logger *log.Service // 日志服务
configDir string // 配置目录
settingsPath string // 设置文件路径
mu sync.RWMutex // 读写锁
fileProvider *file.File // 文件提供器,用于监听
koanf *koanf.Koanf // koanf 实例
logger *log.LogService // 日志服务
configDir string // 配置目录
settingsPath string // 设置文件路径
mu sync.RWMutex // 读写锁
fileProvider *file.File // 文件提供器,用于监听
// 配置通知服务
notificationService *ConfigNotificationService
@@ -55,7 +55,7 @@ func (e *ConfigError) Is(target error) bool {
}
// NewConfigService 创建新的配置服务实例
func NewConfigService(logger *log.Service) *ConfigService {
func NewConfigService(logger *log.LogService) *ConfigService {
// 获取用户主目录
homeDir, err := os.UserHomeDir()
if err != nil {

View File

@@ -63,6 +63,19 @@ CREATE TABLE IF NOT EXISTS key_bindings (
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(command, extension)
)`
// Themes table
sqlCreateThemesTable = `
CREATE TABLE IF NOT EXISTS themes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
type TEXT NOT NULL,
colors TEXT NOT NULL,
is_default INTEGER NOT NULL DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE(type, is_default)
)`
)
// ColumnInfo 存储列的信息
@@ -80,7 +93,7 @@ type TableModel struct {
// DatabaseService provides shared database functionality
type DatabaseService struct {
configService *ConfigService
logger *log.Service
logger *log.LogService
db *sql.DB
mu sync.RWMutex
ctx context.Context
@@ -88,7 +101,7 @@ type DatabaseService struct {
}
// NewDatabaseService creates a new database service
func NewDatabaseService(configService *ConfigService, logger *log.Service) *DatabaseService {
func NewDatabaseService(configService *ConfigService, logger *log.LogService) *DatabaseService {
if logger == nil {
logger = log.New()
}
@@ -112,6 +125,8 @@ func (ds *DatabaseService) registerAllModels() {
ds.RegisterModel("extensions", &models.Extension{})
// 快捷键表
ds.RegisterModel("key_bindings", &models.KeyBinding{})
// 主题表
ds.RegisterModel("themes", &models.Theme{})
}
// ServiceStartup initializes the service when the application starts
@@ -181,6 +196,7 @@ func (ds *DatabaseService) createTables() error {
sqlCreateDocumentsTable,
sqlCreateExtensionsTable,
sqlCreateKeyBindingsTable,
sqlCreateThemesTable,
}
for _, table := range tables {
@@ -204,6 +220,9 @@ func (ds *DatabaseService) createIndexes() error {
`CREATE INDEX IF NOT EXISTS idx_key_bindings_command ON key_bindings(command)`,
`CREATE INDEX IF NOT EXISTS idx_key_bindings_extension ON key_bindings(extension)`,
`CREATE INDEX IF NOT EXISTS idx_key_bindings_enabled ON key_bindings(enabled)`,
// Themes indexes
`CREATE INDEX IF NOT EXISTS idx_themes_type ON themes(type)`,
`CREATE INDEX IF NOT EXISTS idx_themes_is_default ON themes(is_default)`,
}
for _, index := range indexes {

View File

@@ -7,12 +7,12 @@ import (
// DialogService 对话框服务,处理文件选择等对话框操作
type DialogService struct {
logger *log.Service
logger *log.LogService
window *application.WebviewWindow // 绑定的窗口
}
// NewDialogService 创建新的对话框服务实例
func NewDialogService(logger *log.Service) *DialogService {
func NewDialogService(logger *log.LogService) *DialogService {
if logger == nil {
logger = log.New()
}

View File

@@ -79,13 +79,13 @@ WHERE id = ?`
// DocumentService provides document management functionality
type DocumentService struct {
databaseService *DatabaseService
logger *log.Service
logger *log.LogService
mu sync.RWMutex
ctx context.Context
}
// NewDocumentService creates a new document service
func NewDocumentService(databaseService *DatabaseService, logger *log.Service) *DocumentService {
func NewDocumentService(databaseService *DatabaseService, logger *log.LogService) *DocumentService {
if logger == nil {
logger = log.New()
}
@@ -216,14 +216,11 @@ func (ds *DocumentService) CreateDocument(title string) (*models.Document, error
// LockDocument 锁定文档,防止删除
func (ds *DocumentService) LockDocument(id int64) error {
ds.mu.Lock()
defer ds.mu.Unlock()
if ds.databaseService == nil || ds.databaseService.db == nil {
return errors.New("database service not available")
}
// 检查文档是否存在且未删除
// 检查文档是否存在且未删除(不加锁避免死锁)
doc, err := ds.GetDocumentByID(id)
if err != nil {
return fmt.Errorf("failed to get document: %w", err)
@@ -240,6 +237,10 @@ func (ds *DocumentService) LockDocument(id int64) error {
return nil
}
// 现在加锁执行锁定操作
ds.mu.Lock()
defer ds.mu.Unlock()
_, err = ds.databaseService.db.Exec(sqlSetDocumentLocked, time.Now().Format("2006-01-02 15:04:05"), id)
if err != nil {
return fmt.Errorf("failed to lock document: %w", err)
@@ -249,14 +250,11 @@ func (ds *DocumentService) LockDocument(id int64) error {
// UnlockDocument 解锁文档
func (ds *DocumentService) UnlockDocument(id int64) error {
ds.mu.Lock()
defer ds.mu.Unlock()
if ds.databaseService == nil || ds.databaseService.db == nil {
return errors.New("database service not available")
}
// 检查文档是否存在
// 检查文档是否存在(不加锁避免死锁)
doc, err := ds.GetDocumentByID(id)
if err != nil {
return fmt.Errorf("failed to get document: %w", err)
@@ -270,6 +268,10 @@ func (ds *DocumentService) UnlockDocument(id int64) error {
return nil
}
// 现在加锁执行解锁操作
ds.mu.Lock()
defer ds.mu.Unlock()
_, err = ds.databaseService.db.Exec(sqlSetDocumentUnlocked, time.Now().Format("2006-01-02 15:04:05"), id)
if err != nil {
return fmt.Errorf("failed to unlock document: %w", err)
@@ -311,10 +313,8 @@ func (ds *DocumentService) UpdateDocumentTitle(id int64, title string) error {
// DeleteDocument marks a document as deleted (default document with ID=1 cannot be deleted)
func (ds *DocumentService) DeleteDocument(id int64) error {
ds.mu.Lock()
defer ds.mu.Unlock()
if ds.databaseService == nil || ds.databaseService.db == nil {
ds.logger.Error("database service not available")
return errors.New("database service not available")
}
@@ -323,7 +323,7 @@ func (ds *DocumentService) DeleteDocument(id int64) error {
return fmt.Errorf("cannot delete the default document")
}
// 检查文档是否锁定
// 检查文档是否存在和锁定状态(不加锁避免死锁)
doc, err := ds.GetDocumentByID(id)
if err != nil {
return fmt.Errorf("failed to get document: %w", err)
@@ -335,6 +335,10 @@ func (ds *DocumentService) DeleteDocument(id int64) error {
return fmt.Errorf("cannot delete locked document: %d", id)
}
// 现在加锁执行删除操作
ds.mu.Lock()
defer ds.mu.Unlock()
_, err = ds.databaseService.db.Exec(sqlMarkDocumentAsDeleted, time.Now().Format("2006-01-02 15:04:05"), id)
if err != nil {
return fmt.Errorf("failed to mark document as deleted: %w", err)

View File

@@ -41,7 +41,7 @@ WHERE id = ?`
// ExtensionService 扩展管理服务
type ExtensionService struct {
databaseService *DatabaseService
logger *log.Service
logger *log.LogService
mu sync.RWMutex
ctx context.Context
@@ -73,7 +73,7 @@ func (e *ExtensionError) Is(target error) bool {
}
// NewExtensionService 创建扩展服务实例
func NewExtensionService(databaseService *DatabaseService, logger *log.Service) *ExtensionService {
func NewExtensionService(databaseService *DatabaseService, logger *log.LogService) *ExtensionService {
if logger == nil {
logger = log.New()
}

View File

@@ -24,17 +24,19 @@ import (
// HotkeyService Windows全局热键服务
type HotkeyService struct {
logger *log.Service
logger *log.LogService
configService *ConfigService
windowService *WindowService
app *application.App
mainWindow *application.WebviewWindow
mu sync.RWMutex
currentHotkey *models.HotkeyCombo
isRegistered atomic.Bool
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
ctx context.Context
cancelFunc atomic.Value // 使用atomic.Value存储cancel函数避免竞态条件
wg sync.WaitGroup
}
// HotkeyError 热键错误
@@ -51,24 +53,48 @@ 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, logger *log.Service) *HotkeyService {
func NewHotkeyService(configService *ConfigService, windowService *WindowService, logger *log.LogService) *HotkeyService {
if logger == nil {
logger = log.New()
}
ctx, cancel := context.WithCancel(context.Background())
return &HotkeyService{
service := &HotkeyService{
logger: logger,
configService: configService,
windowService: windowService,
ctx: ctx,
cancel: cancel,
}
// 初始化时设置cancel函数
service.setCancelFunc(cancel)
return service
}
// Initialize 初始化热键服务
func (hs *HotkeyService) Initialize(app *application.App) error {
func (hs *HotkeyService) Initialize(app *application.App, mainWindow *application.WebviewWindow) error {
hs.app = app
hs.mainWindow = mainWindow
config, err := hs.configService.GetConfig()
if err != nil {
@@ -119,7 +145,7 @@ func (hs *HotkeyService) RegisterHotkey(hotkey *models.HotkeyCombo) error {
hs.currentHotkey = hotkey
hs.isRegistered.Store(true)
hs.cancel = cancel
hs.setCancelFunc(cancel)
return nil
}
@@ -137,13 +163,15 @@ func (hs *HotkeyService) unregisterInternal() error {
return nil
}
if hs.cancel != nil {
hs.cancel()
// 原子地获取并调用cancel函数
if cancel := hs.getCancelFunc(); cancel != nil {
cancel()
hs.wg.Wait()
}
hs.currentHotkey = nil
hs.isRegistered.Store(false)
hs.clearCancelFunc()
return nil
}
@@ -165,7 +193,7 @@ func (hs *HotkeyService) hotkeyListener(ctx context.Context, hotkey *models.Hotk
return
}
ticker := time.NewTicker(100 * time.Millisecond)
ticker := time.NewTicker(50 * time.Millisecond)
defer ticker.Stop()
var wasPressed bool
@@ -199,11 +227,61 @@ func cBool(b bool) C.int {
return 0
}
// toggleWindow 切换窗口
// toggleWindow 切换窗口显示状态
func (hs *HotkeyService) toggleWindow() {
if hs.app != nil {
hs.app.Event.Emit("hotkey:toggle-window", nil)
if hs.mainWindow == nil {
hs.logger.Error("main window not set")
return
}
// 检查主窗口是否可见
if hs.isWindowVisible(hs.mainWindow) {
// 如果主窗口可见,隐藏所有窗口
hs.hideAllWindows()
} else {
// 如果主窗口不可见,显示所有窗口
hs.showAllWindows()
}
}
// isWindowVisible 检查窗口是否可见
func (hs *HotkeyService) isWindowVisible(window *application.WebviewWindow) bool {
return window.IsVisible()
}
// hideAllWindows 隐藏所有窗口
func (hs *HotkeyService) hideAllWindows() {
// 隐藏主窗口
hs.mainWindow.Hide()
// 隐藏所有子窗口
if hs.windowService != nil {
openWindows := hs.windowService.GetOpenWindows()
for _, windowInfo := range openWindows {
windowInfo.Window.Hide()
}
}
hs.logger.Debug("all windows hidden")
}
// showAllWindows 显示所有窗口
func (hs *HotkeyService) showAllWindows() {
// 显示主窗口
hs.mainWindow.Show()
hs.mainWindow.Restore()
hs.mainWindow.Focus()
// 显示所有子窗口
if hs.windowService != nil {
openWindows := hs.windowService.GetOpenWindows()
for _, windowInfo := range openWindows {
windowInfo.Window.Show()
windowInfo.Window.Restore()
}
}
hs.logger.Debug("all windows shown")
}
// keyToVirtualKeyCode 键名转虚拟键码
@@ -261,7 +339,10 @@ func (hs *HotkeyService) IsRegistered() bool {
// ServiceShutdown 关闭服务
func (hs *HotkeyService) ServiceShutdown() error {
hs.cancel()
// 原子地获取并调用cancel函数
if cancel := hs.getCancelFunc(); cancel != nil {
cancel()
}
hs.wg.Wait()
return nil
}

View File

@@ -66,6 +66,7 @@ int isHotkeyRegistered() {
import "C"
import (
"context"
"fmt"
"sync"
"sync/atomic"
@@ -80,12 +81,15 @@ var globalHotkeyService *HotkeyService
// HotkeyService macOS全局热键服务
type HotkeyService struct {
logger *log.Service
logger *log.LogService
configService *ConfigService
windowService *WindowService
app *application.App
mainWindow *application.WebviewWindow
mu sync.RWMutex
isRegistered atomic.Bool
currentHotkey *models.HotkeyCombo
cancelFunc atomic.Value // 使用atomic.Value存储cancel函数避免竞态条件
}
// HotkeyError 热键错误
@@ -104,8 +108,28 @@ 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, logger *log.Service) *HotkeyService {
func NewHotkeyService(configService *ConfigService, windowService *WindowService, logger *log.LogService) *HotkeyService {
if logger == nil {
logger = log.New()
}
@@ -113,6 +137,7 @@ func NewHotkeyService(configService *ConfigService, logger *log.Service) *Hotkey
service := &HotkeyService{
logger: logger,
configService: configService,
windowService: windowService,
}
// 设置全局实例
@@ -122,8 +147,9 @@ func NewHotkeyService(configService *ConfigService, logger *log.Service) *Hotkey
}
// Initialize 初始化热键服务
func (hs *HotkeyService) Initialize(app *application.App) error {
func (hs *HotkeyService) Initialize(app *application.App, mainWindow *application.WebviewWindow) error {
hs.app = app
hs.mainWindow = mainWindow
// 加载并应用当前配置
config, err := hs.configService.GetConfig()
@@ -285,9 +311,59 @@ func (hs *HotkeyService) IsRegistered() bool {
// ToggleWindow 切换窗口显示状态
func (hs *HotkeyService) ToggleWindow() {
if hs.app != nil {
hs.app.EmitEvent("hotkey:toggle-window", nil)
if hs.mainWindow == nil {
hs.logger.Error("main window not set")
return
}
// 检查主窗口是否可见
if hs.isWindowVisible(hs.mainWindow) {
// 如果主窗口可见,隐藏所有窗口
hs.hideAllWindows()
} else {
// 如果主窗口不可见,显示所有窗口
hs.showAllWindows()
}
}
// isWindowVisible 检查窗口是否可见
func (hs *HotkeyService) isWindowVisible(window *application.WebviewWindow) bool {
return window.IsVisible()
}
// hideAllWindows 隐藏所有窗口
func (hs *HotkeyService) hideAllWindows() {
// 隐藏主窗口
hs.mainWindow.Hide()
// 隐藏所有子窗口
if hs.windowService != nil {
openWindows := hs.windowService.GetOpenWindows()
for _, windowInfo := range openWindows {
windowInfo.Window.Hide()
}
}
hs.logger.Debug("all windows hidden")
}
// showAllWindows 显示所有窗口
func (hs *HotkeyService) showAllWindows() {
// 显示主窗口
hs.mainWindow.Show()
hs.mainWindow.Restore()
hs.mainWindow.Focus()
// 显示所有子窗口
if hs.windowService != nil {
openWindows := hs.windowService.GetOpenWindows()
for _, windowInfo := range openWindows {
windowInfo.Window.Show()
windowInfo.Window.Restore()
}
}
hs.logger.Debug("all windows shown")
}
// ServiceShutdown 关闭热键服务

View File

@@ -141,17 +141,19 @@ import (
// HotkeyService Linux全局热键服务
type HotkeyService struct {
logger *log.Service
logger *log.LogService
configService *ConfigService
windowService *WindowService
app *application.App
mainWindow *application.WebviewWindow
mu sync.RWMutex
currentHotkey *models.HotkeyCombo
isRegistered atomic.Bool
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
ctx context.Context
cancelFunc atomic.Value // 使用atomic.Value存储cancel函数避免竞态条件
wg sync.WaitGroup
}
// HotkeyError 热键错误
@@ -169,24 +171,48 @@ 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, logger *log.Service) *HotkeyService {
func NewHotkeyService(configService *ConfigService, windowService *WindowService, logger *log.LogService) *HotkeyService {
if logger == nil {
logger = log.New()
}
ctx, cancel := context.WithCancel(context.Background())
return &HotkeyService{
service := &HotkeyService{
logger: logger,
configService: configService,
windowService: windowService,
ctx: ctx,
cancel: cancel,
}
// 初始化时设置cancel函数
service.setCancelFunc(cancel)
return service
}
// Initialize 初始化热键服务
func (hs *HotkeyService) Initialize(app *application.App) error {
func (hs *HotkeyService) Initialize(app *application.App, mainWindow *application.WebviewWindow) error {
hs.app = app
hs.mainWindow = mainWindow
if int(C.initX11Display()) == 0 {
return &HotkeyError{"init_x11", fmt.Errorf("failed to initialize X11 display")}
@@ -253,7 +279,7 @@ func (hs *HotkeyService) RegisterHotkey(hotkey *models.HotkeyCombo) error {
hs.currentHotkey = hotkey
hs.isRegistered.Store(true)
hs.cancel = cancel
hs.setCancelFunc(cancel)
return nil
}
@@ -271,8 +297,9 @@ func (hs *HotkeyService) unregisterInternal() error {
return nil
}
if hs.cancel != nil {
hs.cancel()
// 原子地获取并调用cancel函数
if cancel := hs.getCancelFunc(); cancel != nil {
cancel()
hs.wg.Wait()
}
@@ -283,6 +310,7 @@ func (hs *HotkeyService) unregisterInternal() error {
hs.currentHotkey = nil
hs.isRegistered.Store(false)
hs.clearCancelFunc()
return nil
}
@@ -298,7 +326,8 @@ func (hs *HotkeyService) UpdateHotkey(enable bool, hotkey *models.HotkeyCombo) e
func (hs *HotkeyService) hotkeyListener(ctx context.Context, ready chan<- error) {
defer hs.wg.Done()
ticker := time.NewTicker(100 * time.Millisecond)
// 优化轮询频率从100ms改为50ms提高响应性
ticker := time.NewTicker(50 * time.Millisecond)
defer ticker.Stop()
ready <- nil // 标记准备就绪
@@ -315,11 +344,61 @@ func (hs *HotkeyService) hotkeyListener(ctx context.Context, ready chan<- error)
}
}
// toggleWindow 切换窗口
// toggleWindow 切换窗口显示状态
func (hs *HotkeyService) toggleWindow() {
if hs.app != nil {
hs.app.EmitEvent("hotkey:toggle-window", nil)
if hs.mainWindow == nil {
hs.logger.Error("main window not set")
return
}
// 检查主窗口是否可见
if hs.isWindowVisible(hs.mainWindow) {
// 如果主窗口可见,隐藏所有窗口
hs.hideAllWindows()
} else {
// 如果主窗口不可见,显示所有窗口
hs.showAllWindows()
}
}
// isWindowVisible 检查窗口是否可见
func (hs *HotkeyService) isWindowVisible(window *application.WebviewWindow) bool {
return window.IsVisible()
}
// hideAllWindows 隐藏所有窗口
func (hs *HotkeyService) hideAllWindows() {
// 隐藏主窗口
hs.mainWindow.Hide()
// 隐藏所有子窗口
if hs.windowService != nil {
openWindows := hs.windowService.GetOpenWindows()
for _, windowInfo := range openWindows {
windowInfo.Window.Hide()
}
}
hs.logger.Debug("all windows hidden")
}
// showAllWindows 显示所有窗口
func (hs *HotkeyService) showAllWindows() {
// 显示主窗口
hs.mainWindow.Show()
hs.mainWindow.Restore()
hs.mainWindow.Focus()
// 显示所有子窗口
if hs.windowService != nil {
openWindows := hs.windowService.GetOpenWindows()
for _, windowInfo := range openWindows {
windowInfo.Window.Show()
windowInfo.Window.Restore()
}
}
hs.logger.Debug("all windows shown")
}
// keyToX11KeyCode 键名转X11键码
@@ -386,7 +465,10 @@ func (hs *HotkeyService) IsRegistered() bool {
// ServiceShutdown 关闭服务
func (hs *HotkeyService) ServiceShutdown() error {
hs.cancel()
// 原子地获取并调用cancel函数
if cancel := hs.getCancelFunc(); cancel != nil {
cancel()
}
hs.wg.Wait()
C.closeX11Display()
return nil

View File

@@ -51,7 +51,7 @@ const (
// KeyBindingService 快捷键管理服务
type KeyBindingService struct {
databaseService *DatabaseService
logger *log.Service
logger *log.LogService
mu sync.RWMutex
ctx context.Context
@@ -83,7 +83,7 @@ func (e *KeyBindingError) Is(target error) bool {
}
// NewKeyBindingService 创建快捷键服务实例
func NewKeyBindingService(databaseService *DatabaseService, logger *log.Service) *KeyBindingService {
func NewKeyBindingService(databaseService *DatabaseService, logger *log.LogService) *KeyBindingService {
if logger == nil {
logger = log.New()
}

View File

@@ -33,22 +33,24 @@ type MigrationProgress struct {
// MigrationService 迁移服务
type MigrationService struct {
logger *log.Service
mu sync.RWMutex
progress atomic.Value // stores MigrationProgress
logger *log.LogService
dbService *DatabaseService
mu sync.RWMutex
progress atomic.Value // stores MigrationProgress
ctx context.Context
cancel context.CancelFunc
}
// NewMigrationService 创建迁移服务
func NewMigrationService(logger *log.Service) *MigrationService {
func NewMigrationService(dbService *DatabaseService, logger *log.LogService) *MigrationService {
if logger == nil {
logger = log.New()
}
ms := &MigrationService{
logger: logger,
logger: logger,
dbService: dbService,
}
// 初始化进度
@@ -104,6 +106,17 @@ func (ms *MigrationService) MigrateDirectory(srcPath, dstPath string) error {
return ms.failWithError(err)
}
// 迁移前断开数据库连接
ms.updateProgress(MigrationProgress{
Status: MigrationStatusMigrating,
Progress: 10,
})
if ms.dbService != nil {
if err := ms.dbService.ServiceShutdown(); err != nil {
ms.logger.Error("Failed to close database connection", "error", err)
}
}
// 执行原子迁移
if err := ms.atomicMove(ctx, srcPath, dstPath); err != nil {
return ms.failWithError(err)
@@ -177,10 +190,17 @@ func (ms *MigrationService) atomicMove(ctx context.Context, srcPath, dstPath str
})
if err := os.Rename(srcPath, dstPath); err == nil {
// 重命名成功更新进度到90%
ms.updateProgress(MigrationProgress{
Status: MigrationStatusMigrating,
Progress: 90,
})
ms.logger.Info("Directory migration completed using direct rename", "src", srcPath, "dst", dstPath)
return nil
}
// 重命名失败,使用压缩迁移
ms.logger.Info("Direct rename failed, using compress migration", "src", srcPath, "dst", dstPath)
ms.updateProgress(MigrationProgress{
Status: MigrationStatusMigrating,
Progress: 30,
@@ -249,12 +269,18 @@ func (ms *MigrationService) compressMove(ctx context.Context, srcPath, dstPath s
default:
}
// 验证迁移是否成功
if err := ms.verifyMigration(dstPath); err != nil {
// 迁移验证失败,清理目标目录
os.RemoveAll(dstPath)
return fmt.Errorf("migration verification failed: %v", err)
}
// 删除源目录
ms.updateProgress(MigrationProgress{
Status: MigrationStatusMigrating,
Progress: 90,
})
os.RemoveAll(srcPath)
return nil
}
@@ -404,6 +430,29 @@ func (ms *MigrationService) isSubDirectory(parent, target string) bool {
return len(target) > len(parent) && strings.HasPrefix(target, parent)
}
// verifyMigration 验证迁移是否成功
func (ms *MigrationService) verifyMigration(dstPath string) error {
// 检查目标目录是否存在
dstStat, err := os.Stat(dstPath)
if err != nil {
return fmt.Errorf("target directory does not exist: %v", err)
}
if !dstStat.IsDir() {
return fmt.Errorf("target path is not a directory")
}
// 简单验证:检查目标目录是否非空
isEmpty, err := ms.isDirectoryEmpty(dstPath)
if err != nil {
return fmt.Errorf("failed to check target directory: %v", err)
}
if isEmpty {
return fmt.Errorf("target directory is empty after migration")
}
return nil
}
// CancelMigration 取消迁移
func (ms *MigrationService) CancelMigration() error {
ms.mu.Lock()

View File

@@ -26,7 +26,7 @@ type SelfUpdateResult struct {
// SelfUpdateService 自我更新服务
type SelfUpdateService struct {
logger *log.Service
logger *log.LogService
configService *ConfigService
config *models.AppConfig
@@ -35,7 +35,7 @@ type SelfUpdateService struct {
}
// NewSelfUpdateService 创建自我更新服务实例
func NewSelfUpdateService(configService *ConfigService, logger *log.Service) (*SelfUpdateService, error) {
func NewSelfUpdateService(configService *ConfigService, logger *log.LogService) (*SelfUpdateService, error) {
// 获取配置
appConfig, err := configService.GetConfig()
if err != nil {

View File

@@ -23,8 +23,9 @@ type ServiceManager struct {
startupService *StartupService
selfUpdateService *SelfUpdateService
translationService *TranslationService
themeService *ThemeService
BackupService *BackupService
logger *log.Service
logger *log.LogService
}
// NewServiceManager 创建新的服务管理器实例
@@ -39,7 +40,7 @@ func NewServiceManager() *ServiceManager {
databaseService := NewDatabaseService(configService, logger)
// 初始化迁移服务
migrationService := NewMigrationService(logger)
migrationService := NewMigrationService(databaseService, logger)
// 初始化文档服务
documentService := NewDocumentService(databaseService, logger)
@@ -51,7 +52,7 @@ func NewServiceManager() *ServiceManager {
systemService := NewSystemService(logger)
// 初始化热键服务
hotkeyService := NewHotkeyService(configService, logger)
hotkeyService := NewHotkeyService(configService, windowService, logger)
// 初始化对话服务
dialogService := NewDialogService(logger)
@@ -77,6 +78,9 @@ func NewServiceManager() *ServiceManager {
// 初始化翻译服务
translationService := NewTranslationService(logger)
// 初始化主题服务
themeService := NewThemeService(databaseService, logger)
// 初始化备份服务
backupService := NewBackupService(configService, databaseService, logger)
@@ -119,6 +123,7 @@ func NewServiceManager() *ServiceManager {
startupService: startupService,
selfUpdateService: selfUpdateService,
translationService: translationService,
themeService: themeService,
BackupService: backupService,
logger: logger,
}
@@ -141,6 +146,7 @@ func (sm *ServiceManager) GetServices() []application.Service {
application.NewService(sm.startupService),
application.NewService(sm.selfUpdateService),
application.NewService(sm.translationService),
application.NewService(sm.themeService),
application.NewService(sm.BackupService),
}
return services
@@ -157,7 +163,7 @@ func (sm *ServiceManager) GetDialogService() *DialogService {
}
// GetLogger 获取日志服务实例
func (sm *ServiceManager) GetLogger() *log.Service {
func (sm *ServiceManager) GetLogger() *log.LogService {
return sm.logger
}
@@ -210,3 +216,8 @@ func (sm *ServiceManager) GetWindowService() *WindowService {
func (sm *ServiceManager) GetDocumentService() *DocumentService {
return sm.documentService
}
// GetThemeService 获取主题服务实例
func (sm *ServiceManager) GetThemeService() *ThemeService {
return sm.themeService
}

View File

@@ -15,14 +15,14 @@ import (
// DarwinStartupImpl macOS 平台开机启动实现
type DarwinStartupImpl struct {
logger *log.Service
logger *log.LogService
disabled bool
appPath string
appName string
}
// newStartupImplementation 创建平台特定的开机启动实现
func newStartupImplementation(logger *log.Service) StartupImplementation {
func newStartupImplementation(logger *log.LogService) StartupImplementation {
return &DarwinStartupImpl{
logger: logger,
}

View File

@@ -13,7 +13,7 @@ import (
// LinuxStartupImpl Linux 平台开机启动实现
type LinuxStartupImpl struct {
logger *log.Service
logger *log.LogService
autostartDir string
execPath string
appName string
@@ -37,7 +37,7 @@ X-GNOME-Autostart-enabled=true
`
// newStartupImplementation 创建平台特定的开机启动实现
func newStartupImplementation(logger *log.Service) StartupImplementation {
func newStartupImplementation(logger *log.LogService) StartupImplementation {
return &LinuxStartupImpl{
logger: logger,
}

View File

@@ -7,7 +7,7 @@ import (
// StartupService 开机启动服务
type StartupService struct {
configService *ConfigService
logger *log.Service
logger *log.LogService
impl StartupImplementation
initError error
}
@@ -19,7 +19,7 @@ type StartupImplementation interface {
}
// NewStartupService 创建开机启动服务实例
func NewStartupService(configService *ConfigService, logger *log.Service) *StartupService {
func NewStartupService(configService *ConfigService, logger *log.LogService) *StartupService {
service := &StartupService{
configService: configService,
logger: logger,

View File

@@ -15,7 +15,7 @@ import (
// WindowsStartupImpl Windows 平台开机启动实现
type WindowsStartupImpl struct {
logger *log.Service
logger *log.LogService
registryKey string
execPath string
workingDir string
@@ -23,7 +23,7 @@ type WindowsStartupImpl struct {
}
// newStartupImplementation 创建平台特定的开机启动实现
func newStartupImplementation(logger *log.Service) StartupImplementation {
func newStartupImplementation(logger *log.LogService) StartupImplementation {
return &WindowsStartupImpl{
logger: logger,
}

View File

@@ -15,7 +15,7 @@ import (
type StoreOption struct {
FilePath string
AutoSave bool
Logger *log.Service
Logger *log.LogService
}
// Store 泛型存储服务
@@ -25,7 +25,7 @@ type Store[T any] struct {
dataMap sync.Map // thread-safe map
unsaved atomic.Bool
initOnce sync.Once
logger *log.Service
logger *log.LogService
}
// NewStore 存储服务

View File

@@ -9,7 +9,7 @@ import (
// SystemService 系统监控服务
type SystemService struct {
logger *log.Service
logger *log.LogService
}
// MemoryStats 内存统计信息
@@ -29,7 +29,7 @@ type MemoryStats struct {
}
// NewSystemService 创建新的系统服务实例
func NewSystemService(logger *log.Service) *SystemService {
func NewSystemService(logger *log.LogService) *SystemService {
return &SystemService{
logger: logger,
}

View File

@@ -0,0 +1,275 @@
package services
import (
"context"
"database/sql"
"fmt"
"time"
"voidraft/internal/models"
"github.com/wailsapp/wails/v3/pkg/application"
"github.com/wailsapp/wails/v3/pkg/services/log"
)
// ThemeService 主题服务
type ThemeService struct {
databaseService *DatabaseService
logger *log.LogService
ctx context.Context
}
// NewThemeService 创建新的主题服务
func NewThemeService(databaseService *DatabaseService, logger *log.LogService) *ThemeService {
if logger == nil {
logger = log.New()
}
return &ThemeService{
databaseService: databaseService,
logger: logger,
}
}
// ServiceStartup 服务启动时初始化
func (ts *ThemeService) ServiceStartup(ctx context.Context, options application.ServiceOptions) error {
ts.ctx = ctx
// 初始化默认主题
return ts.initializeDefaultThemes()
}
// getDB 获取数据库连接
func (ts *ThemeService) getDB() *sql.DB {
return ts.databaseService.db
}
// initializeDefaultThemes 初始化默认主题
func (ts *ThemeService) initializeDefaultThemes() error {
db := ts.getDB()
if db == nil {
return fmt.Errorf("database not available")
}
// 检查是否已存在默认主题
var count int
err := db.QueryRow("SELECT COUNT(*) FROM themes WHERE is_default = 1").Scan(&count)
if err != nil {
return fmt.Errorf("failed to check existing themes: %w", err)
}
if count > 0 {
return nil // 默认主题已存在
}
// 创建默认深色主题
darkTheme := &models.Theme{
Name: "Default Dark",
Type: models.ThemeTypeDark,
Colors: *models.NewDefaultDarkTheme(),
IsDefault: true,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
// 创建默认浅色主题
lightTheme := &models.Theme{
Name: "Default Light",
Type: models.ThemeTypeLight,
Colors: *models.NewDefaultLightTheme(),
IsDefault: true,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
// 插入默认主题
if _, err := ts.CreateTheme(darkTheme); err != nil {
return fmt.Errorf("failed to create default dark theme: %w", err)
}
if _, err := ts.CreateTheme(lightTheme); err != nil {
return fmt.Errorf("failed to create default light theme: %w", err)
}
return nil
}
// GetDefaultThemes 获取默认主题
func (ts *ThemeService) GetDefaultThemes() (map[models.ThemeType]*models.Theme, error) {
query := `
SELECT id, name, type, colors, is_default, created_at, updated_at
FROM themes
WHERE is_default = 1
ORDER BY type
`
db := ts.getDB()
rows, err := db.Query(query)
if err != nil {
return nil, fmt.Errorf("failed to query default themes: %w", err)
}
defer rows.Close()
themes := make(map[models.ThemeType]*models.Theme)
for rows.Next() {
theme := &models.Theme{}
err := rows.Scan(
&theme.ID,
&theme.Name,
&theme.Type,
&theme.Colors,
&theme.IsDefault,
&theme.CreatedAt,
&theme.UpdatedAt,
)
if err != nil {
return nil, fmt.Errorf("failed to scan theme: %w", err)
}
themes[theme.Type] = theme
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("failed to iterate themes: %w", err)
}
return themes, nil
}
// GetThemeByType 根据类型获取默认主题
func (ts *ThemeService) GetThemeByType(themeType models.ThemeType) (*models.Theme, error) {
query := `
SELECT id, name, type, colors, is_default, created_at, updated_at
FROM themes
WHERE type = ? AND is_default = 1
LIMIT 1
`
theme := &models.Theme{}
db := ts.getDB()
err := db.QueryRow(query, themeType).Scan(
&theme.ID,
&theme.Name,
&theme.Type,
&theme.Colors,
&theme.IsDefault,
&theme.CreatedAt,
&theme.UpdatedAt,
)
if err != nil {
if err == sql.ErrNoRows {
return nil, fmt.Errorf("no default theme found for type: %s", themeType)
}
return nil, fmt.Errorf("failed to get theme by type: %w", err)
}
return theme, nil
}
// UpdateThemeColors 更新主题颜色
func (ts *ThemeService) UpdateThemeColors(themeType models.ThemeType, colors models.ThemeColorConfig) error {
query := `
UPDATE themes
SET colors = ?, updated_at = ?
WHERE type = ? AND is_default = 1
`
db := ts.getDB()
_, err := db.Exec(query, colors, time.Now(), themeType)
if err != nil {
return fmt.Errorf("failed to update theme colors: %w", err)
}
return nil
}
// ResetThemeColors 重置主题颜色为默认值
func (ts *ThemeService) ResetThemeColors(themeType models.ThemeType) error {
var defaultColors models.ThemeColorConfig
switch themeType {
case models.ThemeTypeDark:
defaultColors = *models.NewDefaultDarkTheme()
case models.ThemeTypeLight:
defaultColors = *models.NewDefaultLightTheme()
default:
return fmt.Errorf("unknown theme type: %s", themeType)
}
return ts.UpdateThemeColors(themeType, defaultColors)
}
// CreateTheme 创建新主题
func (ts *ThemeService) CreateTheme(theme *models.Theme) (*models.Theme, error) {
query := `
INSERT INTO themes (name, type, colors, is_default, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?)
`
db := ts.getDB()
result, err := db.Exec(
query,
theme.Name,
theme.Type,
theme.Colors,
theme.IsDefault,
theme.CreatedAt,
theme.UpdatedAt,
)
if err != nil {
return nil, fmt.Errorf("failed to create theme: %w", err)
}
id, err := result.LastInsertId()
if err != nil {
return nil, fmt.Errorf("failed to get theme ID: %w", err)
}
theme.ID = int(id)
return theme, nil
}
// GetAllThemes 获取所有主题
func (ts *ThemeService) GetAllThemes() ([]*models.Theme, error) {
query := `
SELECT id, name, type, colors, is_default, created_at, updated_at
FROM themes
ORDER BY is_default DESC, created_at ASC
`
db := ts.getDB()
rows, err := db.Query(query)
if err != nil {
return nil, fmt.Errorf("failed to query themes: %w", err)
}
defer rows.Close()
var themes []*models.Theme
for rows.Next() {
theme := &models.Theme{}
err := rows.Scan(
&theme.ID,
&theme.Name,
&theme.Type,
&theme.Colors,
&theme.IsDefault,
&theme.CreatedAt,
&theme.UpdatedAt,
)
if err != nil {
return nil, fmt.Errorf("failed to scan theme: %w", err)
}
themes = append(themes, theme)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("failed to iterate themes: %w", err)
}
return themes, nil
}
// ServiceShutdown 服务关闭
func (ts *ThemeService) ServiceShutdown() error {
return nil
}

View File

@@ -10,7 +10,7 @@ import (
// TranslationService 翻译服务
type TranslationService struct {
logger *log.Service
logger *log.LogService
factory *translator.TranslatorFactory
defaultTimeout time.Duration
translators map[translator.TranslatorType]translator.Translator
@@ -18,7 +18,7 @@ type TranslationService struct {
}
// NewTranslationService 创建翻译服务实例
func NewTranslationService(logger *log.Service) *TranslationService {
func NewTranslationService(logger *log.LogService) *TranslationService {
service := &TranslationService{
logger: logger,
factory: translator.NewTranslatorFactory(),

View File

@@ -7,14 +7,14 @@ import (
// TrayService 系统托盘服务
type TrayService struct {
logger *log.Service
logger *log.LogService
configService *ConfigService
app *application.App
mainWindow *application.WebviewWindow
}
// NewTrayService 创建新的系统托盘服务实例
func NewTrayService(logger *log.Service, configService *ConfigService) *TrayService {
func NewTrayService(logger *log.LogService, configService *ConfigService) *TrayService {
return &TrayService{
logger: logger,
configService: configService,
@@ -42,7 +42,6 @@ func (ts *TrayService) HandleWindowClose() {
if ts.ShouldMinimizeToTray() {
// 隐藏到托盘
ts.mainWindow.Hide()
ts.app.Event.Emit("window:hidden", nil)
} else {
// 直接退出应用
ts.app.Quit()
@@ -54,7 +53,6 @@ func (ts *TrayService) HandleWindowMinimize() {
if ts.ShouldMinimizeToTray() {
// 隐藏到托盘
ts.mainWindow.Hide()
ts.app.Event.Emit("window:hidden", nil)
}
}
@@ -64,9 +62,6 @@ func (ts *TrayService) ShowWindow() {
ts.mainWindow.Show()
ts.mainWindow.Restore()
ts.mainWindow.Focus()
if ts.app != nil {
ts.app.Event.Emit("window:shown", nil)
}
}
}

View File

@@ -18,7 +18,7 @@ type WindowInfo struct {
// WindowService 窗口管理服务
type WindowService struct {
logger *log.Service
logger *log.LogService
documentService *DocumentService
app *application.App
mainWindow *application.WebviewWindow
@@ -27,7 +27,7 @@ type WindowService struct {
}
// NewWindowService 创建新的窗口服务实例
func NewWindowService(logger *log.Service, documentService *DocumentService) *WindowService {
func NewWindowService(logger *log.LogService, documentService *DocumentService) *WindowService {
if logger == nil {
logger = log.New()
}

11
main.go
View File

@@ -25,6 +25,7 @@ var assets embed.FS
// logs any error that might occur.
func main() {
serviceManager := services.NewServiceManager()
var window *application.WebviewWindow
var encryptionKey = [32]byte{
0x1e, 0x1f, 0x1c, 0x1d, 0x1a, 0x1b, 0x18, 0x19,
@@ -51,6 +52,13 @@ func main() {
SingleInstance: &application.SingleInstanceOptions{
UniqueID: "com.voidraft",
EncryptionKey: encryptionKey,
OnSecondInstanceLaunch: func(data application.SecondInstanceData) {
if window != nil {
window.Show()
window.Restore()
window.Focus()
}
},
AdditionalData: map[string]string{
"launchtime": time.Now().Local().String(),
},
@@ -82,6 +90,7 @@ func main() {
URL: "/",
})
mainWindow.Center()
window = mainWindow
// 获取托盘服务并设置应用引用
trayService := serviceManager.GetTrayService()
@@ -96,7 +105,7 @@ func main() {
// 初始化热键服务
hotkeyService := serviceManager.GetHotkeyService()
err := hotkeyService.Initialize(app)
err := hotkeyService.Initialize(app, mainWindow)
if err != nil {
panic(err)
}