Repository navigation
Expand file tree
/
Copy pathServerHost.cs
More file actions
240 lines (220 loc) · 6.12 KB
/
Copy pathServerHost.cs
File metadata and controls
240 lines (220 loc) · 6.12 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
// Copyright (c) Files Community
// Licensed under the MIT License.
using Windows.System;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Windows.Win32;
using Windows.Win32.Foundation;
using Windows.Win32.UI.WindowsAndMessaging;
namespace Files.App.Server;
internal static class ServerHost
{
private static readonly Lock gate = new();
private readonly record struct ClientWindow(HWND Handle, uint ProcessId);
private static readonly Dictionary<long, (Process Process, ClientWindow Window)> clients = [];
private static long nextClient;
private static bool hadClient;
private static bool startupGraceExpired;
private static Timer? startupGrace;
private static bool quitting;
private static int pendingUpdates;
private static SystemTrayIcon? tray;
private static DispatcherQueueController controller = null!;
private static BackgroundSettingsMonitor settings = null!;
internal static void Initialize()
{
controller = DispatcherQueueController.CreateOnDedicatedThread();
settings = new BackgroundSettingsMonitor();
settings.Changed += OnSettingsChanged;
OnSettingsChanged();
startupGrace = new Timer(_ =>
{
lock (gate)
startupGraceExpired = true;
ExitIfIdle();
}, null, TimeSpan.FromSeconds(30), Timeout.InfiniteTimeSpan);
}
internal static (long Id, bool CanRestorePreviousSession) AddClient(int processId)
{
lock (gate)
{
if (quitting || Program.ExitSignal.Task.IsCompleted)
throw new COMException("The server is shutting down.", unchecked((int)0x80010108));
var id = ++nextClient;
Process? process = null;
try
{
process = Process.GetProcessById(processId);
process.Exited += (_, _) => controller.DispatcherQueue.TryEnqueue(() => RemoveClient(id));
process.EnableRaisingEvents = true;
// Decide under the registration lock so simultaneous launches cannot both restore.
var canRestorePreviousSession = clients.Values.All(client => client.Process.HasExited);
clients.Add(id, (process, default));
hadClient = true;
RecycleBinCatalog.AddClient(id);
return (id, canRestorePreviousSession);
}
catch
{
process?.Dispose();
controller.DispatcherQueue.TryEnqueue(ExitIfIdle);
throw;
}
}
}
internal static void SetWindow(long id, long handle)
{
var window = new HWND((nint)handle);
uint processId = 0;
if (!window.IsNull)
PInvoke.GetWindowThreadProcessId(window, out processId);
var clientWindow = new ClientWindow(window, processId);
bool closeWindow;
lock (gate)
{
if (!clients.TryGetValue(id, out var client))
return;
if (!window.IsNull && processId != client.Process.Id)
return;
clients[id] = (client.Process, clientWindow);
closeWindow = quitting;
}
if (closeWindow && IsClientWindow(clientWindow))
PInvoke.PostMessage(window, PInvoke.WM_CLOSE, default, default);
}
internal static void BeginUpdate()
{
lock (gate)
pendingUpdates++;
}
internal static void EndUpdate()
{
lock (gate)
pendingUpdates = Math.Max(0, pendingUpdates - 1);
controller.DispatcherQueue.TryEnqueue(ExitIfIdle);
}
internal static void BeginPinnedFoldersUpdate(long id)
{
lock (gate)
{
if (!clients.ContainsKey(id))
throw new ObjectDisposedException(nameof(AppService));
ServerEvents.BeginPinnedFoldersUpdate(id);
}
}
internal static void RemoveClient(long id)
{
Process process;
lock (gate)
{
if (!clients.Remove(id, out var client))
return;
process = client.Process;
}
process.Dispose();
ServerEvents.RemoveClient(id);
RecycleBinCatalog.RemoveClient(id);
if (!Program.ExitSignal.Task.IsCompleted)
{
settings.Refresh();
controller.DispatcherQueue.TryEnqueue(ExitIfIdle);
}
}
private static void ExitIfIdle()
{
lock (gate)
{
if (clients.Count == 0 && (quitting || (hadClient && pendingUpdates > 0) ||
(!settings.KeepRunning && (hadClient || startupGraceExpired))))
Program.ExitSignal.TrySetResult(true);
}
}
private static void OnSettingsChanged()
{
if (!Program.ExitSignal.Task.IsCompleted)
{
controller.DispatcherQueue.TryEnqueue(() =>
{
try
{
if (settings.ShowTrayIcon && !quitting)
(tray ??= new SystemTrayIcon()).Show();
else
tray?.Hide();
}
catch (Exception ex)
{
Program.Logger.LogWarning(ex, "Could not update the server tray icon.");
}
ExitIfIdle();
});
}
}
internal static nint GetDialogWindowHandle() => (tray ??= new SystemTrayIcon()).WindowHandle;
internal static bool ActivateWindow()
{
ClientWindow[] windows;
lock (gate)
windows = clients.Values.Select(client => client.Window).ToArray();
foreach (var window in windows)
{
if (!IsClientWindow(window))
continue;
if (PInvoke.IsIconic(window.Handle))
PInvoke.ShowWindow(window.Handle, SHOW_WINDOW_CMD.SW_RESTORE);
PInvoke.SetForegroundWindow(window.Handle);
return true;
}
return false;
}
private static bool IsClientWindow(ClientWindow window)
=> !window.Handle.IsNull && window.ProcessId != 0 &&
PInvoke.GetWindowThreadProcessId(window.Handle, out var processId) != 0 && processId == window.ProcessId;
internal static void RequestQuit()
{
ClientWindow[] windows;
lock (gate)
{
quitting = true;
windows = clients.Values.Select(client => client.Window).ToArray();
}
tray?.Hide();
foreach (var window in windows)
{
if (IsClientWindow(window))
PInvoke.PostMessage(window.Handle, PInvoke.WM_CLOSE, default, default);
}
ExitIfIdle();
}
internal static Task InvokeAsync(Action action)
{
var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
if (!controller.DispatcherQueue.TryEnqueue(() =>
{
try
{
action();
completion.SetResult();
}
catch (Exception ex)
{
completion.SetException(ex);
}
}))
completion.SetException(new InvalidOperationException("The server dispatcher is shutting down."));
return completion.Task;
}
internal static async Task ShutdownAsync()
{
startupGrace?.Dispose();
settings.Dispose();
await InvokeAsync(() =>
{
StartupServices.Stop();
tray?.Dispose();
tray = null;
});
await controller.ShutdownQueueAsync();
}
}