-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNotificationManager.cs
More file actions
362 lines (316 loc) · 12.8 KB
/
Copy pathNotificationManager.cs
File metadata and controls
362 lines (316 loc) · 12.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
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Threading;
using notifyIcon = System.Windows.Forms.NotifyIcon;
namespace TimeTask
{
/// <summary>
/// 通知管理器(唯一托盘图标)
/// - 静默通知:托盘图标闪烁
/// - Toast 通知:Windows 系统通知
/// - 交流/会议录音状态实时展示(与草稿提醒共用同一个图标)
/// - 恰到好处的触发策略
/// </summary>
public class NotificationManager : IDisposable
{
private readonly TaskDraftManager _draftManager;
private readonly ConversationCaptureService _capture;
private readonly Action _openInbox;
private readonly string _hotkeyHint;
private notifyIcon _notifyIcon;
private DispatcherTimer _checkTimer;
private int _blinkCount = 0;
private bool _isBlinking = false;
private const int MaxBlinkCount = 6; // 闪烁6次后停止
// 通知阈值
private const int DraftNotificationThreshold = 1; // 有草稿即提示
private const int WorkReminderIntervalMinutes = 240; // 每4小时提醒一次
private static readonly TimeSpan DraftNotificationCooldown = TimeSpan.FromMinutes(30);
// 状态
private DateTime _lastWorkReminder = DateTime.MinValue;
private int _consecutiveDraftCounts = 0;
private DateTime _lastDraftNotificationTime = DateTime.MinValue;
private int _lastNotifiedDraftCount = 0;
public NotificationManager(TaskDraftManager draftManager, ConversationCaptureService capture = null, Action openInbox = null, string hotkeyHint = "Ctrl+Alt+R")
{
_draftManager = draftManager ?? throw new ArgumentNullException(nameof(draftManager));
_capture = capture;
_openInbox = openInbox;
_hotkeyHint = hotkeyHint;
InitializeNotifyIcon();
StartMonitoring();
UpdateTooltip(_draftManager?.UnprocessedCount ?? 0); // 立即反映初始 ASR 状态(如“模型加载中…”)
if (_capture != null)
{
_capture.StatusChanged += OnCaptureStatusChanged;
}
}
private void InitializeNotifyIcon()
{
try
{
_notifyIcon = new notifyIcon
{
Icon = LoadTrayIcon() ?? System.Drawing.Icon.ExtractAssociatedIcon(
System.Reflection.Assembly.GetExecutingAssembly().Location
),
Text = "TimeTask - 任务管理助手",
Visible = true
};
_notifyIcon.ContextMenuStrip = new System.Windows.Forms.ContextMenuStrip();
_notifyIcon.ContextMenuStrip.Items.Add("显示主窗口", null, (s, e) => ShowMainWindow());
if (_capture != null)
{
_notifyIcon.ContextMenuStrip.Items.Add($"开始/停止记录 ({_hotkeyHint})", null, (s, e) => _capture.Toggle());
_notifyIcon.ContextMenuStrip.Items.Add("查看行动收件箱", null, (s, e) => _openInbox?.Invoke());
}
_notifyIcon.ContextMenuStrip.Items.Add("-");
_notifyIcon.ContextMenuStrip.Items.Add("退出", null, (s, e) => ExitApplication());
// 双击打开主窗口
_notifyIcon.DoubleClick += (s, e) => ShowMainWindow();
Console.WriteLine("[NotificationManager] NotifyIcon initialized (single tray icon).");
}
catch (Exception ex)
{
Console.WriteLine($"[NotificationManager] Failed to initialize NotifyIcon: {ex.Message}");
}
}
/// <summary>
/// 加载自定义托盘图标(四色象限时钟:蓝/红/绿/黄对应四象限,白色指针呼应“时间管理”)。
/// 图标以 WPF Resource 嵌入(Assets/TimeTaskTray.ico,含 256/48/32/16 四帧);
/// 托盘取 16px 帧最锐利;加载失败时回退到程序图标。
/// </summary>
private static System.Drawing.Icon LoadTrayIcon()
{
try
{
var uri = new Uri("pack://application:,,,/Assets/TimeTaskTray.ico", UriKind.Absolute);
var resource = System.Windows.Application.GetResourceStream(uri);
if (resource == null) return null;
using (var stream = resource.Stream)
{
return new System.Drawing.Icon(stream, new System.Drawing.Size(16, 16));
}
}
catch (Exception ex)
{
Console.WriteLine($"[NotificationManager] Custom tray icon load failed: {ex.Message}");
return null;
}
}
private void StartMonitoring()
{
_checkTimer = new DispatcherTimer();
_checkTimer.Interval = TimeSpan.FromMinutes(1); // 每分钟检查一次
_checkTimer.Tick += OnCheckTick;
_checkTimer.Start();
Console.WriteLine("[NotificationManager] Monitoring started.");
}
private void OnCheckTick(object sender, EventArgs e)
{
if (_draftManager == null) return;
int unprocessedCount = _draftManager.UnprocessedCount;
// 1. 检查草稿累积
if (unprocessedCount >= DraftNotificationThreshold)
{
// 连续2次检查都超过阈值才通知,避免瞬间波动
_consecutiveDraftCounts++;
if (_consecutiveDraftCounts >= 2)
{
TryShowDraftNotification(unprocessedCount);
_consecutiveDraftCounts = 0; // 重置
}
}
else
{
_consecutiveDraftCounts = 0;
}
// 2. 工作休息提醒(基于时间)
CheckWorkReminder();
// 3. 更新托盘图标提示
UpdateTooltip(unprocessedCount);
}
private void CheckWorkReminder()
{
var now = DateTime.Now;
// 只在工作时间提醒 (9:00 - 18:00)
if (now.Hour < 9 || now.Hour >= 18)
return;
// 检查是否过了提醒间隔
if (now - _lastWorkReminder > TimeSpan.FromMinutes(WorkReminderIntervalMinutes))
{
// 检查用户是否处于"工作状态"(通过检查草稿活跃度判断)
var recentDrafts = _draftManager.GetUnprocessedDrafts()
.Where(d => (now - d.LastDetected) < TimeSpan.FromHours(2))
.ToList();
if (recentDrafts.Count > 0)
{
ShowWorkReminder();
_lastWorkReminder = now;
}
}
}
private void TryShowDraftNotification(int count)
{
try
{
var now = DateTime.Now;
if (now - _lastDraftNotificationTime < DraftNotificationCooldown && count <= _lastNotifiedDraftCount)
{
return;
}
// 使用 Toast 通知(可忽略,不打断工作)
_notifyIcon.ShowBalloonTip(
5000, // 显示5秒
"TimeTask - 任务提醒",
$"检测到 {count} 个潜在任务。点击查看并添加到四象限。",
ToolTipIcon.Info
);
// 托盘图标闪烁
StartBlinking();
_lastDraftNotificationTime = now;
_lastNotifiedDraftCount = count;
Console.WriteLine($"[NotificationManager] Draft notification shown: {count} drafts.");
}
catch (Exception ex)
{
Console.WriteLine($"[NotificationManager] Failed to show notification: {ex.Message}");
}
}
private void ShowWorkReminder()
{
try
{
_notifyIcon.ShowBalloonTip(
5000,
"TimeTask - 休息提醒",
"你已经持续工作一段时间了。建议休息一下,或者查看任务草稿。",
ToolTipIcon.Info
);
Console.WriteLine("[NotificationManager] Work reminder shown.");
}
catch (Exception ex)
{
Console.WriteLine($"[NotificationManager] Failed to show work reminder: {ex.Message}");
}
}
private void StartBlinking()
{
if (_isBlinking || _notifyIcon == null) return;
_isBlinking = true;
_blinkCount = 0;
var blinkTimer = new DispatcherTimer();
blinkTimer.Interval = TimeSpan.FromMilliseconds(500);
blinkTimer.Tick += (s, e) =>
{
_blinkCount++;
_notifyIcon.Visible = (_blinkCount % 2 == 0);
if (_blinkCount >= MaxBlinkCount)
{
blinkTimer.Stop();
_isBlinking = false;
_notifyIcon.Visible = true; // 确保图标可见
}
};
blinkTimer.Start();
}
private void OnCaptureStatusChanged()
{
var app = System.Windows.Application.Current;
if (app?.Dispatcher != null && !app.Dispatcher.CheckAccess())
{
try { app.Dispatcher.BeginInvoke(new Action(RefreshTooltip)); return; }
catch { }
}
RefreshTooltip();
}
private void RefreshTooltip()
{
int draftCount = _draftManager?.UnprocessedCount ?? 0;
UpdateTooltip(draftCount);
}
private void UpdateTooltip(int draftCount)
{
if (_notifyIcon == null) return;
string text;
if (_capture != null && _capture.IsRecording)
{
string mode = _capture.CurrentMode == ConversationCaptureService.CaptureMode.Meeting ? "会议"
: _capture.CurrentMode == ConversationCaptureService.CaptureMode.Quick ? "口述" : "交流";
string mmss = _capture.Elapsed.ToString(@"mm\:ss");
string mic = _capture.MicActive ? "麦克风✓" : "麦克风·";
string sys = _capture.SystemActive ? "系统✓" : "系统·";
text = $"● 录音中 {mmss} · {mode} · {mic} · {sys}";
}
else
{
if (draftCount > 0)
text = $"TimeTask - ({draftCount} 个草稿)";
else if (_capture != null && !_capture.AsrAvailable)
text = $"TimeTask - {_capture.AsrStatusText}";
else
text = "TimeTask - 运行中";
}
try
{
_notifyIcon.Text = text.Length > 127 ? text.Substring(0, 127) : text;
}
catch { }
}
private void ShowMainWindow()
{
try
{
var mainWindow = System.Windows.Application.Current.Windows.OfType<Window>()
.FirstOrDefault(w => w.GetType().Name == "MainWindow");
if (mainWindow != null)
{
mainWindow.Show();
mainWindow.Activate();
mainWindow.WindowState = WindowState.Normal;
}
}
catch (Exception ex)
{
Console.WriteLine($"[NotificationManager] Failed to show main window: {ex.Message}");
}
}
private void ExitApplication()
{
System.Windows.Application.Current.Shutdown();
}
/// <summary>
/// 弹出托盘气泡,用于全局快捷键切录音状态时的轻量反馈。
/// </summary>
public void ShowBalloon(string title, string text, ToolTipIcon icon = ToolTipIcon.Info)
{
if (_notifyIcon == null) return;
try { _notifyIcon.ShowBalloonTip(3000, title, text, icon); }
catch { }
}
public void Dispose()
{
try
{
if (_capture != null)
{
_capture.StatusChanged -= OnCaptureStatusChanged;
}
}
catch { }
try
{
_checkTimer?.Stop();
_checkTimer = null;
_notifyIcon?.Dispose();
_notifyIcon = null;
}
catch { }
}
}
}