Skip to content

Commit bfe8207

Browse files
committed
Fix cold-start icons and server session recovery
1 parent 5f424a6 commit bfe8207

9 files changed

Lines changed: 400 additions & 95 deletions

File tree

‎src/Files.App.Server/AppService.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ public sealed partial class AppService : IDisposable
1313
internal bool IsDisposed => disposed != 0;
1414

1515
public bool CanRestorePreviousSession { get; }
16+
public int ProcessId => Environment.ProcessId;
1617
public PinnedFoldersService PinnedFolders { get; }
1718
public RecycleBinService RecycleBin { get; }
1819

‎src/Files.App.Server/Caching/DirectoryChangeMonitor.cs‎

Lines changed: 69 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ namespace Files.App.Server;
99
internal sealed partial class DirectoryChangeMonitor : IDisposable
1010
{
1111
private readonly Lock gate = new();
12+
private readonly Lock configureGate = new();
1213
private readonly string directory;
1314
private readonly string filter;
1415
private readonly bool recursive;
@@ -17,19 +18,26 @@ internal sealed partial class DirectoryChangeMonitor : IDisposable
1718
private FileSystemWatcher? parentWatcher;
1819
private bool watchingTarget;
1920
private bool disposed;
21+
private long configurationVersion;
2022

2123
internal DirectoryChangeMonitor(string directory, string filter, bool recursive, Action<FileSystemEventArgs> changed)
2224
{
2325
this.directory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(directory));
2426
this.filter = filter;
2527
this.recursive = recursive;
2628
this.changed = changed;
27-
lock (gate)
28-
Configure();
29+
Configure();
2930
}
3031

3132
private void Configure()
3233
{
34+
long version;
35+
lock (gate)
36+
{
37+
if (disposed)
38+
return;
39+
version = ++configurationVersion;
40+
}
3341
var existing = directory;
3442
var next = directory;
3543
while (!Directory.Exists(existing))
@@ -54,13 +62,29 @@ private void Configure()
5462
replacement.Dispose();
5563
throw;
5664
}
57-
var previous = watcher;
58-
var previousParent = parentWatcher;
59-
watcher = replacement;
60-
parentWatcher = replacementParent;
61-
watchingTarget = targetExists;
65+
FileSystemWatcher? previous;
66+
FileSystemWatcher? previousParent;
67+
lock (gate)
68+
{
69+
if (disposed || version != configurationVersion)
70+
{
71+
previous = replacement;
72+
previousParent = replacementParent;
73+
}
74+
else
75+
{
76+
previous = watcher;
77+
previousParent = parentWatcher;
78+
watcher = replacement;
79+
parentWatcher = replacementParent;
80+
watchingTarget = targetExists;
81+
}
82+
}
6283
previous?.Dispose();
6384
previousParent?.Dispose();
85+
// The missing component may have appeared before its parent watch was enabled.
86+
if (!targetExists && Directory.Exists(next))
87+
Configure();
6488
}
6589

6690
private FileSystemWatcher CreateWatcher(string path, string pattern, bool includeSubdirectories, NotifyFilters notifyFilter)
@@ -95,19 +119,23 @@ private bool Relevant(string path)
95119

96120
private void OnChanged(object sender, FileSystemEventArgs args)
97121
{
122+
bool reconfigure;
98123
lock (gate)
99124
{
100125
if (disposed || (!ReferenceEquals(sender, watcher) && !ReferenceEquals(sender, parentWatcher)))
101126
return;
102-
if (ReferenceEquals(sender, parentWatcher) || !watchingTarget || !Directory.Exists(directory))
103-
{
104-
Reconfigure();
105-
args = new FileSystemEventArgs(WatcherChangeTypes.All, directory, string.Empty);
106-
}
107-
else if (!Relevant(args.FullPath) && !(args is RenamedEventArgs renamed && Relevant(renamed.OldFullPath)))
127+
reconfigure = ReferenceEquals(sender, parentWatcher) || !watchingTarget;
128+
}
129+
if (reconfigure || !Directory.Exists(directory))
130+
{
131+
if (!Reconfigure(sender))
108132
return;
133+
args = new FileSystemEventArgs(WatcherChangeTypes.All, directory, string.Empty);
109134
}
110-
changed(args);
135+
else if (!Relevant(args.FullPath) && !(args is RenamedEventArgs renamed && Relevant(renamed.OldFullPath)))
136+
return;
137+
if (!Volatile.Read(ref disposed))
138+
changed(args);
111139
}
112140

113141
private void OnError(object sender, ErrorEventArgs args)
@@ -116,33 +144,48 @@ private void OnError(object sender, ErrorEventArgs args)
116144
{
117145
if (disposed || (!ReferenceEquals(sender, watcher) && !ReferenceEquals(sender, parentWatcher)))
118146
return;
119-
if (args.GetException() is not InternalBufferOverflowException)
120-
Reconfigure();
121147
}
122-
changed(new FileSystemEventArgs(WatcherChangeTypes.All, directory, string.Empty));
148+
if (args.GetException() is not InternalBufferOverflowException && !Reconfigure(sender))
149+
return;
150+
if (!Volatile.Read(ref disposed))
151+
changed(new FileSystemEventArgs(WatcherChangeTypes.All, directory, string.Empty));
123152
}
124153

125-
private void Reconfigure()
154+
private bool Reconfigure(object sender)
126155
{
127-
try
156+
lock (configureGate)
128157
{
129-
Configure();
130-
}
131-
catch (Exception ex)
132-
{
133-
Program.Logger.LogWarning(ex, "Could not update a directory watch.");
158+
lock (gate)
159+
{
160+
if (disposed || (!ReferenceEquals(sender, watcher) && !ReferenceEquals(sender, parentWatcher)))
161+
return false;
162+
}
163+
try
164+
{
165+
Configure();
166+
}
167+
catch (Exception ex)
168+
{
169+
Program.Logger.LogWarning(ex, "Could not update a directory watch.");
170+
}
171+
return !Volatile.Read(ref disposed);
134172
}
135173
}
136174

137175
public void Dispose()
138176
{
177+
FileSystemWatcher? previous;
178+
FileSystemWatcher? previousParent;
139179
lock (gate)
140180
{
141181
disposed = true;
142-
watcher?.Dispose();
182+
configurationVersion++;
183+
previous = watcher;
184+
previousParent = parentWatcher;
143185
watcher = null;
144-
parentWatcher?.Dispose();
145186
parentWatcher = null;
146187
}
188+
previous?.Dispose();
189+
previousParent?.Dispose();
147190
}
148191
}

‎src/Files.App.Server/Catalogs/CatalogWatchers.cs‎

Lines changed: 48 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,11 @@ namespace Files.App.Server;
99

1010
internal static class CatalogWatchers
1111
{
12-
private static readonly List<DirectoryChangeMonitor> watchers = [];
12+
private static List<DirectoryChangeMonitor> watchers = [];
1313
private static readonly Lazy<bool> initialized = new(Start);
1414
private static readonly Lock recycleBinGate = new();
15-
private static readonly List<DirectoryChangeMonitor> recycleBins = [];
15+
private static List<DirectoryChangeMonitor> recycleBins = [];
16+
private static long recycleBinVersion;
1617
private static bool stopped;
1718

1819
internal static void Initialize() => _ = initialized.Value;
@@ -48,13 +49,16 @@ private static bool Start()
4849

4950
internal static void RefreshRecycleBinWatcher()
5051
{
52+
long version;
5153
lock (recycleBinGate)
5254
{
5355
if (stopped)
5456
return;
55-
foreach (var watcher in recycleBins)
56-
watcher.Dispose();
57-
recycleBins.Clear();
57+
version = ++recycleBinVersion;
58+
}
59+
var replacements = new List<DirectoryChangeMonitor>();
60+
try
61+
{
5862
using var identity = WindowsIdentity.GetCurrent();
5963
var sid = identity.User?.Value;
6064
if (!string.IsNullOrEmpty(sid))
@@ -66,11 +70,29 @@ internal static void RefreshRecycleBinWatcher()
6670
var watcher = SafetyExtensions.IgnoreExceptions(() => new DirectoryChangeMonitor(
6771
Path.Combine(drive.Name, "$RECYCLE.BIN", sid), "*", false, OnRecycleBinChanged), Program.Logger);
6872
if (watcher is not null)
69-
recycleBins.Add(watcher);
73+
replacements.Add(watcher);
7074
}
7175
}
72-
RecycleBinCatalog.RecordChange(new FileSystemEventArgs(WatcherChangeTypes.All, string.Empty, string.Empty), refresh: true);
7376
}
77+
catch
78+
{
79+
foreach (var watcher in replacements)
80+
watcher.Dispose();
81+
throw;
82+
}
83+
List<DirectoryChangeMonitor> previous;
84+
bool installed;
85+
lock (recycleBinGate)
86+
{
87+
installed = !stopped && version == recycleBinVersion;
88+
previous = installed ? recycleBins : replacements;
89+
if (installed)
90+
recycleBins = replacements;
91+
}
92+
foreach (var watcher in previous)
93+
watcher.Dispose();
94+
if (installed)
95+
RecycleBinCatalog.RecordChange(new FileSystemEventArgs(WatcherChangeTypes.All, string.Empty, string.Empty), refresh: true);
7496
}
7597

7698
private static void OnRecycleBinChanged(FileSystemEventArgs e)
@@ -96,7 +118,16 @@ private static void Watch(string directory, string filter, Action changed)
96118
return;
97119
try
98120
{
99-
watchers.Add(new DirectoryChangeMonitor(directory, filter, true, _ => changed()));
121+
var watcher = new DirectoryChangeMonitor(directory, filter, true, _ => changed());
122+
lock (recycleBinGate)
123+
{
124+
if (!stopped)
125+
{
126+
watchers.Add(watcher);
127+
return;
128+
}
129+
}
130+
watcher.Dispose();
100131
}
101132
catch (Exception ex)
102133
{
@@ -106,14 +137,18 @@ private static void Watch(string directory, string filter, Action changed)
106137

107138
internal static void Dispose()
108139
{
109-
foreach (var watcher in watchers)
110-
watcher.Dispose();
140+
List<DirectoryChangeMonitor> previous;
141+
List<DirectoryChangeMonitor> previousBins;
111142
lock (recycleBinGate)
112143
{
113144
stopped = true;
114-
foreach (var watcher in recycleBins)
115-
watcher.Dispose();
116-
recycleBins.Clear();
145+
recycleBinVersion++;
146+
previous = watchers;
147+
previousBins = recycleBins;
148+
watchers = [];
149+
recycleBins = [];
117150
}
151+
foreach (var watcher in previous.Concat(previousBins))
152+
watcher.Dispose();
118153
}
119154
}

‎src/Files.App.Server/Files.App.Server.csproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@
5656
<ItemGroup>
5757
<ProjectReference Include="..\Files.Storage\Files.Storage.csproj" />
5858
<ProjectReference Include="..\Files.Shared\Files.Shared.csproj" />
59+
<ProjectReference Include="..\Files.Core.SourceGenerator\Files.Core.SourceGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
5960
</ItemGroup>
6061

6162
</Project>

‎src/Files.App.Server/ServerHost.cs‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using Windows.System;
55
using Microsoft.Extensions.Logging;
66
using System.Diagnostics;
7+
using System.Runtime.InteropServices;
78
using Windows.Win32;
89
using Windows.Win32.Foundation;
910
using Windows.Win32.UI.WindowsAndMessaging;
@@ -18,6 +19,8 @@ internal static class ServerHost
1819
private static readonly Dictionary<long, (Process Process, ClientWindow Window)> clients = [];
1920
private static long nextClient;
2021
private static bool hadClient;
22+
private static bool startupGraceExpired;
23+
private static Timer? startupGrace;
2124
private static bool quitting;
2225
private static int pendingUpdates;
2326
private static SystemTrayIcon? tray;
@@ -30,17 +33,22 @@ internal static void Initialize()
3033
settings = new BackgroundSettingsMonitor();
3134
settings.Changed += OnSettingsChanged;
3235
OnSettingsChanged();
36+
startupGrace = new Timer(_ =>
37+
{
38+
lock (gate)
39+
startupGraceExpired = true;
40+
ExitIfIdle();
41+
}, null, TimeSpan.FromSeconds(30), Timeout.InfiniteTimeSpan);
3342
}
3443

3544
internal static (long Id, bool CanRestorePreviousSession) AddClient(int processId)
3645
{
3746
lock (gate)
3847
{
39-
if (Program.ExitSignal.Task.IsCompleted)
40-
throw new InvalidOperationException("The server is shutting down.");
48+
if (quitting || Program.ExitSignal.Task.IsCompleted)
49+
throw new COMException("The server is shutting down.", unchecked((int)0x80010108));
4150

4251
var id = ++nextClient;
43-
hadClient = true;
4452
Process? process = null;
4553
try
4654
{
@@ -50,6 +58,7 @@ internal static (long Id, bool CanRestorePreviousSession) AddClient(int processI
5058
// Decide under the registration lock so simultaneous launches cannot both restore.
5159
var canRestorePreviousSession = clients.Values.All(client => client.Process.HasExited);
5260
clients.Add(id, (process, default));
61+
hadClient = true;
5362
RecycleBinCatalog.AddClient(id);
5463
return (id, canRestorePreviousSession);
5564
}
@@ -129,7 +138,8 @@ private static void ExitIfIdle()
129138
{
130139
lock (gate)
131140
{
132-
if (clients.Count == 0 && (quitting || (hadClient && (!settings.KeepRunning || pendingUpdates > 0))))
141+
if (clients.Count == 0 && (quitting || (!hadClient && startupGraceExpired) ||
142+
(hadClient && (!settings.KeepRunning || pendingUpdates > 0))))
133143
Program.ExitSignal.TrySetResult(true);
134144
}
135145
}
@@ -217,6 +227,7 @@ internal static Task InvokeAsync(Action action)
217227

218228
internal static async Task ShutdownAsync()
219229
{
230+
startupGrace?.Dispose();
220231
settings.Dispose();
221232
await InvokeAsync(() =>
222233
{

0 commit comments

Comments
 (0)