-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrayContext.cs
More file actions
180 lines (159 loc) · 6.7 KB
/
Copy pathTrayContext.cs
File metadata and controls
180 lines (159 loc) · 6.7 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
using System.Drawing.Drawing2D;
namespace Letterhold;
public sealed class TrayContext : ApplicationContext
{
private readonly AppConfig _config;
private readonly MappingEngine _engine = new();
private readonly SessionWatcher _watcher = new();
private readonly NotifyIcon _tray;
private readonly Icon _iconHealthy;
private readonly Icon _iconDegraded;
private readonly Icon _iconError;
private readonly Icon _iconIdle;
private readonly SynchronizationContext _ui;
private SettingsForm? _settingsForm;
public TrayContext(AppConfig config)
{
_config = config;
_ui = SynchronizationContext.Current ?? new WindowsFormsSynchronizationContext();
_iconHealthy = CreateDriveIcon(Color.FromArgb(0x1E, 0xA5, 0x77));
_iconDegraded = CreateDriveIcon(Color.FromArgb(0xE8, 0xA6, 0x2B));
_iconError = CreateDriveIcon(Color.FromArgb(0xD3, 0x4A, 0x3A));
_iconIdle = CreateDriveIcon(Color.FromArgb(0x6C, 0x74, 0x7E));
var menu = new ContextMenuStrip();
menu.Items.Add("Settings…", null, (_, _) => ShowSettings());
menu.Items.Add("Remap all now", null, (_, _) => _ = _engine.RunPassAsync(resetBackoff: true));
menu.Items.Add("Open log", null, (_, _) => OpenLog());
menu.Items.Add(new ToolStripSeparator());
// Exit keeps drives mapped (least surprise); removal in Settings disconnects.
menu.Items.Add("Exit", null, (_, _) => ExitThread());
Theme.Style(menu);
Theme.Changed += () => _ui.Post(_ => Theme.Style(menu), null);
_tray = new NotifyIcon
{
Icon = _iconHealthy,
Text = "Letterhold",
Visible = true,
ContextMenuStrip = menu,
};
_tray.DoubleClick += (_, _) => ShowSettings();
_engine.StatusChanged += () => _ui.Post(_ => RefreshTray(), null);
_watcher.Reconnected += reason => _ = RemapOnSessionReconnectAsync();
_engine.SetMappings(_config.Mappings);
_engine.StartHealthTimer(_config.Settings.HealthCheckIntervalSec);
_ = _engine.RunPassAsync(resetBackoff: true);
}
public MappingEngine Engine => _engine;
public AppConfig Config => _config;
public void ShowSettings()
{
if (_settingsForm is { IsDisposed: false })
{
_settingsForm.Show();
_settingsForm.WindowState = FormWindowState.Normal;
_settingsForm.Activate();
return;
}
_settingsForm = new SettingsForm(this);
_settingsForm.Show();
}
/// <summary>Called from the background thread listening for a second instance.</summary>
public void ShowSettingsFromOtherThread() => _ui.Post(_ => ShowSettings(), null);
public void ApplyConfigChanges()
{
ConfigStore.Save(_config);
_engine.SetMappings(_config.Mappings);
_engine.StartHealthTimer(_config.Settings.HealthCheckIntervalSec);
Autostart.Apply(_config.Settings.Autostart);
_ = _engine.RunPassAsync(resetBackoff: true);
}
private async Task RemapOnSessionReconnectAsync()
{
await _engine.OnSessionReconnectAsync().ConfigureAwait(false);
var (connected, enabled) = _engine.GetSummary();
if (enabled > 0)
_ui.Post(_ => _tray.ShowBalloonTip(3000, "Letterhold",
$"Session reconnected. {connected} of {enabled} drives mapped.",
connected == enabled ? ToolTipIcon.Info : ToolTipIcon.Warning), null);
}
private void RefreshTray()
{
var (connected, enabled) = _engine.GetSummary();
_tray.Icon = enabled == 0 ? _iconIdle
: connected == enabled ? _iconHealthy
: connected == 0 ? _iconError
: _iconDegraded;
string text = enabled == 0
? "Letterhold — no mappings"
: $"Letterhold — {connected} of {enabled} connected";
// NotifyIcon.Text hard limit is 63 chars.
_tray.Text = text.Length <= 63 ? text : text[..63];
}
/// <summary>
/// Applies a batch of global DOS-device changes via the elevated helper (one UAC
/// prompt), then re-runs a pass so the new state shows immediately. UI thread.
/// </summary>
public async Task<(GlobalApplyOutcome Outcome, string Message)> ApplyGlobalAsync(IReadOnlyList<GlobalOp> ops)
{
var result = await GlobalDeviceService.ApplyElevatedAsync(ops).ConfigureAwait(true);
_engine.SetMappings(_config.Mappings);
_ = _engine.RunPassAsync(resetBackoff: true);
return result;
}
private static void OpenLog()
{
try
{
if (!File.Exists(Logger.FilePath))
Logger.Info("Log opened");
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(Logger.FilePath)
{
UseShellExecute = true,
});
}
catch (Exception ex)
{
MessageBox.Show($"Couldn't open the log file.\n{ex.Message}", "Letterhold",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
/// <summary>
/// Tray glyph: a rounded drive "tag" in the status colour with a light label slot
/// and a status LED — reads clearly at 16 px and replaces the old plain dot.
/// </summary>
private static Icon CreateDriveIcon(Color accent)
{
using var bmp = new Bitmap(32, 32);
using (var g = Graphics.FromImage(bmp))
{
g.SmoothingMode = SmoothingMode.AntiAlias;
var body = new Rectangle(4, 7, 24, 19);
using (var path = Theme.RoundedRect(body, 5))
{
using var shade = new LinearGradientBrush(body,
ControlPaint.Light(accent, 0.15f), ControlPaint.Dark(accent, 0.05f), 90f);
g.FillPath(shade, path);
}
// Label slot — the "letter" the tag holds.
var slot = new Rectangle(8, 12, 16, 6);
using (var path = Theme.RoundedRect(slot, 2))
using (var light = new SolidBrush(Color.FromArgb(0xF2, 0xFF, 0xFF, 0xFF)))
g.FillPath(light, path);
// Status LED.
using var led = new SolidBrush(Color.FromArgb(0xF2, 0xFF, 0xFF, 0xFF));
g.FillEllipse(led, 21.5f, 20.5f, 3.2f, 3.2f);
}
// GetHicon leaks a GDI handle unless DestroyIcon is called; these few icons live
// for the whole process, so the leak is bounded and fine.
return Icon.FromHandle(bmp.GetHicon());
}
protected override void ExitThreadCore()
{
_tray.Visible = false;
_tray.Dispose();
_watcher.Dispose();
_engine.Dispose();
Logger.Info("Exit (mappings left in place)");
base.ExitThreadCore();
}
}