Debian Codegraph @

src/files/castleinternalfilemonitor.pas

raw
1 {
2 Copyright 2023-2024 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Monitor when files change on disk,
17 to enable auto-reloading them. }
18 unit CastleInternalFileMonitor;
19
20 {$I castleconf.inc}
21
22 interface
23
24 uses SysUtils, Classes, Generics.Collections,
25 CastleUtils, CastleClassUtils;
26
27 type
28 { Monitor when files change on disk,
29 to enable auto-reloading them.
30 Use only through singleton @link(FileMonitor).
31
32 To make the file monitor actually do something, you have to set both
33 PossiblyEnabled and Enabled to @true.
34
35 - Before first URL calls Watch, call FileMonitor.MakePossiblyEnabled.
36
37 Right now this is automatically done when DEBUG is defined when
38 compiling CGE. Also CGE editor does it.
39
40 This allows to completely avoid any overhead of FileMonitor in release
41 version, for users, when data is never observed, because it is not supposed
42 to change.
43
44 - Set Enabled to @true anytime you want.
45 It can be toggled between @false and @true freely.
46
47 Only when both PossiblyEnabled and Enabled are @true,
48 the monitor actually does its work fully.
49
50 When PossiblyEnabled = @true but Enabled = @false,
51 the monitor does minimal work (collecting the files to watch)
52 to allow to later resume in case you toggle Enabled to @true.
53 But otherwise monitor doesn't check file times,
54 doesn't generate OnChanged events. }
55 TCastleFileMonitor = class
56 private
57 type
58 TFileInfo = class
59 public
60 { URL of the watched file.
61 Always an absolute URL.
62 For now only file:// URLs are supported.
63 The purpose of this is to watch files on regular filesystem,
64 files in castle-data:// can be resolved to regular files too on desktop.
65 We use URLs (not filenames) just in case in the future more options
66 will be possible (e.g. in case CGE editor will run on web some day).}
67 Url: String;
68
69 { Last seen modified time of the file.
70 0 if cannot be obtained. }
71 LastModified: TDateTime;
72
73 { Always non-nil, non-empty instance
74 of TSimpleNotifyEventList with non-nil and valid callbacks to call. }
75 OnChanged: TSimpleNotifyEventList;
76
77 { When this is > 0, we are in the middle of iteration over
78 OnChanged callbacks. In this case outside code should not modify
79 OnChanged count (it can only set some items to @nil)
80 or free this instance.
81
82 This prevents undefined behavior in case some OnChanged
83 callback unwatches the URL, changing the OnChanged order
84 or even freeing TFileInfo class while we're in the middle of iteration
85 over OnChanged.
86
87 Testcase: just change image used by TCastleImageControl, once.
88 It will then exactly do this: TCastleImagePersistent.ReloadUrl
89 temporatily unwatches the URL, freeing TFileInfo, only to watch it again.
90 The incorrect log
91 Notified about change of URL "" because last modification time...
92 with empty URL (which shall not be possible, TFileInfo never has URL='')
93 appears, without the protection given by this field.
94 }
95 InsideExecuteAll: Cardinal;
96
97 constructor Create;
98 destructor Destroy; override;
99
100 { Update LastModified value based on the file last modified time.
101 Calls OnChanged if the file was modified since last time
102 and CallChanged. }
103 procedure UpdateLastModified(const CallChanged: Boolean);
104
105 { Execute all OnChanged callbacks, safely (manages InsideExecuteAll
106 and later cleanup of @nil OnChanged callbacks). }
107 procedure ExecuteAllChanged;
108 end;
109
110 { Map from URL to the list of events that should be notified when URL
111 contents change.
112 Key is equal to corresponding TFileInfo.Url.
113 Value is never nil. }
114 TFiles = {$ifdef FPC}specialize{$endif} TObjectDictionary<String, TFileInfo>;
115 var
116 FFiles: TFiles;
117 FPossiblyEnabledFinalized: Boolean;
118 FPossiblyEnabled: Boolean;
119 FEnabled: Boolean;
120
121 { Convert to final URL to watch (that can be put in TFileInfo.Url),
122 making URL absolute, and not using castle-data://.
123 Returns '' if cannot be watched. }
124 function UrlToWatch(const Url: String): String;
125
126 { Stop watching given URL for changes.
127 Makes a warning if it was not watched.
128 This is private -- external code should use
129 "class procedure Unwatch". }
130 procedure UnwatchCore(const Url: String; const Notify: TSimpleNotifyEvent);
131
132 procedure SetEnabled(const Value: Boolean);
133 public
134 constructor Create;
135 destructor Destroy; override;
136
137 { Start watching given URL for changes.
138 Returns @false if this URL type cannot be watched.
139 If it returns @true, make sure to always call @link(Unwatch)
140 when you're done with this URL. }
141 function Watch(const Url: String; const Notify: TSimpleNotifyEvent): Boolean;
142
143 { Stop watching given URL for changes, for singleton @link(FileMonitor).
144 Makes a warning if it was not watched.
145
146 This is a class method, and it is hardcoded that it works
147 on singleton @link(FileMonitor) in this unit.
148 Though this is inconsistent with other methods in this class,
149 but it is safer: This way external code is secured in case
150 it will call "unwatch" after finalization of this unit is done,
151 at which point the @link(FileMonitor) has been freed and shall not be
152 recreated.
153 This class method handles this internally and gracefully. }
154 class procedure Unwatch(const Url: String; const Notify: TSimpleNotifyEvent);
155
156 { Scan watched files for changes to their last-modified time,
157 and base on this possibly fire some notifications.
158 Nice to use from CGE editor e.g. when it gets focus (when switching
159 to it from other applications). }
160 procedure CheckChanges;
161
162 { Fire change notifications for given file.
163 Can be called when we @italic(know) given file changed,
164 e.g. because it was modified using CGE editor process
165 (like using a sprite sheet editor).
166
167 Note: This also updates saved last-modified time,
168 so that the file is not detected as changed again by next
169 @link(CheckChanges) call. }
170 procedure Changed(const Url: String);
171
172 { Set PossiblyEnabled to @true.
173 Only possible if no file initialized watching yet. }
174 procedure MakePossiblyEnabled;
175
176 { Was MakePossiblyEnabled called. }
177 property PossiblyEnabled: Boolean read FPossiblyEnabled;
178
179 { Is monitoring enabled. Both PossiblyEnabled and Enabled must be @true
180 to actually monitor files. }
181 property Enabled: Boolean read FEnabled write SetEnabled;
182 end;
183
184 type
185 { Helper to use TCastleFileMonitor in most typical fashion:
186 you have a URL variable, String, and you have a parameter-less method
187 that reloads the contents based on this.
188
189 The record has been designed such that when it is filled with all zeroes
190 (which happens when class is created that has a field of this type),
191 this is also a valid state.
192 And calling @link(Finish) on this state is OK. }
193 TUrlMonitoring = record
194 strict private
195 FWatching: Boolean;
196 FReloadUrl: TSimpleNotifyEvent;
197 public
198 procedure Init(const ReloadUrl: TSimpleNotifyEvent);
199 procedure Finish(const Url: String);
200 procedure ChangeUrl(var Url: String; const NewUrl: String);
201 end;
202
203 { Monitor when files change on disk,
204 to enable auto-reloading them at design-time. }
205 function FileMonitor: TCastleFileMonitor;
206
207 implementation
208
209 uses CastleUriUtils, CastleLog, CastleApplicationProperties;
210
211 var
212 FFinalizationDone: Boolean;
213
214 { TFileInfo -------------------------------------------------------------- }
215
216 constructor TCastleFileMonitor.TFileInfo.Create;
217 begin
218 inherited;
219 OnChanged := TSimpleNotifyEventList.Create;
220 end;
221
222 destructor TCastleFileMonitor.TFileInfo.Destroy;
223 begin
224 FreeAndNil(OnChanged);
225 inherited;
226 end;
227
228 procedure TCastleFileMonitor.TFileInfo.UpdateLastModified(const CallChanged: Boolean);
229 var
230 NewLastModified: TDateTime;
231 begin
232 if not FileAge(UriToFilenameSafe(Url), NewLastModified) then
233 begin
234 WritelnWarning('File Monitor', 'Cannot get last modified time of URL "' + Url + '", it will not be watched reliably');
235 NewLastModified := 0;
236 end;
237
238 if CallChanged and
239 (LastModified <> NewLastModified) then
240 begin
241 ExecuteAllChanged;
242 WritelnLog('File Monitor', 'Notified about change of URL "' + Url + '" because last modification time changed');
243 end;
244
245 LastModified := NewLastModified;
246 end;
247
248 procedure TCastleFileMonitor.TFileInfo.ExecuteAllChanged;
249 begin
250 Inc(InsideExecuteAll);
251 try
252 OnChanged.ExecuteAll();
253 finally Dec(InsideExecuteAll) end;
254
255 if InsideExecuteAll = 0 then
256 OnChanged.Pack;
257
258 { If OnChanged.Count = 0 we could actually destroy ourselves,
259 doing Self.Destroy. That's what happens if someone unwatches the file
260 for the last time when InsideExecuteAll = 0.
261
262 But doing so would cause more trouble than benefits:
263
264 - All code calling ExecuteAllChanged would have to be prepared that
265 TFileInfo later possibly doesn't exist. E.g. our own UpdateLastModified
266 would have to exit after ExecuteAllChanged, not do anything more.
267
268 - And actually, leaving TFileInfo with empty OnChanged means less work.
269 Because almost always, when someone unwatches URL during
270 OnChanged.ExecuteAll, it means the URL was unwatched only temporarily
271 by ReloadUrl.
272 It is watched immediately right after.
273 So destroying TFileInfo instance only to recreate it later is pointless
274 work.
275
276 - And it is harmless. TFileInfo with empty OnChanged works OK.
277 }
278 end;
279
280 { TCastleFileMonitor ------------------------------------------------------ }
281
282 constructor TCastleFileMonitor.Create;
283 begin
284 inherited;
285 FFiles := TFiles.Create([doOwnsValues]);
286 end;
287
288 destructor TCastleFileMonitor.Destroy;
289 begin
290 FreeAndNil(FFiles);
291 inherited;
292 end;
293
294 function TCastleFileMonitor.UrlToWatch(const Url: String): String;
295 begin
296 // resolve castle-data://
297 Result := ResolveCastleDataURL(AbsoluteURI(Url));
298
299 // only watch regular files
300 if UriToFilenameSafe(Result) = '' then
301 Result := '';
302 end;
303
304 function TCastleFileMonitor.Watch(const Url: String; const Notify: TSimpleNotifyEvent): Boolean;
305 var
306 UrlWatch: String;
307 FileInfo: TFileInfo;
308 begin
309 FPossiblyEnabledFinalized := true; // cannot change FPossiblyEnabled anymore
310 if not FPossiblyEnabled then
311 Exit(false); // early exit, we will never watch anything
312
313 UrlWatch := UrlToWatch(Url);
314 Result := UrlWatch <> '';
315 if Result then
316 begin
317 if not FFiles.TryGetValue(UrlWatch, FileInfo) then
318 begin
319 FileInfo := TFileInfo.Create;
320 FileInfo.Url := UrlWatch;
321 { Read initial LastModified regardless of Enabled, to later not think
322 that "everything changed" when setting Enabled = true. }
323 FileInfo.UpdateLastModified(false);
324 FFiles.Add(UrlWatch, FileInfo);
325 end;
326 FileInfo.OnChanged.Add(Notify);
327 end;
328 end;
329
330 procedure TCastleFileMonitor.UnwatchCore(const Url: String; const Notify: TSimpleNotifyEvent);
331 var
332 UrlWatch: String;
333 FileInfo: TFileInfo;
334 begin
335 if not FPossiblyEnabled then
336 Exit; // early exit, we will never watch anything
337
338 UrlWatch := UrlToWatch(Url);
339 if FFiles.TryGetValue(UrlWatch, FileInfo) then
340 begin
341 if FileInfo.InsideExecuteAll <> 0 then
342 begin
343 FileInfo.OnChanged.Unassign(Notify);
344 //WritelnLog('Unwatching URL when we iterate inside its own OnChanged');
345 end else
346 begin
347 FileInfo.OnChanged.Remove(Notify);
348 if FileInfo.OnChanged.Count = 0 then
349 FFiles.Remove(UrlWatch);
350 end;
351 end else
352 WritelnWarning('File Monitor', 'Cannot unwatch URL "' + Url + '", it was not watched by anything');
353 end;
354
355 procedure TCastleFileMonitor.CheckChanges;
356 var
357 FileInfo: TFileInfo;
358 begin
359 if not (PossiblyEnabled and Enabled) then
360 Exit;
361
362 for FileInfo in FFiles.Values do
363 FileInfo.UpdateLastModified(true);
364 end;
365
366 procedure TCastleFileMonitor.Changed(const Url: String);
367 var
368 UrlWatch: String;
369 FileInfo: TFileInfo;
370 begin
371 if not (PossiblyEnabled and Enabled) then
372 Exit;
373
374 UrlWatch := UrlToWatch(Url);
375 if FFiles.TryGetValue(UrlWatch, FileInfo) then
376 begin
377 FileInfo.UpdateLastModified(false);
378 FileInfo.ExecuteAllChanged;
379 WritelnLog('File Monitor', 'Notified about change of URL "' + Url + '" because changed explicitly by the editor');
380 end;
381 end;
382
383 class procedure TCastleFileMonitor.Unwatch(
384 const Url: String; const Notify: TSimpleNotifyEvent);
385 begin
386 if FFinalizationDone then
387 begin
388 { Note that we haven't actually experienced this situation in the real code
389 of editor (though at one point we thought we do, but it was a different problem).
390 But this code and log remains, in case it will appear one day. }
391 WritelnLog('File Monitor', 'Unwatching URL "' + Url + '" after finalization of this unit is done, this is normal -> ignoring');
392 end else
393 begin
394 FileMonitor.UnwatchCore(Url, Notify);
395 end;
396 end;
397
398 { TUrlMonitoring ---------------------------------------------------------- }
399
400 procedure TUrlMonitoring.Init(const ReloadUrl: TSimpleNotifyEvent);
401 begin
402 FWatching := false;
403 FReloadUrl := ReloadUrl;
404 end;
405
406 procedure TUrlMonitoring.Finish(const Url: String);
407 begin
408 if FWatching then
409 begin
410 TCastleFileMonitor.Unwatch(Url, FReloadUrl);
411 FWatching := false;
412 end;
413 end;
414
415 procedure TUrlMonitoring.ChangeUrl(var Url: String; const NewUrl: String);
416 begin
417 if Url <> NewUrl then
418 begin
419 Assert(Assigned(FReloadUrl), 'FReloadUrl must be assigned when ChangeUrl is called; this means you have to use TUrlMonitoring.Init before ChangeUrl');
420
421 { Unwatch previous URL, if any was watched }
422 Finish(Url);
423
424 Url := NewUrl;
425
426 { Watch new URL.
427 Ignore Url = '', it conventionally means "load nothing" in CGE components. }
428 if Url <> '' then
429 FWatching := FileMonitor.Watch(Url, FReloadUrl);
430 end;
431 end;
432
433 procedure TCastleFileMonitor.MakePossiblyEnabled;
434 begin
435 if FPossiblyEnabledFinalized and (not FPossiblyEnabled) then
436 raise Exception.Create('Too late to call FileMonitor.MakePossiblyEnabled, some file already called Watch (and we optimized it out, assuming FileMonitor.PossiblyEnabled = false).');
437 FPossiblyEnabled := true;
438 end;
439
440 procedure TCastleFileMonitor.SetEnabled(const Value: Boolean);
441 begin
442 if FEnabled <> Value then
443 begin
444 FEnabled := Value;
445 if FEnabled then
446 { We didn't call UpdateLastModified when Eaabled = false.
447 So now we can update them, updating LastModified, and calling OnChanged
448 if anything changed. }
449 CheckChanges;
450 end;
451 end;
452
453 { global -------------------------------------------------------------------- }
454
455 var
456 FFileMonitor: TCastleFileMonitor;
457
458 function FileMonitor: TCastleFileMonitor;
459 begin
460 if FFinalizationDone then
461 begin
462 WritelnWarning('Accessing FileMonitor singleton after finalization of this unit is done.' +
463 ' We create a new instance, empty, that will leak.' +
464 ' You should avoid this situation, following the pattern of class method "TCastleFileMonitor.Unwatch".');
465 end;
466 if FFileMonitor = nil then
467 FFileMonitor := TCastleFileMonitor.Create;
468 Result := FFileMonitor;
469 end;
470
471 procedure InitializeFileMonitorDebug;
472 begin
473 FileMonitor.MakePossiblyEnabled;
474 end;
475
476 initialization
477 ApplicationProperties.AddInitializeDebugListener(
478 {$ifdef FPC}@{$endif} InitializeFileMonitorDebug);
479 { TODO: The InitializeFileMonitorDebug is called from here only
480 temporarily (in case user didn't update the project to have new
481 CastleAutoGenerated that calls ApplicationProperties.InitializeDebug,
482 but expects to have file monitor working). }
483 {$ifdef DEBUG}
484 InitializeFileMonitorDebug;
485 {$endif}
486 finalization
487 FreeAndNil(FFileMonitor);
488 FFinalizationDone := true;
489 end.