Debian Codegraph @

src/files/castlefindfiles.pas

raw
1 {
2 Copyright 2002-2023 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 { Finding files matching some mask. }
17 unit CastleFindFiles;
18
19 {$I castleconf.inc}
20
21 interface
22
23 uses SysUtils, Classes, Generics.Collections, DOM,
24 CastleUtils;
25
26 type
27 { Information about a single file or directory collected by FindFiles. }
28 TFileInfo = record
29 { Filename, without any directory path. }
30 Name: String;
31 { Expanded (with absolute path) file name.
32 Only when URL is using "file" protocol.
33 You should prefer to use URL field instead of this,
34 to work with all possible URLs. }
35 AbsoluteName: String;
36 { Absolute URL. }
37 Url: String;
38 Directory: Boolean;
39
40 { Whether this is a symbolic link.
41 Note that this is independent from Directory:
42 symlinks may have Directory=false (when the symlink is to file)
43 or Directory=true (when the symlink is to directory,
44 and thus can be browsed like directory). }
45 Symlink: Boolean;
46
47 { File size in bytes.
48
49 Undefined in case of @link(Directory), we do not sum the directory size
50 (all files inside) here, as it is a costly operation for large directories.
51 Use @link(DirectorySize) if you want to calculate directory size.
52
53 This may be 0 in case of URL pointing to non-local file, e.g. http
54 (though we cannot search in such URLs anyway). }
55 Size: QWord;
56 end;
57
58 { Returned by FindFilesList. }
59 TFileInfoList = class({$ifdef FPC}specialize{$endif} TStructList<TFileInfo>)
60 { Sort alphabetically by @link(TFileInfo.Url).
61 Useful, since the order returned by @link(FindFilesList) is undefined. }
62 procedure SortUrls;
63 end;
64
65 { Called for each file found.
66 StopSearch is always initially @false, you can change it to @true to stop
67 the enclosing FindFiles call. }
68 TFoundFileProc = procedure (const FileInfo: TFileInfo; Data: Pointer; var StopSearch: Boolean);
69 TFoundFileMethod = procedure (const FileInfo: TFileInfo; var StopSearch: Boolean) of object;
70
71 TFindFilesOption = (
72 { If ffRecursive is in Options then FindFiles (and friends) descend into
73 subdirectories.
74
75 Note that we always descend into @italic(every) subdirectory (not only
76 into those matching Mask, that would be pretty useless (and is a problem
77 with Unix shell expansion)).
78
79 Note that including ffRecursive in Options
80 is something completely different than the FindDirectories parameter:
81 FindDirectories says whether to report directories to FileProc;
82 ffRecursive says whether to descend into directories and enumerate
83 their files too.
84
85 Recursive does @italic(not) descend into symlinks to directories on Unix
86 right now. The reason is that this would risk an infinite loop
87 (unless some time-consuming precautions would be taken, or a level limit).
88 In other words, it's just not implemented.
89 But it @italic(may) be implemented someday, as this would be definitely
90 something useful. }
91 ffRecursive,
92
93 { Determines the order of reporting directory contents.
94 Meaningfull only if ffRecursive is also included in Options.
95
96 If not included, then directory contents (files and directories
97 matching mask) are reported to the callback first.
98 And only then we enter the subdirectories.
99
100 If ffDirContentsLast is included, then we first enter subdirectories.
101 Only then we list directory contents to the callback. }
102 ffDirContentsLast,
103
104 { If ffReadAllFirst is included in the Options then before calling FileProc,
105 we will first read @italic(all) file information to an internal array.
106 And only then we will call FileProc for each item of this array.
107
108 Why this may be useful? This way changes to the directory
109 (like renaming / deleting / creating files) will not have any effect
110 on the list of files we will get. This is important if our FileProc
111 may modify the directory contents. Without ffReadAllFirst,
112 it's undefined (OS-dependent and sometimes just random)
113 if the new file names will appear in the directory list. }
114 ffReadAllFirst);
115 TFindFilesOptions = set of TFindFilesOption;
116
117 { Find all files matching the given mask, and call FileProc for them.
118
119 @param(Path Path URL to search inside.
120 May be absolute or relative. Like everywhere in our engine,
121 it can also be a local filesystem path, although we advice using
122 URLs for everything. May, but doesn't have to, end with slash or PathDelim.
123 Empty Path means "the current directory".)
124
125 @param(Mask Mask of the files to search, may contain wildcards * and ?.)
126
127 @param(PathAndMask Overloaded versions without separate Path and Mask parameters
128 just assume that PathAndMask contain concatenated Path + Mask,
129 separated by any valid path delimiter.)
130
131 @param(FindDirectories Should directories also be found
132 (reported by FileProc). Note that this is completely independent
133 from whether we work recursively (ffRecursive in Options).)
134
135 @param(FileProc Called on each file found.
136 May be @nil (useful if you are only interested in the number of files found,
137 returned by this function).)
138
139 @param(FileProcData Pointer passed to every call of FileProc.
140 This routine just passes FileProcData value as "Data" parameter to each FileProc call.
141 It is a pointer that may have absolutely any meaning you want,
142 and may point to any data structure you want,
143 it is useful to communicate information between the caller and the FileProc implementation.
144
145 If you don't need this, then just ignore the "Data" in your FileProc implementation,
146 and pass anything (like @nil) as FileProcData value.
147
148 Note that the overloaded version with FileMethod parameter doesn't have
149 any FileProcData, as in this case the instance that implements FileMethod
150 may carry any additional information necessary.)
151
152 @param(Options A set of options. See TFindFilesOption for meaning
153 of each option.)
154
155 @returns(How many times FileProc was called, that is: how many
156 files/directories were matching. Useful to report to user how many
157 files were processed, in particular to warn if nothing was processed.)
158
159 @groupBegin }
160 function FindFiles(const Path, Mask: string; const FindDirectories: boolean;
161 const FileMethod: TFoundFileMethod; const Options: TFindFilesOptions): Cardinal; overload;
162 function FindFiles(const Path, Mask: string; const FindDirectories: boolean;
163 const FileProc: TFoundFileProc; const FileProcData: Pointer;
164 const Options: TFindFilesOptions): Cardinal; overload;
165
166 function FindFiles(const PathAndMask: string; const FindDirectories: boolean;
167 const FileMethod: TFoundFileMethod; const Options: TFindFilesOptions): Cardinal; overload;
168 function FindFiles(const PathAndMask: string; const FindDirectories: boolean;
169 const FileProc: TFoundFileProc; const FileProcData: Pointer;
170 const Options: TFindFilesOptions): Cardinal; overload;
171 { @groupEnd }
172
173 { Like @link(FindFiles), but return found files as a list.
174 Caller is resopnsible for freeing the returned list. }
175 function FindFilesList(const Path, Mask: string; const FindDirectories: boolean;
176 const Options: TFindFilesOptions): TFileInfoList;
177
178 { Search for a file, ignoring the case.
179 Path must be absolute URL and contain the final slash.
180 Returns URL relative to Path.
181
182 We prefer to return just Base, if it exists, or when no alternative exists.
183 When Base doesn't exist but some likely alternative exists (e.g. with
184 different case), we return it.
185
186 Looks for normal files/symlinks, that can be opened as usual files.
187 Not directories.
188
189 Returns if some file was found. Note that even when we return @false,
190 we still set NewBase (to original Base). }
191 function SearchFileHard(Path: string; const Base: string; out NewBase: string): boolean;
192
193 { Find first file matching given Mask inside Path.
194 If found, returns @true and sets FileInfo.
195 Otherwise, returns @false and leaves FileInfo undefined. }
196 function FindFirstFile(const Path, Mask: string;
197 const FindDirectories: boolean; const Options: TFindFilesOptions;
198 out FileInfo: TFileInfo): boolean;
199
200 { Find first file matching given Mask inside Path, always ignores case
201 (regardless of OS conventions).
202 If found, returns @true and sets FileInfo.
203 Otherwise, returns @false and leaves FileInfo undefined. }
204 function FindFirstFileIgnoreCase(const Path, Mask: string;
205 const FindDirectories: boolean; const Options: TFindFilesOptions;
206 out FileInfo: TFileInfo): boolean;
207
208 implementation
209
210 uses URIParser, StrUtils, Generics.Defaults,
211 CastleUriUtils, CastleLog, CastleXmlUtils, CastleStringUtils,
212 CastleInternalDirectoryInformation, CastleFilesUtils;
213
214 function CompareFileInfo(
215 {$ifdef GENERICS_CONSTREF}constref{$else}const{$endif}
216 Left, Right: TFileInfo): Integer;
217 begin
218 Result := AnsiCompareStr(Left.Url, Right.Url);
219 end;
220
221 procedure TFileInfoList.SortUrls;
222 type
223 TFileInfoComparer = {$ifdef FPC}specialize{$endif} TComparer<TFileInfo>;
224 begin
225 Sort(TFileInfoComparer.Construct({$ifdef FPC}@{$endif} CompareFileInfo));
226 end;
227
228 { Note that some limitations of FindFirst/FindNext underneath are reflected in our
229 functionality. Under Windows, mask is treated somewhat hacky:
230
231 @orderedList(
232 @item(Every filename conceptually has an extention under Windows,
233 so *.* matches any file. On more sane OSes, *.* matches only
234 files with a dot inside a filename.)
235
236 @item(Extensions may be shortened to the first 3 letters.
237 For example searching for @code(*.txt) actually searches
238 for @code(*.txt*), that is it finds all the files with extensions
239 starting from txt.)
240 )
241 }
242
243 { On Windows, the FindFirst/FindNext follow broken Windows API behavior
244 that only compares the first 3 letters of the extension.
245 So e.g. searching for '*.pas' will also find 'emacs-backup-file.pas~' .
246 To be sensible, and to be consistent across platforms, we fix it by
247 additional IsWild check.
248 This also matters e.g. for Pascal files list found by
249 "castle-engine generate-program" -- we don't want there
250 'emacs-backup-file.pas~'. }
251 {$ifdef MSWINDOWS}
252 {$define DOUBLE_CHECK_WILDCARD}
253 {$endif}
254
255 { FindFiles ------------------------------------------------------------------ }
256
257 { This is equivalent to FindFiles with Recursive = false
258 and ReadAllFirst = false. }
259 function FindFiles_NonRecursive(const Path, Mask: string;
260 const FindDirectories: boolean;
261 const FileProc: TFoundFileProc; const FileProcData: Pointer;
262 var StopSearch: Boolean): Cardinal;
263
264 procedure UseLocalFileSystem;
265 var
266 AbsoluteName, LocalPath: string;
267 FileRec: TSearchRec;
268 Attr, SearchError: Integer;
269 FileInfo: TFileInfo;
270 begin
271 Result := 0;
272
273 {$warnings off}
274 { don't warn that faXxx are unportable }
275 Attr := faReadOnly or faHidden or faArchive
276 { for symlinks with old FPC versions } or faSysFile
277 { for symlinks with new FPC versions, at least FPC >= 3.0.2 } or faSymLink;
278 {$warnings on}
279 if FindDirectories then
280 Attr := Attr or faDirectory;
281
282 if Path <> '' then
283 LocalPath := UriToFilenameSafe(Path)
284 else
285 LocalPath := GetCurrentDir;
286 LocalPath := InclPathDelim(LocalPath);
287 SearchError := FindFirst(LocalPath + Mask, Attr, FileRec);
288 try
289 while (SearchError = 0) and (not StopSearch) do
290 begin
291 // do not enumerate directory names '.' and '..'
292 if not (
293 ((FileRec.Attr and faDirectory) <> 0) and
294 SpecialDirName(FileRec.Name))
295 {$ifdef DOUBLE_CHECK_WILDCARD}
296 and IsWild(FileRec.Name, Mask, { IgnoreCase } not FileNameCaseSensitive)
297 {$endif}
298 then
299 begin
300 AbsoluteName := LocalPath + FileRec.Name;
301 Inc(Result);
302
303 FileInfo := Default(TFileInfo);
304 FileInfo.AbsoluteName := AbsoluteName;
305 FileInfo.Name := FileRec.Name;
306 FileInfo.Directory := (FileRec.Attr and faDirectory) <> 0;
307 FileInfo.Size := FileRec.Size;
308 {$warnings off} // we know faSymLink is platform-specific, this is OK
309 FileInfo.Symlink := (FileRec.Attr and faSymLink) <> 0;
310 {$warnings on}
311 FileInfo.URL := FilenameToUriSafe(AbsoluteName);
312 if Assigned(FileProc) then
313 FileProc(FileInfo, FileProcData, StopSearch);
314 end;
315
316 SearchError := FindNext(FileRec);
317 end;
318 finally FindClose(FileRec) end;
319 end;
320
321 procedure UseDataDirectoryInformation;
322 var
323 U: TURI;
324 PathPartsStr: String;
325 PathEntry: TDirectoryInformation.TEntry;
326 F: TDirectoryInformation.TFile;
327 PathDir, D: TDirectoryInformation.TDirectory;
328 FileInfo: TFileInfo;
329 begin
330 U := ParseURI(Path);
331 PathPartsStr := PrefixRemove('/', U.Path + U.Document, false);
332 PathEntry := DataDirectoryInformation.FindEntry(PathPartsStr);
333 if PathEntry is TDirectoryInformation.TDirectory then
334 begin
335 PathDir := TDirectoryInformation.TDirectory(PathEntry);
336
337 if FindDirectories then
338 for D in PathDir.Directories do
339 if IsWild(D.Name, Mask, false) then
340 begin
341 Inc(Result);
342 FileInfo := Default(TFileInfo); // clear information like FileInfo.Size to zero
343 FileInfo.Name := D.Name;
344 FileInfo.Directory := true;
345 FileInfo.URL := URIIncludeSlash(Path) + D.Name;
346 if Assigned(FileProc) then
347 begin
348 FileProc(FileInfo, FileProcData, StopSearch);
349 if StopSearch then Break;
350 end;
351 end;
352
353 if not StopSearch then
354 for F in PathDir.Files do
355 if IsWild(F.Name, Mask, false) then
356 begin
357 Inc(Result);
358 FileInfo := Default(TFileInfo);
359 FileInfo.Name := F.Name;
360 FileInfo.Directory := false;
361 FileInfo.Size := F.Size;
362 FileInfo.URL := URIIncludeSlash(Path) + F.Name;
363 FileInfo.Symlink := false; // packaged data cannot contain symlinks, as they are not portable to all platforms
364 if Assigned(FileProc) then
365 begin
366 FileProc(FileInfo, FileProcData, StopSearch);
367 if StopSearch then Break;
368 end;
369 end;
370 end;
371 end;
372
373 var
374 P: string;
375 begin
376 P := URIProtocol(Path);
377
378 if (P = 'file') or (P = '') then
379 UseLocalFileSystem
380 else
381 if P = 'castle-data' then
382 begin
383 if (DisableDataDirectoryInformation = 0) and
384 (DataDirectoryInformation <> nil) then
385 UseDataDirectoryInformation
386 else
387 Result := FindFiles_NonRecursive(ResolveCastleDataURL(Path), Mask,
388 FindDirectories, FileProc, FileProcData, StopSearch);
389 end else
390 WritelnLog('FindFiles',
391 'Searching inside filesystem with protocol %s not possible, ignoring path "%s"',
392 [P, UriCaption(Path)]);
393 end;
394
395 { This is equivalent to FindFiles with Recursive = true,
396 and ReadAllFirst = false. }
397 function FindFiles_Recursive(const Path, Mask: string; const FindDirectories: boolean;
398 const FileProc: TFoundFileProc; const FileProcData: Pointer;
399 const DirContentsLast: boolean; var StopSearch: Boolean): Cardinal;
400
401 procedure WriteDirContent;
402 begin
403 Result := Result +
404 FindFiles_NonRecursive(Path, Mask, FindDirectories, FileProc, FileProcData, StopSearch);
405 end;
406
407 procedure UseLocalFileSystem;
408 var
409 LocalPath: string;
410 FileRec: TSearchRec;
411 SearchError: integer;
412 begin
413 if Path <> '' then
414 LocalPath := UriToFilenameSafe(Path)
415 else
416 LocalPath := GetCurrentDir;
417 LocalPath := InclPathDelim(LocalPath);
418
419 {$warnings off}
420 SearchError := FindFirst(LocalPath + '*',
421 faDirectory { potential flags on directory: } or faSysFile or faArchive or faReadOnly or faHidden,
422 FileRec);
423 {$warnings on}
424 try
425 while (SearchError = 0) and (not StopSearch) do
426 begin
427 if ((faDirectory and FileRec.Attr) <> 0) and
428 (not SpecialDirName(FileRec.Name)) then
429 Result := Result +
430 FindFiles_Recursive(FilenameToUriSafe(LocalPath + FileRec.Name), Mask,
431 FindDirectories, FileProc, FileProcData, DirContentsLast, StopSearch);
432 SearchError := FindNext(FileRec);
433 end;
434 finally FindClose(FileRec) end;
435 end;
436
437 procedure UseDataDirectoryInformation;
438 var
439 U: TURI;
440 PathPartsStr: String;
441 PathEntry: TDirectoryInformation.TEntry;
442 PathDir, D: TDirectoryInformation.TDirectory;
443 begin
444 U := ParseURI(Path);
445 PathPartsStr := PrefixRemove('/', U.Path + U.Document, false);
446 PathEntry := DataDirectoryInformation.FindEntry(PathPartsStr);
447 if PathEntry is TDirectoryInformation.TDirectory then
448 begin
449 PathDir := TDirectoryInformation.TDirectory(PathEntry);
450 for D in PathDir.Directories do
451 begin
452 FindFiles_Recursive(URIIncludeSlash(Path) + D.Name, Mask,
453 FindDirectories, FileProc, FileProcData, DirContentsLast, StopSearch);
454 if StopSearch then Break;
455 end;
456 end;
457 end;
458
459 { Search in subdirectories recursively. }
460 procedure WriteSubdirs;
461 var
462 P: string;
463 begin
464 P := URIProtocol(Path);
465
466 if (P = 'file') or (P = '') then
467 UseLocalFileSystem
468 else
469 if P = 'castle-data' then
470 begin
471 if (DisableDataDirectoryInformation = 0) and
472 (DataDirectoryInformation <> nil) then
473 UseDataDirectoryInformation
474 else
475 raise EInternalError.Create('This case should cause recursive exit earlier in FindFiles_Recursive');
476 end else
477 WritelnLog('FindFiles',
478 'Searching inside subdirectories with protocol %s not possible, ignoring path "%s"',
479 [P, UriCaption(Path)]);
480 end;
481
482 begin
483 Result := 0;
484
485 { early exit if we should do ResolveCastleDataURL and call ourselves }
486 if (URIProtocol(Path) = 'castle-data') and
487 not ( (DisableDataDirectoryInformation = 0) and
488 (DataDirectoryInformation <> nil) ) then
489 begin
490 Exit(FindFiles_Recursive(ResolveCastleDataURL(Path), Mask,
491 FindDirectories, FileProc, FileProcData, DirContentsLast, StopSearch));
492 end;
493
494 if DirContentsLast then
495 begin
496 WriteSubdirs; if StopSearch then Exit;
497 WriteDirContent; if StopSearch then Exit;
498 end else
499 begin
500 WriteDirContent; if StopSearch then Exit;
501 WriteSubdirs; if StopSearch then Exit;
502 end;
503 end;
504
505 { This is equivalent to FindFiles with ReadAllFirst = false. }
506 function FindFiles_NonReadAllFirst(const Path, Mask: string; const FindDirectories: boolean;
507 const FileProc: TFoundFileProc; const FileProcData: Pointer;
508 const Recursive, DirContentsLast: boolean): Cardinal;
509 var
510 StopSearch: Boolean;
511 begin
512 StopSearch := false;
513 if Recursive then
514 Result := FindFiles_Recursive(Path, Mask, FindDirectories, fileProc, FileProcData, DirContentsLast, StopSearch)
515 else
516 Result := FindFiles_NonRecursive(Path, Mask, FindDirectories, fileProc, FileProcData, StopSearch);
517 end;
518
519 procedure FileProc_AddToFileInfos(
520 const FileInfo: TFileInfo; Data: Pointer; var StopSearch: Boolean);
521 begin
522 TFileInfoList(Data).Add(FileInfo);
523 end;
524
525 function FindFiles(const Path, Mask: string; const FindDirectories: boolean;
526 const FileProc: TFoundFileProc; const FileProcData: Pointer;
527 const Options: TFindFilesOptions): Cardinal;
528 var
529 FileInfos: TFileInfoList;
530 i: Integer;
531 StopSearch: Boolean;
532 begin
533 if ffReadAllFirst in Options then
534 begin
535 FileInfos := TFileInfoList.Create;
536 try
537 Result := FindFiles_NonReadAllFirst(Path, Mask, FindDirectories,
538 @FileProc_AddToFileInfos, FileInfos,
539 ffRecursive in Options,
540 ffDirContentsLast in Options);
541 if Assigned(FileProc) then
542 begin
543 StopSearch := false;
544 for i := 0 to FileInfos.Count - 1 do
545 begin
546 FileProc(FileInfos.L[i], FileProcData, StopSearch);
547 if StopSearch then Break;
548 end;
549 end;
550 finally FileInfos.Free end;
551 end else
552 begin
553 Result := FindFiles_NonReadAllFirst(Path, Mask, FindDirectories,
554 FileProc, FileProcData,
555 ffRecursive in Options,
556 ffDirContentsLast in Options);
557 end;
558 end;
559
560 function FindFiles(const PathAndMask: string; const FindDirectories: boolean;
561 const FileProc: TFoundFileProc; const FileProcData: Pointer;
562 const Options: TFindFilesOptions): Cardinal;
563 begin
564 Result := FindFiles(ExtractURIPath(PathAndMask), ExtractURIName(PathAndMask),
565 FindDirectories, FileProc, FileProcData, Options);
566 end;
567
568 { FindFiles with TFoundFileMethod -------------------------------------------- }
569
570 type
571 TFoundFileMethodWrapper = record
572 FileMethod: TFoundFileMethod;
573 end;
574 PFoundFileMethodWrapper = ^TFoundFileMethodWrapper;
575
576 procedure FoundFileProcToMethod(
577 const FileInfo: TFileInfo; Data: Pointer; var StopSearch: Boolean);
578 var
579 FileMethod: TFoundFileMethod;
580 begin
581 FileMethod := PFoundFileMethodWrapper(Data)^.FileMethod;
582 if Assigned(FileMethod) then
583 FileMethod(FileInfo, StopSearch);
584 end;
585
586 function FindFiles(const Path, Mask: string; const FindDirectories: boolean;
587 const FileMethod: TFoundFileMethod; const Options: TFindFilesOptions): Cardinal;
588 var
589 FileMethodWrapper: TFoundFileMethodWrapper;
590 begin
591 FileMethodWrapper.FileMethod := FileMethod;
592 Result := FindFiles(Path, Mask, FindDirectories,
593 {$ifdef FPC}@{$endif} FoundFileProcToMethod,
594 @FileMethodWrapper, Options);
595 end;
596
597 function FindFiles(const PathAndMask: string; const FindDirectories: boolean;
598 const FileMethod: TFoundFileMethod; const Options: TFindFilesOptions): Cardinal;
599 begin
600 Result := FindFiles(ExtractURIPath(PathAndMask), ExtractURIName(PathAndMask),
601 FindDirectories, FileMethod, Options);
602 end;
603
604 { related utilities ---------------------------------------------------------- }
605
606 type
607 TSearchFileHardHelper = class
608 Base: string;
609 IsFound: boolean;
610 Found: string;
611 procedure Callback(const FileInfo: TFileInfo; var StopSearch: Boolean);
612 end;
613
614 procedure TSearchFileHardHelper.Callback(const FileInfo: TFileInfo; var StopSearch: Boolean);
615 begin
616 if AnsiSameText(FileInfo.Name, Base) then
617 begin
618 Found := FileInfo.Name;
619 IsFound := true;
620 StopSearch := true;
621 end;
622 end;
623
624 function SearchFileHard(Path: string; const Base: string; out NewBase: string): boolean;
625 var
626 Helper: TSearchFileHardHelper;
627 P: string;
628 begin
629 NewBase := Base;
630 Result := false;
631
632 P := URIProtocol(Path);
633 if P = 'file' then
634 { convert Path to filename and continue }
635 Path := UriToFilenameSafe(Path)
636 else
637 if (P = 'castle-nx-contents') or
638 (P = 'castle-nx-save') then
639 Exit(URIFileExists(Path + Base)) // URIFileExists handles castle-nx-contents and castle-nx-save
640 else
641 if P <> '' then
642 { we can't do anything with different protocols
643 (note that empty protocol means it's a filename, so this is OK). }
644 Exit(true);
645
646 if RegularFileExists(Path + Base) then Exit(true);
647
648 Helper := TSearchFileHardHelper.Create;
649 try
650 Helper.Base := Base;
651 FindFiles(Path + '*', false, {$ifdef FPC}@{$endif}Helper.Callback, []);
652 Result := Helper.IsFound;
653 if Result then
654 NewBase := Helper.Found;
655 finally FreeAndNil(Helper) end;
656 end;
657
658 type
659 TFindFirstFileHelper = class
660 IsFound: boolean;
661 FoundFile: TFileInfo;
662 procedure Callback(const FileInfo: TFileInfo; var StopSearch: Boolean);
663 end;
664
665 procedure TFindFirstFileHelper.Callback(const FileInfo: TFileInfo; var StopSearch: Boolean);
666 begin
667 FoundFile := FileInfo;
668 IsFound := true;
669 StopSearch := true;
670 end;
671
672 function FindFirstFile(const Path, Mask: string;
673 const FindDirectories: boolean; const Options: TFindFilesOptions;
674 out FileInfo: TFileInfo): boolean;
675 var
676 Helper: TFindFirstFileHelper;
677 begin
678 Helper := TFindFirstFileHelper.Create;
679 try
680 FindFiles(Path, Mask, FindDirectories,
681 {$ifdef FPC}@{$endif} Helper.Callback, Options);
682 Result := Helper.IsFound;
683 if Result then
684 FileInfo := Helper.FoundFile;
685 finally FreeAndNil(Helper) end;
686 end;
687
688 type
689 TFindFirstFileIgnoreCaseHelper = class
690 Mask: String;
691 IsFound: boolean;
692 FoundFile: TFileInfo;
693 procedure Callback(const FileInfo: TFileInfo; var StopSearch: Boolean);
694 end;
695
696 procedure TFindFirstFileIgnoreCaseHelper.Callback(const FileInfo: TFileInfo; var StopSearch: Boolean);
697 begin
698 if IsWild(FileInfo.Name, Mask, { IgnoreCase } true) then
699 begin
700 FoundFile := FileInfo;
701 IsFound := true;
702 StopSearch := true;
703 end;
704 end;
705
706 function FindFirstFileIgnoreCase(const Path, Mask: string;
707 const FindDirectories: boolean; const Options: TFindFilesOptions;
708 out FileInfo: TFileInfo): boolean;
709 var
710 Helper: TFindFirstFileIgnoreCaseHelper;
711 begin
712 Helper := TFindFirstFileIgnoreCaseHelper.Create;
713 try
714 Helper.Mask := Mask;
715 { We enumerate all files (so it doesn't matter if FindFirst/Next,
716 which may be using native OS functions when searching local file system,
717 are case-sensitive or not).
718 Then we check Mask in TFindFirstFileIgnoreCaseHelper.Callback . }
719 FindFiles(Path, '*', FindDirectories,
720 {$ifdef FPC}@{$endif} Helper.Callback, Options);
721 Result := Helper.IsFound;
722 if Result then
723 FileInfo := Helper.FoundFile;
724 finally FreeAndNil(Helper) end;
725 end;
726
727 type
728 TFindFilesListHelper = class
729 List: TFileInfoList;
730 procedure Callback(const FileInfo: TFileInfo; var StopSearch: Boolean);
731 end;
732
733 procedure TFindFilesListHelper.Callback(const FileInfo: TFileInfo; var StopSearch: Boolean);
734 begin
735 List.Add(FileInfo);
736 end;
737
738 function FindFilesList(const Path, Mask: string; const FindDirectories: boolean;
739 const Options: TFindFilesOptions): TFileInfoList;
740 var
741 Helper: TFindFilesListHelper;
742 begin
743 Result := TFileInfoList.Create;
744 try
745 Helper := TFindFilesListHelper.Create;
746 try
747 Helper.List := Result;
748 FindFiles(Path, Mask, FindDirectories,
749 {$ifdef FPC}@{$endif} Helper.Callback, Options);
750 finally FreeAndNil(Helper) end;
751 except FreeAndNil(Result); raise end;
752 end;
753
754 end.