-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNoteData.cs
More file actions
498 lines (419 loc) · 18.8 KB
/
NoteData.cs
File metadata and controls
498 lines (419 loc) · 18.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace StickyNote
{
public class NoteData
{
public string Id { get; set; } = Guid.NewGuid().ToString();
public string Title { get; set; } = "";
public string Content { get; set; } = ""; // RTF 格式
public double Left { get; set; }
public double Top { get; set; }
public double Width { get; set; }
public double Height { get; set; }
public bool IsTopmost { get; set; }
public string ColorHex { get; set; } = "#DCEDC8";
public double Opacity { get; set; } = 1.0;
public float FontSize { get; set; } = 13f;
public bool IsBold { get; set; }
public bool IsItalic { get; set; }
public bool IsUnderline { get; set; }
public bool IsStrikethrough { get; set; }
public string Alignment { get; set; } = "Left";
public bool IsCustomTitle { get; set; } = false;
// 组织与管理:标签 / 分组 / 收藏
public List<string> Tags { get; set; } = new();
public string GroupName { get; set; } = "默认";
public bool IsFavorite { get; set; } = false;
// 组织与管理:归档 / 回收站状态
public bool IsArchived { get; set; } = false;
public bool IsDeleted { get; set; } = false;
public DateTime? DeletedAtUtc { get; set; }
// 组织与管理:时间轴
public DateTime CreatedAtUtc { get; set; } = DateTime.UtcNow;
public DateTime UpdatedAtUtc { get; set; } = DateTime.UtcNow;
// 编辑历史(用于撤销/重做;可选跨会话持久化)
public List<string> UndoRtfHistory { get; set; } = new();
public List<string> RedoRtfHistory { get; set; } = new();
// P1: 纯文本预览缓存(不序列化,运行时生成)
[JsonIgnore]
public string PlainPreview { get; set; } = "";
}
/// <summary>
/// 应用级设置(窗口位置、分隔条宽度等)— 保存在独立 JSON 中
/// </summary>
public class AppSettings
{
public int WindowLeft { get; set; } = -1;
public int WindowTop { get; set; } = -1;
public int WindowWidth { get; set; } = 520;
public int WindowHeight { get; set; } = 340;
public int SplitterWidth { get; set; } = 110;
// 编辑区显示设置
public bool EditorWordWrap { get; set; } = false;
public bool ShowHorizontalScrollBar { get; set; } = true;
public bool ShowVerticalScrollBar { get; set; } = true;
// 编辑区版式:行高(百分比)与内边距(px)
public int EditorLineHeightPercent { get; set; } = 130;
public int EditorPaddingPx { get; set; } = 8;
// 底部工具栏是否随窗口宽度自动换行
public bool ToolbarAutoWrap { get; set; } = true;
// UI 缩放与主题
public int UiScalePercent { get; set; } = 100; // 90/100/125/150
public string ThemeMode { get; set; } = "System"; // Light / Dark / System
// 自动保存间隔(秒):0 代表手动保存
public int AutoSaveSeconds { get; set; } = 10;
// 撤销/重做历史设置
public bool EnablePersistentUndoRedo { get; set; } = false;
public int UndoHistoryDepth { get; set; } = 80;
// 启动后最小化到托盘
public bool StartMinimizedToTray { get; set; } = false;
// 全局置顶可覆盖单便签
public bool GlobalTopmost { get; set; } = false;
// 自动备份策略
public int BackupKeepDays { get; set; } = 7;
public int BackupKeepVersions { get; set; } = 20;
// 拖拽吸附阈值(px),0=关闭吸附
public int SnapThresholdPx { get; set; } = 8;
// 颜色菜单:最近使用颜色(最多 10 个)
public List<string> RecentColorHexes { get; set; } = new();
// 首次引导:是否已展示(展示后不重复打扰)
public bool OnboardingDismissed { get; set; } = false;
// 组织与管理:便签排序模式(Manual / UpdatedDesc / CreatedDesc)
public string NoteSortMode { get; set; } = "Manual";
// 组织与管理:是否仅显示收藏便签
public bool FavoriteOnlyView { get; set; } = false;
}
public static class NoteManager
{
private static readonly string DataDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"StickyNote");
private static readonly string FilePath = Path.Combine(DataDir, "StickyNotes_Data.json");
private static readonly string SettingsPath = Path.Combine(DataDir, "AppSettings.json");
private static readonly string BackupDir = Path.Combine(DataDir, "backups");
private static List<NoteData> _notes = new();
private static NoteData? _lastDeleted;
private static DateTime _lastBackupUtc = DateTime.MinValue;
private static string _lastBackupFingerprint = string.Empty;
private static AppSettings _settings = new();
public static AppSettings Settings => _settings;
public static void AddNote(NoteData note)
{
_notes.Add(note);
SaveNotes();
}
public static void RemoveNote(NoteData note)
{
var target = _notes.FirstOrDefault(n => n.Id == note.Id);
if (target != null)
{
_lastDeleted = target;
_notes.Remove(target);
}
SaveNotes();
}
public static bool SaveNotes(out string? errorMessage)
{
errorMessage = null;
string? temp = null;
try
{
Directory.CreateDirectory(DataDir);
bool persistHistory = _settings.EnablePersistentUndoRedo;
var payload = persistHistory
? _notes
: _notes.Select(CreateSnapshotWithoutHistory).ToList();
string json = JsonSerializer.Serialize(payload, new JsonSerializerOptions { WriteIndented = false });
temp = FilePath + ".tmp";
string bak = FilePath + ".bak";
File.WriteAllText(temp, json);
if (File.Exists(FilePath)) File.Replace(temp, FilePath, bak);
else File.Move(temp, FilePath);
TryCreateBackupSnapshot(json);
return true;
}
catch (Exception ex)
{
errorMessage = "便签保存失败,请检查磁盘空间、目录权限或日志文件。";
Logger.Error($"保存便签失败。数据文件: {FilePath}; 临时文件: {temp ?? "<null>"}", ex);
CleanupTempFileIfExists(temp);
return false;
}
}
public static bool SaveNotes()
=> SaveNotes(out _);
public static List<NoteData> LoadNotes()
{
if (!File.Exists(FilePath)) { _notes = new(); return _notes; }
try
{
string json = File.ReadAllText(FilePath);
_notes = JsonSerializer.Deserialize<List<NoteData>>(json) ?? new();
_notes = _notes.GroupBy(n => n.Id).Select(g => g.Last()).ToList();
bool persistHistory = _settings.EnablePersistentUndoRedo;
foreach (var note in _notes)
{
note.Tags ??= new List<string>();
note.GroupName = string.IsNullOrWhiteSpace(note.GroupName) ? "默认" : note.GroupName.Trim();
if (note.CreatedAtUtc == default) note.CreatedAtUtc = DateTime.UtcNow;
if (note.UpdatedAtUtc == default) note.UpdatedAtUtc = note.CreatedAtUtc;
note.UndoRtfHistory ??= new List<string>();
note.RedoRtfHistory ??= new List<string>();
if (!persistHistory)
{
note.UndoRtfHistory.Clear();
note.RedoRtfHistory.Clear();
}
}
return _notes;
}
catch (Exception ex)
{
Logger.Error($"加载便签失败。数据文件: {FilePath}", ex);
_notes = new();
return _notes;
}
}
public static IReadOnlyList<NoteData> GetAll() => _notes;
public static bool RestoreLastDeleted()
{
// 兼容旧逻辑:恢复“物理删除”的最近一条
if (_lastDeleted != null)
{
_notes.Add(_lastDeleted);
_lastDeleted = null;
SaveNotes();
return true;
}
// 新逻辑:恢复“回收站软删除”的最近一条
var target = _notes
.Where(n => n.IsDeleted)
.OrderByDescending(n => n.DeletedAtUtc ?? DateTime.MinValue)
.FirstOrDefault();
if (target == null) return false;
target.IsDeleted = false;
target.DeletedAtUtc = null;
target.UpdatedAtUtc = DateTime.UtcNow;
SaveNotes();
return true;
}
// ── 应用设置 ────────────────────────────────────────────────
public static void LoadSettings()
{
try
{
if (File.Exists(SettingsPath))
_settings = JsonSerializer.Deserialize<AppSettings>(File.ReadAllText(SettingsPath)) ?? new();
}
catch (Exception ex)
{
Logger.Error($"加载设置失败。设置文件: {SettingsPath}", ex);
_settings = new();
}
NormalizeSettings();
}
public static bool SaveSettings(out string? errorMessage)
{
errorMessage = null;
try
{
NormalizeSettings();
Directory.CreateDirectory(DataDir);
File.WriteAllText(SettingsPath, JsonSerializer.Serialize(_settings, new JsonSerializerOptions { WriteIndented = false }));
return true;
}
catch (Exception ex)
{
errorMessage = "设置保存失败,请检查目录权限或日志文件。";
Logger.Error($"保存设置失败。设置文件: {SettingsPath}", ex);
return false;
}
}
public static bool SaveSettings()
=> SaveSettings(out _);
private static void NormalizeSettings()
{
int[] validScale = { 90, 100, 125, 150 };
if (!validScale.Contains(_settings.UiScalePercent))
_settings.UiScalePercent = 100;
if (!string.Equals(_settings.ThemeMode, "Light", StringComparison.OrdinalIgnoreCase)
&& !string.Equals(_settings.ThemeMode, "Dark", StringComparison.OrdinalIgnoreCase)
&& !string.Equals(_settings.ThemeMode, "System", StringComparison.OrdinalIgnoreCase))
{
_settings.ThemeMode = "System";
}
_settings.AutoSaveSeconds = _settings.AutoSaveSeconds switch
{
0 => 0,
5 => 5,
10 => 10,
30 => 30,
_ => 10
};
_settings.UndoHistoryDepth = Math.Clamp(_settings.UndoHistoryDepth, 10, 200);
_settings.EditorLineHeightPercent = Math.Clamp(_settings.EditorLineHeightPercent, 100, 220);
_settings.EditorPaddingPx = Math.Clamp(_settings.EditorPaddingPx, 0, 40);
_settings.BackupKeepDays = Math.Clamp(_settings.BackupKeepDays, 1, 365);
_settings.BackupKeepVersions = Math.Clamp(_settings.BackupKeepVersions, 1, 500);
_settings.SnapThresholdPx = Math.Clamp(_settings.SnapThresholdPx, 0, 32);
_settings.RecentColorHexes ??= new List<string>();
_settings.RecentColorHexes = _settings.RecentColorHexes
.Where(IsValidHexColor)
.Select(NormalizeHexColor)
.Distinct(StringComparer.OrdinalIgnoreCase)
.Take(10)
.ToList();
if (!string.Equals(_settings.NoteSortMode, "Manual", StringComparison.OrdinalIgnoreCase)
&& !string.Equals(_settings.NoteSortMode, "UpdatedDesc", StringComparison.OrdinalIgnoreCase)
&& !string.Equals(_settings.NoteSortMode, "CreatedDesc", StringComparison.OrdinalIgnoreCase))
{
_settings.NoteSortMode = "Manual";
}
}
private static bool IsValidHexColor(string? value)
{
if (string.IsNullOrWhiteSpace(value)) return false;
string v = value.Trim();
if (v.Length != 7 || v[0] != '#') return false;
for (int i = 1; i < v.Length; i++)
{
char c = v[i];
bool hex = (c >= '0' && c <= '9')
|| (c >= 'a' && c <= 'f')
|| (c >= 'A' && c <= 'F');
if (!hex) return false;
}
return true;
}
private static string NormalizeHexColor(string value)
=> value.Trim().ToUpperInvariant();
private static void TryCreateBackupSnapshot(string json)
{
try
{
Directory.CreateDirectory(BackupDir);
string fingerprint = $"{json.Length}:{ComputeSha256(json)}";
var nowUtc = DateTime.UtcNow;
bool changed = !string.Equals(fingerprint, _lastBackupFingerprint, StringComparison.Ordinal);
bool intervalElapsed = (nowUtc - _lastBackupUtc) >= TimeSpan.FromSeconds(30);
if (!changed || !intervalElapsed) return;
_lastBackupFingerprint = fingerprint;
_lastBackupUtc = nowUtc;
string fileName = $"StickyNotes_{DateTime.Now:yyyyMMdd_HHmmss}.json";
File.WriteAllText(Path.Combine(BackupDir, fileName), json);
CleanupBackups();
}
catch (Exception ex)
{
Logger.Error($"创建便签备份失败。备份目录: {BackupDir}", ex);
}
}
private static void CleanupBackups()
{
try
{
if (!Directory.Exists(BackupDir)) return;
var files = Directory.GetFiles(BackupDir, "StickyNotes_*.json")
.Select(path =>
{
var fi = new FileInfo(path);
var ts = TryParseBackupTimestamp(Path.GetFileNameWithoutExtension(path)) ?? fi.CreationTime;
return new { fi.FullName, fi.Name, Timestamp = ts };
})
.OrderByDescending(x => x.Timestamp)
.ToList();
if (files.Count == 0) return;
int keepDays = Math.Max(1, _settings.BackupKeepDays);
int keepVersions = Math.Max(1, _settings.BackupKeepVersions);
DateTime threshold = DateTime.Now.AddDays(-keepDays);
var keep = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var item in files.Take(keepVersions))
keep.Add(item.FullName);
foreach (var item in files)
if (item.Timestamp >= threshold)
keep.Add(item.FullName);
foreach (var item in files)
if (!keep.Contains(item.FullName) && File.Exists(item.FullName))
File.Delete(item.FullName);
}
catch (Exception ex)
{
Logger.Error($"清理便签备份失败。备份目录: {BackupDir}", ex);
}
}
private static void CleanupTempFileIfExists(string? tempPath)
{
if (string.IsNullOrWhiteSpace(tempPath) || !File.Exists(tempPath)) return;
try
{
File.Delete(tempPath);
}
catch (Exception ex)
{
Logger.Warning($"清理临时保存文件失败: {tempPath}; {ex.Message}");
}
}
private static DateTime? TryParseBackupTimestamp(string fileNameWithoutExt)
{
// StickyNotes_yyyyMMdd_HHmmss
const string prefix = "StickyNotes_";
if (!fileNameWithoutExt.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return null;
string ts = fileNameWithoutExt.Substring(prefix.Length);
if (DateTime.TryParseExact(ts, "yyyyMMdd_HHmmss", CultureInfo.InvariantCulture,
DateTimeStyles.None, out var result))
{
return result;
}
return null;
}
private static NoteData CreateSnapshotWithoutHistory(NoteData source)
{
return new NoteData
{
Id = source.Id,
Title = source.Title,
Content = source.Content,
Left = source.Left,
Top = source.Top,
Width = source.Width,
Height = source.Height,
IsTopmost = source.IsTopmost,
ColorHex = source.ColorHex,
Opacity = source.Opacity,
FontSize = source.FontSize,
IsBold = source.IsBold,
IsItalic = source.IsItalic,
IsUnderline = source.IsUnderline,
IsStrikethrough = source.IsStrikethrough,
Alignment = source.Alignment,
IsCustomTitle = source.IsCustomTitle,
// 组织与管理相关字段必须随快照持久化
Tags = source.Tags?.ToList() ?? new List<string>(),
GroupName = string.IsNullOrWhiteSpace(source.GroupName) ? "默认" : source.GroupName,
IsFavorite = source.IsFavorite,
IsArchived = source.IsArchived,
IsDeleted = source.IsDeleted,
DeletedAtUtc = source.DeletedAtUtc,
CreatedAtUtc = source.CreatedAtUtc,
UpdatedAtUtc = source.UpdatedAtUtc,
UndoRtfHistory = new List<string>(),
RedoRtfHistory = new List<string>()
};
}
private static string ComputeSha256(string text)
{
using var sha = SHA256.Create();
var bytes = Encoding.UTF8.GetBytes(text);
var hash = sha.ComputeHash(bytes);
return Convert.ToHexString(hash);
}
}
}