-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
6111 lines (5364 loc) · 249 KB
/
MainWindow.xaml.cs
File metadata and controls
6111 lines (5364 loc) · 249 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;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media; // Added for VisualTreeHelper
using System.Threading.Tasks; // Added for Task.Delay and async/await
using System.Globalization; // Required for CultureInfo
using System.Windows.Data; // Required for IMultiValueConverter
using System.Threading; // For Timer (though DispatcherTimer is in System.Windows.Threading)
using System.Configuration; // Required for SettingsPropertyNotFoundException
using System.Collections.ObjectModel; // Required for ObservableCollection
using System.Text.Json; // For JSON serialization
using System.Text; // For StringBuilder and encoding
namespace TimeTask
{
public static class HelperClass
{
public static List<ItemGrid> ReadCsv(string filepath)
{
if (!File.Exists(filepath))
{
return null;
}
int parseScore = 0;
var allLines = File.ReadAllLines(filepath).Where(arg => !string.IsNullOrWhiteSpace(arg));
var result =
from line in allLines.Skip(1).Take(allLines.Count() - 1)
let temparry = line.Split(',')
let parse = int.TryParse(temparry[1], out parseScore)
let isCompleted = temparry.Length > 3 && temparry[3] != null && temparry[3] == "True"
let parsedLastModifiedDate = temparry.Length > 7 && DateTime.TryParse(temparry[7], out DateTime lmd) ? lmd : DateTime.Now
select new ItemGrid {
Task = temparry[0],
Score = parseScore,
Result = temparry[2],
IsActive = !isCompleted, // IsActive is the opposite of is_completed
Importance = temparry.Length > 4 && !string.IsNullOrWhiteSpace(temparry[4]) ? temparry[4] : "Unknown",
Urgency = temparry.Length > 5 && !string.IsNullOrWhiteSpace(temparry[5]) ? temparry[5] : "Unknown",
CreatedDate = temparry.Length > 6 && DateTime.TryParse(temparry[6], out DateTime cd) ? cd : DateTime.Now,
LastModifiedDate = parsedLastModifiedDate,
ReminderTime = temparry.Length > 8 && DateTime.TryParse(temparry[8], out DateTime rt) ? rt : (DateTime?)null,
LongTermGoalId = temparry.Length > 9 && !string.IsNullOrWhiteSpace(temparry[9]) ? temparry[9] : null,
OriginalScheduledDay = temparry.Length > 10 && int.TryParse(temparry[10], out int osd) ? osd : 0,
IsActiveInQuadrant = temparry.Length > 11 && bool.TryParse(temparry[11], out bool iaiq) ? iaiq : true, // Default to true for backward compatibility
InactiveWarningCount = temparry.Length > 12 && int.TryParse(temparry[12], out int iwc) ? iwc : 0,
LastProgressDate = temparry.Length > 13 && DateTime.TryParse(temparry[13], out DateTime lpd) ? lpd : parsedLastModifiedDate,
LastInteractionDate = temparry.Length > 14 && DateTime.TryParse(temparry[14], out DateTime lid) ? lid : parsedLastModifiedDate,
ReminderSnoozeUntil = temparry.Length > 15 && DateTime.TryParse(temparry[15], out DateTime rsu) ? rsu : (DateTime?)null,
LastReminderDate = temparry.Length > 16 && DateTime.TryParse(temparry[16], out DateTime lrd) ? lrd : (DateTime?)null,
SourceTaskID = temparry.Length > 17 && !string.IsNullOrWhiteSpace(temparry[17]) ? temparry[17] : null
};
var result_list = new List<ItemGrid>();
try
{
result_list = result.ToList();
}
catch (Exception ex) { // Catch specific exceptions if possible, or log general ones
Console.WriteLine($"Error parsing CSV lines: {ex.Message}");
// Add a default item or handle error as appropriate
result_list.Add(new ItemGrid { Task = "csv文件错误", Score = 0, Result= "", IsActive = true, Importance = "Unknown", Urgency = "Unknown", CreatedDate = DateTime.Now, LastModifiedDate = DateTime.Now, IsActiveInQuadrant = true, InactiveWarningCount = 0 });
}
return result_list;
}
public static void WriteCsv(IEnumerable<ItemGrid> items, string filepath)
{
var temparray = items.Select(item =>
$"{item.Task},{item.Score},{item.Result},{(item.IsActive ? "False" : "True")},{item.Importance ?? "Unknown"},{item.Urgency ?? "Unknown"},{item.CreatedDate:o},{item.LastModifiedDate:o},{item.ReminderTime?.ToString("o") ?? ""},{item.LongTermGoalId ?? ""},{item.OriginalScheduledDay},{item.IsActiveInQuadrant},{item.InactiveWarningCount},{item.LastProgressDate:o},{item.LastInteractionDate:o},{item.ReminderSnoozeUntil?.ToString("o") ?? ""},{item.LastReminderDate?.ToString("o") ?? ""},{item.SourceTaskID ?? ""}"
).ToArray();
var contents = new string[temparray.Length + 2];
Array.Copy(temparray, 0, contents, 1, temparray.Length);
// Updated header
contents[0] = "task,score,result,is_completed,importance,urgency,createdDate,lastModifiedDate,reminderTime,longTermGoalId,originalScheduledDay,isActiveInQuadrant,inactiveWarningCount,lastProgressDate,lastInteractionDate,reminderSnoozeUntil,lastReminderDate,sourceTaskId";
File.WriteAllLines(filepath, contents);
}
public static List<LongTermGoal> ReadLongTermGoalsCsv(string filepath)
{
if (!File.Exists(filepath))
{
return new List<LongTermGoal>();
}
var allLines = File.ReadAllLines(filepath).Where(arg => !string.IsNullOrWhiteSpace(arg)).ToList();
if (allLines.Count <= 1)
{
return new List<LongTermGoal>();
}
var goals = new List<LongTermGoal>();
foreach (var line in allLines.Skip(1))
{
var fields = line.Split(',');
if (fields.Length >= 5)
{
try
{
var goal = new LongTermGoal
{
Id = fields[0],
Description = fields[1].Replace(";;;", ","),
TotalDuration = fields[2],
CreationDate = DateTime.TryParse(fields[3], out DateTime cd) ? cd : DateTime.MinValue,
IsActive = bool.TryParse(fields[4], out bool ia) && ia,
IsLearningPlan = fields.Length > 5 && bool.TryParse(fields[5], out bool ilp) && ilp,
Subject = fields.Length > 6 ? fields[6].Replace(";;;", ",") : null,
StartDate = fields.Length > 7 && DateTime.TryParse(fields[7], out DateTime sd) ? sd : (DateTime?)null,
TotalStages = fields.Length > 8 && int.TryParse(fields[8], out int ts) ? ts : 0,
CompletedStages = fields.Length > 9 && int.TryParse(fields[9], out int cs) ? cs : 0
};
goals.Add(goal);
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing LongTermGoal line: {line}. Error: {ex.Message}");
}
}
}
return goals;
}
public static void WriteLongTermGoalsCsv(List<LongTermGoal> goals, string filepath)
{
var directory = Path.GetDirectoryName(filepath);
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
var lines = new List<string> { "Id,Description,TotalDuration,CreationDate,IsActive,IsLearningPlan,Subject,StartDate,TotalStages,CompletedStages" };
foreach (var goal in goals)
{
string safeDescription = goal.Description?.Replace(",", ";;;") ?? "";
string safeSubject = goal.Subject?.Replace(",", ";;;") ?? "";
lines.Add($"{goal.Id},{safeDescription},{goal.TotalDuration},{goal.CreationDate:o},{goal.IsActive},{goal.IsLearningPlan},{safeSubject},{goal.StartDate?.ToString("o") ?? ""},{goal.TotalStages},{goal.CompletedStages}");
}
File.WriteAllLines(filepath, lines);
}
public static List<LearningPlan> ReadLearningPlansCsv(string filepath)
{
if (!File.Exists(filepath))
{
return new List<LearningPlan>();
}
var allLines = File.ReadAllLines(filepath).Where(arg => !string.IsNullOrWhiteSpace(arg)).ToList();
if (allLines.Count <= 1)
{
return new List<LearningPlan>();
}
var plans = new List<LearningPlan>();
foreach (var line in allLines.Skip(1))
{
var fields = line.Split(',');
if (fields.Length >= 10)
{
try
{
var plan = new LearningPlan
{
Id = fields[0],
Subject = fields[1].Replace(";;;", ","),
Goal = fields[2].Replace(";;;", ","),
Duration = fields[3],
CreationDate = DateTime.TryParse(fields[4], out DateTime cd) ? cd : DateTime.MinValue,
StartDate = DateTime.TryParse(fields[5], out DateTime sd) ? sd : (DateTime?)null,
EndDate = DateTime.TryParse(fields[6], out DateTime ed) ? ed : (DateTime?)null,
IsActive = bool.TryParse(fields[7], out bool ia) && ia,
TotalStages = int.TryParse(fields[8], out int ts) ? ts : 0,
CompletedStages = int.TryParse(fields[9], out int cs) ? cs : 0
};
plans.Add(plan);
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing LearningPlan line: {line}. Error: {ex.Message}");
}
}
}
return plans;
}
public static void WriteLearningPlansCsv(List<LearningPlan> plans, string filepath)
{
var directory = Path.GetDirectoryName(filepath);
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
var lines = new List<string> { "Id,Subject,Goal,Duration,CreationDate,StartDate,EndDate,IsActive,TotalStages,CompletedStages" };
foreach (var plan in plans)
{
string safeSubject = plan.Subject?.Replace(",", ";;;") ?? "";
string safeGoal = plan.Goal?.Replace(",", ";;;") ?? "";
lines.Add($"{plan.Id},{safeSubject},{safeGoal},{plan.Duration},{plan.CreationDate:o},{plan.StartDate?.ToString("o") ?? ""},{plan.EndDate?.ToString("o") ?? ""},{plan.IsActive},{plan.TotalStages},{plan.CompletedStages}");
}
File.WriteAllLines(filepath, lines);
}
public static List<LearningMilestone> ReadLearningMilestonesCsv(string filepath)
{
if (!File.Exists(filepath))
{
return new List<LearningMilestone>();
}
var allLines = File.ReadAllLines(filepath).Where(arg => !string.IsNullOrWhiteSpace(arg)).ToList();
if (allLines.Count <= 1)
{
return new List<LearningMilestone>();
}
var milestones = new List<LearningMilestone>();
foreach (var line in allLines.Skip(1))
{
var fields = line.Split(',');
if (fields.Length >= 9)
{
try
{
var milestone = new LearningMilestone
{
Id = fields[0],
LearningPlanId = fields[1],
StageName = fields[2].Replace(";;;", ","),
Description = fields[3].Replace(";;;", ","),
StageNumber = int.TryParse(fields[4], out int sn) ? sn : 0,
TargetDate = DateTime.TryParse(fields[5], out DateTime td) ? td : (DateTime?)null,
IsCompleted = bool.TryParse(fields[6], out bool ic) && ic,
CompletedDate = DateTime.TryParse(fields[7], out DateTime ccd) ? ccd : (DateTime?)null,
AssociatedTaskId = fields.Length > 8 ? fields[8] : null
};
milestones.Add(milestone);
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing LearningMilestone line: {line}. Error: {ex.Message}");
}
}
}
return milestones;
}
public static void WriteLearningMilestonesCsv(List<LearningMilestone> milestones, string filepath)
{
var directory = Path.GetDirectoryName(filepath);
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
var lines = new List<string> { "Id,LearningPlanId,StageName,Description,StageNumber,TargetDate,IsCompleted,CompletedDate,AssociatedTaskId" };
foreach (var milestone in milestones)
{
string safeStageName = milestone.StageName?.Replace(",", ";;;") ?? "";
string safeDescription = milestone.Description?.Replace(",", ";;;") ?? "";
lines.Add($"{milestone.Id},{milestone.LearningPlanId},{safeStageName},{safeDescription},{milestone.StageNumber},{milestone.TargetDate?.ToString("o") ?? ""},{milestone.IsCompleted},{milestone.CompletedDate?.ToString("o") ?? ""},{milestone.AssociatedTaskId ?? ""}");
}
File.WriteAllLines(filepath, lines);
}
}
public class ItemGrid
{
public string Task { set; get; }
public int Score { set; get; }
public string Result { set; get; }
/// <summary>
/// Gets or sets a value indicating whether the task is active.
/// True if the task is pending, False if it's completed.
/// </summary>
public bool IsActive { set; get; }
public string Importance { set; get; } = "Unknown";
public string Urgency { set; get; } = "Unknown";
public DateTime CreatedDate { set; get; } = DateTime.Now;
public DateTime LastModifiedDate { set; get; } = DateTime.Now;
public DateTime LastProgressDate { get; set; } = DateTime.Now;
public DateTime LastInteractionDate { get; set; } = DateTime.Now;
public DateTime? ReminderTime { get; set; } = null;
public DateTime? ReminderSnoozeUntil { get; set; } = null;
public DateTime? LastReminderDate { get; set; } = null;
public string TaskType { get; set; }
public DateTime? CompletionTime { get; set; }
public string CompletionStatus { get; set; }
public string AssignedRole { get; set; }
public string SourceTaskID { get; set; } // To map to SourceTaskID from the database
// New properties for Long-Term Goal association
public string LongTermGoalId { get; set; } = null; // ID of the parent LongTermGoal
public int OriginalScheduledDay { get; set; } = 0; // Day index for tasks from a long-term plan
public bool IsActiveInQuadrant { get; set; } = true; // True if the task should be displayed in the main quadrants
// New property for inactivity warning
public int InactiveWarningCount { get; set; } = 0;
}
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
// using System.Threading.Tasks; // Moved to top
// Removed redundant nested namespace TimeTask
public partial class MainWindow : Window
{
public sealed class FocusBoardSnapshot
{
public ItemGrid PrimaryTask { get; set; }
public string PrimaryMeta { get; set; }
public ItemGrid ReminderTask { get; set; }
public string ReminderMeta { get; set; }
public ItemGrid StuckTask { get; set; }
public string StuckMeta { get; set; }
}
public sealed class SystemProgressSnapshot
{
public int Level { get; set; }
public int Experience { get; set; }
public int NextLevelExperience { get; set; }
public string StageText { get; set; }
public string NarrativeText { get; set; }
public string ActiveQuestText { get; set; }
public string RecommendedSkillText { get; set; }
public List<SystemSkillNodeSnapshot> SkillNodes { get; set; } = new List<SystemSkillNodeSnapshot>();
}
public sealed class SystemSkillNodeSnapshot
{
public string SkillId { get; set; }
public string Title { get; set; }
public int Level { get; set; }
public string MetaText { get; set; }
public string ToolTipText { get; set; }
}
private LlmService _llmService;
private bool _llmConfigErrorDetectedInLoad = false; // Flag for LLM config error during load
// Configurable timeout settings with defaults
private static TimeSpan StaleTaskThreshold => TimeSpan.FromDays(Properties.Settings.Default.StaleTaskThresholdDays);
private static int MaxInactiveWarnings => Properties.Settings.Default.MaxInactiveWarnings;
private static TimeSpan FirstWarningAfter => TimeSpan.FromDays(Properties.Settings.Default.FirstWarningAfterDays);
private static TimeSpan SecondWarningAfter => TimeSpan.FromDays(Properties.Settings.Default.SecondWarningAfterDays);
private System.Windows.Threading.DispatcherTimer _reminderTimer;
private System.Windows.Threading.DispatcherTimer _draftBadgeTimer;
private System.Windows.Threading.DispatcherTimer _voiceStatusAnimTimer;
private VoiceListenerState _voiceListenerState = VoiceListenerState.Unknown;
private TaskDraftManager _draftBadgeManager;
private UserProfileManager _userProfileManager;
private bool _proactiveAssistEnabled = true;
private bool _behaviorLearningEnabled = true;
private bool _stuckNudgesEnabled = true;
private bool _llmSkillAssistEnabled = true;
private bool _nonBlockingInteractionEnabled = true;
private int _quietHoursStart = 22;
private int _quietHoursEnd = 8;
private const int DailyReminderLimit = 3;
private static readonly TimeSpan ReminderCooldown = TimeSpan.FromMinutes(45);
private int _remindersShownToday = 0;
private DateTime _reminderCounterDate = DateTime.Today;
private readonly Dictionary<string, TaskInteractionState> _taskInteractionStates = new Dictionary<string, TaskInteractionState>();
private readonly Dictionary<string, List<string>> _pendingReminderSkillIds = new Dictionary<string, List<string>>();
private const int DefaultDailyStuckNudgeLimit = 2;
private static readonly TimeSpan StuckNudgeCooldown = TimeSpan.FromHours(2);
private static readonly TimeSpan DefaultStuckNoProgressThreshold = TimeSpan.FromMinutes(90);
private static readonly TimeSpan MinStuckNoProgressThreshold = TimeSpan.FromMinutes(60);
private static readonly TimeSpan MaxStuckNoProgressThreshold = TimeSpan.FromMinutes(180);
private const int MinDailyStuckNudgeLimit = 1;
private const int MaxDailyStuckNudgeLimit = 3;
private TimeSpan _adaptiveStuckNoProgressThreshold = DefaultStuckNoProgressThreshold;
private int _adaptiveDailyStuckNudgeLimit = DefaultDailyStuckNudgeLimit;
private DateTime _lastAdaptiveTuneAt = DateTime.MinValue;
private int _stuckNudgesShownToday = 0;
private DateTime _stuckNudgeCounterDate = DateTime.Today;
private DateTime _lastStuckNudgeAt = DateTime.MinValue;
private ItemGrid _primaryFocusTask;
private ItemGrid _reminderFocusTask;
private ItemGrid _stuckFocusTask;
private readonly Dictionary<Border, SystemSkillNodeSnapshot> _skillTreeNodeMap = new Dictionary<Border, SystemSkillNodeSnapshot>();
private readonly List<string> _systemTickerMessages = new List<string>();
private System.Windows.Threading.DispatcherTimer _systemTickerTimer;
private int _systemTickerIndex;
private bool _isSystemPanelCompactMode = true;
private DatabaseService _databaseService;
private System.Windows.Threading.DispatcherTimer _syncTimer;
private KnowledgeSyncService _knowledgeSyncService;
private KnowledgeArtifactService _knowledgeArtifactService;
private System.Windows.Threading.DispatcherTimer _knowledgeSyncTimer;
private System.Windows.Threading.DispatcherTimer _knowledgeSyncDebounceTimer;
private FileSystemWatcher _obsidianWatcher;
private bool _knowledgeSyncRunning = false;
private HashSet<string> _syncedTaskSourceIDs = new HashSet<string>();
private bool _isFirstSyncAttempted = false; // To control initial sync message
// 新增智能系统
private SmartGuidanceManager _smartGuidanceManager;
private ConversationRecorder _conversationRecorder;
private UserBehaviorObserver _behaviorObserver;
private AdaptiveGoalManager _adaptiveGoalManager;
private LifeProfileEngine _lifeProfileEngine;
private DecisionEngine _decisionEngine;
private WeeklyReviewEngine _weeklyReviewEngine;
private GoalHierarchyEngine _goalHierarchyEngine;
private System.Windows.Threading.DispatcherTimer _smartSystemTimer;
private System.Windows.Threading.DispatcherTimer _conversationIdleTimer;
private DateTime _lastVoiceConversationSegmentAtUtc = DateTime.MinValue;
private DateTime _lastStrategyCycleAt = DateTime.MinValue;
private DateTime _lastWeeklyReviewNoticeDate = DateTime.MinValue;
private static readonly TimeSpan ConversationIdleTimeout = TimeSpan.FromSeconds(75);
private TimeSpan _strategyCycleInterval = TimeSpan.FromMinutes(30);
private DayOfWeek _weeklyReviewPublishDay = DayOfWeek.Monday;
private int _strategyTopFocusCount = 5;
private DecisionEngineOptions _decisionOptions = new DecisionEngineOptions();
private ItemGrid _draggedItem;
private DataGrid _sourceDataGrid;
private Point? _dragStartPoint; // To store the starting point of a potential drag
[DllImport("user32.dll", SetLastError = true)]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpWindowClass, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);
const int GWL_HWNDPARENT = -8;
[DllImport("user32.dll")]
static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
internal string currentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); // Made internal for test access
int task1_selected_indexs = -1;
int task2_selected_indexs = -1;
int task3_selected_indexs = -1;
int task4_selected_indexs = -1;
private LongTermGoal _activeLongTermGoal;
private void LoadActiveLongTermGoalAndRefreshDisplay()
{
string longTermGoalsCsvPath = Path.Combine(currentPath, "data", "long_term_goals.csv");
if (File.Exists(longTermGoalsCsvPath))
{
List<LongTermGoal> allLongTermGoals = HelperClass.ReadLongTermGoalsCsv(longTermGoalsCsvPath);
_activeLongTermGoal = allLongTermGoals.FirstOrDefault(g => g.IsActive);
}
else
{
_activeLongTermGoal = null;
}
UpdateLongTermGoalBadge();
}
public void UpdateLongTermGoalBadge()
{
if (_activeLongTermGoal != null)
{
ActiveLongTermGoalDisplay.Visibility = Visibility.Visible;
if (_activeLongTermGoal.IsLearningPlan)
{
ActiveLongTermGoalName.Text = $"{TruncateText(_activeLongTermGoal.Subject, 15)}计划";
double progress = _activeLongTermGoal.ProgressPercentage;
LongTermGoalBadge.Text = $"{progress:F0}%";
}
else
{
ActiveLongTermGoalName.Text = TruncateText(_activeLongTermGoal.Description, 20);
int pendingSubTasks = 0;
string[] csvFiles = { "1.csv", "2.csv", "3.csv", "4.csv" };
for (int i = 0; i < csvFiles.Length; i++)
{
string filePath = Path.Combine(currentPath, "data", csvFiles[i]);
if (File.Exists(filePath))
{
List<ItemGrid> items = HelperClass.ReadCsv(filePath);
if (items != null)
{
pendingSubTasks += items.Count(item => item.LongTermGoalId == _activeLongTermGoal.Id && item.IsActive);
}
}
}
LongTermGoalBadge.Text = pendingSubTasks.ToString();
}
}
else
{
ActiveLongTermGoalDisplay.Visibility = Visibility.Collapsed;
}
}
private string TruncateText(string text, int maxLength)
{
if (string.IsNullOrEmpty(text)) return string.Empty;
return text.Length <= maxLength ? text : text.Substring(0, maxLength) + "...";
}
public void loadDataGridView()
{
LoadActiveLongTermGoalAndRefreshDisplay(); // Load active goal and update its display
_llmConfigErrorDetectedInLoad = false;
string[] csvFiles = { "1.csv", "2.csv", "3.csv", "4.csv" };
DataGrid[] dataGrids = { task1, task2, task3, task4 };
for (int i = 0; i < csvFiles.Length; i++)
{
string filePath = Path.Combine(currentPath, "data", csvFiles[i]);
List<ItemGrid> allItemsInCsv = HelperClass.ReadCsv(filePath);
List<ItemGrid> itemsToDisplayInQuadrant;
if (allItemsInCsv == null)
{
Console.WriteLine($"Error reading CSV file: {filePath}. Or file is empty/new.");
allItemsInCsv = new List<ItemGrid>();
}
else
{
foreach (var item in allItemsInCsv)
{
if (!string.IsNullOrWhiteSpace(item.SourceTaskID) && !_syncedTaskSourceIDs.Contains(item.SourceTaskID))
{
_syncedTaskSourceIDs.Add(item.SourceTaskID);
}
}
}
// Filter tasks for display: only those marked IsActiveInQuadrant
itemsToDisplayInQuadrant = allItemsInCsv.Where(item => item.IsActiveInQuadrant).ToList();
dataGrids[i].ItemsSource = null;
dataGrids[i].ItemsSource = itemsToDisplayInQuadrant;
if (!dataGrids[i].Items.SortDescriptions.Contains(new SortDescription("Score", ListSortDirection.Descending)))
{
dataGrids[i].Items.SortDescriptions.Add(new SortDescription("Score", ListSortDirection.Descending));
}
// After all files are processed, show a single notification if LLM config error was detected
if (_llmConfigErrorDetectedInLoad)
{
MessageBox.Show(this, "During task loading, some AI assistant features may have been limited due to a configuration issue (e.g., missing or placeholder API key). Please check the application's setup if you expect full AI functionality.",
"LLM Configuration Issue", MessageBoxButton.OK, MessageBoxImage.Warning);
// As per requirement, not resetting _llmConfigErrorDetectedInLoad here.
}
}
}
public void DataGrid_MouseDoubleClick_AddTask(object sender, MouseButtonEventArgs e)
{
if (!(sender is DataGrid dataGrid)) return;
var hitTestResult = VisualTreeHelper.HitTest(dataGrid, e.GetPosition(dataGrid));
if (hitTestResult?.VisualHit == null)
{
return;
}
var visualHit = hitTestResult.VisualHit;
while (visualHit != null && visualHit != dataGrid)
{
if (visualHit is DataGridRow || visualHit is System.Windows.Controls.Primitives.DataGridColumnHeader || visualHit is DataGridCell)
{
return;
}
visualHit = VisualTreeHelper.GetParent(visualHit);
}
TryOpenAddTaskDialogForDataGrid(dataGrid);
}
private void TryOpenAddTaskDialogForDataGrid(DataGrid dataGrid)
{
int quadrantIndex = -1;
switch (dataGrid.Name)
{
case "task1": quadrantIndex = 0; break;
case "task2": quadrantIndex = 1; break;
case "task3": quadrantIndex = 2; break;
case "task4": quadrantIndex = 3; break;
}
if (quadrantIndex == -1)
{
Console.WriteLine($"Error: Could not determine quadrant index for DataGrid named {dataGrid.Name}");
return;
}
if (_llmService == null)
{
MessageBox.Show("LLM Service is not available.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
AddTaskWindow addTaskWindow = new AddTaskWindow(_llmService, quadrantIndex);
bool? dialogResult = addTaskWindow.ShowDialog();
if (dialogResult == true && addTaskWindow.TaskAdded && addTaskWindow.NewTask != null)
{
ItemGrid newTask = addTaskWindow.NewTask;
int finalQuadrantIndex = AddTaskWindow.GetIndexFromPriority(newTask.Importance, newTask.Urgency);
DataGrid targetDataGrid = null;
switch (finalQuadrantIndex)
{
case 0: targetDataGrid = task1; break;
case 1: targetDataGrid = task2; break;
case 2: targetDataGrid = task3; break;
case 3: targetDataGrid = task4; break;
default:
MessageBox.Show("Invalid quadrant specified for the new task after dialog.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
string csvFileNumber = GetQuadrantNumber(targetDataGrid.Name);
List<ItemGrid> items = targetDataGrid.ItemsSource as List<ItemGrid>;
if (items == null)
{
items = new List<ItemGrid>();
targetDataGrid.ItemsSource = items;
}
items.Add(newTask);
TrackTaskInteraction(newTask, "progress");
RecordTaskProgressProfile(newTask, "manual_create");
for (int i = 0; i < items.Count; i++)
{
items[i].Score = items.Count - i;
}
RefreshDataGrid(targetDataGrid);
if (!string.IsNullOrEmpty(csvFileNumber))
{
update_csv(targetDataGrid, csvFileNumber);
}
else
{
MessageBox.Show($"Could not determine CSV file for quadrant: {targetDataGrid.Name}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
public MainWindow()
{
InitializeComponent();
I18n.LanguageChanged += I18n_LanguageChanged;
InitializeVoiceStatusIndicator();
this.Closed += MainWindow_Closed;
// 初始化用户体验改进功能
UXImprovements.Initialize(this);
// 配置验证已移除
_llmService = LlmService.Create();
_userProfileManager = new UserProfileManager();
LoadProactiveConfig();
UpdateAdaptiveNudgeParameters(force: true);
var normalizedPosition = NormalizeWindowPosition(
(double)Properties.Settings.Default.Left,
(double)Properties.Settings.Default.Top,
this.Width,
this.Height);
this.Left = normalizedPosition.X;
this.Top = normalizedPosition.Y;
loadDataGridView();
UpdateFocusBoard();
InitializeSystemPanelBehavior();
// Attach CellEditEnding event handler to all DataGrids
task1.CellEditEnding += DataGrid_CellEditEnding;
task2.CellEditEnding += DataGrid_CellEditEnding;
task3.CellEditEnding += DataGrid_CellEditEnding;
task4.CellEditEnding += DataGrid_CellEditEnding;
// Initialize and start the reminder timer with configurable interval
_reminderTimer = new System.Windows.Threading.DispatcherTimer();
_reminderTimer.Interval = TimeSpan.FromSeconds(Properties.Settings.Default.ReminderCheckIntervalSeconds);
_reminderTimer.Tick += ReminderTimer_Tick;
_reminderTimer.Start();
// Start periodic task reminder checks
StartPeriodicTaskReminderChecks();
InitializeSyncService();
_knowledgeArtifactService = KnowledgeArtifactService.CreateFromAppSettings(currentPath);
// 应用快速改进功能
ApplyQuickImprovements();
InitializeDraftBadgeMonitor();
InitializeKnowledgeSyncService();
// 初始化智能系统
InitializeSmartSystems();
}
private void I18n_LanguageChanged(object sender, EventArgs e)
{
if (!Dispatcher.CheckAccess())
{
Dispatcher.BeginInvoke(new Action(() => I18n_LanguageChanged(sender, e)));
return;
}
UpdateFocusBoard();
ApplySystemPanelMode();
UpdateVoiceStatusUi(VoiceListenerStatusCenter.Current);
}
private void InitializeSystemPanelBehavior()
{
try
{
_systemTickerTimer = new System.Windows.Threading.DispatcherTimer();
_systemTickerTimer.Interval = TimeSpan.FromSeconds(7);
_systemTickerTimer.Tick += SystemTickerTimer_Tick;
_systemTickerTimer.Start();
ApplySystemPanelMode();
}
catch (Exception ex)
{
Console.WriteLine($"System panel behavior init failed: {ex.Message}");
}
}
private void InitializeVoiceStatusIndicator()
{
try
{
_voiceStatusAnimTimer = new System.Windows.Threading.DispatcherTimer();
_voiceStatusAnimTimer.Interval = TimeSpan.FromMilliseconds(280);
_voiceStatusAnimTimer.Tick += VoiceStatusAnimTimer_Tick;
VoiceListenerStatusCenter.StatusChanged += VoiceListenerStatusCenter_StatusChanged;
UpdateVoiceStatusUi(VoiceListenerStatusCenter.Current);
}
catch (Exception ex)
{
Console.WriteLine($"Voice status indicator init failed: {ex.Message}");
}
}
private void VoiceListenerStatusCenter_StatusChanged(object sender, VoiceListenerStatus status)
{
if (!Dispatcher.CheckAccess())
{
Dispatcher.BeginInvoke(new Action(() => UpdateVoiceStatusUi(status)));
return;
}
UpdateVoiceStatusUi(status);
}
private void UpdateVoiceStatusUi(VoiceListenerStatus status)
{
if (status == null || VoiceStatusButton == null || VoiceStatusIcon == null || VoiceStatusDot == null || VoiceStatusText == null)
return;
_voiceListenerState = status.State;
string statusLabel = GetVoiceStatusLabel(status.State);
string tooltipMessage = string.IsNullOrWhiteSpace(status.Message) ? statusLabel : status.Message;
string updatedLocal = status.UpdatedAtUtc.ToLocalTime().ToString("HH:mm:ss");
VoiceStatusButton.ToolTip = $"{I18n.T("Voice_StatusTitle")}: {statusLabel}\n{tooltipMessage}\n{I18n.T("Voice_StatusUpdatedAt")}: {updatedLocal}";
VoiceStatusText.Text = BuildVoiceStatusText(statusLabel, status.Message);
switch (status.State)
{
case VoiceListenerState.Installing:
case VoiceListenerState.Loading:
ApplyVoiceStatusBrush("#FFECEFF1", "#FFB0BEC5", "#FF90A4AE");
StopVoiceStatusAnimation();
break;
case VoiceListenerState.Unavailable:
ApplyVoiceStatusBrush("#FFECEFF1", "#FFB0BEC5", "#FF90A4AE");
StopVoiceStatusAnimation();
break;
case VoiceListenerState.Ready:
ApplyVoiceStatusBrush("#FFE8F5E9", "#FFA5D6A7", "#FF2E7D32");
StopVoiceStatusAnimation();
break;
case VoiceListenerState.Recognizing:
ApplyVoiceStatusBrush("#FFE3F2FD", "#FF90CAF9", "#FF1E88E5");
StartVoiceStatusAnimation();
break;
default:
ApplyVoiceStatusBrush("#FFECEFF1", "#FFCFD8DC", "#FF90A4AE");
StopVoiceStatusAnimation();
break;
}
}
private static string GetVoiceStatusLabel(VoiceListenerState state)
{
switch (state)
{
case VoiceListenerState.Installing:
case VoiceListenerState.Loading:
return I18n.T("Voice_StatusUnavailable");
case VoiceListenerState.Unavailable:
return I18n.T("Voice_StatusUnavailable");
case VoiceListenerState.Ready:
return I18n.T("Voice_StatusReady");
case VoiceListenerState.Recognizing:
return I18n.T("Voice_StatusRecognizing");
default:
return I18n.T("Voice_StatusUnknown");
}
}
private static string BuildVoiceStatusText(string statusLabel, string statusMessage)
{
string msg = statusMessage ?? string.Empty;
int retrySec = ParseRetryAfterSeconds(msg);
if (retrySec > 0)
{
return I18n.Tf("Voice_StatusCooldownFormat", FormatDuration(retrySec));
}
if (!string.IsNullOrWhiteSpace(msg))
{
string compact = msg.Replace(":", " ").Trim();
if (compact.Length > 28)
{
compact = compact.Substring(0, 28) + "...";
}
return compact;
}
return I18n.Tf("Voice_StatusPrefixFormat", statusLabel);
}
private static int ParseRetryAfterSeconds(string message)
{
if (string.IsNullOrWhiteSpace(message))
return 0;
const string token = "retry-after-sec=";
int idx = message.IndexOf(token, StringComparison.OrdinalIgnoreCase);
if (idx < 0)
return 0;
int start = idx + token.Length;
int end = start;
while (end < message.Length && char.IsDigit(message[end]))
{
end++;
}
if (end <= start)
return 0;
string number = message.Substring(start, end - start);
return int.TryParse(number, out int sec) ? sec : 0;
}
private static string FormatDuration(int totalSeconds)
{
if (totalSeconds <= 0)
return I18n.Tf("Duration_Seconds", 0);
int minutes = totalSeconds / 60;
int seconds = totalSeconds % 60;
if (minutes <= 0)
return I18n.Tf("Duration_Seconds", seconds);
if (seconds == 0)
return I18n.Tf("Duration_Minutes", minutes);
return I18n.Tf("Duration_MinutesSeconds", minutes, seconds);
}
private void ApplyVoiceStatusBrush(string bgHex, string borderHex, string fgHex)
{
var bg = (Brush)new BrushConverter().ConvertFromString(bgHex);
var border = (Brush)new BrushConverter().ConvertFromString(borderHex);
var fg = (Brush)new BrushConverter().ConvertFromString(fgHex);
VoiceStatusButton.Background = bg;
VoiceStatusButton.BorderBrush = border;
VoiceStatusIcon.Foreground = fg;
VoiceStatusText.Foreground = fg;
VoiceStatusDot.Fill = fg;
}
private void StartVoiceStatusAnimation()
{
if (_voiceStatusAnimTimer != null && !_voiceStatusAnimTimer.IsEnabled)
{
_voiceStatusAnimTimer.Start();
}
}
private void StopVoiceStatusAnimation()
{
if (_voiceStatusAnimTimer != null && _voiceStatusAnimTimer.IsEnabled)
{
_voiceStatusAnimTimer.Stop();
}
if (VoiceStatusScale != null)
{
VoiceStatusScale.ScaleX = 1.0;
VoiceStatusScale.ScaleY = 1.0;
}
if (VoiceStatusIcon != null)
{
VoiceStatusIcon.Opacity = 1.0;
}
}
private void VoiceStatusAnimTimer_Tick(object sender, EventArgs e)
{
if (VoiceStatusScale == null || VoiceStatusIcon == null)
return;
bool activePulse = _voiceListenerState == VoiceListenerState.Recognizing;
if (!activePulse)
{
StopVoiceStatusAnimation();
return;
}
bool enlarged = VoiceStatusScale.ScaleX > 1.05;
VoiceStatusScale.ScaleX = enlarged ? 1.0 : 1.16;
VoiceStatusScale.ScaleY = enlarged ? 1.0 : 1.16;
VoiceStatusIcon.Opacity = enlarged ? 1.0 : 0.72;
}
private void MainWindow_Closed(object sender, EventArgs e)
{
try
{
VoiceListenerStatusCenter.StatusChanged -= VoiceListenerStatusCenter_StatusChanged;
I18n.LanguageChanged -= I18n_LanguageChanged;
VoiceListenerStatusCenter.RecognitionCaptured -= VoiceListenerStatusCenter_RecognitionCaptured;
TaskDraftManager.DraftsChanged -= TaskDraftManager_DraftsChanged;
if (_voiceStatusAnimTimer != null)
{
_voiceStatusAnimTimer.Stop();
_voiceStatusAnimTimer.Tick -= VoiceStatusAnimTimer_Tick;
_voiceStatusAnimTimer = null;
}
if (_systemTickerTimer != null)
{
_systemTickerTimer.Stop();
_systemTickerTimer.Tick -= SystemTickerTimer_Tick;
_systemTickerTimer = null;
}
if (_conversationIdleTimer != null)
{
_conversationIdleTimer.Stop();
_conversationIdleTimer.Tick -= ConversationIdleTimer_Tick;
_conversationIdleTimer = null;
}
if (_knowledgeSyncTimer != null)
{
_knowledgeSyncTimer.Stop();
_knowledgeSyncTimer = null;
}
if (_knowledgeSyncDebounceTimer != null)
{
_knowledgeSyncDebounceTimer.Stop();
_knowledgeSyncDebounceTimer = null;
}
if (_obsidianWatcher != null)
{
_obsidianWatcher.EnableRaisingEvents = false;
_obsidianWatcher.Dispose();
_obsidianWatcher = null;
}
_conversationRecorder?.EndSession();
_draftBadgeManager?.Dispose();
}