-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs.bak
More file actions
1673 lines (1502 loc) · 63.6 KB
/
MainWindow.xaml.cs.bak
File metadata and controls
1673 lines (1502 loc) · 63.6 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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using System.Windows.Documents;
using System.Windows.Media.Animation;
using System.Collections.ObjectModel;
using System.ComponentModel;
namespace StickyNote
{
// 标签项数据模型
public class TabItem : INotifyPropertyChanged
{
private string _title = "便签";
private string _preview = string.Empty;
public string Id { get; set; } = string.Empty;
public string Title
{
get => _title;
set
{
if (_title != value)
{
_title = value;
OnPropertyChanged(nameof(Title));
}
}
}
public string Preview
{
get => _preview;
set
{
if (_preview != value)
{
_preview = value;
OnPropertyChanged(nameof(Preview));
}
}
}
public NoteData NoteData { get; set; } = null!;
public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public partial class MainWindow : Window
{
// 标签管理
private ObservableCollection<TabItem> _tabs = new ObservableCollection<TabItem>();
private TabItem? _currentTab;
private bool _isInitializing = true;
private DispatcherTimer _saveTimer;
private bool _isSnapping = false;
private DispatcherTimer _toastTimer;
public static readonly RoutedUICommand NewCmd = new RoutedUICommand("New", "New", typeof(MainWindow));
public static readonly RoutedUICommand DeleteCmd = new RoutedUICommand("Delete", "Delete", typeof(MainWindow));
public static readonly RoutedUICommand ToggleTopmostCmd = new RoutedUICommand("Topmost", "Topmost", typeof(MainWindow));
public static readonly RoutedUICommand CloseCmd = new RoutedUICommand("Close", "Close", typeof(MainWindow));
public static readonly RoutedUICommand ExportCmd = new RoutedUICommand("Export", "Export", typeof(MainWindow));
public static readonly RoutedUICommand InsertSeparatorCmd = new RoutedUICommand("Separator", "Separator", typeof(MainWindow));
public string NoteId => _currentTab?.NoteData?.Id ?? string.Empty;
// 构造函数:支持传入已有的数据
public MainWindow(NoteData? data = null)
{
try
{
InitializeComponent();
try
{
var icoPath = System.IO.Path.Combine(AppContext.BaseDirectory, "app.ico");
if (System.IO.File.Exists(icoPath))
{
using var s = System.IO.File.OpenRead(icoPath);
var decoder = new System.Windows.Media.Imaging.IconBitmapDecoder(s, System.Windows.Media.Imaging.BitmapCreateOptions.None, System.Windows.Media.Imaging.BitmapCacheOption.OnLoad);
this.Icon = decoder.Frames[0];
}
else
{
var exeIcon = System.Drawing.Icon.ExtractAssociatedIcon(System.Diagnostics.Process.GetCurrentProcess().MainModule!.FileName!);
if (exeIcon != null)
{
var src = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(exeIcon.Handle, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
this.Icon = src;
}
}
}
catch { }
// 初始化标签列表
TabList.ItemsSource = _tabs;
// 加载所有便签作为标签
LoadAllNotesAsTabs();
// 如果没有标签,显示空状态
if (_tabs.Count == 0)
{
_currentTab = null;
UpdateEmptyState();
}
else
{
// 选择第一个标签
TabList.SelectedIndex = 0;
}
_isInitializing = false;
_saveTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(400) };
_saveTimer.Tick += (s, e) => { _saveTimer.Stop(); NoteManager.SaveNotes(); };
_toastTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1200) };
_toastTimer.Tick += (s, e) => { _toastTimer.Stop(); StatusText.Opacity = 0; };
this.CommandBindings.Add(new CommandBinding(NewCmd, (s, e) => NewNote_Click(s, e)));
this.CommandBindings.Add(new CommandBinding(DeleteCmd, (s, e) => DeleteNote_Click(s, e)));
this.CommandBindings.Add(new CommandBinding(ToggleTopmostCmd, (s, e) => { btnTopmost.IsChecked = !(btnTopmost.IsChecked == true); PinButton_Click(s, e); }));
this.CommandBindings.Add(new CommandBinding(CloseCmd, (s, e) => CloseButton_Click(s, e)));
this.CommandBindings.Add(new CommandBinding(ExportCmd, (s, e) => Export_Click(s, e)));
this.CommandBindings.Add(new CommandBinding(InsertSeparatorCmd, (s, e) => InsertSeparator()));
this.SizeChanged += (s, e) => SaveState();
this.LocationChanged += (s, e) => { SnapToEdges(); SaveState(); };
}
catch (Exception ex)
{
System.Windows.MessageBox.Show($"初始化错误: {ex.Message}\n{ex.StackTrace}");
}
}
// 加载所有便签作为标签
private void LoadAllNotesAsTabs()
{
var notes = NoteManager.LoadNotes();
foreach (var note in notes)
{
if (string.IsNullOrEmpty(note.Title))
{
note.Title = GetNoteTitle(note.Content);
}
var tab = new TabItem
{
Id = note.Id,
Title = note.Title,
Preview = GetNotePreview(note.Content),
NoteData = note
};
_tabs.Add(tab);
}
}
// 创建新标签
public void CreateNewTab()
{
var noteData = new NoteData
{
Id = Guid.NewGuid().ToString(),
Title = "便签",
Content = "",
Width = this.Width,
Height = this.Height,
Left = this.Left,
Top = this.Top,
ColorHex = "#E8D096",
Opacity = 1.0,
IsTopmost = false,
FontSize = 16,
IsBold = false,
IsItalic = false,
IsUnderline = false,
IsStrikethrough = false,
Alignment = TextAlignment.Left.ToString()
};
var tab = new TabItem
{
Id = noteData.Id,
Title = "便签",
Preview = "",
NoteData = noteData
};
_tabs.Add(tab);
NoteManager.AddNote(noteData);
TabList.SelectedItem = tab;
}
// 刷新标签列表
public void RefreshTabs()
{
_tabs.Clear();
LoadAllNotesAsTabs();
if (_tabs.Count > 0)
{
TabList.SelectedIndex = _tabs.Count - 1; // 选择最后一个(刚恢复的)
}
else
{
_currentTab = null;
UpdateEmptyState();
}
}
// 获取便签标题
private string GetNoteTitle(string content)
{
if (string.IsNullOrEmpty(content)) return "便签";
string text = content;
if (content.TrimStart().StartsWith("<FlowDocument"))
{
try
{
var doc = System.Windows.Markup.XamlReader.Parse(content) as FlowDocument;
if (doc != null)
{
var range = new TextRange(doc.ContentStart, doc.ContentEnd);
text = range.Text;
}
}
catch { }
}
var firstLine = text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ?? "便签";
if (firstLine.Length > 15) firstLine = firstLine.Substring(0, 15) + "...";
return firstLine;
}
// 获取便签预览
private string GetNotePreview(string content)
{
if (string.IsNullOrEmpty(content)) return "";
string text = content;
if (content.TrimStart().StartsWith("<FlowDocument"))
{
try
{
var doc = System.Windows.Markup.XamlReader.Parse(content) as FlowDocument;
if (doc != null)
{
var range = new TextRange(doc.ContentStart, doc.ContentEnd);
text = range.Text;
}
}
catch { }
}
// 移除第一行作为标题,剩下的作为预览
var lines = text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
if (lines.Length <= 1) return "";
var preview = string.Join(" ", lines.Skip(1));
if (preview.Length > 50) preview = preview.Substring(0, 50) + "...";
return preview;
}
private bool _isLoading = false;
private void UpdateEmptyState()
{
bool isEmpty = _tabs.Count == 0;
if (EmptyStateText != null)
{
EmptyStateText.Visibility = isEmpty ? Visibility.Visible : Visibility.Collapsed;
}
if (rtbContent != null)
{
rtbContent.Visibility = isEmpty ? Visibility.Collapsed : Visibility.Visible;
rtbContent.IsEnabled = !isEmpty;
}
// 禁用/启用一些按钮
if (PaletteBtn != null) PaletteBtn.IsEnabled = !isEmpty;
if (btnTopmost != null) btnTopmost.IsEnabled = !isEmpty;
}
// 将数据渲染到 UI
private void ApplyDataToUI()
{
UpdateEmptyState();
if (_currentTab?.NoteData == null) return;
_isLoading = true;
try
{
var noteData = _currentTab.NoteData;
this.Topmost = noteData.IsTopmost;
this.Opacity = noteData.Opacity;
SetDocumentFromContent(noteData.Content);
btnTopmost.IsChecked = noteData.IsTopmost;
try
{
MainBorder.Background = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString(noteData.ColorHex));
}
catch { }
UpdateShadowForDpi();
UpdateForegroundForBackground(noteData.ColorHex);
UpdatePaperBrush(noteData.ColorHex);
if (noteData.FontSize > 0) rtbContent.FontSize = noteData.FontSize;
rtbContent.FontWeight = noteData.IsBold ? FontWeights.Bold : FontWeights.Normal;
rtbContent.FontStyle = noteData.IsItalic ? FontStyles.Italic : FontStyles.Normal;
if (!string.IsNullOrEmpty(noteData.Alignment))
{
if (Enum.TryParse<TextAlignment>(noteData.Alignment, out var a))
rtbContent.Document.TextAlignment = a;
}
}
finally
{
_isLoading = false;
}
}
// 保存当前状态
private void SaveState()
{
if (_isInitializing || _isLoading || _currentTab?.NoteData == null)
{
return;
}
var noteData = _currentTab.NoteData;
noteData.Left = this.Left;
noteData.Top = this.Top;
noteData.Width = this.Width;
noteData.Height = this.Height;
noteData.Content = GetDocumentXaml();
noteData.IsTopmost = this.Topmost;
noteData.FontSize = rtbContent.FontSize;
noteData.IsBold = rtbContent.FontWeight == FontWeights.Bold;
noteData.IsItalic = rtbContent.FontStyle == FontStyles.Italic;
noteData.Alignment = rtbContent.Document.TextAlignment.ToString();
// 更新标签的标题和预览
noteData.Title = _currentTab.Title;
_currentTab.Preview = GetNotePreview(noteData.Content);
ScheduleSave();
}
private void ScheduleSave()
{
_saveTimer.Stop();
_saveTimer.Start();
}
// --- 交互事件 ---
private void NewNote_Click(object sender, RoutedEventArgs e)
{
CreateNewTab();
}
private void Minimize_Click(object sender, RoutedEventArgs e)
{
this.WindowState = WindowState.Minimized;
}
private void Maximize_Click(object sender, RoutedEventArgs e)
{
if (this.WindowState == WindowState.Maximized)
{
this.WindowState = WindowState.Normal;
}
else
{
this.WindowState = WindowState.Maximized;
}
}
protected override void OnStateChanged(EventArgs e)
{
base.OnStateChanged(e);
if (this.WindowState == WindowState.Minimized)
{
MainBorder.CacheMode = null;
App.FlushMemory(); // Release memory immediately upon minimizing
}
else
{
MainBorder.CacheMode = new BitmapCache();
}
if (pathMaximize != null)
{
if (this.WindowState == WindowState.Maximized)
{
// Restore icon (Two overlapping squares)
pathMaximize.Data = Geometry.Parse("M4,4 L4,12 L12,12 L12,4 Z M6,4 L6,2 L14,2 L14,10 L12,10");
}
else
{
// Maximize icon (Single square)
pathMaximize.Data = Geometry.Parse("M2,2 L12,2 L12,12 L2,12 Z");
}
}
}
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
this.WindowState = WindowState.Minimized; // 最小化窗口而不是关闭
}
private void PinButton_Click(object sender, RoutedEventArgs e)
{
this.Topmost = btnTopmost.IsChecked == true;
SaveState();
ShowStatus(this.Topmost ? "已置顶" : "取消置顶");
AdjustTopmostVisuals();
}
private void RtbContent_TextChanged(object sender, TextChangedEventArgs e)
{
SaveState();
UpdateCurrentTabPreview();
}
// 更新当前标签的预览
private void UpdateCurrentTabPreview()
{
if (_currentTab != null && !_isInitializing)
{
var content = GetDocumentXaml();
_currentTab.Preview = GetNotePreview(content);
}
}
private void AddTodo_Click(object sender, RoutedEventArgs e)
{
// 在当前光标位置插入未完成的代办事项符号
InsertTodoAtCurrentPosition(false);
}
private void InsertTodoAtCurrentPosition(bool isCompleted)
{
// 获取当前文档
var doc = rtbContent.Document;
if (doc == null) return;
// 获取当前光标位置
TextPointer caretPos = rtbContent.CaretPosition;
if (caretPos == null) return;
// 创建一个新的Run,包含代办事项符号
string todoSymbol = isCompleted ? "☑ " : "☐ ";
Run todoRun = new Run(todoSymbol);
// 获取当前段落
Paragraph currentParagraph = caretPos.Paragraph;
if (currentParagraph == null)
{
// 如果没有段落,创建一个新段落
currentParagraph = new Paragraph(todoRun) { Margin = new Thickness(0) };
doc.Blocks.Add(currentParagraph);
// 将光标移动到代办事项符号后面
rtbContent.CaretPosition = todoRun.ContentEnd;
return;
}
// 检查当前段落是否已经有代办事项符号
bool hasTodo = false;
TextPointer start = currentParagraph.ContentStart;
while (start != null && start.CompareTo(currentParagraph.ContentEnd) < 0)
{
if (start.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
{
string text = start.GetTextInRun(LogicalDirection.Forward);
if (text.Contains("☐") || text.Contains("☑"))
{
hasTodo = true;
break;
}
start = start.GetPositionAtOffset(text.Length, LogicalDirection.Forward);
}
else
{
start = start.GetNextContextPosition(LogicalDirection.Forward);
}
}
if (!hasTodo)
{
// 如果当前段落没有代办事项符号,在段落开头插入
currentParagraph.Inlines.InsertBefore(currentParagraph.Inlines.FirstInline, todoRun);
}
else
{
// 如果当前段落已有代办事项符号,在当前光标位置创建新段落并插入
Paragraph newParagraph = new Paragraph(todoRun) { Margin = new Thickness(0) };
doc.Blocks.InsertAfter(currentParagraph, newParagraph);
}
// 将光标移动到代办事项符号后面
rtbContent.CaretPosition = todoRun.ContentEnd;
}
// 处理RichTextBox的点击事件,用于切换代办事项状态
private void RtbContent_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
// 获取点击位置
System.Windows.Point clickPoint = e.GetPosition(rtbContent);
// 将点击位置转换为TextPointer
TextPointer textPosition = rtbContent.GetPositionFromPoint(clickPoint, true);
if (textPosition == null) return;
// 检查点击位置是否在代办事项符号上
TextPointer start = textPosition.GetInsertionPosition(LogicalDirection.Backward);
TextPointer end = textPosition.GetInsertionPosition(LogicalDirection.Forward);
// 扩大搜索范围,确保能找到代办事项符号
start = start.GetNextInsertionPosition(LogicalDirection.Backward) ?? start;
end = end.GetNextInsertionPosition(LogicalDirection.Forward) ?? end;
// 获取点击位置周围的文本
TextRange range = new TextRange(start, end);
string text = range.Text;
// 检查是否包含代办事项符号
int uncheckedIndex = text.IndexOf("☐");
int checkedIndex = text.IndexOf("☑");
if (uncheckedIndex >= 0)
{
// 将未完成的代办事项切换为已完成
ReplaceTodoSymbol(start, "☐", "☑");
}
else if (checkedIndex >= 0)
{
// 将已完成的代办事项切换为未完成
ReplaceTodoSymbol(start, "☑", "☐");
}
}
private void ReplaceTodoSymbol(TextPointer start, string oldSymbol, string newSymbol)
{
// 在文档中查找并替换代办事项符号
TextPointer current = start;
while (current != null && current.CompareTo(rtbContent.Document.ContentEnd) < 0)
{
if (current.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
{
string textRun = current.GetTextInRun(LogicalDirection.Forward);
int index = textRun.IndexOf(oldSymbol);
if (index >= 0)
{
// 找到符号,替换它
TextPointer symbolStart = current.GetPositionAtOffset(index);
TextPointer symbolEnd = symbolStart.GetPositionAtOffset(oldSymbol.Length);
rtbContent.BeginChange();
try
{
TextRange symbolRange = new TextRange(symbolStart, symbolEnd);
symbolRange.Text = newSymbol;
// 如果是标记为完成(☑),则将该行移动到末尾
if (newSymbol == "☑")
{
Paragraph para = symbolStart.Paragraph;
if (para != null && para.Parent is FlowDocument doc && doc == rtbContent.Document)
{
// 检查是否已经是最后一段
if (doc.Blocks.LastBlock != para)
{
// 记录原来位置的下一个段落,用于保持视觉位置
Block nextBlock = para.NextBlock;
doc.Blocks.Remove(para);
doc.Blocks.Add(para);
// 如果有下一个段落,将光标移过去,防止视角跳到文档末尾
if (nextBlock != null)
{
rtbContent.CaretPosition = nextBlock.ContentStart;
nextBlock.BringIntoView();
}
else
{
rtbContent.ScrollToEnd();
}
}
}
}
}
finally
{
rtbContent.EndChange();
}
break;
}
}
current = current.GetNextContextPosition(LogicalDirection.Forward);
}
}
// --- 批量操作与编号 ---
private List<Paragraph> GetSelectedParagraphs()
{
var list = new List<Paragraph>();
var start = rtbContent.Selection.Start;
var end = rtbContent.Selection.End;
// 确保 start < end
if (start.CompareTo(end) > 0) (start, end) = (end, start);
Block current = rtbContent.Document.Blocks.FirstBlock;
while (current != null)
{
// 检查交叉:Block Start <= Selection End AND Block End >= Selection Start
if (current.ContentStart.CompareTo(end) <= 0 && current.ContentEnd.CompareTo(start) >= 0)
{
if (current is Paragraph p) list.Add(p);
}
if (current.ContentStart.CompareTo(end) > 0) break;
current = current.NextBlock;
}
return list;
}
private void BatchSetTodo_Click(object sender, RoutedEventArgs e)
{
var paras = GetSelectedParagraphs();
if (paras.Count == 0) return;
rtbContent.BeginChange();
try
{
foreach (var p in paras)
{
string text = new TextRange(p.ContentStart, p.ContentEnd).Text;
if (!text.StartsWith("☐ ") && !text.StartsWith("☑ "))
{
// 确保 Paragraph 有 Inline,如果没有(空行),添加一个 Run
if (p.Inlines.Count == 0)
{
p.Inlines.Add(new Run("☐ "));
}
else
{
p.Inlines.InsertBefore(p.Inlines.FirstInline, new Run("☐ "));
}
}
}
}
finally
{
rtbContent.EndChange();
SaveState();
}
}
private void BatchUnsetTodo_Click(object sender, RoutedEventArgs e)
{
var paras = GetSelectedParagraphs();
if (paras.Count == 0) return;
rtbContent.BeginChange();
try
{
foreach (var p in paras)
{
TextPointer start = p.ContentStart.GetInsertionPosition(LogicalDirection.Forward);
string text = start.GetTextInRun(LogicalDirection.Forward);
if (text.StartsWith("☐ ") || text.StartsWith("☑ "))
{
TextPointer delEnd = start.GetPositionAtOffset(2);
new TextRange(start, delEnd).Text = "";
}
else if (text.StartsWith("☐") || text.StartsWith("☑"))
{
TextPointer delEnd = start.GetPositionAtOffset(1);
new TextRange(start, delEnd).Text = "";
}
}
}
finally
{
rtbContent.EndChange();
SaveState();
}
}
private void BatchCheckTodo_Click(object sender, RoutedEventArgs e)
{
var paras = GetSelectedParagraphs();
if (paras.Count == 0) return;
rtbContent.BeginChange();
try
{
foreach (var p in paras)
{
TextPointer start = p.ContentStart.GetInsertionPosition(LogicalDirection.Forward);
string text = start.GetTextInRun(LogicalDirection.Forward);
if (text.StartsWith("☐"))
{
TextPointer symbolEnd = start.GetPositionAtOffset(1);
new TextRange(start, symbolEnd).Text = "☑";
}
}
}
finally
{
rtbContent.EndChange();
SaveState();
}
}
private void BatchUncheckTodo_Click(object sender, RoutedEventArgs e)
{
var paras = GetSelectedParagraphs();
if (paras.Count == 0) return;
rtbContent.BeginChange();
try
{
foreach (var p in paras)
{
TextPointer start = p.ContentStart.GetInsertionPosition(LogicalDirection.Forward);
string text = start.GetTextInRun(LogicalDirection.Forward);
if (text.StartsWith("☑"))
{
TextPointer symbolEnd = start.GetPositionAtOffset(1);
new TextRange(start, symbolEnd).Text = "☐";
}
}
}
finally
{
rtbContent.EndChange();
SaveState();
}
}
private void BatchNumbering_Click(object sender, RoutedEventArgs e)
{
if (sender is MenuItem item && item.Tag is string style)
{
var paras = GetSelectedParagraphs();
if (paras.Count == 0) return;
rtbContent.BeginChange();
try
{
// 先尝试移除现有的编号,避免重复添加
RemoveNumbering(paras);
int index = 1;
foreach (var p in paras)
{
string text = new TextRange(p.ContentStart, p.ContentEnd).Text;
if (string.IsNullOrWhiteSpace(text)) continue;
string prefix = "";
switch (style)
{
case "1.": prefix = $"{index}. "; break;
case "1)": prefix = $"{index}) "; break;
case "①": prefix = $"{GetCircleNumber(index)} "; break;
case "A.": prefix = $"{GetAlphaNumber(index)}. "; break;
}
if (p.Inlines.Count == 0)
p.Inlines.Add(new Run(prefix));
else
p.Inlines.InsertBefore(p.Inlines.FirstInline, new Run(prefix));
index++;
}
}
finally
{
rtbContent.EndChange();
SaveState();
}
}
}
private void BatchRemoveNumbering_Click(object sender, RoutedEventArgs e)
{
var paras = GetSelectedParagraphs();
if (paras.Count == 0) return;
rtbContent.BeginChange();
try
{
RemoveNumbering(paras);
}
finally
{
rtbContent.EndChange();
SaveState();
}
}
private void RemoveNumbering(List<Paragraph> paras)
{
foreach (var p in paras)
{
TextPointer start = p.ContentStart.GetInsertionPosition(LogicalDirection.Forward);
string text = start.GetTextInRun(LogicalDirection.Forward);
// 匹配常见的编号格式
// 1. 1) ① A. (1) 等
// 这里使用简单的逻辑判断,移除开头的特定模式
int removeLen = 0;
// 检查 A. B. ...
if (text.Length >= 3 && char.IsLetter(text[0]) && text[1] == '.' && text[2] == ' ')
removeLen = 3;
// 检查数字开头的 1. 10. 1) 10) ...
else if (char.IsDigit(text[0]))
{
int i = 0;
while (i < text.Length && char.IsDigit(text[i])) i++;
if (i < text.Length && (text[i] == '.' || text[i] == ')') && i + 1 < text.Length && text[i+1] == ' ')
{
removeLen = i + 2;
}
}
// 检查 ① ... ⑳
else if (text.Length >= 2 && text[0] >= '①' && text[0] <= '⑳' && text[1] == ' ')
{
removeLen = 2;
}
// 检查 (1) ...
else if (text.StartsWith("(") && text.Contains(")") && text.IndexOf(")") < 6)
{
int idx = text.IndexOf(")");
if (idx + 1 < text.Length && text[idx+1] == ' ')
{
// 确保括号里是数字
bool isNum = true;
for(int k=1; k<idx; k++) if(!char.IsDigit(text[k])) { isNum = false; break; }
if (isNum) removeLen = idx + 2;
}
}
if (removeLen > 0)
{
TextPointer delEnd = start.GetPositionAtOffset(removeLen);
new TextRange(start, delEnd).Text = "";
}
}
}
private string GetCircleNumber(int i)
{
if (i >= 1 && i <= 20) return ((char)('①' + i - 1)).ToString();
return $"({i})";
}
private string GetAlphaNumber(int i)
{
string res = "";
while (i > 0)
{
i--;
res = (char)('A' + (i % 26)) + res;
i /= 26;
}
return res;
}
// 右键菜单:改颜色
// 标签选择变化事件
private void TabList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
// 切换前保存当前便签的内容
// 使用 _currentTab 来保存离开的那个便签的状态
if (_currentTab != null && _currentTab.NoteData != null)
{
// 只有当 _currentTab 确实是之前选中的那个便签时才保存
// 防止事件多次触发导致的混乱
try
{
SaveState();
}
catch (Exception ex)
{
Logger.Log($"SaveState failed during switch: {ex.Message}");
}
}
// 获取新选中的标签
StickyNote.TabItem? selectedTab = null;
if (e.AddedItems.Count > 0)
{
selectedTab = e.AddedItems[0] as StickyNote.TabItem;
}
if (selectedTab == null)
{
selectedTab = TabList.SelectedItem as StickyNote.TabItem;
}
if (selectedTab != null)
{
_currentTab = selectedTab;
ApplyDataToUI();
}
}
catch (Exception ex)
{
Logger.Log($"Error in TabList_SelectionChanged: {ex.Message}");
}
}
private void TabList_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
try
{
// 获取点击的 ListBoxItem
var item = ItemsControl.ContainerFromElement(TabList, e.OriginalSource as DependencyObject) as ListBoxItem;
if (item != null && item.Content is StickyNote.TabItem clickedTab)
{
// 如果点击的是当前已经选中的标签,强制刷新 UI
// 这解决了 ListBox 选中状态与实际内容不一致的问题
if (clickedTab == _currentTab)
{
Logger.Log($"Forcing reload for clicked tab: {clickedTab.Title}");
ApplyDataToUI();
}
else if (TabList.SelectedItem == clickedTab && _currentTab != clickedTab)
{
// 如果 ListBox 认为它被选中了,但 _currentTab 不是它,说明状态不同步
// 手动触发切换逻辑
Logger.Log($"Fixing sync issue for tab: {clickedTab.Title}");
_currentTab = clickedTab;
ApplyDataToUI();
}
}
}
catch (Exception ex)
{
Logger.Log($"Error in TabList_PreviewMouseLeftButtonUp: {ex.Message}");
}
}
// 双击标签重命名
private void TabList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (TabList.SelectedItem is TabItem tab)
{
RenameTabDialog(tab);
}
}
// 添加标签按钮点击事件
private void AddTab_Click(object sender, RoutedEventArgs e)
{
CreateNewTab();
}
// 重命名标签
private void RenameTab_Click(object sender, RoutedEventArgs e)
{
if (sender is MenuItem menuItem && menuItem.DataContext is TabItem tab)
{
RenameTabDialog(tab);
}
}
// 重命名标签对话框
private void RenameTabDialog(TabItem tab)
{
var dialog = new Window
{