/// 持久化层:负责项目文件的读写、自动保存与崩溃恢复。 /// /// 存储布局(位于用户 AppData/LocalAppData 下的 `SequenceDiagramStudio`): /// - `autosave/current.seq.json`:最近一次项目快照; /// - `autosave/session.json`:会话元数据(来源路径、是否干净、更新时间); /// - `<项目路径>.bak`:保存前自动生成的备份。 /// /// 与上层关系:AppController 通过单例 [Storage.instance] 调用自动保存与保存; /// 本层只依赖模型层,不感知 UI。 library; import 'dart:convert'; import 'dart:io'; import '../model/models.dart'; /// 崩溃恢复信息:描述一次可恢复的自动保存会话。 class RecoveryInfo { /// 构造恢复信息。 /// /// 参数 [content]:自动保存的项目 JSON 文本;[updatedAt]:快照时间; /// [projectPath]:原始文件路径(可空);[bakPath]/[bakContent]:备份文件 /// 路径与其内容(可空,仅在备份存在且可解析时提供)。 RecoveryInfo({ required this.content, required this.updatedAt, this.projectPath, this.bakPath, this.bakContent, }); /// 自动保存的项目 JSON 文本。 final String content; /// 自动保存时间。 final DateTime updatedAt; /// 原项目文件路径;null 表示该项目从未保存过。 final String? projectPath; /// 备份文件路径。 final String? bakPath; /// 备份文件内容(已通过解析校验)。 final String? bakContent; } /// 持久化单例:封装应用目录、自动保存文件与项目读写逻辑。 class Storage { /// 私有构造,强制通过 [instance] 访问。 Storage._(); /// 全局唯一实例。 static final Storage instance = Storage._(); /// 应用数据根目录。 late final Directory appDir; /// 自动保存目录。 late final Directory autosaveDir; /// 当前项目快照文件(`current.seq.json`)。 late final File currentFile; /// 会话元数据文件(`session.json`)。 late final File sessionFile; /// 是否已完成初始化,避免重复创建目录。 bool _inited = false; /// 初始化存储目录与文件引用(幂等)。 /// /// 目录优先级:`APPDATA` > `LOCALAPPDATA` > 系统临时目录;随后创建 /// `autosave` 子目录。副作用:设置 [appDir]/[autosaveDir]/[currentFile]/ /// [sessionFile] 并置 [_inited]。 Future init() async { if (_inited) return; final String base = Platform.environment['APPDATA'] ?? Platform.environment['LOCALAPPDATA'] ?? Directory.systemTemp.path; appDir = Directory('$base${Platform.pathSeparator}SequenceDiagramStudio'); autosaveDir = Directory('${appDir.path}${Platform.pathSeparator}autosave'); currentFile = File('${autosaveDir.path}${Platform.pathSeparator}current.seq.json'); sessionFile = File('${autosaveDir.path}${Platform.pathSeparator}session.json'); if (!await autosaveDir.exists()) { await autosaveDir.create(recursive: true); } _inited = true; } /// 写入自动保存快照与会话元数据。 /// /// 参数 [project]:项目;[projectPath]:来源文件路径;[clean]:是否已正常 /// 保存(true 表示下次启动无需恢复)。 /// 副作用:覆盖写入 [currentFile] 与 [sessionFile],均 flush 到磁盘。 Future writeAutosave( Project project, { String? projectPath, bool clean = false, }) async { await init(); // 先写项目快照,再写元数据,尽量保证二者一致。 await currentFile.writeAsString(project.encode(), flush: true); final Map meta = { 'projectPath': projectPath, 'clean': clean, 'updatedAt': DateTime.now().toIso8601String(), }; await sessionFile.writeAsString(jsonEncode(meta), flush: true); } /// 将会话标记为“干净”(已正常保存/退出),保留原有元数据。 /// /// 参数 [projectPath]:可选,更新记录的文件路径。 /// 若元数据文件缺失或损坏则使用空对象重建。 Future markClean({String? projectPath}) async { await init(); // 尝试读取现有元数据,失败时回退为空对象。 Map meta = {}; if (await sessionFile.exists()) { try { meta = jsonDecode(await sessionFile.readAsString()) as Map; } catch (_) { meta = {}; } } meta['projectPath'] = projectPath ?? meta['projectPath']; meta['clean'] = true; meta['updatedAt'] = DateTime.now().toIso8601String(); await sessionFile.writeAsString(jsonEncode(meta), flush: true); } /// 检查是否存在需要恢复的未保存会话。 /// /// 返回:可恢复时返回 [RecoveryInfo];以下任一情况返回 null: /// 快照/元数据文件不存在、元数据标记为 clean、元数据或快照无法解析。 /// 若存在对应 `.bak` 备份且可解析,会一并读入 [RecoveryInfo.bakContent]。 Future checkRecovery() async { await init(); // 前置条件:快照与元数据文件都必须存在。 if (!await currentFile.exists() || !await sessionFile.exists()) return null; Map meta; try { meta = jsonDecode(await sessionFile.readAsString()) as Map; } catch (_) { return null; } // 已标记干净:无需恢复。 if (meta['clean'] == true) return null; // 校验快照内容可解析,避免恢复出损坏数据。 String content; try { content = await currentFile.readAsString(); Project.decode(content); } catch (_) { return null; } // 若记录了来源路径,尝试读取并校验对应的 .bak 备份。 final String? path = meta['projectPath'] as String?; String? bakContent; if (path != null) { final File bak = File('$path.bak'); if (await bak.exists()) { try { bakContent = await bak.readAsString(); Project.decode(bakContent); } catch (_) { bakContent = null; } } } // 解析更新时间;无法解析时回退为当前时间。 DateTime updated = DateTime.now(); final String? ts = meta['updatedAt'] as String?; if (ts != null) { updated = DateTime.tryParse(ts) ?? updated; } return RecoveryInfo( content: content, updatedAt: updated, projectPath: path, bakPath: path != null ? '$path.bak' : null, bakContent: bakContent, ); } /// 清除恢复数据:删除快照文件并把会话标记为干净。 Future clearRecovery() async { await init(); if (await currentFile.exists()) await currentFile.delete(); await markClean(); } /// 返回给定项目路径对应的备份文件句柄(`.bak`)。 static File bakFor(String path) => File('$path.bak'); /// 若 [path] 处已存在文件,则复制一份为 `.bak`。 /// /// 复制失败时静默忽略(备份失败不应阻断保存流程)。 Future backupExisting(String path) async { final File target = File(path); if (await target.exists()) { try { await target.copy('$path.bak'); } catch (_) {} } } /// 将项目保存到 [path]。 /// /// 流程:初始化 -> 备份已有文件 -> 确保父目录存在 -> 写入项目 JSON -> /// 同步写自动保存(标记为干净)。返回保存路径。 Future saveProject(String path, Project project) async { await init(); // 1) 覆盖前先备份,防止写坏原文件。 await backupExisting(path); final File target = File(path); final Directory parent = target.parent; // 2) 父目录不存在时递归创建。 if (!await parent.exists()) { await parent.create(recursive: true); } // 3) 写入项目并 flush;随后把自动保存标记为干净。 await target.writeAsString(project.encode(), flush: true); await writeAutosave(project, projectPath: path, clean: true); return path; } /// 读取文本文件;文件不存在时返回 null。 Future readFile(String path) async { final File f = File(path); if (!await f.exists()) return null; return f.readAsString(); } }