Debian Codegraph @

src/files/castlefilesutils.pas

raw
1 {
2 Copyright 2002-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 { Operations on files.
17
18 Includes functions to help cross-platform programs to know
19 where to read/write files:
20 @unorderedList(
21 @itemSpacing Compact
22 @item(ApplicationConfig -- user config files)
23 )
24
25 Hints about what to use (and what not to use) in a cross-platform applications
26 using Castle Game Engine:
27
28 @unorderedList(
29 @item(
30 To get a nice application name, use the @code(ApplicationName)
31 function (defined in the standard SysUtils unit for FPC,
32 or CastleUtils unit for Delphi).
33 Every application can customize it by assigning OnGetApplicationName
34 or (often more comfortable) assigning
35 @link(TCastleApplicationProperties.ApplicationName ApplicationProperties.ApplicationName).
36 The Castle Game Engine units use it where appropriate.
37 )
38
39 @item(
40 Use URLs for everything.
41 See https://castle-engine.io/manual_network.php .
42 )
43
44 @item(
45 Use "castle-data:/xxx" URLs to refer to the data directory of your project.
46 See https://castle-engine.io/data .
47 For example:
48 @longCode(#
49 MyImage := LoadImage('castle-data:/gui/my_image.png');
50 #)
51 )
52
53 @item(
54 Use the @link(ApplicationConfig) for all URLs where you save or load
55 the user configuration files, savegames etc.
56 )
57
58 @item(
59 Do not try to get the application name, or executable file name,
60 using ParamStr(0). Do not rely on Lazarus Application.ExeName
61 or our own (deprecated) @link(ExeName).
62
63 The "executable file name" is just not 100% reliably available on all OSes.
64 And in some cases, like Android or iOS, the concept of
65 @italic("executable file name") doesn't even make sense,
66 as your application is a library being called by a higher-level application
67 (written in Java or Objective-C), and it's really an "internal matter"
68 where is the executable file that started it.
69 )
70
71 @item(
72 Use CastleFindFiles unit to search for files and directories.
73 It nicely works with URLs, has some support for the Android "assets"
74 filesystem, and it has more comfortable API (e.g. searching recursively
75 or not is just a matter of passing a particular flag).
76
77 Do not use standard FindFirst/FindNext.
78 )
79
80 @item(
81 Read and write all data using streams (TStream) descendants.
82 Open and save these streams using our CastleDownload unit.
83 )
84 )
85 }
86 unit CastleFilesUtils;
87
88 {$I castleconf.inc}
89
90 interface
91
92 uses {$ifdef MSWINDOWS} Windows, {$endif}
93 {$ifdef UNIX} {$ifdef FPC} BaseUnix, Unix, {$endif} {$endif}
94 SysUtils, CastleUtils;
95
96 type
97 EExeNameNotAvailable = class(Exception);
98 ERemoveFailed = class(Exception);
99
100 { Full (absolute) FileName to executable file of this program.
101 If it's impossible to obtain, raises exception @link(EExeNameNotAvailable).
102
103 Under Windows this is simply ParamStr(0) (and it never raises
104 exception), but under other OSes it's not so simple to obtain
105 (although it's important to note that usually programs under
106 UNIX should not need this, actually).
107
108 Internal implementation notes:
109
110 Under UNIXes other than Linux I don't know how to obtain this,
111 so e.g. under FreeBSD this will always raise an exception.
112 Under Linux I'm trying to read file /proc/getpid()/exe,
113 this should work under most Linuxes as long as user
114 compiled Linux kernel with /proc support. So under Linux
115 this may work, but still you should be always prepared that it
116 may raise @link(EExeNameNotAvailable). }
117 function ExeName: string; deprecated 'as this function is not portable (may raise exception on non-Windows), it should not be used in a cross-platform game code';
118
119 { The name of our program.
120
121 @deprecated Deprecated, this is equivalent to ApplicationName,
122 and you should just call ApplicationName directly in new code.
123 ApplicationName is included in standard FPC SysUtils unit for FPC,
124 has good default and is easily configurable by callback OnGetApplicationName
125 or our @link(TCastleApplicationProperties.ApplicationName ApplicationProperties.ApplicationName).
126 See http://www.freepascal.org/docs-html/rtl/sysutils/getappconfigdir.html .
127
128 This is suitable to show to user. It should also indicate how to run the program,
129 usually it should be the basename of the executable (although we do not depend
130 on it technically). It may be used to derive config file/dir for our program,
131 see ApplicationConfig. }
132 function ProgramName: string; deprecated;
133
134 { Returns @true if file exists and is a "regular" file.
135
136 Detects and returns @false for special Windows files
137 like 'con', 'c:\con', 'c:\somedir\con' etc.
138 ('con' is a special device name).
139
140 Returns @false for directories (on all operating systems,
141 unlike FPC FileExists which is inconsistent between OSes
142 -- on Unix, FPC FileExists surprisingly answers @true for a directory).
143
144 Consider using URIExists or URIFileExists instead of this function,
145 since in CGE you should use URLs for everything. }
146 function RegularFileExists(const FileName: String): Boolean;
147
148 function NormalFileExists(const FileName: String): Boolean; deprecated 'use RegularFileExists';
149
150 { Path to store user configuration files.
151 This is some directory that should be writeable
152 and that is a standard directory under this OS to put user config files.
153 Always returns absolute (not relative) path. Result contains trailing
154 PathDelim.
155
156 @deprecated Deprecated, use ApplicationConfig instead. }
157 function UserConfigPath: string; deprecated;
158
159 { Filename to store user configuration.
160 Always returns absolute (not relative) path.
161
162 Returns FileName that:
163 @unorderedList(
164 @itemSpacing Compact
165 @item is inside UserConfigPath
166 @item depends on ApplicationName
167 @item(has given Extension. Extension should contain
168 beginning dot. E.g. FExtension = '.ini'. This way you can pass
169 FExtension = '' to have a FileName without extension.)
170 )
171
172 @deprecated Deprecated,
173 use ApplicationConfig(ApplicationName + Extension) instead. }
174 function UserConfigFile(const Extension: string): string; deprecated;
175
176 var
177 { URL used as a prefix of all @link(ApplicationConfig) returned URLs.
178 This overrides any autodetection of a suitable "user config" directory
179 done by default by @link(ApplicationConfig).
180
181 This must always end with a slash, if it's not empty. }
182 ApplicationConfigOverride: string;
183
184 { URL where we should read and write configuration files.
185 This always returns a @code(file://...) URL,
186 which is comfortable since our engine operates on URLs most of the time.
187
188 Given Path specifies a name of the file (with possible subdirectories)
189 under the user config directory. The Path is a relative URL, so you should
190 always use slashes (regardless of OS), and you can escape characters by %xx.
191 We make sure that the directory (including
192 the subdirectories you specify in Path) exists, creating it if necessary.
193 But we do not create the file. We should have permissions
194 to write inside the given directory (although, as always on multi-process OS,
195 the only 100% way to know if you can write there is to actually try it).
196
197 This uses FPC GetAppConfigDir under the hood.
198 Which in turn looks at ApplicationName, and may use
199 OS-specific algorithm to find good config directory, see
200 http://www.freepascal.org/docs-html/rtl/sysutils/ongetapplicationname.html .
201 On UNIX this follows XDG Base Directory Specification,
202 see http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
203 (simplifying: looks inside ~/.config/<application-name>/). }
204 function ApplicationConfig(const Path: string): string;
205
206 { @deprecated }
207 function ApplicationData(const Path: String): String; deprecated 'use ''castle-data:/xxx'' instead of ApplicationData(''xxx'')';
208
209 var
210 { URL used as the base application data directory.
211 Overrides the platform-specific autodetection of this directory.
212 See @url(https://castle-engine.io/data data directory
213 documentation).
214
215 If it's not empty, this must always end with a slash.
216
217 This cannot start with 'castle-data:/...', since it would mean that
218 ResolveCastleDataUrl can never finish its job. }
219 ApplicationDataOverride: string;
220
221 {$ifdef UNIX}
222 { User's home directory, with trailing PathDelim.
223
224 Taken from environment variable $HOME, unless it's empty or unset,
225 in which case we take this from Unix user database by real uid.
226 This is what bash does (more-or-less, when home directory does
227 not exist strange things happen), that's what programs should
228 do according to `info libc' and Kambi preferences. }
229 function HomePath: string;
230 {$endif}
231
232 { Expand tilde (~) in path, just like shell. Expands ~ to
233 ExclPathDelim(HomePath) under UNIX. Under Windows, does nothing. }
234 function ExpandHomePath(const FileName: string): string;
235
236 { Remove file.
237
238 Similar to standard DeleteFile, but this checks result and raises exception
239 or makes a warning (see Warn parameter) in case of trouble
240
241 When Warn = @false (default) raises an exception on failure,
242 otherwise (when Warn = @true) makes only WritelnWarning on failure.
243 @raises ERemoveFailed If delete failed, and Warn = @false. }
244 procedure CheckDeleteFile(const FileName: string; const Warn: Boolean = false);
245
246 { Remove empty directory.
247
248 Similar to standard RemoveDir, but this checks result and raises exception
249 or makes a warning (see Warn parameter) in case of trouble.
250
251 When Warn = @false (default) raises an exception on failure,
252 otherwise (when Warn = @true) makes only WritelnWarning on failure.
253 @raises ERemoveFailed If delete failed, and Warn = @false. }
254 procedure CheckRemoveDir(const DirFileName: string; const Warn: Boolean = false);
255
256 { Make sure directory exists, eventually creating it and all directories along the way.
257
258 Similar to standard ForceDirectories, but this checks result and raises exception
259 in case of trouble. }
260 procedure CheckForceDirectories(const Dir: string);
261
262 { Copy file from Source to Dest.
263 The directory of Dest must already exist.
264 File is overwritten unconditionally. }
265 procedure CheckCopyFile(const Source, Dest: string);
266
267 { Move file from Source to Dest.
268 The directory of Dest must already exist.
269 File is overwritten unconditionally. }
270 procedure CheckRenameFile(const Source, Dest: string);
271
272 { Remove the directory DirName, @italic(recursively, unconditionally,
273 with all the files and subdirectories inside).
274 DirName may but doesn't have to end with PathDelim.
275
276 In case of symlinks, removes the symlink (but does not descend inside,
277 i.e. will not remove files inside a symlink to a directory).
278
279 When Warn = @false (default) raises an exception on failure,
280 otherwise (when Warn = @true) makes only WritelnWarning on failure.
281 @raises ERemoveFailed If delete failed, and Warn = @false. }
282 procedure RemoveNonEmptyDir(const DirName: string; const Warn: Boolean = false);
283
284 { Copies the contents from SourceDir to DestinationDir.
285 DestinationDir and necessary subdirectories are created, if needed.
286 Both SourceDir and DestinationDir may, but do not have to, end with PathDelim.
287
288 Note that DestinationDir contents are not cleared here.
289 In effect, the existing files (present in DestinationDir before the copy operation,
290 and not overwritten by corresponding files in SourceDir) will be left.
291 If you need to clear them, consider using
292
293 @longCode(#
294 if DirectoryExists(DestinationDir) then
295 RemoveNonEmptyDir(DestinationDir);
296 CopyDirectory(SourceDir, DestinationDir);
297 #)
298 }
299 procedure CopyDirectory(SourcePath, DestinationPath: string);
300
301 { Substitute @code(%d) in given URL (UrlPattern) with successive numbers,
302 until the resulting URL (which can be just a filename) doesn't exist.
303
304 We start with number = 0 and do @code(Url := Format(UrlPattern, [Number])),
305 until we find non-existing URL. Example UrlPattern is @code('screenshot_%d.png'),
306 by saving to this UrlPattern you're relatively sure that each save goes
307 to a new file.
308
309 Since we use standard @code(Format) function,
310 you can use any @url(https://www.freepascal.org/docs-html/rtl/sysutils/format.html Format placeholder syntax).
311 E.g. use @code('screenshot_%.04d.png') to have a number padded with zeros,
312 with results like @code('screenshot_0005.png').
313
314 Note that it's possible on every OS that some other program,
315 or a second copy of your own program, will write to the resulting URL
316 between FileNameAutoInc determined it doesn't exist and you opened the file.
317 So using this cannot guarantee that you really always write to a new file
318 -- as always, be prepared for anything happening in parallel
319 when dealing with a filesystem.
320
321 The overloaded version with separate UrlPrefix and UrlSuffixWithPattern
322 replaces @code(%d) in UrlSuffixWithPattern,
323 and then glues (unmodified) UrlPrefix with (processed) UrlSuffixWithPattern.
324 This is useful when you have a user-specified path,
325 where you don't want to perform %d substitution.
326 Alternative is to wrap the string in @link(SUnformattable).
327
328 Example usage to save a screenshot:
329
330 @longCode(#
331 ScreenshotUrl := FileNameAutoInc(SaveScreenPath, 'screenshot_%d.png');
332 #)
333
334 Note that to save a screenshot in the most cross-platform way possible, we advise using
335 @link(TCastleContainer.SaveScreenToDefaultFile Window.Container.SaveScreenToDefaultFile)
336 instead, it will use @link(SaveScreenPath) or more elebarate mechanism to work on all platforms.
337
338 Example usage to save anything else to user config:
339
340 @longCode(#
341 SaveSomethingUrl := FileNameAutoInc(ApplicationConfig('save_something_%d.png'));
342 #)
343
344 Note that it will be replaced soon by @code(SaveSomethingUrl := FileNameAutoInc('castle-config:/', 'save_something_%d.png'))
345 which also deals with the (unlikely, but still) possibility that ApplicationConfig
346 will contain a percent sign.
347 }
348 function FileNameAutoInc(const UrlPattern: string): string; overload;
349 function FileNameAutoInc(const UrlPrefix, UrlSuffixWithPattern: string): string; overload;
350
351 function FnameAutoInc(const UrlPattern: string): string;
352 deprecated 'use FileNameAutoInc';
353
354 { Parent directory name.
355
356 Given DirName may be absolute or relative.
357 Given DirName may but doesn't have to include trailing PathDelim.
358 Result is always absolute FileName, and contains trailing PathDelim.
359
360 Returns the same DirName if there's no parent directory.
361
362 When DoExpandDirName = false then it is assumed that DirName already
363 is absolute path. Then this function is pure string-operation
364 (no actual reading of any filesystem info), so it works faster and
365 DirName does not need to exist. }
366 function ParentPath(DirName: string;
367 DoExpandDirName: Boolean = true): string;
368 deprecated 'use URLs and operate on them using CastleUriUtils unit';
369
370 { Combines BasePath with RelPath into complete path.
371
372 BasePath may be an absolute path or relative path.
373 Also RelPath may be an absolute path or relative path.
374
375 If RelPath is absolute, result is just RelPath.
376 Otherwise, result is path starting from BasePath with RelPath applied
377 (whether the result is absolute or relative depends on whether BasePath
378 was absolute or relative).
379
380 Usually you should instead operate on URLs
381 and combine them using @link(CastleUriUtils.CombineURI). }
382 function CombinePaths(BasePath, RelPath: string): string;
383
384 { Search a file on $PATH. Works with double quotes around components
385 of path list, avoiding this bug: http://bugs.freepascal.org/view.php?id=19279.
386 See http://www.freepascal.org/docs-html/rtl/sysutils/filesearch.html
387 for original FileSearch docs.
388
389 In FPC >= 2.5.1, you should instead use just ExeSearch(Name).
390 It also will use $PATH and avoid double quotes problems on Windows.
391 See http://bugs.freepascal.org/view.php?id=19282 and
392 fix on http://svn.freepascal.org/cgi-bin/viewvc.cgi?view=rev&revision=17717 . }
393 Function PathFileSearch(Const Name : String; ImplicitCurrentDir : Boolean = True) : String;
394
395 { Find program on $PATH. Automatically adds ExeExtension, so don't add it yourself.
396 On Windows, may also add alternative executable extensions (.com, .bat, .cmd).
397 Searches in $PATH (and, if OS does this, in current directory --- this is standard
398 on Windows but not on Unix).
399 Returns '' (if not found) or absolute FileName. }
400 function FindExe(const ExeName: string): string;
401
402 { Add an exe file extension, searching for an existing file starting with ExePath.
403 On non-Windows, this is just equal to ExePath + ExeExtension,
404 which in practice is just equal to ExePath (since ExeExtension is empty on Unix).
405 But on Windows, this tries to append other extensions (.com, .bat, .cmd,
406 just like @link(FindExe)), depending on what file exists. }
407 function AddExeExtension(const ExePath: string): string;
408
409 { Get temporary FileName, suitable for ApplicationName, checking that
410 it doesn't exist. }
411 function GetTempFileNameCheck: string;
412
413 { Return a prefix (beginning of an absolute FileName)
414 to save a series of temporary files. }
415 function GetTempFileNamePrefix: string;
416
417 {$ifdef DARWIN}
418 { Main directory of the current macOS bundle, including final slash.
419 Empty string if we're not run from a bundle. }
420 function BundlePath: string;
421 {$endif}
422
423 { Read file or URL contents to a string.
424 MimeType is returned, calculated just like the @link(Download) function. }
425 function FileToString(const Url: String;
426 out MimeType: string): AnsiString; overload;
427 function FileToString(const Url: String): AnsiString; overload;
428
429 procedure StringToFile(const Url: String; const Contents: AnsiString);
430
431 { Recommended path where to put screenshots on the current platform.
432 Always ends with PathDelim and returns a directory that exists.
433
434 Empty string means that we cannot recommend any safe path to store screenshots
435 (on some platforms, like mobile or console, it's not so easy to just store a file
436 in the filesystem, without any permissions;
437 and on some platforms they may have special API for this stuff). }
438 function SaveScreenPath: String;
439
440 { Calculate size of all files in this dir. }
441 function DirectorySize(const Dir: String): QWord;
442
443 implementation
444
445 uses {$ifdef MSWINDOWS} ShlObj, {$endif}
446 {$ifdef DARWIN} MacOSAll, {$endif} Classes,
447 {$ifdef FPC} Process, {$endif}
448 CastleStringUtils,
449 {$ifdef MSWINDOWS} CastleDynLib, {$endif} CastleLog,
450 CastleUriUtils, CastleFindFiles, CastleClassUtils, CastleDownload,
451 CastleApplicationProperties;
452
453 var
454 { Initialized once in initialization, afterwards constant. }
455 FExeName: string;
456
457 function ExeName: string;
458 begin
459 if FExeName = '' then
460 raise EExeNameNotAvailable.Create(
461 'ExeName: Cannot obtain FileName of executable of this program');
462 Result := FExeName;
463 end;
464
465 function ProgramName: string;
466 begin
467 Result := ApplicationName;
468 end;
469
470 function NormalFileExists(const FileName: string): Boolean;
471 begin
472 Result := RegularFileExists(FileName);
473 end;
474
475 function RegularFileExists(const FileName: string): Boolean;
476 {$ifdef MSWINDOWS}
477 var
478 S: String;
479 begin
480 {$warnings off}
481 S := UpperCase(ExtractOnlyFileName(FileName));
482 {$warnings on}
483 Result := FileExists(FileName) and
484 (not( (S = 'CON') or (S = 'PRN') or (S = 'NUL') or
485 (S = 'LPT1') or (S = 'LPT2') or (S = 'LPT3') or (S = 'LPT4') or
486 (S = 'COM1') or (S = 'COM2') or (S = 'COM3') or (S = 'COM4') ) );
487 {$else}
488 begin
489 Result := FileExists(FileName) and not DirectoryExists(FileName);
490 {$endif}
491 end;
492
493 function UserConfigPath: string;
494 begin
495 Result := ApplicationConfig('');
496 end;
497
498 function UserConfigFile(const Extension: string): string;
499 begin
500 Result := ApplicationConfig(ApplicationName + Extension);
501 end;
502
503 function ApplicationConfig(const Path: string): string;
504 var
505 ConfigDir: string;
506 begin
507 if ApplicationConfigOverride <> '' then
508 Exit(ApplicationConfigOverride + Path);
509
510 { ApplicationConfig relies that ApplicationConfigOverride is set
511 (on iOS, it's not set before CGEApp_Initialize called;
512 on Android, it's not set before AndroidMainImplementation called). }
513 if not ApplicationProperties._FileAccessSafe then
514 WritelnWarning('Using ApplicationConfig(''%s'') before the Application.OnInitialize was called. ' +
515 'This is not reliable on mobile platforms (Android, iOS). ' +
516 'This usually happens if you open a file from the "initialization" section of a unit. ' +
517 'You should do it in Application.OnInitialize instead.',
518 [Path]);
519
520 ConfigDir := InclPathDelim(GetAppConfigDir(false));
521 Result := FilenameToUriSafe(ConfigDir + Path);
522 end;
523
524 function ApplicationData(const Path: String): String;
525 begin
526 Result := 'castle-data:/' + Path;
527 end;
528
529 { other file utilities ---------------------------------------------------- }
530
531 {$ifdef UNIX}
532 function HomePath: string;
533 begin
534 { home dir jest dla mnie zmienna $HOME a nie tym co moglbym uzyskac z libc
535 pytajac o uzytkownika real uid i jego home dir zapisany w /etc/passwd.
536
537 Jest to zgodne z tym co mi radza w info libc, ze zdrowym rozsadkiem
538 (bo, jak napisali w info libc, konfigurowac $HOME jest userowi duzo
539 latwiej) i zgodne z tym co robi np. bash. Co wiecej, sprawdzilem i
540 bash rozwija $HOME nawet gdy jest zle (np. rowne 'gowno' lub '').
541
542 Gdy HOME jest niezdefiniowane lub nieprawidlowe to dopiero bash zwraca
543 homedir z user database, chociaz np. w prompt nie wyswietla ~. }
544
545 result := GetEnvironmentVariable('HOME');
546
547 { TODO: with Libc we could take home dir from user-database looking for real-uid
548
549 if (result='') or (not DirectoryExists(result)) then
550 begin
551 alloc := 0;
552 Buffer := nil;
553 repeat
554 alloc := alloc+200;
555 Buffer := Libc.Realloc(Buffer,alloc);
556 until getpwuid_r(getuid, ResultBuf, Buffer, alloc, dummy)=0;
557 SetString(result, ResultBuf.pw_dir, strlen(ResultBuf.pw_dir));
558 Libc.free(Buffer);
559 end;
560
561 }
562
563 Result := InclPathDelim(Result);
564 end;
565 {$endif}
566
567 function ExpandHomePath(const FileName: string): string;
568 {$ifdef UNIX}
569 begin
570 { Rozwin '~' w nazwe home dir. Rozwin '~/xxx' w homedir+'/xxx'. }
571 if Length(FileName) = 1 then
572 begin
573 if FileName[1] = '~' then
574 Result := ExclPathDelim(HomePath) else
575 Result := FileName;
576 end else
577 if (Length(FileName) > 0) and (FileName[1] = '~') then
578 Result := HomePath + SEnding(FileName, 3) else
579 Result := FileName;
580 {$else}
581 begin
582 result := FileName;
583 {$endif}
584 end;
585
586 procedure CheckDeleteFile(const FileName: string; const Warn: Boolean);
587 begin
588 if not SysUtils.DeleteFile(FileName) then
589 begin
590 if Warn then
591 WritelnWarning('File', Format('Cannot delete file "%s"', [FileName])) else
592 raise ERemoveFailed.Create(Format('Cannot delete file "%s"', [FileName]));
593 end;
594 end;
595
596 procedure CheckRemoveDir(const DirFileName: string; const Warn: Boolean = false);
597 begin
598 if not RemoveDir(DirFileName) then
599 begin
600 if Warn then
601 WritelnWarning('File', Format('Cannot remove directory "%s"', [DirFileName])) else
602 raise ERemoveFailed.Create(Format('Cannot remove directory "%s"', [DirFileName]));
603 end;
604 end;
605
606 procedure CheckForceDirectories(const Dir: string);
607 begin
608 if not ForceDirectories(Dir) then
609 raise Exception.CreateFmt('Cannot create directory "%s"', [Dir]);
610 end;
611
612 procedure CheckCopyFile(const Source, Dest: string);
613 var
614 SourceFile, DestFile: TFileStream;
615 begin
616 SourceFile := TFileStream.Create(Source, fmOpenRead);
617 try
618 DestFile := TFileStream.Create(Dest, fmCreate);
619 try
620 DestFile.CopyFrom(SourceFile, SourceFile.Size);
621 finally FreeAndNil(DestFile) end;
622 finally FreeAndNil(SourceFile) end;
623 end;
624
625 procedure CheckRenameFile(const Source, Dest: string);
626 begin
627 {$ifdef MSWINDOWS}
628 { On Windows, we have to remove Dest explicitly, otherwise RenameFile will fail
629 when Dest exists }
630 SysUtils.DeleteFile(Dest);
631 {$endif}
632 if not RenameFile(Source, Dest) then
633 begin
634 {$ifdef UNIX}
635 WritelnLog('File', Format('Cannot rename/move from "%s" to "%s", assuming it''s because they are on different disks, trying slower copy+delete approach', [Source, Dest]));
636 CheckCopyFile(Source, Dest);
637 CheckDeleteFile(Source, false);
638 {$else}
639 raise Exception.CreateFmt('Cannot rename/move from "%s" to "%s"', [Source, Dest]);
640 {$endif}
641 end;
642 end;
643
644 { RemoveNonEmptyDir with helpers ---------------------------------------------------------- }
645
646 procedure RemoveNonEmptyDir_Internal(const FileInfo: TFileInfo; Data: Pointer; var StopSearch: Boolean);
647 var
648 Warn: Boolean;
649 begin
650 Warn := PBoolean(Data)^;
651
652 if FileInfo.Directory and not FileInfo.Symlink then
653 RemoveNonEmptyDir(FileInfo.AbsoluteName, Warn)
654 else
655 CheckDeleteFile(FileInfo.AbsoluteName, Warn);
656 end;
657
658 procedure RemoveNonEmptyDir(const DirName: string; const Warn: Boolean = false);
659 begin
660 { Note that we don't use ffRecursive,
661 as we don't want to descend into directory with symlink.
662 We will implement recursion in RemoveNonEmptyDir_Internal manually. }
663 FindFiles(DirName, '*', true, @RemoveNonEmptyDir_Internal, @Warn, []);
664 CheckRemoveDir(Dirname, Warn);
665 end;
666
667 { CopyDirectory with helpers ------------------------------------------------- }
668
669 type
670 TCopyDirectoryHandler = class
671 SourcePath, DestinationPath: String;
672 procedure FoundFile(const FileInfo: TFileInfo; var StopSearch: Boolean);
673 end;
674
675 procedure TCopyDirectoryHandler.FoundFile(const FileInfo: TFileInfo; var StopSearch: Boolean);
676 var
677 NewFileName: String;
678 begin
679 { Safer to use FileNameCaseSensitive always.
680 On Windows, this should still be true, as we glue SourcePath with rest ourselves
681 in CastleFindFiles. }
682 if not IsPrefix(SourcePath, FileInfo.AbsoluteName, false) then
683 raise Exception.CreateFmt('Cannot copy directory, filename in source directory ("%s") does not have prefix of this directory ("%s")', [
684 FileInfo.AbsoluteName,
685 SourcePath
686 ]);
687 NewFileName := DestinationPath + PrefixRemove(SourcePath, FileInfo.AbsoluteName, false);
688 CheckForceDirectories(ExtractFilePath(NewFileName));
689 CheckCopyFile(FileInfo.AbsoluteName, NewFileName);
690 end;
691
692 procedure CopyDirectory(SourcePath, DestinationPath: String);
693 var
694 Handler: TCopyDirectoryHandler;
695 begin
696 SourcePath := ExpandFileName(InclPathDelim(SourcePath));
697 DestinationPath := ExpandFileName(InclPathDelim(DestinationPath));
698
699 Handler := TCopyDirectoryHandler.Create;
700 try
701 Handler.SourcePath := SourcePath;
702 Handler.DestinationPath := DestinationPath;
703 FindFiles(SourcePath, '*', false, {$ifdef FPC}@{$endif} Handler.FoundFile, [ffRecursive]);
704 finally FreeAndNil(Handler) end;
705 end;
706
707 { various -------------------------------------------------------------------- }
708
709 function FileNameAutoInc(const UrlPattern: string): string;
710 begin
711 Result := FileNameAutoInc('', UrlPattern);
712 end;
713
714 function FileNameAutoInc(const UrlPrefix, UrlSuffixWithPattern: string): string;
715 var
716 I: Integer;
717 begin
718 I := 0;
719 repeat
720 Result := UrlPrefix + Format(UrlSuffixWithPattern, [I]);
721 if URIExists(Result) in [ueNotExists, ueUnknown] then
722 Exit;
723 Inc(I);
724 until false;
725 end;
726
727 function FnameAutoInc(const UrlPattern: string): string;
728 begin
729 Result := FileNameAutoInc(UrlPattern);
730 end;
731
732 { Note: the only things here that makes this function belong to
733 CastleFilesUtils instead of casleutils_filenames.inc is
734 using ExpandFileName. }
735
736 function ParentPath(DirName: string; DoExpandDirName: Boolean): string;
737 var p: integer;
738 begin
739 {$ifdef MSWINDOWS}
740 { if it's only drive name - return(dirname) }
741 if (DirName[2]=DriveDelim) and
742 ( (Length(DirName)=2) or
743 ((Length(DirName)=3) and (DirName[3]=PathDelim)) ) then
744 begin
745 Result := InclPathDelim(DirName);
746 Exit;
747 end;
748 {$endif}
749 if DoExpandDirName then
750 DirName := ExpandFileName(DirName);
751 DirName := ExclPathDelim(DirName);
752 p := LastDelimiter(PathDelim, DirName);
753 if p>0 then Result := Copy(DirName,1,p) else Result := RootDir;
754 end;
755
756 function CombinePaths(BasePath, RelPath: string): string;
757 begin
758 if IsPathAbsolute(RelPath) then
759 begin
760 Result := RelPath;
761 end else
762 {$ifdef MSWINDOWS}
763 if IsPathAbsoluteOnDrive(RelPath) then
764 begin
765 if IsPathAbsolute(BasePath) then
766 Result := BasePath[1] + DriveDelim + RelPath
767 else
768 Result := RelPath;
769 end else
770 {$endif}
771 begin
772 repeat
773 if (Copy(RelPath, 1, 2) = './')
774 {$ifdef MSWINDOWS} or (Copy(RelPath, 1, 2) = '.\') {$endif} then
775 RelPath := SEnding(RelPath, 3) else
776 if (Copy(RelPath, 1, 3) = '../')
777 {$ifdef MSWINDOWS} or (Copy(RelPath, 1, 3) = '..\') {$endif} then
778 begin
779 BasePath := ExtractFileDir(ExclPathDelim(BasePath));
780 RelPath := SEnding(RelPath, 4);
781 end else
782 Break;
783 until false;
784
785 if BasePath = '' then
786 Result := RelPath
787 else
788 Result := InclPathDelim(BasePath) + RelPath;
789 end;
790 end;
791
792 Function PathFileSearch(Const Name : String; ImplicitCurrentDir : Boolean = True) : String;
793
794 {$ifdef FPC}
795
796 { This is identical to FileSearch, except on Windows each $PATH component
797 is stripped from surrounding double quotes.
798
799 Also, uses RegularFileExists instead of FileExists,
800 thus it avoids FPC FileExists inconsistency
801 (on Unix, FPC FileExists returns true).
802 It matters, otherwise e.g. searching for "fpc" on Unix
803 could find directory "fpc" that is under a directory on $PATH. }
804
805 Var
806 I : Integer;
807 Temp : String;
808
809 begin
810 Result:=Name;
811 temp:=SetDirSeparators(GetEnvironmentVariable('PATH'));
812 // Start with checking the file in the current directory
813 If ImplicitCurrentDir and (Result <> '') and RegularFileExists(Result) Then
814 exit;
815 while True do begin
816 If Temp = '' then
817 Break; // No more directories to search - fail
818 I:=pos(PathSeparator,Temp);
819 If I<>0 then
820 begin
821 Result:=Copy (Temp,1,i-1);
822 system.Delete(Temp,1,I);
823 end
824 else
825 begin
826 Result:=Temp;
827 Temp:='';
828 end;
829 If Result<>'' then
830 begin
831 { On Windows, each path on the list may be surrounded by quotes. }
832 {$ifdef MSWINDOWS}
833 if (Length(Result) >= 2) and
834 (Result[1] = '"') and
835 (Result[Length(Result)] = '"') then
836 Result := Copy(Result, 2, Length(Result) - 2);
837 {$endif}
838 Result:=IncludeTrailingPathDelimiter(Result)+name;
839 end;
840 If (Result <> '') and RegularFileExists(Result) Then
841 exit;
842 end;
843 result:='';
844 end;
845
846 {$else}
847
848 begin
849 Result := FileSearch(Name, GetEnvironmentVariable('PATH'));
850 end;
851
852 {$endif}
853
854 function FindExe(const ExeName: string): string;
855 begin
856 {$ifdef MSWINDOWS}
857 { The default order of extensions is .com, .exe, .bat, .cmd,
858 see http://stackoverflow.com/questions/605101/order-in-which-command-prompt-executes-files-with-the-same-name-a-bat-vs-a-cmd }
859 Result := PathFileSearch(ExeName + '.com', true);
860 if Result = '' then
861 Result := PathFileSearch(ExeName + '.exe' { ExeExtension }, true);
862 if Result = '' then
863 Result := PathFileSearch(ExeName + '.bat', true);
864 if Result = '' then
865 Result := PathFileSearch(ExeName + '.cmd', true);
866 {$else}
867 Result := PathFileSearch(ExeName + ExeExtension, false);
868 {$endif}
869
870 { On Windows when PathFileSearch gets ImplicitCurrentDir = true,
871 then it can return relative filename.
872 And we want to use ImplicitCurrentDir to search also the current dir
873 (as standard on Windows).
874
875 On all platforms, even disregarding ImplicitCurrentDir, PathFileSearch
876 doesn't exactly guarantee an absolute path. It should usually be true because $PATH
877 should contain only absolute paths, but this is nowhere guaranteed,
878 user can set there anything, on any OS.
879
880 So better do ExpandFileName to make sure the result in absolute,
881 as promised in FindExe API. E.g. RunCommandSimple usage in ToolCommonUtils
882 assumes it, checking IsPathAbsolute to know whether FindExe should be used again. }
883 if Result <> '' then
884 Result := ExpandFileName(Result);
885 end;
886
887 function AddExeExtension(const ExePath: string): string;
888 begin
889 {$ifdef MSWINDOWS}
890 { The default order of extensions is .com, .exe, .bat, .cmd,
891 see http://stackoverflow.com/questions/605101/order-in-which-command-prompt-executes-files-with-the-same-name-a-bat-vs-a-cmd }
892 if RegularFileExists(ExePath + '.com') then
893 Result := ExePath + '.com' else
894 if RegularFileExists(ExePath + '.exe' { ExeExtension }) then
895 Result := ExePath + '.exe' { ExeExtension } else
896 if RegularFileExists(ExePath + '.bat') then
897 Result := ExePath + '.bat' else
898 if RegularFileExists(ExePath + '.cmd') then
899 Result := ExePath + '.cmd' else
900 {$else}
901 Result := ExePath + ExeExtension;
902 {$endif}
903 end;
904
905 {$ifdef MSWINDOWS}
906 { Get preferred user directory.
907 The DirectoryId is a CSIDL_xxx constant, https://docs.microsoft.com/pl-pl/windows/win32/shell/csidl .
908
909 Returns always a directory with trailing path delimiter,
910 unless it is not possible to get then returns ''.
911 Checks that directory exists.
912 }
913 function GetUserPath(const DirectoryId: Integer): String;
914 var
915 Dir: array [0 .. MAX_PATH] of AnsiChar;
916 begin
917 if (SHGetFolderPath(0, DirectoryId, 0, 0, @Dir) = S_OK) and
918 DirectoryExists(Dir) then
919 Result := InclPathDelim(Dir)
920 else
921 Result := '';
922 end;
923 {$endif}
924
925 {$if defined(UNIX) and (not (defined(DARWIN) or defined(ANDROID) or defined(CASTLE_NINTENDO_SWITCH) or defined(CASTLE_IOS)))}
926 { Get preferred user directory, by calling xdg-user-dir
927 ( https://jlk.fjfi.cvut.cz/arch/manpages/man/xdg-user-dir.1.en ).
928
929 Returns always a directory with trailing path delimiter,
930 unless it is not possible to get then returns HomePath
931 (a safe default on normal Unix to store stuff).
932 Checks that directory exists.
933 }
934 function GetUserPath(const DirectoryId: String): String;
935 var
936 Exe, Dir: String;
937 begin
938 Result := HomePath;
939
940 {$ifdef FPC}
941 Exe := FindExe('xdg-user-dir');
942 if Exe = '' then
943 Exit;
944
945 Dir := '';
946 if RunCommand(Exe, [DirectoryId], Dir) then
947 begin
948 Dir := Trim(Dir);
949 if (Dir <> '') and DirectoryExists(Dir) then
950 Result := InclPathDelim(Dir);
951 end else
952 {$endif}
953
954 WritelnWarning('xdg-user-dir call failed');
955 end;
956 {$endif}
957
958 {$ifndef FPC}
959
960 { Get temporary FileName, also creating this file.
961 There seems to be no cross-platform function for this in Delphi. }
962 function GetTempFileNameDelphi(const Prefix: AnsiString): AnsiString;
963 {$ifdef MSWINDOWS}
964 var
965 MyPath, MyFileName: array [0..MAX_PATH] of AnsiChar;
966 begin
967 FillChar(MyPath, MAX_PATH, 0);
968 FillChar(MyFileName, MAX_PATH, 0);
969 OSCheck(GetTempPathA(SizeOf(MyPath), MyPath) <> 0);
970 OSCheck(GetTempFileNameA(MyPath, PAnsiChar(Prefix), 0, MyFileName) <> 0);
971 Result := MyFileName;
972 {$endif}
973 {$ifdef UNIX}
974 begin
975 // TODO: trivial impl for Delphi on Linux
976 Result := '/tmp/' + Prefix;
977 {$endif}
978 end;
979
980 function GetTempFileNameCheck: string;
981 begin
982 Result := GetTempFileNameDelphi(ApplicationName);
983 end;
984
985 function GetTempFileNamePrefix: string;
986 begin
987 Result := GetTempFileNameDelphi(ApplicationName);
988 end;
989 {$else}
990
991 function GetTempFileNameCheck: string;
992 begin
993 Result := GetTempFileName('', ApplicationName);
994 { Be paranoid and check whether file does not exist. }
995 if RegularFileExists(Result) or
996 DirectoryExists(Result) then
997 raise Exception.CreateFmt('Temporary file "%s" already exists', [Result]);
998 end;
999
1000 function GetTempFileNamePrefix: string;
1001 var
1002 FileInfo: TFileInfo;
1003 begin
1004 Result := GetTempFileName('', ApplicationName) + '_' +
1005 { Although GetTempFileName should add some randomization here,
1006 there's no guarantee. And we really need randomization ---
1007 we may load ffmpeg output using image %d pattern, so we don't want to
1008 accidentally pick up other images in the temporary directory
1009 (e.g. leftovers from previous TRangeScreenShot.BeginCapture). }
1010 { System.Random, not just Random, to avoid using Random from MacOSAll unit. }
1011 IntToStr(System.Random(MaxInt)) + '_';
1012
1013 { Check is it really Ok. }
1014 if FindFirstFile(Result, '*', true, [], FileInfo) then
1015 raise Exception.CreateFmt('Failed to generate unique temporary file prefix "%s": FileName "%s" already exists',
1016 [Result, FileInfo.AbsoluteName]);
1017 end;
1018
1019 {$endif}
1020
1021 {$ifdef DARWIN}
1022 var
1023 BundlePathCached: Boolean;
1024 BundlePathCache: string;
1025
1026 function BundlePath: string;
1027 { Based on
1028 http://wiki.freepascal.org/OS_X_Programming_Tips#How_to_obtain_the_path_to_the_Bundle }
1029 var
1030 bundle: CFBundleRef;
1031 pathRef: CFUrlRef;
1032 pathCFStr: CFStringRef;
1033 pathStr: shortstring;
1034 begin
1035 if not BundlePathCached then
1036 begin
1037 bundle := CFBundleGetMainBundle();
1038 if bundle = nil then
1039 begin
1040 BundlePathCache := '';
1041 WritelnLog('We cannot detect our macOS AppBundle. Probably the application was run directly (like a Unix application, without being wrapped in a directory like "xxx.app"). Some GUI features (like application menu) will not work without running through AppBundle.');
1042 end else
1043 begin
1044 pathRef := CFBundleCopyBundleUrl(bundle);
1045 pathCFStr := CFUrlCopyFileSystemPath(pathRef, kCFUrlPOSIXPathStyle);
1046 CFStringGetPascalString(pathCFStr, @pathStr, 255, CFStringGetSystemEncoding());
1047 CFRelease(pathRef);
1048 CFRelease(pathCFStr);
1049 BundlePathCache := pathStr;
1050 BundlePathCache := InclPathDelim(BundlePathCache);
1051 end;
1052 BundlePathCached := true;
1053 end;
1054 Result := BundlePathCache;
1055 end;
1056 {$endif DARWIN}
1057
1058 function FileToString(const Url: String;
1059 out MimeType: string): AnsiString;
1060 var
1061 F: TStream;
1062 begin
1063 F := Download(Url, [], MimeType);
1064 try
1065 { Some streams can be optimized, just load file straight to string memory }
1066 if (F is TFileStream) or
1067 (F is TMemoryStream) then
1068 begin
1069 SetLength(Result, F.Size);
1070 if F.Size <> 0 then
1071 F.ReadBuffer(Result[1], Length(Result));
1072 end else
1073 Result := ReadGrowingStreamToString(F);
1074 finally FreeAndNil(F) end;
1075 end;
1076
1077 function FileToString(const Url: String): AnsiString;
1078 var
1079 MimeType: string;
1080 begin
1081 Result := FileToString(Url, MimeType { ignored });
1082 end;
1083
1084 procedure StringToFile(const Url: String; const Contents: AnsiString);
1085 var
1086 F: TStream;
1087 begin
1088 F := UrlSaveStream(Url);
1089 try
1090 if Length(Contents) <> 0 then
1091 F.WriteBuffer(Contents[1], Length(Contents));
1092 finally FreeAndNil(F) end;
1093 end;
1094
1095 var
1096 CachedSaveScreenPath: String;
1097 HasCachedSaveScreenPath: Boolean;
1098
1099 function SaveScreenPath: String;
1100 begin
1101 if HasCachedSaveScreenPath then
1102 Exit(CachedSaveScreenPath);
1103
1104 {$if defined(ANDROID) or defined(CASTLE_IOS) or defined(CASTLE_NINTENDO_SWITCH)}
1105 { These platforms require special treatment. Although we could use
1106
1107 Result := UriToFilenameSafe(ApplicationConfig(''));
1108
1109 but then we risk storing more data than expected (users/OS don't expect us
1110 to fill this space uncontrollably, and users also don't have direct
1111 access to the ApplicationConfig space). }
1112 Result := '';
1113 {$else}
1114 {$if defined(DARWIN)}
1115 Result := HomePath; // TODO: probably there's some macOS specific API to get this
1116 {$elseif defined(UNIX)}
1117 Result := GetUserPath('PICTURES');
1118 {$elseif defined(MSWINDOWS)}
1119 Result := GetUserPath(CSIDL_MYPICTURES);
1120 {$else}
1121 Result := '';
1122 {$endif}
1123 {$endif}
1124
1125 CachedSaveScreenPath := Result;
1126 HasCachedSaveScreenPath := true;
1127 end;
1128
1129 { DirectorySize utility ------------------------------------------------------ }
1130
1131 type
1132 TDirectorySizeHelper = class
1133 public
1134 { Total size of all files in the directory. }
1135 Size: QWord;
1136 procedure FoundFile(const FileInfo: TFileInfo; var StopSearch: Boolean);
1137 end;
1138
1139 procedure TDirectorySizeHelper.FoundFile(const FileInfo: TFileInfo; var StopSearch: Boolean);
1140 begin
1141 Size := Size + FileInfo.Size;
1142 end;
1143
1144 function DirectorySize(const Dir: String): QWord;
1145 var
1146 Helper: TDirectorySizeHelper;
1147 begin
1148 Helper := TDirectorySizeHelper.Create;
1149 try
1150 FindFiles(Dir, '*', false, {$ifdef FPC}@{$endif}Helper.FoundFile, [ffRecursive]);
1151 Result := Helper.Size;
1152 finally FreeAndNil(Helper) end;
1153 end;
1154
1155 procedure InitializeExeName;
1156 {$ifdef LINUX}
1157 var
1158 ExeLinkName: String;
1159 {$endif}
1160 begin
1161 { Initialize FExeName. }
1162 FExeName :=
1163 {$ifdef MSWINDOWS} ExeNameFromGetModule
1164 // On non-Windows OSes, using ParamStr(0) for this is not reliable, but at least it's some default
1165 {$else} ParamStr(0)
1166 {$endif};
1167
1168 {$if defined(LINUX) and defined(FPC)}
1169 // TODO: we could port this to Delphi
1170 { Under Linux, try to use /proc/getpid()/exe.
1171 This is more reliable than ParamStr(0),
1172 as ParamStr(0) is set by the calling process,
1173 and it may be absolute or relative, it may be symlink,
1174 and in general it may contain anything. }
1175 ExeLinkName := '/proc/' + IntToStr(FpGetpid) + '/exe';
1176 try
1177 FExeName := CastleReadLink(ExeLinkName);
1178 except
1179 on EOSError do
1180 WritelnWarning('Cannot read "%s" (to get ExeName on Linux)', [ExeLinkName]);
1181 end;
1182 {$endif}
1183 end;
1184
1185 initialization
1186 InitializeExeName;
1187 end.