✨ Added data migration service
This commit is contained in:
@@ -62,6 +62,23 @@ export class Menu {
|
||||
}
|
||||
}
|
||||
|
||||
export class WebviewWindow {
|
||||
|
||||
/** Creates a new WebviewWindow instance. */
|
||||
constructor($$source: Partial<WebviewWindow> = {}) {
|
||||
|
||||
Object.assign(this, $$source);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new WebviewWindow instance from a string or object.
|
||||
*/
|
||||
static createFrom($$source: any = {}): WebviewWindow {
|
||||
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
|
||||
return new WebviewWindow($$parsedSource as Partial<WebviewWindow>);
|
||||
}
|
||||
}
|
||||
|
||||
// Private type creation functions
|
||||
const $$createType0 = Menu.createFrom;
|
||||
const $$createType1 = $Create.Nullable($$createType0);
|
||||
|
@@ -5,6 +5,42 @@
|
||||
// @ts-ignore: Unused imports
|
||||
import {Create as $Create} from "@wailsio/runtime";
|
||||
|
||||
/**
|
||||
* A Duration represents the elapsed time between two instants
|
||||
* as an int64 nanosecond count. The representation limits the
|
||||
* largest representable duration to approximately 290 years.
|
||||
*/
|
||||
export enum Duration {
|
||||
/**
|
||||
* The Go zero value for the underlying type of the enum.
|
||||
*/
|
||||
$zero = 0,
|
||||
|
||||
minDuration = -9223372036854775808,
|
||||
maxDuration = 9223372036854775807,
|
||||
|
||||
/**
|
||||
* Common durations. There is no definition for units of Day or larger
|
||||
* to avoid confusion across daylight savings time zone transitions.
|
||||
*
|
||||
* To count the number of units in a [Duration], divide:
|
||||
*
|
||||
* second := time.Second
|
||||
* fmt.Print(int64(second/time.Millisecond)) // prints 1000
|
||||
*
|
||||
* To convert an integer number of units to a Duration, multiply:
|
||||
*
|
||||
* seconds := 10
|
||||
* fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
|
||||
*/
|
||||
Nanosecond = 1,
|
||||
Microsecond = 1000,
|
||||
Millisecond = 1000000,
|
||||
Second = 1000000000,
|
||||
Minute = 60000000000,
|
||||
Hour = 3600000000000,
|
||||
};
|
||||
|
||||
/**
|
||||
* A Time represents an instant in time with nanosecond precision.
|
||||
*
|
||||
|
@@ -348,20 +348,9 @@ export class GeneralConfig {
|
||||
"alwaysOnTop": boolean;
|
||||
|
||||
/**
|
||||
* 默认数据存储路径
|
||||
* 数据存储路径
|
||||
*/
|
||||
"defaultDataPath": string;
|
||||
|
||||
/**
|
||||
* 数据存储路径配置
|
||||
* 是否使用自定义数据路径
|
||||
*/
|
||||
"useCustomDataPath": boolean;
|
||||
|
||||
/**
|
||||
* 自定义数据存储路径
|
||||
*/
|
||||
"customDataPath": string;
|
||||
"dataPath": string;
|
||||
|
||||
/**
|
||||
* 全局热键设置
|
||||
@@ -379,14 +368,8 @@ export class GeneralConfig {
|
||||
if (!("alwaysOnTop" in $$source)) {
|
||||
this["alwaysOnTop"] = false;
|
||||
}
|
||||
if (!("defaultDataPath" in $$source)) {
|
||||
this["defaultDataPath"] = "";
|
||||
}
|
||||
if (!("useCustomDataPath" in $$source)) {
|
||||
this["useCustomDataPath"] = false;
|
||||
}
|
||||
if (!("customDataPath" in $$source)) {
|
||||
this["customDataPath"] = "";
|
||||
if (!("dataPath" in $$source)) {
|
||||
this["dataPath"] = "";
|
||||
}
|
||||
if (!("enableGlobalHotkey" in $$source)) {
|
||||
this["enableGlobalHotkey"] = false;
|
||||
@@ -402,10 +385,10 @@ export class GeneralConfig {
|
||||
* Creates a new GeneralConfig instance from a string or object.
|
||||
*/
|
||||
static createFrom($$source: any = {}): GeneralConfig {
|
||||
const $$createField5_0 = $$createType7;
|
||||
const $$createField3_0 = $$createType7;
|
||||
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
|
||||
if ("globalHotkey" in $$parsedSource) {
|
||||
$$parsedSource["globalHotkey"] = $$createField5_0($$parsedSource["globalHotkey"]);
|
||||
$$parsedSource["globalHotkey"] = $$createField3_0($$parsedSource["globalHotkey"]);
|
||||
}
|
||||
return new GeneralConfig($$parsedSource as Partial<GeneralConfig>);
|
||||
}
|
||||
|
@@ -50,6 +50,14 @@ export function Set(key: string, value: any): Promise<void> & { cancel(): void }
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* SetDataPathChangeCallback 设置数据路径配置变更回调
|
||||
*/
|
||||
export function SetDataPathChangeCallback(callback: any): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(393017412, callback) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* SetHotkeyChangeCallback 设置热键配置变更回调
|
||||
*/
|
||||
|
@@ -10,6 +10,10 @@
|
||||
// @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";
|
||||
|
||||
/**
|
||||
* SelectDirectory 打开目录选择对话框
|
||||
*/
|
||||
@@ -17,3 +21,11 @@ export function SelectDirectory(): Promise<string> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(2249533621) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* SetWindow 设置绑定的窗口
|
||||
*/
|
||||
export function SetWindow(window: application$0.WebviewWindow | null): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(968177170, window) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
@@ -15,7 +15,7 @@ import {Call as $Call, Create as $Create} from "@wailsio/runtime";
|
||||
import * as models$0 from "../models/models.js";
|
||||
|
||||
/**
|
||||
* ForceSave 强制保存当前文档
|
||||
* ForceSave 强制保存
|
||||
*/
|
||||
export function ForceSave(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(2767091023) as any;
|
||||
@@ -23,7 +23,7 @@ export function ForceSave(): Promise<void> & { cancel(): void } {
|
||||
}
|
||||
|
||||
/**
|
||||
* GetActiveDocument 获取当前活动文档
|
||||
* GetActiveDocument 获取活动文档
|
||||
*/
|
||||
export function GetActiveDocument(): Promise<models$0.Document | null> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(1785823398) as any;
|
||||
@@ -35,15 +35,7 @@ export function GetActiveDocument(): Promise<models$0.Document | null> & { cance
|
||||
}
|
||||
|
||||
/**
|
||||
* GetActiveDocumentContent 获取当前活动文档内容
|
||||
*/
|
||||
export function GetActiveDocumentContent(): Promise<string> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(922617063) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize 初始化文档服务
|
||||
* Initialize 初始化服务
|
||||
*/
|
||||
export function Initialize(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3418008221) as any;
|
||||
@@ -51,15 +43,23 @@ export function Initialize(): Promise<void> & { cancel(): void } {
|
||||
}
|
||||
|
||||
/**
|
||||
* SaveDocumentSync 同步保存文档内容
|
||||
* OnDataPathChanged 处理数据路径变更
|
||||
*/
|
||||
export function SaveDocumentSync(content: string): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3770207288, content) as any;
|
||||
export function OnDataPathChanged(oldPath: string, newPath: string): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(269349439, oldPath, newPath) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* ServiceShutdown 服务关闭
|
||||
* ReloadDocument 重新加载文档
|
||||
*/
|
||||
export function ReloadDocument(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3093415283) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* ServiceShutdown 关闭服务
|
||||
*/
|
||||
export function ServiceShutdown(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(638578044) as any;
|
||||
@@ -67,7 +67,7 @@ export function ServiceShutdown(): Promise<void> & { cancel(): void } {
|
||||
}
|
||||
|
||||
/**
|
||||
* UpdateActiveDocumentContent 更新当前活动文档内容
|
||||
* UpdateActiveDocumentContent 更新文档内容
|
||||
*/
|
||||
export function UpdateActiveDocumentContent(content: string): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(1486276638, content) as any;
|
||||
|
@@ -5,12 +5,14 @@ import * as ConfigService from "./configservice.js";
|
||||
import * as DialogService from "./dialogservice.js";
|
||||
import * as DocumentService from "./documentservice.js";
|
||||
import * as HotkeyService from "./hotkeyservice.js";
|
||||
import * as MigrationService from "./migrationservice.js";
|
||||
import * as SystemService from "./systemservice.js";
|
||||
export {
|
||||
ConfigService,
|
||||
DialogService,
|
||||
DocumentService,
|
||||
HotkeyService,
|
||||
MigrationService,
|
||||
SystemService
|
||||
};
|
||||
|
||||
|
@@ -0,0 +1,62 @@
|
||||
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
|
||||
// This file is automatically generated. DO NOT EDIT
|
||||
|
||||
/**
|
||||
* MigrationService 迁移服务
|
||||
* @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 from "./models.js";
|
||||
|
||||
/**
|
||||
* CancelMigration 取消迁移
|
||||
*/
|
||||
export function CancelMigration(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(1813274502) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* GetProgress 获取当前进度
|
||||
*/
|
||||
export function GetProgress(): Promise<$models.MigrationProgress> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3413264131) as any;
|
||||
let $typingPromise = $resultPromise.then(($result: any) => {
|
||||
return $$createType0($result);
|
||||
}) as any;
|
||||
$typingPromise.cancel = $resultPromise.cancel.bind($resultPromise);
|
||||
return $typingPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* MigrateDirectory 迁移目录
|
||||
*/
|
||||
export function MigrateDirectory(srcPath: string, dstPath: string): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(311970580, srcPath, dstPath) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* ServiceShutdown 服务关闭
|
||||
*/
|
||||
export function ServiceShutdown(): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(3472042605) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* SetProgressCallback 设置进度回调
|
||||
*/
|
||||
export function SetProgressCallback(callback: $models.MigrationProgressCallback): Promise<void> & { cancel(): void } {
|
||||
let $resultPromise = $Call.ByID(75752256, callback) as any;
|
||||
return $resultPromise;
|
||||
}
|
||||
|
||||
// Private type creation functions
|
||||
const $$createType0 = $models.MigrationProgress.createFrom;
|
@@ -5,6 +5,10 @@
|
||||
// @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";
|
||||
|
||||
/**
|
||||
* MemoryStats 内存统计信息
|
||||
*/
|
||||
@@ -71,3 +75,152 @@ export class MemoryStats {
|
||||
return new MemoryStats($$parsedSource as Partial<MemoryStats>);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* MigrationProgress 迁移进度信息
|
||||
*/
|
||||
export class MigrationProgress {
|
||||
/**
|
||||
* 迁移状态
|
||||
*/
|
||||
"status": MigrationStatus;
|
||||
|
||||
/**
|
||||
* 当前处理的文件
|
||||
*/
|
||||
"currentFile": string;
|
||||
|
||||
/**
|
||||
* 已处理文件数
|
||||
*/
|
||||
"processedFiles": number;
|
||||
|
||||
/**
|
||||
* 总文件数
|
||||
*/
|
||||
"totalFiles": number;
|
||||
|
||||
/**
|
||||
* 已处理字节数
|
||||
*/
|
||||
"processedBytes": number;
|
||||
|
||||
/**
|
||||
* 总字节数
|
||||
*/
|
||||
"totalBytes": number;
|
||||
|
||||
/**
|
||||
* 进度百分比 (0-100)
|
||||
*/
|
||||
"progress": number;
|
||||
|
||||
/**
|
||||
* 状态消息
|
||||
*/
|
||||
"message": string;
|
||||
|
||||
/**
|
||||
* 错误信息
|
||||
*/
|
||||
"error"?: string;
|
||||
|
||||
/**
|
||||
* 开始时间
|
||||
*/
|
||||
"startTime": time$0.Time;
|
||||
|
||||
/**
|
||||
* 估计剩余时间
|
||||
*/
|
||||
"estimatedTime": time$0.Duration;
|
||||
|
||||
/** Creates a new MigrationProgress instance. */
|
||||
constructor($$source: Partial<MigrationProgress> = {}) {
|
||||
if (!("status" in $$source)) {
|
||||
this["status"] = ("" as MigrationStatus);
|
||||
}
|
||||
if (!("currentFile" in $$source)) {
|
||||
this["currentFile"] = "";
|
||||
}
|
||||
if (!("processedFiles" in $$source)) {
|
||||
this["processedFiles"] = 0;
|
||||
}
|
||||
if (!("totalFiles" in $$source)) {
|
||||
this["totalFiles"] = 0;
|
||||
}
|
||||
if (!("processedBytes" in $$source)) {
|
||||
this["processedBytes"] = 0;
|
||||
}
|
||||
if (!("totalBytes" in $$source)) {
|
||||
this["totalBytes"] = 0;
|
||||
}
|
||||
if (!("progress" in $$source)) {
|
||||
this["progress"] = 0;
|
||||
}
|
||||
if (!("message" in $$source)) {
|
||||
this["message"] = "";
|
||||
}
|
||||
if (!("startTime" in $$source)) {
|
||||
this["startTime"] = null;
|
||||
}
|
||||
if (!("estimatedTime" in $$source)) {
|
||||
this["estimatedTime"] = (0 as time$0.Duration);
|
||||
}
|
||||
|
||||
Object.assign(this, $$source);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new MigrationProgress instance from a string or object.
|
||||
*/
|
||||
static createFrom($$source: any = {}): MigrationProgress {
|
||||
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
|
||||
return new MigrationProgress($$parsedSource as Partial<MigrationProgress>);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* MigrationProgressCallback 进度回调函数类型
|
||||
*/
|
||||
export type MigrationProgressCallback = any;
|
||||
|
||||
/**
|
||||
* MigrationStatus 迁移状态
|
||||
*/
|
||||
export enum MigrationStatus {
|
||||
/**
|
||||
* The Go zero value for the underlying type of the enum.
|
||||
*/
|
||||
$zero = "",
|
||||
|
||||
/**
|
||||
* 空闲状态
|
||||
*/
|
||||
MigrationStatusIdle = "idle",
|
||||
|
||||
/**
|
||||
* 准备中
|
||||
*/
|
||||
MigrationStatusPreparing = "preparing",
|
||||
|
||||
/**
|
||||
* 迁移中
|
||||
*/
|
||||
MigrationStatusMigrating = "migrating",
|
||||
|
||||
/**
|
||||
* 完成
|
||||
*/
|
||||
MigrationStatusCompleted = "completed",
|
||||
|
||||
/**
|
||||
* 失败
|
||||
*/
|
||||
MigrationStatusFailed = "failed",
|
||||
|
||||
/**
|
||||
* 取消
|
||||
*/
|
||||
MigrationStatusCancelled = "cancelled",
|
||||
};
|
||||
|
1
frontend/components.d.ts
vendored
1
frontend/components.d.ts
vendored
@@ -9,6 +9,7 @@ export {}
|
||||
declare module 'vue' {
|
||||
export interface GlobalComponents {
|
||||
MemoryMonitor: typeof import('./src/components/monitor/MemoryMonitor.vue')['default']
|
||||
MigrationProgress: typeof import('./src/components/migration/MigrationProgress.vue')['default']
|
||||
RouterLink: typeof import('vue-router')['RouterLink']
|
||||
RouterView: typeof import('vue-router')['RouterView']
|
||||
Toolbar: typeof import('./src/components/toolbar/Toolbar.vue')['default']
|
||||
|
540
frontend/src/components/migration/MigrationProgress.vue
Normal file
540
frontend/src/components/migration/MigrationProgress.vue
Normal file
@@ -0,0 +1,540 @@
|
||||
<template>
|
||||
<div v-if="visible" class="migration-overlay">
|
||||
<div class="migration-modal">
|
||||
<div class="migration-header">
|
||||
<h3>{{ t('migration.title') }}</h3>
|
||||
<div class="migration-status" :class="status">
|
||||
{{ getStatusText() }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="migration-content">
|
||||
<div class="progress-container">
|
||||
<div class="progress-bar">
|
||||
<div
|
||||
class="progress-fill"
|
||||
:style="{ width: `${progress.progress || 0}%` }"
|
||||
:class="status"
|
||||
></div>
|
||||
</div>
|
||||
<div class="progress-text">
|
||||
{{ Math.round(progress.progress || 0) }}%
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="migration-details">
|
||||
<div v-if="progress.message" class="message">
|
||||
{{ progress.message }}
|
||||
</div>
|
||||
|
||||
<div v-if="progress.currentFile" class="current-file">
|
||||
<span class="label">{{ t('migration.currentFile') }}:</span>
|
||||
<span class="file-name">{{ progress.currentFile }}</span>
|
||||
</div>
|
||||
|
||||
<div class="stats" v-if="progress.totalFiles > 0">
|
||||
<div class="stat-item">
|
||||
<span class="label">{{ t('migration.files') }}:</span>
|
||||
<span class="value">{{ progress.processedFiles }} / {{ progress.totalFiles }}</span>
|
||||
</div>
|
||||
|
||||
<div class="stat-item" v-if="progress.totalBytes > 0">
|
||||
<span class="label">{{ t('migration.size') }}:</span>
|
||||
<span class="value">{{ formatBytes(progress.processedBytes) }} / {{ formatBytes(progress.totalBytes) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="stat-item" v-if="progress.estimatedTime && status === 'migrating'">
|
||||
<span class="label">{{ t('migration.timeRemaining') }}:</span>
|
||||
<span class="value">{{ formatDuration(progress.estimatedTime) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="progress.error" class="error-message">
|
||||
<span class="error-icon">⚠️</span>
|
||||
{{ progress.error }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="migration-actions">
|
||||
<button
|
||||
v-if="status === 'completed'"
|
||||
@click="handleComplete"
|
||||
class="action-button success"
|
||||
>
|
||||
{{ t('migration.complete') }}
|
||||
</button>
|
||||
|
||||
<button
|
||||
v-if="status === 'failed'"
|
||||
@click="handleRetry"
|
||||
class="action-button retry"
|
||||
>
|
||||
{{ t('migration.retry') }}
|
||||
</button>
|
||||
|
||||
<button
|
||||
v-if="status === 'failed'"
|
||||
@click="handleClose"
|
||||
class="action-button secondary"
|
||||
>
|
||||
{{ t('migration.close') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch, onMounted, onUnmounted } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { MigrationService } from '../../../bindings/voidraft/internal/services';
|
||||
|
||||
interface MigrationProgress {
|
||||
status: string;
|
||||
currentFile: string;
|
||||
processedFiles: number;
|
||||
totalFiles: number;
|
||||
processedBytes: number;
|
||||
totalBytes: number;
|
||||
progress: number;
|
||||
message: string;
|
||||
error?: string;
|
||||
startTime: string;
|
||||
estimatedTime: number;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
visible: boolean;
|
||||
}
|
||||
|
||||
interface Emits {
|
||||
(e: 'complete'): void;
|
||||
(e: 'close'): void;
|
||||
(e: 'retry'): void;
|
||||
}
|
||||
|
||||
const props = defineProps<Props>();
|
||||
const emit = defineEmits<Emits>();
|
||||
const { t } = useI18n();
|
||||
|
||||
// 迁移进度状态
|
||||
const progress = ref<MigrationProgress>({
|
||||
status: 'idle',
|
||||
currentFile: '',
|
||||
processedFiles: 0,
|
||||
totalFiles: 0,
|
||||
processedBytes: 0,
|
||||
totalBytes: 0,
|
||||
progress: 0,
|
||||
message: '',
|
||||
startTime: '',
|
||||
estimatedTime: 0
|
||||
});
|
||||
|
||||
const status = computed(() => progress.value.status);
|
||||
|
||||
// 定时器用于轮询进度
|
||||
let progressTimer: number | null = null;
|
||||
|
||||
// 轮询迁移进度
|
||||
const pollProgress = async () => {
|
||||
try {
|
||||
const currentProgress = await MigrationService.GetProgress();
|
||||
progress.value = currentProgress;
|
||||
|
||||
// 如果迁移完成或失败,停止轮询
|
||||
if (currentProgress.status === 'completed' || currentProgress.status === 'failed' || currentProgress.status === 'cancelled') {
|
||||
stopPolling();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to get migration progress:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// 开始轮询
|
||||
const startPolling = () => {
|
||||
if (progressTimer) return;
|
||||
|
||||
// 立即获取一次进度
|
||||
pollProgress();
|
||||
|
||||
// 每500ms轮询一次
|
||||
progressTimer = window.setInterval(pollProgress, 500);
|
||||
};
|
||||
|
||||
// 停止轮询
|
||||
const stopPolling = () => {
|
||||
if (progressTimer) {
|
||||
clearInterval(progressTimer);
|
||||
progressTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
// 监听可见性变化
|
||||
watch(() => props.visible, (visible) => {
|
||||
if (visible) {
|
||||
startPolling();
|
||||
} else {
|
||||
stopPolling();
|
||||
}
|
||||
});
|
||||
|
||||
// 组件挂载时开始轮询(如果可见)
|
||||
onMounted(() => {
|
||||
if (props.visible) {
|
||||
startPolling();
|
||||
}
|
||||
});
|
||||
|
||||
// 组件卸载时停止轮询
|
||||
onUnmounted(() => {
|
||||
stopPolling();
|
||||
});
|
||||
|
||||
// 获取状态文本
|
||||
const getStatusText = () => {
|
||||
switch (status.value) {
|
||||
case 'preparing':
|
||||
return t('migration.preparing');
|
||||
case 'migrating':
|
||||
return t('migration.migrating');
|
||||
case 'completed':
|
||||
return t('migration.completed');
|
||||
case 'failed':
|
||||
return t('migration.failed');
|
||||
case 'cancelled':
|
||||
return t('migration.cancelled');
|
||||
default:
|
||||
return t('migration.idle');
|
||||
}
|
||||
};
|
||||
|
||||
// 格式化字节数
|
||||
const formatBytes = (bytes: number): string => {
|
||||
if (bytes === 0) return '0 B';
|
||||
|
||||
const k = 1024;
|
||||
const sizes = ['B', 'KB', 'MB', 'GB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
|
||||
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
|
||||
};
|
||||
|
||||
// 格式化持续时间
|
||||
const formatDuration = (nanoseconds: number): string => {
|
||||
const seconds = Math.floor(nanoseconds / 1000000000);
|
||||
|
||||
if (seconds < 60) {
|
||||
return `${seconds}秒`;
|
||||
} else if (seconds < 3600) {
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
return `${minutes}分钟`;
|
||||
} else {
|
||||
const hours = Math.floor(seconds / 3600);
|
||||
const minutes = Math.floor((seconds % 3600) / 60);
|
||||
return `${hours}小时${minutes}分钟`;
|
||||
}
|
||||
};
|
||||
|
||||
// 处理完成
|
||||
const handleComplete = () => {
|
||||
emit('complete');
|
||||
};
|
||||
|
||||
// 处理重试
|
||||
const handleRetry = () => {
|
||||
emit('retry');
|
||||
};
|
||||
|
||||
// 处理关闭
|
||||
const handleClose = () => {
|
||||
emit('close');
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.migration-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background-color: rgba(0, 0, 0, 0.7);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 9999;
|
||||
backdrop-filter: blur(4px);
|
||||
}
|
||||
|
||||
.migration-modal {
|
||||
background-color: #2a2a2a;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #444444;
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
max-height: 80vh;
|
||||
overflow: hidden;
|
||||
animation: modalSlideIn 0.3s ease-out;
|
||||
}
|
||||
|
||||
@keyframes modalSlideIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-20px) scale(0.95);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0) scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
.migration-header {
|
||||
padding: 20px 24px 16px;
|
||||
border-bottom: 1px solid #444444;
|
||||
|
||||
h3 {
|
||||
margin: 0 0 8px 0;
|
||||
color: #e0e0e0;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.migration-status {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
padding: 4px 8px;
|
||||
border-radius: 4px;
|
||||
display: inline-block;
|
||||
|
||||
&.preparing {
|
||||
color: #ffc107;
|
||||
background-color: rgba(255, 193, 7, 0.1);
|
||||
}
|
||||
|
||||
&.migrating {
|
||||
color: #17a2b8;
|
||||
background-color: rgba(23, 162, 184, 0.1);
|
||||
}
|
||||
|
||||
&.completed {
|
||||
color: #28a745;
|
||||
background-color: rgba(40, 167, 69, 0.1);
|
||||
}
|
||||
|
||||
&.failed {
|
||||
color: #dc3545;
|
||||
background-color: rgba(220, 53, 69, 0.1);
|
||||
}
|
||||
|
||||
&.cancelled {
|
||||
color: #6c757d;
|
||||
background-color: rgba(108, 117, 125, 0.1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.migration-content {
|
||||
padding: 20px 24px;
|
||||
max-height: 60vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.progress-container {
|
||||
margin-bottom: 20px;
|
||||
|
||||
.progress-bar {
|
||||
width: 100%;
|
||||
height: 8px;
|
||||
background-color: #444444;
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 8px;
|
||||
|
||||
.progress-fill {
|
||||
height: 100%;
|
||||
transition: width 0.3s ease;
|
||||
border-radius: 4px;
|
||||
|
||||
&.preparing {
|
||||
background-color: #ffc107;
|
||||
}
|
||||
|
||||
&.migrating {
|
||||
background-color: #17a2b8;
|
||||
background-image: linear-gradient(
|
||||
45deg,
|
||||
rgba(255, 255, 255, 0.1) 25%,
|
||||
transparent 25%,
|
||||
transparent 50%,
|
||||
rgba(255, 255, 255, 0.1) 50%,
|
||||
rgba(255, 255, 255, 0.1) 75%,
|
||||
transparent 75%,
|
||||
transparent
|
||||
);
|
||||
background-size: 20px 20px;
|
||||
animation: progressStripes 1s linear infinite;
|
||||
}
|
||||
|
||||
&.completed {
|
||||
background-color: #28a745;
|
||||
}
|
||||
|
||||
&.failed {
|
||||
background-color: #dc3545;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.progress-text {
|
||||
text-align: center;
|
||||
color: #b0b0b0;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes progressStripes {
|
||||
0% {
|
||||
background-position: 0 0;
|
||||
}
|
||||
100% {
|
||||
background-position: 20px 0;
|
||||
}
|
||||
}
|
||||
|
||||
.migration-details {
|
||||
.message {
|
||||
color: #e0e0e0;
|
||||
font-size: 14px;
|
||||
margin-bottom: 12px;
|
||||
padding: 8px 12px;
|
||||
background-color: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.current-file {
|
||||
margin-bottom: 12px;
|
||||
font-size: 13px;
|
||||
|
||||
.label {
|
||||
color: #888888;
|
||||
}
|
||||
|
||||
.file-name {
|
||||
color: #e0e0e0;
|
||||
font-family: 'Consolas', 'Courier New', monospace;
|
||||
word-break: break-all;
|
||||
}
|
||||
}
|
||||
|
||||
.stats {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
|
||||
.stat-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
font-size: 13px;
|
||||
|
||||
.label {
|
||||
color: #888888;
|
||||
}
|
||||
|
||||
.value {
|
||||
color: #e0e0e0;
|
||||
font-weight: 500;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.error-message {
|
||||
margin-top: 16px;
|
||||
padding: 12px;
|
||||
background-color: rgba(220, 53, 69, 0.1);
|
||||
border: 1px solid rgba(220, 53, 69, 0.3);
|
||||
border-radius: 4px;
|
||||
color: #ff6b6b;
|
||||
font-size: 13px;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
|
||||
.error-icon {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.migration-actions {
|
||||
padding: 16px 24px 20px;
|
||||
border-top: 1px solid #444444;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 12px;
|
||||
|
||||
.action-button {
|
||||
padding: 8px 16px;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&.success {
|
||||
background-color: #28a745;
|
||||
color: white;
|
||||
|
||||
&:hover {
|
||||
background-color: #218838;
|
||||
}
|
||||
}
|
||||
|
||||
&.retry {
|
||||
background-color: #17a2b8;
|
||||
color: white;
|
||||
|
||||
&:hover {
|
||||
background-color: #138496;
|
||||
}
|
||||
}
|
||||
|
||||
&.secondary {
|
||||
background-color: #6c757d;
|
||||
color: white;
|
||||
|
||||
&:hover {
|
||||
background-color: #5a6268;
|
||||
}
|
||||
}
|
||||
|
||||
&:active {
|
||||
transform: translateY(1px);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 自定义滚动条 */
|
||||
.migration-content::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
.migration-content::-webkit-scrollbar-track {
|
||||
background: #333333;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.migration-content::-webkit-scrollbar-thumb {
|
||||
background: #666666;
|
||||
border-radius: 3px;
|
||||
|
||||
&:hover {
|
||||
background: #777777;
|
||||
}
|
||||
}
|
||||
</style>
|
@@ -45,8 +45,38 @@ export default {
|
||||
loadFailed: 'Failed to load save settings',
|
||||
saveSuccess: 'Save settings updated',
|
||||
saveFailed: 'Failed to update save settings'
|
||||
},
|
||||
migration: {
|
||||
inProgress: 'Migrating data to new path...',
|
||||
success: 'Data migration completed',
|
||||
failed: 'Data migration failed'
|
||||
}
|
||||
},
|
||||
migration: {
|
||||
title: 'Data Migration',
|
||||
preparing: 'Preparing',
|
||||
migrating: 'Migrating',
|
||||
completed: 'Completed',
|
||||
failed: 'Failed',
|
||||
cancelled: 'Cancelled',
|
||||
idle: 'Idle',
|
||||
currentFile: 'Current File',
|
||||
files: 'Files',
|
||||
size: 'Size',
|
||||
timeRemaining: 'Time Remaining',
|
||||
complete: 'Complete',
|
||||
retry: 'Retry',
|
||||
close: 'Close',
|
||||
migrationInProgress: 'Migrating data to new path...',
|
||||
migrationCompleted: 'Data migration completed',
|
||||
migrationFailed: 'Data migration failed',
|
||||
recursiveCopyError: 'Target path cannot be a subdirectory of source path, this would cause infinite recursive copying',
|
||||
targetNotDirectory: 'Target path exists but is not a directory',
|
||||
targetNotEmpty: 'Target directory is not empty, cannot migrate',
|
||||
compressing: 'Compressing source directory...',
|
||||
extracting: 'Extracting to target location...',
|
||||
cleaning: 'Cleaning up source directory...'
|
||||
},
|
||||
settings: {
|
||||
title: 'Settings',
|
||||
backToEditor: 'Back to Editor',
|
||||
@@ -69,13 +99,11 @@ export default {
|
||||
showInSystemTray: 'Show in System Tray',
|
||||
alwaysOnTop: 'Always on Top',
|
||||
dataStorage: 'Data Storage',
|
||||
useCustomDataPath: 'Use custom data storage path',
|
||||
selectDirectory: 'Select Directory',
|
||||
selectDataDirectory: 'Select Data Storage Directory',
|
||||
defaultDataPath: 'Default data storage path',
|
||||
bufferFiles: 'Buffer Files Path',
|
||||
useCustomLocation: 'Use custom location for buffer files',
|
||||
customDataPath: 'Custom Data Storage Path',
|
||||
dataPath: 'Data Storage Path',
|
||||
clickToSelectPath: 'Click to select path',
|
||||
resetDefault: 'Reset Default',
|
||||
resetToDefaultPath: 'Reset to default path',
|
||||
restartRequiredForDataPath: 'Restart required',
|
||||
fontSize: 'Font Size',
|
||||
fontSizeDescription: 'Editor font size',
|
||||
fontSettings: 'Font Settings',
|
||||
@@ -95,6 +123,10 @@ export default {
|
||||
restartRequired: '(Restart required)',
|
||||
saveOptions: 'Save Options',
|
||||
autoSaveDelay: 'Auto Save Delay (ms)',
|
||||
selectDirectoryFailed: 'Failed to select directory'
|
||||
selectDirectoryFailed: 'Failed to select directory',
|
||||
validation: {
|
||||
customPathRequired: 'A valid directory must be selected when enabling custom path',
|
||||
customPathAutoDisabled: 'Custom data path has been automatically disabled due to no valid directory selected'
|
||||
}
|
||||
}
|
||||
};
|
@@ -45,8 +45,38 @@ export default {
|
||||
loadFailed: '加载保存设置失败',
|
||||
saveSuccess: '保存设置已更新',
|
||||
saveFailed: '保存设置更新失败'
|
||||
},
|
||||
migration: {
|
||||
inProgress: '正在迁移数据到新路径...',
|
||||
success: '数据迁移完成',
|
||||
failed: '数据迁移失败'
|
||||
}
|
||||
},
|
||||
migration: {
|
||||
title: '数据迁移',
|
||||
preparing: '准备中',
|
||||
migrating: '迁移中',
|
||||
completed: '已完成',
|
||||
failed: '失败',
|
||||
cancelled: '已取消',
|
||||
idle: '空闲',
|
||||
currentFile: '当前文件',
|
||||
files: '文件',
|
||||
size: '大小',
|
||||
timeRemaining: '剩余时间',
|
||||
complete: '完成',
|
||||
retry: '重试',
|
||||
close: '关闭',
|
||||
migrationInProgress: '正在迁移数据到新路径...',
|
||||
migrationCompleted: '数据迁移完成',
|
||||
migrationFailed: '数据迁移失败',
|
||||
recursiveCopyError: '目标路径不能是源路径的子目录,这会导致无限递归复制',
|
||||
targetNotDirectory: '目标路径存在但不是目录',
|
||||
targetNotEmpty: '目标目录不为空,无法迁移',
|
||||
compressing: '正在压缩源目录...',
|
||||
extracting: '正在解压到目标位置...',
|
||||
cleaning: '正在清理源目录...'
|
||||
},
|
||||
settings: {
|
||||
title: '设置',
|
||||
backToEditor: '返回编辑器',
|
||||
@@ -69,13 +99,11 @@ export default {
|
||||
showInSystemTray: '在系统托盘中显示',
|
||||
alwaysOnTop: '窗口始终置顶',
|
||||
dataStorage: '数据存储',
|
||||
useCustomDataPath: '使用自定义数据存储路径',
|
||||
selectDirectory: '选择目录',
|
||||
selectDataDirectory: '选择数据存储目录',
|
||||
defaultDataPath: '默认数据存储路径',
|
||||
bufferFiles: '缓冲文件路径',
|
||||
useCustomLocation: '使用自定义位置存储缓冲文件',
|
||||
customDataPath: '自定义数据存储路径',
|
||||
dataPath: '数据存储路径',
|
||||
clickToSelectPath: '点击选择路径',
|
||||
resetDefault: '恢复默认',
|
||||
resetToDefaultPath: '恢复为默认路径',
|
||||
restartRequiredForDataPath: '需要重启应用程序',
|
||||
fontSize: '字体大小',
|
||||
fontSizeDescription: '编辑器字体大小',
|
||||
fontSettings: '字体设置',
|
||||
@@ -95,6 +123,10 @@ export default {
|
||||
restartRequired: '(需要重启)',
|
||||
saveOptions: '保存选项',
|
||||
autoSaveDelay: '自动保存延迟(毫秒)',
|
||||
selectDirectoryFailed: '选择目录失败'
|
||||
selectDirectoryFailed: '选择目录失败',
|
||||
validation: {
|
||||
customPathRequired: '启用自定义路径时必须选择一个有效的目录',
|
||||
customPathAutoDisabled: '由于未选择有效目录,自定义数据路径已自动关闭'
|
||||
}
|
||||
}
|
||||
};
|
@@ -47,9 +47,7 @@ type NumberConfigKey = 'fontSize' | 'tabSize' | 'lineHeight';
|
||||
// 配置键映射
|
||||
const GENERAL_CONFIG_KEY_MAP: GeneralConfigKeyMap = {
|
||||
alwaysOnTop: 'general.always_on_top',
|
||||
defaultDataPath: 'general.default_data_path',
|
||||
useCustomDataPath: 'general.use_custom_data_path',
|
||||
customDataPath: 'general.custom_data_path',
|
||||
dataPath: 'general.data_path',
|
||||
enableGlobalHotkey: 'general.enable_global_hotkey',
|
||||
globalHotkey: 'general.global_hotkey'
|
||||
} as const;
|
||||
@@ -115,9 +113,7 @@ const getBrowserLanguage = (): SupportedLocaleType => {
|
||||
const DEFAULT_CONFIG: AppConfig = {
|
||||
general: {
|
||||
alwaysOnTop: false,
|
||||
defaultDataPath: './data',
|
||||
useCustomDataPath: false,
|
||||
customDataPath: '',
|
||||
dataPath: './data',
|
||||
enableGlobalHotkey: false,
|
||||
globalHotkey: {
|
||||
ctrl: false,
|
||||
@@ -333,7 +329,7 @@ export const useConfigStore = defineStore('config', () => {
|
||||
const setters = {
|
||||
fontFamily: (value: string) => safeCall(() => updateEditingConfig('fontFamily', value), 'config.saveFailed', 'config.saveSuccess'),
|
||||
fontWeight: (value: string) => safeCall(() => updateEditingConfig('fontWeight', value), 'config.saveFailed', 'config.saveSuccess'),
|
||||
defaultDataPath: (value: string) => safeCall(() => updateGeneralConfig('defaultDataPath', value), 'config.saveFailed', 'config.saveSuccess'),
|
||||
dataPath: (value: string) => safeCall(() => updateGeneralConfig('dataPath', value), 'config.saveFailed', 'config.saveSuccess'),
|
||||
autoSaveDelay: (value: number) => safeCall(() => updateEditingConfig('autoSaveDelay', value), 'config.saveFailed', 'config.saveSuccess')
|
||||
};
|
||||
|
||||
@@ -382,9 +378,7 @@ export const useConfigStore = defineStore('config', () => {
|
||||
setFontWeight: setters.fontWeight,
|
||||
|
||||
// 路径操作
|
||||
setDefaultDataPath: setters.defaultDataPath,
|
||||
setUseCustomDataPath: (value: boolean) => safeCall(() => updateGeneralConfig('useCustomDataPath', value), 'config.saveFailed', 'config.saveSuccess'),
|
||||
setCustomDataPath: (value: string) => safeCall(() => updateGeneralConfig('customDataPath', value), 'config.saveFailed', 'config.saveSuccess'),
|
||||
setDataPath: setters.dataPath,
|
||||
|
||||
// 保存配置相关方法
|
||||
setAutoSaveDelay: setters.autoSaveDelay,
|
||||
|
@@ -24,7 +24,7 @@ export interface AutoSaveOptions {
|
||||
export function createAutoSavePlugin(options: AutoSaveOptions = {}) {
|
||||
const {
|
||||
onSave = () => {},
|
||||
debounceDelay = 1000 // 默认1000ms延迟,原为300ms
|
||||
debounceDelay = 2000
|
||||
} = options;
|
||||
|
||||
return ViewPlugin.fromClass(
|
||||
|
@@ -1,12 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import { useConfigStore } from '@/stores/configStore';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { ref, watch } from 'vue';
|
||||
import { ref } from 'vue';
|
||||
import { useRouter, useRoute } from 'vue-router';
|
||||
import MemoryMonitor from '@/components/monitor/MemoryMonitor.vue';
|
||||
|
||||
const { t } = useI18n();
|
||||
const configStore = useConfigStore();
|
||||
const router = useRouter();
|
||||
const route = useRoute();
|
||||
|
||||
@@ -28,9 +26,10 @@ const handleNavClick = (item: typeof navItems[0]) => {
|
||||
};
|
||||
|
||||
// 返回编辑器
|
||||
const goBackToEditor = () => {
|
||||
router.push('/');
|
||||
const goBackToEditor = async () => {
|
||||
await router.push('/');
|
||||
};
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
@@ -1,18 +1,22 @@
|
||||
<script setup lang="ts">
|
||||
import { useConfigStore } from '@/stores/configStore';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { computed} from 'vue';
|
||||
import { computed, ref, onMounted } from 'vue';
|
||||
import SettingSection from '../components/SettingSection.vue';
|
||||
import SettingItem from '../components/SettingItem.vue';
|
||||
import ToggleSwitch from '../components/ToggleSwitch.vue';
|
||||
import MigrationProgress from '@/components/migration/MigrationProgress.vue';
|
||||
import { useErrorHandler } from '@/utils/errorHandler';
|
||||
import { DialogService } from '@/../bindings/voidraft/internal/services';
|
||||
import { DialogService, MigrationService } from '@/../bindings/voidraft/internal/services';
|
||||
import * as runtime from '@wailsio/runtime';
|
||||
|
||||
const { t } = useI18n();
|
||||
const configStore = useConfigStore();
|
||||
const { safeCall } = useErrorHandler();
|
||||
|
||||
// 迁移状态
|
||||
const showMigrationProgress = ref(false);
|
||||
|
||||
// 可选键列表
|
||||
const keyOptions = [
|
||||
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
|
||||
@@ -87,34 +91,57 @@ const hotkeyPreview = computed(() => {
|
||||
return parts.join(' + ');
|
||||
});
|
||||
|
||||
// 数据存储路径配置
|
||||
const useCustomDataPath = computed({
|
||||
get: () => configStore.config.general.useCustomDataPath,
|
||||
set: (value: boolean) => configStore.setUseCustomDataPath(value)
|
||||
});
|
||||
// 数据路径配置
|
||||
const currentDataPath = computed(() => configStore.config.general.dataPath);
|
||||
|
||||
// 自定义路径显示
|
||||
const customPathDisplay = computed(() => {
|
||||
return configStore.config.general.customDataPath || '';
|
||||
});
|
||||
|
||||
const selectDirectory = async () => {
|
||||
// 只有开启自定义路径时才能选择
|
||||
if (!useCustomDataPath.value) return;
|
||||
|
||||
// 选择数据存储目录
|
||||
const selectDataDirectory = async () => {
|
||||
try {
|
||||
const selectedPath = await DialogService.SelectDirectory();
|
||||
|
||||
if (selectedPath && selectedPath.trim()) {
|
||||
await configStore.setCustomDataPath(selectedPath.trim());
|
||||
if (selectedPath && selectedPath.trim() && selectedPath !== currentDataPath.value) {
|
||||
// 显示迁移进度对话框
|
||||
showMigrationProgress.value = true;
|
||||
|
||||
// 开始迁移
|
||||
await safeCall(async () => {
|
||||
const oldPath = currentDataPath.value;
|
||||
const newPath = selectedPath.trim();
|
||||
|
||||
// 先启动迁移
|
||||
await MigrationService.MigrateDirectory(oldPath, newPath);
|
||||
|
||||
// 迁移完成后更新配置
|
||||
await configStore.setDataPath(newPath);
|
||||
}, 'migration.migrationFailed');
|
||||
}
|
||||
} catch (error) {
|
||||
// 可以添加用户友好的错误提示
|
||||
await safeCall(async () => {
|
||||
throw error;
|
||||
}, 'settings.selectDirectoryFailed');
|
||||
}
|
||||
};
|
||||
|
||||
// 处理迁移完成
|
||||
const handleMigrationComplete = () => {
|
||||
showMigrationProgress.value = false;
|
||||
// 显示成功消息
|
||||
safeCall(async () => {
|
||||
// 空的成功操作,只为了显示成功消息
|
||||
}, '', 'migration.migrationCompleted');
|
||||
};
|
||||
|
||||
// 处理迁移关闭
|
||||
const handleMigrationClose = () => {
|
||||
showMigrationProgress.value = false;
|
||||
};
|
||||
|
||||
// 处理迁移重试
|
||||
const handleMigrationRetry = () => {
|
||||
// 重新触发路径选择
|
||||
showMigrationProgress.value = false;
|
||||
selectDataDirectory();
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -162,27 +189,20 @@ const selectDirectory = async () => {
|
||||
</SettingSection>
|
||||
|
||||
<SettingSection :title="t('settings.dataStorage')">
|
||||
<SettingItem :title="t('settings.useCustomDataPath')">
|
||||
<ToggleSwitch v-model="useCustomDataPath" />
|
||||
</SettingItem>
|
||||
|
||||
<!-- 路径显示区域 -->
|
||||
<div class="path-section">
|
||||
<div class="path-input-container">
|
||||
<div class="data-path-setting">
|
||||
<div class="setting-header">
|
||||
<div class="setting-title">{{ t('settings.dataPath') }}</div>
|
||||
</div>
|
||||
<div class="data-path-controls">
|
||||
<input
|
||||
type="text"
|
||||
:value="useCustomDataPath ? customPathDisplay : configStore.config.general.defaultDataPath"
|
||||
:value="currentDataPath"
|
||||
readonly
|
||||
:placeholder="useCustomDataPath ? t('settings.selectDataDirectory') : t('settings.defaultDataPath')"
|
||||
:class="[
|
||||
'path-display-input',
|
||||
{ 'clickable': useCustomDataPath, 'disabled': !useCustomDataPath }
|
||||
]"
|
||||
@click="selectDirectory"
|
||||
:placeholder="t('settings.clickToSelectPath')"
|
||||
class="path-display-input"
|
||||
@click="selectDataDirectory"
|
||||
:title="t('settings.clickToSelectPath')"
|
||||
/>
|
||||
<div class="path-label">
|
||||
{{ useCustomDataPath ? t('settings.customDataPath') : t('settings.defaultDataPath') }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</SettingSection>
|
||||
@@ -200,6 +220,14 @@ const selectDirectory = async () => {
|
||||
</div>
|
||||
</div>
|
||||
</SettingSection>
|
||||
|
||||
<!-- 迁移进度对话框 -->
|
||||
<MigrationProgress
|
||||
:visible="showMigrationProgress"
|
||||
@complete="handleMigrationComplete"
|
||||
@close="handleMigrationClose"
|
||||
@retry="handleMigrationRetry"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -312,31 +340,44 @@ const selectDirectory = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
.path-section {
|
||||
margin-top: 10px;
|
||||
padding: 0 20px;
|
||||
.data-path-setting {
|
||||
padding: 14px 0;
|
||||
|
||||
&:hover {
|
||||
background-color: rgba(255, 255, 255, 0.03);
|
||||
}
|
||||
|
||||
.setting-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 12px;
|
||||
|
||||
.setting-title {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: #e0e0e0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.data-path-controls {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
|
||||
.path-input-container {
|
||||
.path-display-input {
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
max-width: 450px;
|
||||
box-sizing: border-box;
|
||||
padding: 8px 12px;
|
||||
padding: 10px 12px;
|
||||
background-color: #3a3a3a;
|
||||
border: 1px solid #555555;
|
||||
border-radius: 4px;
|
||||
color: #e0e0e0;
|
||||
font-size: 13px;
|
||||
line-height: 1.2;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&.disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
background-color: #2a2a2a;
|
||||
border-color: #444444;
|
||||
}
|
||||
|
||||
&.clickable {
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
@@ -348,20 +389,16 @@ const selectDirectory = async () => {
|
||||
outline: none;
|
||||
border-color: #4a9eff;
|
||||
background-color: #404040;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
&::placeholder {
|
||||
color: #888888;
|
||||
}
|
||||
}
|
||||
|
||||
.path-label {
|
||||
margin-top: 4px;
|
||||
color: #888888;
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
.danger-zone {
|
||||
@@ -389,7 +426,7 @@ const selectDirectory = async () => {
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
color: #b0b0b0;
|
||||
color: #cccccc;
|
||||
font-size: 13px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
@@ -398,14 +435,13 @@ const selectDirectory = async () => {
|
||||
.reset-button {
|
||||
padding: 8px 16px;
|
||||
background-color: #dc3545;
|
||||
border: 1px solid #c82333;
|
||||
border: 1px solid #dc3545;
|
||||
border-radius: 4px;
|
||||
color: #ffffff;
|
||||
cursor: pointer;
|
||||
color: white;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
|
||||
&:hover {
|
||||
background-color: #c82333;
|
||||
|
@@ -28,12 +28,8 @@ const (
|
||||
|
||||
// GeneralConfig 通用设置配置
|
||||
type GeneralConfig struct {
|
||||
AlwaysOnTop bool `json:"alwaysOnTop" yaml:"always_on_top" mapstructure:"always_on_top"` // 窗口是否置顶
|
||||
DefaultDataPath string `json:"defaultDataPath" yaml:"default_data_path" mapstructure:"default_data_path"` // 默认数据存储路径
|
||||
|
||||
// 数据存储路径配置
|
||||
UseCustomDataPath bool `json:"useCustomDataPath" yaml:"use_custom_data_path" mapstructure:"use_custom_data_path"` // 是否使用自定义数据路径
|
||||
CustomDataPath string `json:"customDataPath" yaml:"custom_data_path" mapstructure:"custom_data_path"` // 自定义数据存储路径
|
||||
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"` // 是否启用全局热键
|
||||
@@ -111,9 +107,7 @@ func NewDefaultAppConfig() *AppConfig {
|
||||
return &AppConfig{
|
||||
General: GeneralConfig{
|
||||
AlwaysOnTop: false,
|
||||
DefaultDataPath: dataDir,
|
||||
UseCustomDataPath: false,
|
||||
CustomDataPath: "",
|
||||
DataPath: dataDir,
|
||||
EnableGlobalHotkey: false,
|
||||
GlobalHotkey: HotkeyCombo{
|
||||
Ctrl: false,
|
||||
|
@@ -19,6 +19,8 @@ type ConfigChangeType string
|
||||
const (
|
||||
// ConfigChangeTypeHotkey 热键配置变更
|
||||
ConfigChangeTypeHotkey ConfigChangeType = "hotkey"
|
||||
// ConfigChangeTypeDataPath 数据路径配置变更
|
||||
ConfigChangeTypeDataPath ConfigChangeType = "datapath"
|
||||
)
|
||||
|
||||
// ConfigChangeCallback 配置变更回调函数类型
|
||||
@@ -449,6 +451,45 @@ func CreateHotkeyListener(callback func(enable bool, hotkey *models.HotkeyCombo)
|
||||
}
|
||||
}
|
||||
|
||||
// CreateDataPathListener 创建数据路径配置监听器
|
||||
func CreateDataPathListener(callback func(oldPath, newPath string) error) *ConfigListener {
|
||||
return &ConfigListener{
|
||||
Name: "DataPathListener",
|
||||
ChangeType: ConfigChangeTypeDataPath,
|
||||
Callback: func(changeType ConfigChangeType, oldConfig, newConfig interface{}) error {
|
||||
var oldPath, newPath string
|
||||
|
||||
// 处理旧配置
|
||||
if oldAppConfig, ok := oldConfig.(*models.AppConfig); ok {
|
||||
oldPath = oldAppConfig.General.DataPath
|
||||
}
|
||||
|
||||
// 处理新配置
|
||||
if newAppConfig, ok := newConfig.(*models.AppConfig); ok {
|
||||
newPath = newAppConfig.General.DataPath
|
||||
} else if newConfig == nil {
|
||||
// 如果新配置为空,说明配置被删除,使用默认值
|
||||
defaultConfig := models.NewDefaultAppConfig()
|
||||
newPath = defaultConfig.General.DataPath
|
||||
}
|
||||
|
||||
// 只有路径真正改变时才调用回调
|
||||
if oldPath != newPath {
|
||||
return callback(oldPath, newPath)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
DebounceDelay: 100 * time.Millisecond, // 较短的防抖延迟,因为数据路径变更需要快速响应
|
||||
GetConfigFunc: func(v *viper.Viper) interface{} {
|
||||
var config models.AppConfig
|
||||
if err := v.Unmarshal(&config); err != nil {
|
||||
return nil
|
||||
}
|
||||
return &config
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ServiceShutdown 关闭服务
|
||||
func (cns *ConfigNotificationService) ServiceShutdown() error {
|
||||
cns.Cleanup()
|
||||
|
@@ -105,9 +105,7 @@ func setDefaults(v *viper.Viper) {
|
||||
|
||||
// 通用设置默认值
|
||||
v.SetDefault("general.always_on_top", defaultConfig.General.AlwaysOnTop)
|
||||
v.SetDefault("general.default_data_path", defaultConfig.General.DefaultDataPath)
|
||||
v.SetDefault("general.use_custom_data_path", defaultConfig.General.UseCustomDataPath)
|
||||
v.SetDefault("general.custom_data_path", defaultConfig.General.CustomDataPath)
|
||||
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)
|
||||
@@ -257,3 +255,13 @@ func (cs *ConfigService) SetHotkeyChangeCallback(callback func(enable bool, hotk
|
||||
hotkeyListener := CreateHotkeyListener(callback)
|
||||
return cs.notificationService.RegisterListener(hotkeyListener)
|
||||
}
|
||||
|
||||
// SetDataPathChangeCallback 设置数据路径配置变更回调
|
||||
func (cs *ConfigService) SetDataPathChangeCallback(callback func(oldPath, newPath string) error) error {
|
||||
cs.mu.Lock()
|
||||
defer cs.mu.Unlock()
|
||||
|
||||
// 创建数据路径监听器并注册
|
||||
dataPathListener := CreateDataPathListener(callback)
|
||||
return cs.notificationService.RegisterListener(dataPathListener)
|
||||
}
|
||||
|
@@ -8,6 +8,7 @@ import (
|
||||
// DialogService 对话框服务,处理文件选择等对话框操作
|
||||
type DialogService struct {
|
||||
logger *log.LoggerService
|
||||
window *application.WebviewWindow // 绑定的窗口
|
||||
}
|
||||
|
||||
// NewDialogService 创建新的对话框服务实例
|
||||
@@ -18,9 +19,16 @@ func NewDialogService(logger *log.LoggerService) *DialogService {
|
||||
|
||||
return &DialogService{
|
||||
logger: logger,
|
||||
window: nil, // 初始为空,后续通过 SetWindow 设置
|
||||
}
|
||||
}
|
||||
|
||||
// SetWindow 设置绑定的窗口
|
||||
func (ds *DialogService) SetWindow(window *application.WebviewWindow) {
|
||||
ds.window = window
|
||||
ds.logger.Info("Dialog service window binding updated")
|
||||
}
|
||||
|
||||
// SelectDirectory 打开目录选择对话框
|
||||
func (ds *DialogService) SelectDirectory() (string, error) {
|
||||
dialog := application.OpenFileDialogWithOptions(&application.OpenFileDialogOptions{
|
||||
@@ -41,9 +49,9 @@ func (ds *DialogService) SelectDirectory() (string, error) {
|
||||
ResolvesAliases: true, // 解析别名/快捷方式
|
||||
|
||||
// 对话框文本配置
|
||||
Title: "选择数据存储目录",
|
||||
Message: "请选择用于存储应用数据的文件夹",
|
||||
ButtonText: "选择",
|
||||
Title: "Select Directory",
|
||||
Message: "Select the folder where you want to store your app data",
|
||||
ButtonText: "Select",
|
||||
|
||||
// 不设置过滤器,因为我们选择目录
|
||||
Filters: nil,
|
||||
@@ -51,8 +59,8 @@ func (ds *DialogService) SelectDirectory() (string, error) {
|
||||
// 不指定默认目录,让系统决定
|
||||
Directory: "",
|
||||
|
||||
// 不绑定到特定窗口,使用默认行为
|
||||
Window: nil,
|
||||
// 绑定到主窗口
|
||||
Window: ds.window,
|
||||
})
|
||||
|
||||
path, err := dialog.PromptForSingleSelection()
|
||||
|
@@ -1,119 +1,183 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/wailsapp/wails/v3/pkg/services/log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
"voidraft/internal/models"
|
||||
|
||||
"github.com/wailsapp/wails/v3/pkg/services/log"
|
||||
)
|
||||
|
||||
// DocumentError 文档操作错误
|
||||
type DocumentError struct {
|
||||
Operation string // 操作名称
|
||||
Err error // 原始错误
|
||||
}
|
||||
|
||||
// Error 实现error接口
|
||||
func (e *DocumentError) Error() string {
|
||||
return fmt.Sprintf("document error during %s: %v", e.Operation, e.Err)
|
||||
}
|
||||
|
||||
// Unwrap 获取原始错误
|
||||
func (e *DocumentError) Unwrap() error {
|
||||
return e.Err
|
||||
}
|
||||
|
||||
// DocumentService 提供文档管理功能
|
||||
type DocumentService struct {
|
||||
configService *ConfigService
|
||||
logger *log.LoggerService
|
||||
document *models.Document // 文档实例
|
||||
document *models.Document
|
||||
docStore *Store[models.Document]
|
||||
mutex sync.RWMutex // 保护document的读写
|
||||
mutex sync.RWMutex
|
||||
|
||||
// 定时保存
|
||||
saveTimer *time.Timer
|
||||
timerMutex sync.Mutex // 保护定时器操作
|
||||
isDirty bool // 文档是否有未保存的变更
|
||||
|
||||
// 服务控制
|
||||
shutdown chan struct{}
|
||||
shutdownOnce sync.Once
|
||||
// 自动保存优化
|
||||
saveTimer *time.Timer
|
||||
isDirty bool
|
||||
lastSaveTime time.Time
|
||||
pendingContent string // 暂存待保存的内容
|
||||
}
|
||||
|
||||
// NewDocumentService 创建新的文档服务实例
|
||||
// NewDocumentService 创建文档服务
|
||||
func NewDocumentService(configService *ConfigService, logger *log.LoggerService) *DocumentService {
|
||||
if logger == nil {
|
||||
logger = log.New()
|
||||
}
|
||||
|
||||
service := &DocumentService{
|
||||
return &DocumentService{
|
||||
configService: configService,
|
||||
logger: logger,
|
||||
shutdown: make(chan struct{}),
|
||||
}
|
||||
|
||||
return service
|
||||
}
|
||||
|
||||
// Initialize 初始化文档服务
|
||||
// Initialize 初始化服务
|
||||
func (ds *DocumentService) Initialize() error {
|
||||
// 确保文档目录存在
|
||||
if err := ds.ensureDocumentsDir(); err != nil {
|
||||
ds.logger.Error("Document: Failed to ensure documents directory", "error", err)
|
||||
return &DocumentError{Operation: "initialize", Err: err}
|
||||
if err := ds.initStore(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 初始化文档存储
|
||||
if err := ds.initDocumentStore(); err != nil {
|
||||
ds.logger.Error("Document: Failed to initialize document store", "error", err)
|
||||
return &DocumentError{Operation: "init_store", Err: err}
|
||||
}
|
||||
|
||||
// 加载默认文档
|
||||
if err := ds.loadDefaultDocument(); err != nil {
|
||||
ds.logger.Error("Document: Failed to load default document", "error", err)
|
||||
return &DocumentError{Operation: "load_default", Err: err}
|
||||
}
|
||||
|
||||
// 启动定时保存
|
||||
ds.loadDocument()
|
||||
ds.startAutoSave()
|
||||
return nil
|
||||
}
|
||||
|
||||
// initStore 初始化存储
|
||||
func (ds *DocumentService) initStore() error {
|
||||
docPath, err := ds.getDocumentPath()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 确保目录存在
|
||||
if err := os.MkdirAll(filepath.Dir(docPath), 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ds.docStore = NewStore[models.Document](StoreOption{
|
||||
FilePath: docPath,
|
||||
AutoSave: false,
|
||||
Logger: ds.logger,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// startAutoSave 启动定时保存
|
||||
func (ds *DocumentService) startAutoSave() {
|
||||
// getDocumentPath 获取文档路径
|
||||
func (ds *DocumentService) getDocumentPath() (string, error) {
|
||||
config, err := ds.configService.GetConfig()
|
||||
if err != nil {
|
||||
ds.logger.Error("Document: Failed to get config for auto save", "error", err)
|
||||
ds.scheduleNextSave(5 * time.Second) // 默认5秒
|
||||
return
|
||||
return "", err
|
||||
}
|
||||
|
||||
delay := time.Duration(config.Editing.AutoSaveDelay) * time.Millisecond
|
||||
ds.scheduleNextSave(delay)
|
||||
return filepath.Join(config.General.DataPath, "docs", "default.json"), nil
|
||||
}
|
||||
|
||||
// scheduleNextSave 安排下次保存
|
||||
func (ds *DocumentService) scheduleNextSave(delay time.Duration) {
|
||||
ds.timerMutex.Lock()
|
||||
defer ds.timerMutex.Unlock()
|
||||
// loadDocument 加载文档
|
||||
func (ds *DocumentService) loadDocument() {
|
||||
ds.mutex.Lock()
|
||||
defer ds.mutex.Unlock()
|
||||
|
||||
// 停止现有定时器
|
||||
doc := ds.docStore.Get()
|
||||
if doc.Meta.ID == "" {
|
||||
// 创建新文档
|
||||
ds.document = models.NewDefaultDocument()
|
||||
ds.docStore.Set(*ds.document)
|
||||
ds.logger.Info("Document: Created new document")
|
||||
} else {
|
||||
ds.document = &doc
|
||||
ds.logger.Info("Document: Loaded existing document")
|
||||
}
|
||||
}
|
||||
|
||||
// GetActiveDocument 获取活动文档
|
||||
func (ds *DocumentService) GetActiveDocument() (*models.Document, error) {
|
||||
ds.mutex.RLock()
|
||||
defer ds.mutex.RUnlock()
|
||||
|
||||
if ds.document == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// 返回副本
|
||||
docCopy := *ds.document
|
||||
return &docCopy, nil
|
||||
}
|
||||
|
||||
// UpdateActiveDocumentContent 更新文档内容
|
||||
func (ds *DocumentService) UpdateActiveDocumentContent(content string) error {
|
||||
ds.mutex.Lock()
|
||||
defer ds.mutex.Unlock()
|
||||
|
||||
if ds.document != nil {
|
||||
// 只在内容真正改变时才标记为脏
|
||||
if ds.document.Content != content {
|
||||
ds.pendingContent = content
|
||||
ds.isDirty = true
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ForceSave 强制保存
|
||||
func (ds *DocumentService) ForceSave() error {
|
||||
ds.mutex.Lock()
|
||||
defer ds.mutex.Unlock()
|
||||
|
||||
if ds.document == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 应用待保存的内容
|
||||
if ds.pendingContent != "" {
|
||||
ds.document.Content = ds.pendingContent
|
||||
ds.pendingContent = ""
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
ds.document.Meta.LastUpdated = now
|
||||
|
||||
if err := ds.docStore.Set(*ds.document); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := ds.docStore.Save(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ds.isDirty = false
|
||||
ds.lastSaveTime = now
|
||||
ds.logger.Info("Document: Force save completed")
|
||||
return nil
|
||||
}
|
||||
|
||||
// startAutoSave 启动自动保存
|
||||
func (ds *DocumentService) startAutoSave() {
|
||||
delay := 5 * time.Second // 默认延迟
|
||||
|
||||
if config, err := ds.configService.GetConfig(); err == nil {
|
||||
delay = time.Duration(config.Editing.AutoSaveDelay) * time.Millisecond
|
||||
}
|
||||
|
||||
ds.scheduleAutoSave(delay)
|
||||
}
|
||||
|
||||
// scheduleAutoSave 安排自动保存
|
||||
func (ds *DocumentService) scheduleAutoSave(delay time.Duration) {
|
||||
if ds.saveTimer != nil {
|
||||
ds.saveTimer.Stop()
|
||||
}
|
||||
|
||||
// 创建新的定时器
|
||||
ds.saveTimer = time.AfterFunc(delay, func() {
|
||||
ds.performAutoSave()
|
||||
// 安排下次保存
|
||||
ds.startAutoSave()
|
||||
ds.startAutoSave() // 重新安排
|
||||
})
|
||||
}
|
||||
|
||||
@@ -122,188 +186,94 @@ func (ds *DocumentService) performAutoSave() {
|
||||
ds.mutex.Lock()
|
||||
defer ds.mutex.Unlock()
|
||||
|
||||
// 如果没有变更,跳过保存
|
||||
if !ds.isDirty || ds.document == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// 更新元数据并保存
|
||||
ds.document.Meta.LastUpdated = time.Now()
|
||||
// 检查距离上次保存的时间间隔,避免过于频繁的保存
|
||||
now := time.Now()
|
||||
if now.Sub(ds.lastSaveTime) < time.Second {
|
||||
// 如果距离上次保存不到1秒,跳过此次保存
|
||||
// 下一个自动保存周期会重新尝试
|
||||
ds.logger.Debug("Document: Skipping auto save due to recent save")
|
||||
return
|
||||
}
|
||||
|
||||
ds.logger.Info("Document: Auto saving document",
|
||||
"id", ds.document.Meta.ID,
|
||||
"contentLength", len(ds.document.Content))
|
||||
// 应用待保存的内容
|
||||
if ds.pendingContent != "" {
|
||||
ds.document.Content = ds.pendingContent
|
||||
ds.pendingContent = ""
|
||||
}
|
||||
|
||||
ds.document.Meta.LastUpdated = now
|
||||
|
||||
if err := ds.docStore.Set(*ds.document); err != nil {
|
||||
ds.logger.Error("Document: Failed to auto save document", "error", err)
|
||||
ds.logger.Error("Document: Auto save failed", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := ds.docStore.Save(); err != nil {
|
||||
ds.logger.Error("Document: Failed to force save document", "error", err)
|
||||
ds.logger.Error("Document: Auto save failed", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
// 重置脏标记
|
||||
ds.isDirty = false
|
||||
ds.logger.Info("Document: Auto save completed")
|
||||
ds.lastSaveTime = now
|
||||
ds.logger.Debug("Document: Auto save completed")
|
||||
}
|
||||
|
||||
// stopTimer 停止定时器
|
||||
func (ds *DocumentService) stopTimer() {
|
||||
ds.timerMutex.Lock()
|
||||
defer ds.timerMutex.Unlock()
|
||||
|
||||
if ds.saveTimer != nil {
|
||||
ds.saveTimer.Stop()
|
||||
ds.saveTimer = nil
|
||||
}
|
||||
}
|
||||
|
||||
// initDocumentStore 初始化文档存储
|
||||
func (ds *DocumentService) initDocumentStore() error {
|
||||
docPath, err := ds.getDefaultDocumentPath()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ds.logger.Info("Document: Initializing document store", "path", docPath)
|
||||
|
||||
ds.docStore = NewStore[models.Document](StoreOption{
|
||||
FilePath: docPath,
|
||||
AutoSave: true,
|
||||
Logger: ds.logger,
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ensureDocumentsDir 确保文档目录存在
|
||||
func (ds *DocumentService) ensureDocumentsDir() error {
|
||||
config, err := ds.configService.GetConfig()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var dataPath string
|
||||
if config.General.UseCustomDataPath && config.General.CustomDataPath != "" {
|
||||
dataPath = config.General.CustomDataPath
|
||||
} else {
|
||||
dataPath = config.General.DefaultDataPath
|
||||
}
|
||||
|
||||
docsDir := filepath.Join(dataPath, "docs")
|
||||
return os.MkdirAll(docsDir, 0755)
|
||||
}
|
||||
|
||||
// getDocumentsDir 获取文档目录路径
|
||||
func (ds *DocumentService) getDocumentsDir() (string, error) {
|
||||
config, err := ds.configService.GetConfig()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var dataPath string
|
||||
if config.General.UseCustomDataPath && config.General.CustomDataPath != "" {
|
||||
dataPath = config.General.CustomDataPath
|
||||
} else {
|
||||
dataPath = config.General.DefaultDataPath
|
||||
}
|
||||
|
||||
return filepath.Join(dataPath, "docs"), nil
|
||||
}
|
||||
|
||||
// getDefaultDocumentPath 获取默认文档路径
|
||||
func (ds *DocumentService) getDefaultDocumentPath() (string, error) {
|
||||
docsDir, err := ds.getDocumentsDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(docsDir, "default.json"), nil
|
||||
}
|
||||
|
||||
// loadDefaultDocument 加载默认文档
|
||||
func (ds *DocumentService) loadDefaultDocument() error {
|
||||
doc := ds.docStore.Get()
|
||||
|
||||
// ReloadDocument 重新加载文档
|
||||
func (ds *DocumentService) ReloadDocument() error {
|
||||
ds.mutex.Lock()
|
||||
defer ds.mutex.Unlock()
|
||||
|
||||
if doc.Meta.ID == "" {
|
||||
// 创建默认文档
|
||||
ds.document = models.NewDefaultDocument()
|
||||
|
||||
// 保存默认文档
|
||||
if err := ds.docStore.Set(*ds.document); err != nil {
|
||||
return &DocumentError{Operation: "save_default", Err: err}
|
||||
// 强制保存当前文档
|
||||
if ds.document != nil && ds.isDirty {
|
||||
if err := ds.forceSaveInternal(); err != nil {
|
||||
ds.logger.Error("Document: Failed to save before reload", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
ds.logger.Info("Document: Created and saved default document")
|
||||
// 重新初始化存储
|
||||
if err := ds.initStore(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 重新加载文档
|
||||
doc := ds.docStore.Get()
|
||||
if doc.Meta.ID == "" {
|
||||
// 创建新文档
|
||||
ds.document = models.NewDefaultDocument()
|
||||
ds.docStore.Set(*ds.document)
|
||||
ds.logger.Info("Document: Created new document after reload")
|
||||
} else {
|
||||
ds.document = &doc
|
||||
ds.logger.Info("Document: Loaded default document", "id", doc.Meta.ID)
|
||||
ds.logger.Info("Document: Loaded existing document after reload")
|
||||
}
|
||||
|
||||
// 重置状态
|
||||
ds.isDirty = false
|
||||
ds.pendingContent = ""
|
||||
ds.lastSaveTime = time.Now()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetActiveDocument 获取当前活动文档
|
||||
func (ds *DocumentService) GetActiveDocument() (*models.Document, error) {
|
||||
ds.mutex.RLock()
|
||||
defer ds.mutex.RUnlock()
|
||||
|
||||
// forceSaveInternal 内部强制保存(不加锁)
|
||||
func (ds *DocumentService) forceSaveInternal() error {
|
||||
if ds.document == nil {
|
||||
return nil, errors.New("no active document loaded")
|
||||
return nil
|
||||
}
|
||||
|
||||
// 返回副本以防止外部修改
|
||||
docCopy := *ds.document
|
||||
return &docCopy, nil
|
||||
}
|
||||
|
||||
// GetActiveDocumentContent 获取当前活动文档内容
|
||||
func (ds *DocumentService) GetActiveDocumentContent() (string, error) {
|
||||
ds.mutex.RLock()
|
||||
defer ds.mutex.RUnlock()
|
||||
|
||||
if ds.document == nil {
|
||||
return "", errors.New("no active document loaded")
|
||||
// 应用待保存的内容
|
||||
if ds.pendingContent != "" {
|
||||
ds.document.Content = ds.pendingContent
|
||||
ds.pendingContent = ""
|
||||
}
|
||||
|
||||
return ds.document.Content, nil
|
||||
}
|
||||
now := time.Now()
|
||||
ds.document.Meta.LastUpdated = now
|
||||
|
||||
// UpdateActiveDocumentContent 更新当前活动文档内容
|
||||
func (ds *DocumentService) UpdateActiveDocumentContent(content string) error {
|
||||
ds.mutex.Lock()
|
||||
defer ds.mutex.Unlock()
|
||||
|
||||
if ds.document == nil {
|
||||
return errors.New("no active document loaded")
|
||||
}
|
||||
|
||||
// 更新文档内容并标记为脏
|
||||
ds.document.Content = content
|
||||
ds.document.Meta.LastUpdated = time.Now()
|
||||
ds.isDirty = true
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SaveDocumentSync 同步保存文档内容
|
||||
func (ds *DocumentService) SaveDocumentSync(content string) error {
|
||||
ds.mutex.Lock()
|
||||
defer ds.mutex.Unlock()
|
||||
|
||||
if ds.document == nil {
|
||||
return errors.New("no active document loaded")
|
||||
}
|
||||
|
||||
// 更新内容
|
||||
ds.document.Content = content
|
||||
ds.document.Meta.LastUpdated = time.Now()
|
||||
|
||||
// 立即保存
|
||||
if err := ds.docStore.Set(*ds.document); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -312,57 +282,33 @@ func (ds *DocumentService) SaveDocumentSync(content string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// 重置脏标记
|
||||
ds.isDirty = false
|
||||
ds.logger.Info("Document: Sync save completed")
|
||||
ds.lastSaveTime = now
|
||||
return nil
|
||||
}
|
||||
|
||||
// ForceSave 强制保存当前文档
|
||||
func (ds *DocumentService) ForceSave() error {
|
||||
ds.logger.Info("Document: Force save triggered")
|
||||
|
||||
ds.mutex.RLock()
|
||||
if ds.document == nil {
|
||||
ds.mutex.RUnlock()
|
||||
return errors.New("no active document loaded")
|
||||
}
|
||||
content := ds.document.Content
|
||||
ds.mutex.RUnlock()
|
||||
|
||||
return ds.SaveDocumentSync(content)
|
||||
}
|
||||
|
||||
// ServiceShutdown 服务关闭
|
||||
// ServiceShutdown 关闭服务
|
||||
func (ds *DocumentService) ServiceShutdown() error {
|
||||
ds.logger.Info("Document: Service is shutting down...")
|
||||
// 停止定时器
|
||||
if ds.saveTimer != nil {
|
||||
ds.saveTimer.Stop()
|
||||
}
|
||||
|
||||
// 确保只执行一次关闭
|
||||
var shutdownErr error
|
||||
ds.shutdownOnce.Do(func() {
|
||||
// 停止定时器
|
||||
ds.stopTimer()
|
||||
// 最后保存
|
||||
if err := ds.ForceSave(); err != nil {
|
||||
ds.logger.Error("Document: Failed to save on shutdown", "error", err)
|
||||
}
|
||||
|
||||
// 执行最后一次保存
|
||||
ds.mutex.RLock()
|
||||
if ds.document != nil && ds.isDirty {
|
||||
content := ds.document.Content
|
||||
ds.mutex.RUnlock()
|
||||
|
||||
if err := ds.SaveDocumentSync(content); err != nil {
|
||||
ds.logger.Error("Document: Failed to save on shutdown", "error", err)
|
||||
shutdownErr = err
|
||||
} else {
|
||||
ds.logger.Info("Document: Document saved successfully on shutdown")
|
||||
}
|
||||
} else {
|
||||
ds.mutex.RUnlock()
|
||||
}
|
||||
|
||||
// 关闭服务
|
||||
close(ds.shutdown)
|
||||
ds.logger.Info("Document: Service shutdown completed")
|
||||
})
|
||||
|
||||
return shutdownErr
|
||||
ds.logger.Info("Document: Service shutdown completed")
|
||||
return nil
|
||||
}
|
||||
|
||||
// OnDataPathChanged 处理数据路径变更
|
||||
func (ds *DocumentService) OnDataPathChanged(oldPath, newPath string) error {
|
||||
ds.logger.Info("Document: Data path changed, reloading document",
|
||||
"oldPath", oldPath,
|
||||
"newPath", newPath)
|
||||
|
||||
// 重新加载文档以使用新的路径
|
||||
return ds.ReloadDocument()
|
||||
}
|
||||
|
562
internal/services/migration_service.go
Normal file
562
internal/services/migration_service.go
Normal file
@@ -0,0 +1,562 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/wailsapp/wails/v3/pkg/services/log"
|
||||
)
|
||||
|
||||
// MigrationStatus 迁移状态
|
||||
type MigrationStatus string
|
||||
|
||||
const (
|
||||
MigrationStatusIdle MigrationStatus = "idle" // 空闲状态
|
||||
MigrationStatusPreparing MigrationStatus = "preparing" // 准备中
|
||||
MigrationStatusMigrating MigrationStatus = "migrating" // 迁移中
|
||||
MigrationStatusCompleted MigrationStatus = "completed" // 完成
|
||||
MigrationStatusFailed MigrationStatus = "failed" // 失败
|
||||
MigrationStatusCancelled MigrationStatus = "cancelled" // 取消
|
||||
)
|
||||
|
||||
// MigrationProgress 迁移进度信息
|
||||
type MigrationProgress struct {
|
||||
Status MigrationStatus `json:"status"` // 迁移状态
|
||||
CurrentFile string `json:"currentFile"` // 当前处理的文件
|
||||
ProcessedFiles int `json:"processedFiles"` // 已处理文件数
|
||||
TotalFiles int `json:"totalFiles"` // 总文件数
|
||||
ProcessedBytes int64 `json:"processedBytes"` // 已处理字节数
|
||||
TotalBytes int64 `json:"totalBytes"` // 总字节数
|
||||
Progress float64 `json:"progress"` // 进度百分比 (0-100)
|
||||
Message string `json:"message"` // 状态消息
|
||||
Error string `json:"error,omitempty"` // 错误信息
|
||||
StartTime time.Time `json:"startTime"` // 开始时间
|
||||
EstimatedTime time.Duration `json:"estimatedTime"` // 估计剩余时间
|
||||
}
|
||||
|
||||
// MigrationProgressCallback 进度回调函数类型
|
||||
type MigrationProgressCallback func(progress MigrationProgress)
|
||||
|
||||
// MigrationService 迁移服务
|
||||
type MigrationService struct {
|
||||
logger *log.LoggerService
|
||||
mu sync.RWMutex
|
||||
currentProgress MigrationProgress
|
||||
progressCallback MigrationProgressCallback
|
||||
cancelFunc context.CancelFunc
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
// NewMigrationService 创建迁移服务
|
||||
func NewMigrationService(logger *log.LoggerService) *MigrationService {
|
||||
if logger == nil {
|
||||
logger = log.New()
|
||||
}
|
||||
|
||||
return &MigrationService{
|
||||
logger: logger,
|
||||
currentProgress: MigrationProgress{
|
||||
Status: MigrationStatusIdle,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// SetProgressCallback 设置进度回调
|
||||
func (ms *MigrationService) SetProgressCallback(callback MigrationProgressCallback) {
|
||||
ms.mu.Lock()
|
||||
defer ms.mu.Unlock()
|
||||
ms.progressCallback = callback
|
||||
}
|
||||
|
||||
// GetProgress 获取当前进度
|
||||
func (ms *MigrationService) GetProgress() MigrationProgress {
|
||||
ms.mu.RLock()
|
||||
defer ms.mu.RUnlock()
|
||||
return ms.currentProgress
|
||||
}
|
||||
|
||||
// updateProgress 更新进度并触发回调
|
||||
func (ms *MigrationService) updateProgress(progress MigrationProgress) {
|
||||
ms.mu.Lock()
|
||||
ms.currentProgress = progress
|
||||
callback := ms.progressCallback
|
||||
ms.mu.Unlock()
|
||||
|
||||
if callback != nil {
|
||||
callback(progress)
|
||||
}
|
||||
}
|
||||
|
||||
// MigrateDirectory 迁移目录
|
||||
func (ms *MigrationService) MigrateDirectory(srcPath, dstPath string) error {
|
||||
// 创建可取消的上下文
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
ms.mu.Lock()
|
||||
ms.ctx = ctx
|
||||
ms.cancelFunc = cancel
|
||||
ms.mu.Unlock()
|
||||
|
||||
defer func() {
|
||||
ms.mu.Lock()
|
||||
ms.cancelFunc = nil
|
||||
ms.ctx = nil
|
||||
ms.mu.Unlock()
|
||||
}()
|
||||
|
||||
ms.logger.Info("Migration: Starting directory migration",
|
||||
"from", srcPath,
|
||||
"to", dstPath)
|
||||
|
||||
// 初始化进度
|
||||
progress := MigrationProgress{
|
||||
Status: MigrationStatusPreparing,
|
||||
Message: "Preparing migration...",
|
||||
StartTime: time.Now(),
|
||||
}
|
||||
ms.updateProgress(progress)
|
||||
|
||||
// 检查源目录是否存在
|
||||
if _, err := os.Stat(srcPath); os.IsNotExist(err) {
|
||||
progress.Status = MigrationStatusCompleted
|
||||
progress.Message = "Source directory does not exist, skipping migration"
|
||||
progress.Progress = 100
|
||||
ms.updateProgress(progress)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 如果路径相同,不需要迁移
|
||||
srcAbs, _ := filepath.Abs(srcPath)
|
||||
dstAbs, _ := filepath.Abs(dstPath)
|
||||
if srcAbs == dstAbs {
|
||||
progress.Status = MigrationStatusCompleted
|
||||
progress.Message = "Paths are identical, no migration needed"
|
||||
progress.Progress = 100
|
||||
ms.updateProgress(progress)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 检查目标路径是否是源路径的子目录,防止无限递归复制
|
||||
if ms.isSubDirectory(srcAbs, dstAbs) {
|
||||
progress.Status = MigrationStatusFailed
|
||||
progress.Error = "Target path cannot be a subdirectory of source path, this would cause infinite recursive copying"
|
||||
ms.updateProgress(progress)
|
||||
return fmt.Errorf("target path cannot be a subdirectory of source path: src=%s, dst=%s", srcAbs, dstAbs)
|
||||
}
|
||||
|
||||
// 计算目录大小(用于显示进度)
|
||||
totalFiles, totalBytes, err := ms.calculateDirectorySize(ctx, srcPath)
|
||||
if err != nil {
|
||||
progress.Status = MigrationStatusFailed
|
||||
progress.Error = fmt.Sprintf("Failed to calculate directory size: %v", err)
|
||||
ms.updateProgress(progress)
|
||||
return err
|
||||
}
|
||||
|
||||
progress.TotalFiles = totalFiles
|
||||
progress.TotalBytes = totalBytes
|
||||
progress.Status = MigrationStatusMigrating
|
||||
progress.Message = "Starting atomic migration..."
|
||||
ms.updateProgress(progress)
|
||||
|
||||
// 执行原子迁移
|
||||
err = ms.atomicMove(ctx, srcPath, dstPath, &progress)
|
||||
if err != nil {
|
||||
if errors.Is(ctx.Err(), context.Canceled) {
|
||||
progress.Status = MigrationStatusCancelled
|
||||
progress.Error = "Migration cancelled"
|
||||
} else {
|
||||
progress.Status = MigrationStatusFailed
|
||||
progress.Error = fmt.Sprintf("Migration failed: %v", err)
|
||||
}
|
||||
ms.updateProgress(progress)
|
||||
return err
|
||||
}
|
||||
|
||||
// 迁移完成
|
||||
progress.Status = MigrationStatusCompleted
|
||||
progress.Message = "Migration completed"
|
||||
progress.Progress = 100
|
||||
progress.ProcessedFiles = totalFiles
|
||||
progress.ProcessedBytes = totalBytes
|
||||
duration := time.Since(progress.StartTime)
|
||||
ms.updateProgress(progress)
|
||||
|
||||
ms.logger.Info("Migration: Directory migration completed",
|
||||
"from", srcPath,
|
||||
"to", dstPath,
|
||||
"duration", duration,
|
||||
"files", totalFiles,
|
||||
"bytes", totalBytes)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// atomicMove 原子移动目录 - 使用压缩-移动-解压的方式
|
||||
func (ms *MigrationService) atomicMove(ctx context.Context, srcPath, dstPath string, progress *MigrationProgress) error {
|
||||
// 检查是否取消
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
// 确保目标目录的父目录存在
|
||||
dstParent := filepath.Dir(dstPath)
|
||||
if err := os.MkdirAll(dstParent, 0755); err != nil {
|
||||
return fmt.Errorf("Failed to create target parent directory: %v", err)
|
||||
}
|
||||
|
||||
// 检查目标路径情况
|
||||
if stat, err := os.Stat(dstPath); err == nil {
|
||||
if !stat.IsDir() {
|
||||
return fmt.Errorf("Target path exists but is not a directory: %s", dstPath)
|
||||
}
|
||||
|
||||
// 检查目录是否为空
|
||||
isEmpty, err := ms.isDirectoryEmpty(dstPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to check if target directory is empty: %v", err)
|
||||
}
|
||||
|
||||
if !isEmpty {
|
||||
return fmt.Errorf("Target directory is not empty: %s", dstPath)
|
||||
}
|
||||
|
||||
// 目录存在但为空,可以继续迁移
|
||||
ms.logger.Info("Migration: Target directory exists but is empty, proceeding with migration")
|
||||
}
|
||||
|
||||
// 尝试直接重命名(如果在同一分区,这会很快)
|
||||
progress.Message = "Attempting fast move..."
|
||||
ms.updateProgress(*progress)
|
||||
|
||||
if err := os.Rename(srcPath, dstPath); err == nil {
|
||||
// 重命名成功,这是最快的方式
|
||||
ms.logger.Info("Migration: Fast rename successful")
|
||||
return nil
|
||||
}
|
||||
|
||||
// 重命名失败(可能跨分区),使用原子压缩迁移
|
||||
progress.Message = "Starting atomic compress migration..."
|
||||
ms.updateProgress(*progress)
|
||||
|
||||
return ms.atomicCompressMove(ctx, srcPath, dstPath, progress)
|
||||
}
|
||||
|
||||
// atomicCompressMove 原子压缩迁移 - 压缩、移动、解压、清理
|
||||
func (ms *MigrationService) atomicCompressMove(ctx context.Context, srcPath, dstPath string, progress *MigrationProgress) error {
|
||||
// 创建临时压缩文件
|
||||
tempDir := os.TempDir()
|
||||
tempZipFile := filepath.Join(tempDir, fmt.Sprintf("voidraft_migration_%d.zip", time.Now().UnixNano()))
|
||||
|
||||
// 确保临时文件在函数结束时被清理
|
||||
defer func() {
|
||||
if err := os.Remove(tempZipFile); err != nil && !os.IsNotExist(err) {
|
||||
ms.logger.Error("Migration: Failed to clean up temporary zip file", "file", tempZipFile, "error", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// 第一步: 压缩源目录
|
||||
progress.Message = "Compressing source directory..."
|
||||
progress.Progress = 10
|
||||
ms.updateProgress(*progress)
|
||||
|
||||
if err := ms.compressDirectory(ctx, srcPath, tempZipFile, progress); err != nil {
|
||||
return fmt.Errorf("Failed to compress source directory: %v", err)
|
||||
}
|
||||
|
||||
// 检查是否取消
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
// 第二步: 解压到目标位置
|
||||
progress.Message = "Extracting to target location..."
|
||||
progress.Progress = 70
|
||||
ms.updateProgress(*progress)
|
||||
|
||||
if err := ms.extractToDirectory(ctx, tempZipFile, dstPath, progress); err != nil {
|
||||
return fmt.Errorf("Failed to extract to target location: %v", err)
|
||||
}
|
||||
|
||||
// 检查是否取消
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
// 如果取消,需要清理已解压的目标目录
|
||||
os.RemoveAll(dstPath)
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
// 第三步: 删除源目录
|
||||
progress.Message = "Cleaning up source directory..."
|
||||
progress.Progress = 90
|
||||
ms.updateProgress(*progress)
|
||||
|
||||
if err := os.RemoveAll(srcPath); err != nil {
|
||||
ms.logger.Error("Migration: Failed to remove source directory", "error", err)
|
||||
// 不返回错误,因为迁移已经成功
|
||||
}
|
||||
|
||||
progress.Message = "Migration completed"
|
||||
progress.Progress = 100
|
||||
ms.updateProgress(*progress)
|
||||
|
||||
ms.logger.Info("Migration: Atomic compress-move completed successfully")
|
||||
return nil
|
||||
}
|
||||
|
||||
// compressDirectory 压缩目录到zip文件
|
||||
func (ms *MigrationService) compressDirectory(ctx context.Context, srcDir, zipFile string, progress *MigrationProgress) error {
|
||||
// 创建zip文件
|
||||
zipWriter, err := os.Create(zipFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to create zip file: %v", err)
|
||||
}
|
||||
defer zipWriter.Close()
|
||||
|
||||
// 创建zip writer
|
||||
zw := zip.NewWriter(zipWriter)
|
||||
defer zw.Close()
|
||||
|
||||
// 遍历源目录并添加到zip
|
||||
return filepath.Walk(srcDir, func(filePath string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 检查是否取消
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
// 计算相对路径
|
||||
relPath, err := filepath.Rel(srcDir, filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 跳过根目录
|
||||
if relPath == "." {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 更新当前处理的文件
|
||||
progress.CurrentFile = relPath
|
||||
ms.updateProgress(*progress)
|
||||
|
||||
// 创建zip中的文件头
|
||||
header, err := zip.FileInfoHeader(info)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 使用/作为路径分隔符(zip标准)
|
||||
header.Name = strings.ReplaceAll(relPath, string(filepath.Separator), "/")
|
||||
|
||||
// 处理目录
|
||||
if info.IsDir() {
|
||||
header.Name += "/"
|
||||
header.Method = zip.Store
|
||||
} else {
|
||||
header.Method = zip.Deflate
|
||||
}
|
||||
|
||||
// 写入zip文件头
|
||||
writer, err := zw.CreateHeader(header)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 如果是文件,复制内容
|
||||
if !info.IsDir() {
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
_, err = io.Copy(writer, file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// extractToDirectory 从zip文件解压到目录
|
||||
func (ms *MigrationService) extractToDirectory(ctx context.Context, zipFile, dstDir string, progress *MigrationProgress) error {
|
||||
// 打开zip文件
|
||||
reader, err := zip.OpenReader(zipFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Failed to open zip file: %v", err)
|
||||
}
|
||||
defer reader.Close()
|
||||
|
||||
// 确保目标目录存在
|
||||
if err := os.MkdirAll(dstDir, 0755); err != nil {
|
||||
return fmt.Errorf("Failed to create target directory: %v", err)
|
||||
}
|
||||
|
||||
// 解压每个文件
|
||||
for _, file := range reader.File {
|
||||
// 检查是否取消
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
// 更新当前处理的文件
|
||||
progress.CurrentFile = file.Name
|
||||
ms.updateProgress(*progress)
|
||||
|
||||
// 构建目标文件路径
|
||||
dstPath := filepath.Join(dstDir, file.Name)
|
||||
|
||||
// 安全检查:防止zip slip攻击
|
||||
if !strings.HasPrefix(dstPath, filepath.Clean(dstDir)+string(os.PathSeparator)) {
|
||||
return fmt.Errorf("Invalid file path: %s", file.Name)
|
||||
}
|
||||
|
||||
// 处理目录
|
||||
if file.FileInfo().IsDir() {
|
||||
if err := os.MkdirAll(dstPath, file.FileInfo().Mode()); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// 确保父目录存在
|
||||
if err := os.MkdirAll(filepath.Dir(dstPath), 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 解压文件
|
||||
if err := ms.extractFile(file, dstPath); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// extractFile 解压单个文件
|
||||
func (ms *MigrationService) extractFile(file *zip.File, dstPath string) error {
|
||||
// 打开zip中的文件
|
||||
srcFile, err := file.Open()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer srcFile.Close()
|
||||
|
||||
// 创建目标文件
|
||||
dstFile, err := os.OpenFile(dstPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, file.FileInfo().Mode())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer dstFile.Close()
|
||||
|
||||
// 复制文件内容
|
||||
_, err = io.Copy(dstFile, srcFile)
|
||||
return err
|
||||
}
|
||||
|
||||
// isDirectoryEmpty 检查目录是否为空
|
||||
func (ms *MigrationService) isDirectoryEmpty(dirPath string) (bool, error) {
|
||||
f, err := os.Open(dirPath)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
// 尝试读取一个条目
|
||||
_, err = f.Readdir(1)
|
||||
if err == io.EOF {
|
||||
// 目录为空
|
||||
return true, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// 目录不为空
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// isSubDirectory 检查target是否是parent的子目录
|
||||
func (ms *MigrationService) isSubDirectory(parent, target string) bool {
|
||||
// 确保路径以分隔符结尾,以避免误判
|
||||
parent = filepath.Clean(parent) + string(filepath.Separator)
|
||||
target = filepath.Clean(target) + string(filepath.Separator)
|
||||
|
||||
// 检查target是否以parent开头
|
||||
return len(target) > len(parent) && target[:len(parent)] == parent
|
||||
}
|
||||
|
||||
// calculateDirectorySize 计算目录大小和文件数
|
||||
func (ms *MigrationService) calculateDirectorySize(ctx context.Context, dirPath string) (int, int64, error) {
|
||||
var totalFiles int
|
||||
var totalBytes int64
|
||||
|
||||
err := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 检查是否取消
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
if !info.IsDir() {
|
||||
totalFiles++
|
||||
totalBytes += info.Size()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
return totalFiles, totalBytes, err
|
||||
}
|
||||
|
||||
// CancelMigration 取消迁移
|
||||
func (ms *MigrationService) CancelMigration() error {
|
||||
ms.mu.Lock()
|
||||
defer ms.mu.Unlock()
|
||||
|
||||
if ms.cancelFunc != nil {
|
||||
ms.cancelFunc()
|
||||
ms.logger.Info("Migration: Cancellation requested")
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("no active migration to cancel")
|
||||
}
|
||||
|
||||
// ServiceShutdown 服务关闭
|
||||
func (ms *MigrationService) ServiceShutdown() error {
|
||||
ms.logger.Info("Migration: Service is shutting down...")
|
||||
|
||||
// 取消正在进行的迁移
|
||||
if err := ms.CancelMigration(); err != nil {
|
||||
ms.logger.Debug("Migration: No active migration to cancel during shutdown")
|
||||
}
|
||||
|
||||
ms.logger.Info("Migration: Service shutdown completed")
|
||||
return nil
|
||||
}
|
@@ -9,12 +9,13 @@ import (
|
||||
|
||||
// ServiceManager 服务管理器,负责协调各个服务
|
||||
type ServiceManager struct {
|
||||
configService *ConfigService
|
||||
documentService *DocumentService
|
||||
systemService *SystemService
|
||||
hotkeyService *HotkeyService
|
||||
dialogService *DialogService
|
||||
logger *log.LoggerService
|
||||
configService *ConfigService
|
||||
documentService *DocumentService
|
||||
migrationService *MigrationService
|
||||
systemService *SystemService
|
||||
hotkeyService *HotkeyService
|
||||
dialogService *DialogService
|
||||
logger *log.LoggerService
|
||||
}
|
||||
|
||||
// NewServiceManager 创建新的服务管理器实例
|
||||
@@ -25,6 +26,9 @@ func NewServiceManager() *ServiceManager {
|
||||
// 初始化配置服务 - 使用固定配置(当前目录下的 config/config.yaml)
|
||||
configService := NewConfigService(logger)
|
||||
|
||||
// 初始化迁移服务
|
||||
migrationService := NewMigrationService(logger)
|
||||
|
||||
// 初始化文档服务
|
||||
documentService := NewDocumentService(configService, logger)
|
||||
|
||||
@@ -46,6 +50,15 @@ func NewServiceManager() *ServiceManager {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// 设置数据路径变更监听
|
||||
err = configService.SetDataPathChangeCallback(func(oldPath, newPath string) error {
|
||||
return documentService.OnDataPathChanged(oldPath, newPath)
|
||||
})
|
||||
if err != nil {
|
||||
logger.Error("Failed to set data path change callback", "error", err)
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// 初始化文档服务
|
||||
err = documentService.Initialize()
|
||||
if err != nil {
|
||||
@@ -54,12 +67,13 @@ func NewServiceManager() *ServiceManager {
|
||||
}
|
||||
|
||||
return &ServiceManager{
|
||||
configService: configService,
|
||||
documentService: documentService,
|
||||
systemService: systemService,
|
||||
hotkeyService: hotkeyService,
|
||||
dialogService: dialogService,
|
||||
logger: logger,
|
||||
configService: configService,
|
||||
documentService: documentService,
|
||||
migrationService: migrationService,
|
||||
systemService: systemService,
|
||||
hotkeyService: hotkeyService,
|
||||
dialogService: dialogService,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,6 +82,7 @@ func (sm *ServiceManager) GetServices() []application.Service {
|
||||
return []application.Service{
|
||||
application.NewService(sm.configService),
|
||||
application.NewService(sm.documentService),
|
||||
application.NewService(sm.migrationService),
|
||||
application.NewService(sm.systemService),
|
||||
application.NewService(sm.hotkeyService),
|
||||
application.NewService(sm.dialogService),
|
||||
@@ -78,3 +93,8 @@ func (sm *ServiceManager) GetServices() []application.Service {
|
||||
func (sm *ServiceManager) GetHotkeyService() *HotkeyService {
|
||||
return sm.hotkeyService
|
||||
}
|
||||
|
||||
// GetDialogService 获取对话框服务实例
|
||||
func (sm *ServiceManager) GetDialogService() *DialogService {
|
||||
return sm.dialogService
|
||||
}
|
||||
|
Reference in New Issue
Block a user