-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathTrayWindow.xaml.cs
More file actions
337 lines (280 loc) · 11.7 KB
/
Copy pathTrayWindow.xaml.cs
File metadata and controls
337 lines (280 loc) · 11.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
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
using Coder.Desktop.App.Controls;
using Coder.Desktop.App.Models;
using Coder.Desktop.App.Services;
using Coder.Desktop.App.Utils;
using Coder.Desktop.App.Views.Pages;
using CommunityToolkit.Mvvm.Input;
using Microsoft.UI;
using Microsoft.UI.Input;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media.Animation;
using System;
using System.Runtime.InteropServices;
using Windows.Graphics;
using Windows.System;
using Windows.UI.Core;
using WinRT.Interop;
using WindowActivatedEventArgs = Microsoft.UI.Xaml.WindowActivatedEventArgs;
namespace Coder.Desktop.App.Views;
public sealed partial class TrayWindow : Window
{
private const int WIDTH = 300;
private readonly AppWindow _aw;
public double ProxyHeight { get; private set; }
// This is used to know the "start point of the animation"
private int _lastWindowHeight;
private Storyboard? _currentSb;
private NativeApi.POINT? _lastActivatePosition;
private readonly IRpcController _rpcController;
private readonly ICredentialManager _credentialManager;
private readonly ISyncSessionController _syncSessionController;
private readonly TrayWindowLoadingPage _loadingPage;
private readonly TrayWindowDisconnectedPage _disconnectedPage;
private readonly TrayWindowLoginRequiredPage _loginRequiredPage;
private readonly TrayWindowMainPage _mainPage;
public TrayWindow(IRpcController rpcController, ICredentialManager credentialManager,
ISyncSessionController syncSessionController,
TrayWindowLoadingPage loadingPage,
TrayWindowDisconnectedPage disconnectedPage, TrayWindowLoginRequiredPage loginRequiredPage,
TrayWindowMainPage mainPage)
{
_rpcController = rpcController;
_credentialManager = credentialManager;
_syncSessionController = syncSessionController;
_loadingPage = loadingPage;
_disconnectedPage = disconnectedPage;
_loginRequiredPage = loginRequiredPage;
_mainPage = mainPage;
InitializeComponent();
AppWindow.Hide();
Activated += Window_Activated;
RootFrame.SizeChanged += RootFrame_SizeChanged;
_rpcController.StateChanged += RpcController_StateChanged;
_credentialManager.CredentialsChanged += CredentialManager_CredentialsChanged;
_syncSessionController.StateChanged += SyncSessionController_StateChanged;
SetPageByState(_rpcController.GetState(), _credentialManager.GetCachedCredentials(),
_syncSessionController.GetState());
// Setting OpenCommand and ExitCommand directly in the .xaml doesn't seem to work for whatever reason.
TrayIcon.OpenCommand = Tray_OpenCommand;
TrayIcon.ExitCommand = Tray_ExitCommand;
// Hide the title bar and buttons. WinUi 3 provides a method to do this with
// `ExtendsContentIntoTitleBar = true;`, but it automatically adds emulated title bar buttons that cannot be
// removed.
if (AppWindow.Presenter is not OverlappedPresenter presenter)
throw new Exception("Failed to get OverlappedPresenter for window");
presenter.IsMaximizable = false;
presenter.IsMinimizable = false;
presenter.IsResizable = false;
presenter.IsAlwaysOnTop = true;
presenter.SetBorderAndTitleBar(true, false);
AppWindow.IsShownInSwitchers = false;
// Ensure the corner is rounded.
var windowHandle = Win32Interop.GetWindowFromWindowId(AppWindow.Id);
var value = 2;
// Best effort. This does not work on Windows 10.
_ = NativeApi.DwmSetWindowAttribute(windowHandle, 33, ref value, Marshal.SizeOf<int>());
_aw = AppWindow.GetFromWindowId(
Win32Interop.GetWindowIdFromWindow(
WindowNative.GetWindowHandle(this)));
SizeProxy.SizeChanged += (_, e) =>
{
if (_currentSb is null) return; // nothing running
int newHeight = (int)Math.Round(
e.NewSize.Height * DisplayScale.WindowScale(this));
int delta = newHeight - _lastWindowHeight;
if (delta == 0) return;
var pos = _aw.Position;
var size = _aw.Size;
pos.Y -= delta; // grow upward
size.Height = newHeight;
_aw.MoveAndResize(
new RectInt32(pos.X, pos.Y, size.Width, size.Height));
_lastWindowHeight = newHeight;
};
}
private void SetPageByState(RpcModel rpcModel, CredentialModel credentialModel,
SyncSessionControllerStateModel syncSessionModel)
{
if (credentialModel.State == CredentialState.Unknown)
{
SetRootFrame(_loadingPage);
return;
}
switch (rpcModel.RpcLifecycle)
{
case RpcLifecycle.Connected:
if (credentialModel.State == CredentialState.Valid)
SetRootFrame(_mainPage);
else
SetRootFrame(_loginRequiredPage);
break;
case RpcLifecycle.Disconnected:
case RpcLifecycle.Connecting:
default:
SetRootFrame(_disconnectedPage);
break;
}
}
private void RpcController_StateChanged(object? _, RpcModel model)
{
SetPageByState(model, _credentialManager.GetCachedCredentials(), _syncSessionController.GetState());
}
private void CredentialManager_CredentialsChanged(object? _, CredentialModel model)
{
SetPageByState(_rpcController.GetState(), model, _syncSessionController.GetState());
}
private void SyncSessionController_StateChanged(object? _, SyncSessionControllerStateModel model)
{
SetPageByState(_rpcController.GetState(), _credentialManager.GetCachedCredentials(), model);
}
// Sadly this is necessary because Window.Content.SizeChanged doesn't
// trigger when the Page's content changes.
public void SetRootFrame(Page page)
{
if (!DispatcherQueue.HasThreadAccess)
{
DispatcherQueue.TryEnqueue(() => SetRootFrame(page));
return;
}
RootFrame.SetPage(page);
}
private void RootFrame_SizeChanged(object sender, SizedFrameEventArgs e)
{
AnimateWindowHeight(e.NewSize.Height);
}
// We need to animate the height change in code-behind, because XAML
// storyboard animation timeline is immutable - it cannot be changed
// mid-run to accomodate a new height.
private void AnimateWindowHeight(double targetHeight)
{
// If another animation is already running we need to fast forward it.
if (_currentSb is { } oldSb)
{
oldSb.Completed -= OnStoryboardCompleted;
// We need to use SkipToFill, because Stop actually sets Height to 0, which
// makes the window go haywire.
oldSb.SkipToFill();
}
_lastWindowHeight = AppWindow.Size.Height;
var anim = new DoubleAnimation
{
To = targetHeight,
Duration = TimeSpan.FromMilliseconds(200),
EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut },
EnableDependentAnimation = true
};
Storyboard.SetTarget(anim, SizeProxy);
Storyboard.SetTargetProperty(anim, "Height");
var sb = new Storyboard { Children = { anim } };
sb.Completed += OnStoryboardCompleted;
sb.Begin();
_currentSb = sb;
}
private void OnStoryboardCompleted(object? sender, object e)
{
// We need to remove the event handler after the storyboard completes,
// to avoid memory leaks and multiple calls.
if (sender is Storyboard sb)
sb.Completed -= OnStoryboardCompleted;
// SizeChanged handler will stop forwarding resize ticks
// until we start the next storyboard.
_currentSb = null;
}
private void MoveResizeAndActivate()
{
SaveCursorPos();
var size = CalculateWindowSize(RootFrame.GetContentSize().Height);
var pos = CalculateWindowPosition(size);
var rect = new RectInt32(pos.X, pos.Y, size.Width, size.Height);
AppWindow.MoveAndResize(rect);
AppWindow.Show();
NativeApi.SetForegroundWindow(WindowNative.GetWindowHandle(this));
}
private void SaveCursorPos()
{
var res = NativeApi.GetCursorPos(out var cursorPosition);
if (res)
_lastActivatePosition = cursorPosition;
else
// When the cursor position is null, we will spawn the window in
// the bottom right corner of the primary display.
// TODO: log(?) an error when this happens
_lastActivatePosition = null;
}
private SizeInt32 CalculateWindowSize(double height)
{
if (height <= 0) height = 100; // will be resolved next frame typically
var scale = DisplayScale.WindowScale(this);
var newWidth = (int)(WIDTH * scale);
var newHeight = (int)(height * scale);
return new SizeInt32(newWidth, newHeight);
}
private PointInt32 CalculateWindowPosition(SizeInt32 size)
{
var width = size.Width;
var height = size.Height;
var cursorPosition = _lastActivatePosition;
if (cursorPosition is null)
{
var primaryWorkArea = DisplayArea.Primary.WorkArea;
return new PointInt32(
primaryWorkArea.Width - width,
primaryWorkArea.Height - height
);
}
// Spawn the window to the top right of the cursor.
var x = cursorPosition.Value.X + 10;
var y = cursorPosition.Value.Y - 10 - height;
var workArea = DisplayArea.GetFromPoint(
new PointInt32(cursorPosition.Value.X, cursorPosition.Value.Y),
DisplayAreaFallback.Primary
).WorkArea;
// Adjust if the window goes off the right edge of the display.
if (x + width > workArea.X + workArea.Width) x = workArea.X + workArea.Width - width;
// Adjust if the window goes off the bottom edge of the display.
if (y + height > workArea.Y + workArea.Height) y = workArea.Y + workArea.Height - height;
// Adjust if the window goes off the left edge of the display (somehow).
if (x < workArea.X) x = workArea.X;
// Adjust if the window goes off the top edge of the display (somehow).
if (y < workArea.Y) y = workArea.Y;
return new PointInt32(x, y);
}
private void Window_Activated(object sender, WindowActivatedEventArgs e)
{
// Close the window as soon as it loses focus.
if (e.WindowActivationState == WindowActivationState.Deactivated
#if DEBUG
// In DEBUG, holding SHIFT is required to have the window close when it loses focus.
&& InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down)
#endif
)
AppWindow.Hide();
}
[RelayCommand]
private void Tray_Open()
{
MoveResizeAndActivate();
}
[RelayCommand]
private void Tray_Exit()
{
// It's fine that this happens in the background.
_ = ((App)Application.Current).ExitApplication();
}
public static class NativeApi
{
[DllImport("dwmapi.dll")]
public static extern int DwmSetWindowAttribute(IntPtr hwnd, int attribute, ref int value, int size);
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out POINT lpPoint);
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hwnd);
public struct POINT
{
public int X;
public int Y;
}
}
}