-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTrayApplicationContext.cs
More file actions
214 lines (199 loc) · 7.5 KB
/
Copy pathTrayApplicationContext.cs
File metadata and controls
214 lines (199 loc) · 7.5 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
namespace CodexUsageTray;
internal sealed class TrayApplicationContext : ApplicationContext
{
private readonly CodexRateLimitReader _reader = new();
private readonly AlertStateStore _alertStateStore = new();
private readonly UsageHistoryStore _usageHistoryStore = new();
private readonly StartupRegistration _startupRegistration = new();
private readonly CancellationTokenSource _shutdown = new();
private readonly NotifyIcon _weeklyIcon = new();
private readonly ContextMenuStrip _menu = new();
private readonly ToolStripMenuItem _startupItem = new("Start with Windows");
private readonly UsagePopup _popup = new();
private readonly System.Windows.Forms.Timer _pollTimer = new() { Interval = 300_000 };
private UsageSnapshot _snapshot = UsageSnapshot.Initial();
private Icon? _weeklyRenderedIcon;
private bool _refreshing;
/// <summary>
/// Creates the weekly tray icon, its menu, and the periodic refresh loop.
/// </summary>
internal TrayApplicationContext()
{
ToolStripMenuItem refreshItem = new("Refresh");
ToolStripMenuItem exitItem = new("Exit");
refreshItem.Click += async (_, _) => await RefreshAsync();
exitItem.Click += (_, _) => ExitThread();
_startupItem.CheckOnClick = true;
_startupItem.Checked = ReadStartupEnabled();
_startupItem.Click += (_, _) => SetStartupEnabled(_startupItem.Checked);
_menu.Items.AddRange([refreshItem, _startupItem, new ToolStripSeparator(), exitItem]);
_weeklyIcon.ContextMenuStrip = _menu;
_weeklyIcon.Text = "Codex weekly: N/A";
_weeklyIcon.MouseClick += (_, eventArgs) =>
{
if (eventArgs.Button == MouseButtons.Left)
{
ShowPopup();
}
};
ApplySnapshot(_snapshot);
_pollTimer.Tick += async (_, _) => await RefreshAsync();
_pollTimer.Start();
_ = RefreshAsync();
}
/// <summary>
/// Reads the current per-user startup-registration state without preventing launch on registry errors.
/// </summary>
/// <returns><see langword="true"/> when startup registration is enabled.</returns>
private bool ReadStartupEnabled()
{
try
{
return _startupRegistration.IsEnabled();
}
catch
{
return false;
}
}
/// <summary>
/// Applies the requested per-user startup-registration state.
/// </summary>
/// <param name="enabled">Whether the application should start with Windows.</param>
private void SetStartupEnabled(bool enabled)
{
try
{
_startupRegistration.SetEnabled(enabled);
_startupItem.Checked = _startupRegistration.IsEnabled();
}
catch (Exception exception)
{
_startupItem.Checked = ReadStartupEnabled();
MessageBox.Show(
$"Could not update Windows startup: {exception.Message}",
"Codex Usage Tray",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
/// <summary>
/// Shows the combined popup and requests a fresh snapshot.
/// </summary>
private void ShowPopup()
{
_popup.UpdateSnapshot(_snapshot, _refreshing, _usageHistoryStore.Points);
_popup.ShowNearTaskbar();
_ = RefreshAsync();
}
/// <summary>
/// Fetches and applies one snapshot while preventing overlapping requests.
/// </summary>
private async Task RefreshAsync()
{
if (_refreshing || _shutdown.IsCancellationRequested)
{
return;
}
_refreshing = true;
_popup.UpdateSnapshot(_snapshot, refreshing: true, _usageHistoryStore.Points);
try
{
_snapshot = await _reader.FetchAsync(_shutdown.Token);
_usageHistoryStore.Record(_snapshot.Weekly, _snapshot.RefreshedAt);
ApplySnapshot(_snapshot);
ShowLowUsageAlerts(_snapshot);
}
catch (OperationCanceledException) when (_shutdown.IsCancellationRequested)
{
return;
}
catch (Exception exception)
{
_snapshot = UsageSnapshot.Error(exception.Message);
ApplySnapshot(_snapshot);
}
finally
{
_refreshing = false;
if (!_shutdown.IsCancellationRequested)
{
_popup.UpdateSnapshot(_snapshot, refreshing: false, _usageHistoryStore.Points);
}
}
}
/// <summary>
/// Applies one snapshot to the weekly tray icon, tooltip, and popup.
/// </summary>
/// <param name="snapshot">The normalized snapshot to display.</param>
private void ApplySnapshot(UsageSnapshot snapshot)
{
double? weeklyLeft = UsagePopup.CalculateWeeklyLeft(snapshot.Weekly, DateTimeOffset.Now);
Icon weekly = TrayIconRenderer.Render(snapshot.Weekly, weeklyLeft);
Icon? oldWeekly = _weeklyRenderedIcon;
_weeklyRenderedIcon = weekly;
_weeklyIcon.Icon = weekly;
_weeklyIcon.Visible = true;
oldWeekly?.Dispose();
_weeklyIcon.Text = FormatTooltip("Weekly", snapshot.Weekly);
_popup.UpdateSnapshot(snapshot, _refreshing, _usageHistoryStore.Points);
}
/// <summary>
/// Formats one short tray tooltip.
/// </summary>
/// <param name="name">The rate-limit window name.</param>
/// <param name="reading">The normalized limit reading.</param>
/// <returns>A tooltip below the Windows length limit.</returns>
private static string FormatTooltip(string name, LimitReading reading) =>
reading.State == LimitState.Available && reading.RemainingPercent is int remaining
? $"Codex {name}: {Math.Clamp(remaining, 0, 100)}% remaining"
: $"Codex {name}: N/A";
/// <summary>
/// Shows each low-usage balloon at most once for its reset cycle.
/// </summary>
/// <param name="snapshot">The newly fetched usage snapshot.</param>
private void ShowLowUsageAlerts(UsageSnapshot snapshot)
{
ShowLowUsageAlert(_weeklyIcon, "five-hour", "5-hour", snapshot.FiveHour);
ShowLowUsageAlert(_weeklyIcon, "weekly", "weekly", snapshot.Weekly);
}
/// <summary>
/// Shows one native warning balloon when persistence indicates it is due.
/// </summary>
/// <param name="icon">The owning tray icon.</param>
/// <param name="windowKey">The persistence key for the limit window.</param>
/// <param name="displayName">The user-facing limit-window name.</param>
/// <param name="reading">The normalized limit reading.</param>
private void ShowLowUsageAlert(
NotifyIcon icon,
string windowKey,
string displayName,
LimitReading reading)
{
if (!_alertStateStore.ShouldAlert(windowKey, reading))
{
return;
}
icon.ShowBalloonTip(
5_000,
$"Codex {displayName} limit low",
$"{reading.RemainingPercent}% remains until this limit resets.",
ToolTipIcon.Warning);
}
/// <summary>
/// Stops polling, hides the tray icons, and releases all owned resources.
/// </summary>
protected override void ExitThreadCore()
{
_pollTimer.Stop();
_shutdown.Cancel();
_weeklyIcon.Visible = false;
_pollTimer.Dispose();
_popup.Dispose();
_weeklyIcon.Dispose();
_menu.Dispose();
_weeklyRenderedIcon?.Dispose();
_shutdown.Dispose();
base.ExitThreadCore();
}
}