-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.axaml.cs
More file actions
187 lines (170 loc) · 6.35 KB
/
Copy pathMainWindow.axaml.cs
File metadata and controls
187 lines (170 loc) · 6.35 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
using System.ComponentModel;
using System.Runtime.InteropServices;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Styling;
using Avalonia.Threading;
using UsbPulse.Models;
using UsbPulse.Services;
namespace UsbPulse;
public partial class MainWindow : Window, IDisposable
{
private readonly AppearanceService _appearance;
private readonly DeviceMonitor _monitor = new();
private readonly StorageService _storage = new();
private readonly DeviceState _state = new();
private readonly EventRefresh _refresh;
private readonly CancellationTokenSource _lifetime = new();
private readonly bool _acrylicAtStartup;
private bool _disposed;
public event EventHandler? SettingsRequested;
public MainWindow(AppearanceService appearance)
{
_appearance = appearance;
InitializeComponent();
_acrylicAtStartup = OperatingSystem.IsWindows() && Program.StartupSettings.UseAcrylic;
ApplyWindowEffects();
DataContext = _state;
_refresh = new EventRefresh(ScanAsync);
Topmost = appearance.Settings.AlwaysOnTop;
appearance.Changed += AppearanceChanged;
_monitor.Changed += (_, _) => _refresh.Request();
_monitor.Faulted += (_, message) => Dispatcher.UIThread.Post(() => _state.Message = message);
Opened += (_, _) =>
{
PositionBottomRight();
_monitor.Start(this);
_refresh.Request(false);
LowerIfNeeded();
AppLog.Write($"Window ready: position={Position}, scale={RenderScaling}, bounds={Bounds}");
};
SizeChanged += (_, _) => PositionBottomRight();
Screens.Changed += ScreensChanged;
Deactivated += (_, _) => LowerIfNeeded();
Closing += (_, e) =>
{
if (!_disposed && e.CloseReason == WindowCloseReason.WindowClosing)
{
e.Cancel = true;
Hide();
}
};
}
public void ShowCard(bool activate = false)
{
if (_disposed) return;
if (WindowState == WindowState.Minimized)
WindowState = WindowState.Normal;
Show();
PositionBottomRight();
if (activate)
{
WindowState = WindowState.Normal;
Activate();
}
else LowerIfNeeded();
}
public void RefreshDevices() => _refresh.Request(false);
private async Task ScanAsync(CancellationToken token)
{
try
{
var devices = await _storage.GetDevicesAsync(token);
token.ThrowIfCancellationRequested();
await Dispatcher.UIThread.InvokeAsync(() =>
{
if (_disposed || token.IsCancellationRequested) return;
if (_state.Apply(devices)) ShowCard(true);
});
}
catch (OperationCanceledException) { }
catch (Exception ex)
{
AppLog.Write("Cannot enumerate storage", ex);
await Dispatcher.UIThread.InvokeAsync(() => _state.Message = "设备读取失败:" + ex.Message);
}
}
private void RefreshClick(object? sender, RoutedEventArgs e)
{
_state.Message = "";
RefreshDevices();
}
private void SettingsClick(object? sender, RoutedEventArgs e) => SettingsRequested?.Invoke(this, EventArgs.Empty);
private void OpenClick(object? sender, RoutedEventArgs e)
{
if (!_state.CanOpen || _state.Selected is not { } device) return;
try { _storage.Open(device); _state.Message = ""; }
catch (Exception ex) { _state.Message = "打开失败:" + ex.Message; AppLog.Write("Open failed", ex); }
}
private async void EjectClick(object? sender, RoutedEventArgs e)
{
if (!_state.CanEject || _state.Selected is not { } device) return;
_state.Busy = true;
_state.Message = "";
try
{
await _storage.EjectAsync(device, _lifetime.Token);
_state.Message = "";
}
catch (OperationCanceledException) { }
catch (Exception ex)
{
_state.Message = "弹出未完成:" + ex.Message;
AppLog.Write("Eject not confirmed", ex);
}
finally
{
_state.Busy = false;
RefreshDevices();
}
}
private void AppearanceChanged(object? sender, EventArgs e)
{
Topmost = _appearance.Settings.AlwaysOnTop;
ApplyWindowEffects();
LowerIfNeeded();
}
private void ApplyWindowEffects()
{
if (!_acrylicAtStartup) return;
TransparencyLevelHint = [WindowTransparencyLevel.AcrylicBlur, WindowTransparencyLevel.Transparent];
var dark = Application.Current?.ActualThemeVariant == ThemeVariant.Dark;
RootCard.Background = new SolidColorBrush(Color.Parse(dark ? "#D9262626" : "#E6F7F7F7"));
}
private void ScreensChanged(object? sender, EventArgs e) => PositionBottomRight();
private void PositionBottomRight()
{
var screen = Screens.Primary;
if (screen is null) return;
var work = screen.WorkingArea;
var scale = screen.Scaling;
MaxWidth = Math.Max(200, work.Width / scale - 24);
var width = (int)Math.Ceiling((Bounds.Width > 0 ? Bounds.Width : Width) * scale);
var height = (int)Math.Ceiling((Bounds.Height > 0 ? Bounds.Height : 188) * scale);
var gap = (int)Math.Round(8 * scale);
Position = new PixelPoint(Math.Max(work.X, work.Right - width - gap),
Math.Max(work.Y, work.Bottom - height - gap));
}
private void LowerIfNeeded()
{
if (_appearance.Settings.AlwaysOnTop || !IsVisible || _disposed) return;
if (OperatingSystem.IsWindows() && TryGetPlatformHandle() is { } handle)
SetWindowPos(handle.Handle, new IntPtr(1), 0, 0, 0, 0, 0x13);
// Other compositors retain a normal, non-topmost window; do not steal focus.
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_lifetime.Cancel();
_refresh.Dispose();
_monitor.Dispose();
_appearance.Changed -= AppearanceChanged;
Screens.Changed -= ScreensChanged;
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetWindowPos(IntPtr hwnd, IntPtr after, int x, int y, int cx, int cy, uint flags);
}