- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommon.ShellFileSupport.pas
More file actions
Latest commit
524 lines (433 loc) · 14.9 KB
/
Copy pathCommon.ShellFileSupport.pas
File metadata and controls
524 lines (433 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
{*******************************************************}
{ YAGE: Yet Another Global Encoder }
{ Unit: Common.ShellFileSupport }
{ Copyright(c) 2016 Alexander Alexeev }
{*******************************************************}
unit Common.ShellFileSupport;
{$MODE Delphi}
interface
uses
LazUTF8;
type
TDriveNumber = 0..25;
TPathCharType = (gctInvalid, gctLFNChar, gctSeparator, gctShortChar, gctWild);
TPathCharTypes = setof TPathCharType;
TCleanupResult = (pcsReplacedChar, pcsRemovedChar, pcsTruncated);
TCleanupResults = setof TCleanupResult;
PCleanupResults = ^TCleanupResults;
const
InvalidDrive = TDriveNumber(-1);
// Returns the type of character from the path
functionPathGetCharType(const AChar: Char): TPathCharTypes;
// Returns the disk number from the path (InvalidDrive on error)
functionPathGetDriveNumber(const APath: string): TDriveNumber;
// Generates the path to the root directory of the specified disk
functionPathBuildRoot(const ADrive: TDriveNumber): string;
// Canonizes a path by removing special directories from it. and '..'
functionPathCanonicalize(const APath: string): string;
// Connects two paths, adding a path separator if necessary
functionPathAppend(const APath, AMore: string): string;
// Similar to PathAppend, but returns the canonical path (with the remote '.' And '..')
functionPathCombine(const APath, AMore: string): string;
// Returns True if the specified path (file / directory) exists
// Implement in case you don’t want to use the great FileExists / DirectoryExists from Delphi
// Cm.
// http://qc.embarcadero.com/wc/qcmain.aspx?d=3513
// http://qc.embarcadero.com/wc/qcmain.aspx?d=10731
// http://qc.embarcadero.com/wc/qcmain.aspx?d=52905
functionPathFileExists(const APath: string): Boolean;
// Returns true if the path is a directory
// Implement in case you don’t want to use the great FileExists / DirectoryExists from Delphi
// Cm.
// http://qc.embarcadero.com/wc/qcmain.aspx?d=3513
// http://qc.embarcadero.com/wc/qcmain.aspx?d=10731
// http://qc.embarcadero.com/wc/qcmain.aspx?d=52905
functionPathIsDirectory(const APath: string): Boolean;
// Returns True if the path does not contain path delimiters (':' and '\')
functionPathIsFileSpec(const APath: string): Boolean;
// Returns true if the path is relative
functionPathIsRelative(const APath: string): Boolean;
// Returns true if the path is absolute
functionPathIsAbsolute(const APath: string): Boolean;
// Enclose the string in quotes if necessary (presence of spaces)
functionPathQuoteSpaces(const APath: string; const AForce: Boolean = False): string;
// Generates a relative path to the ATo from (relatively) AFrom (the slave '\' denotes the directory)
functionPathRelativePathTo(const AFrom, ATo: string): string;
// Allows relative name to absolute, additionally canonizing the path
functionPathSearchAndQualifyA(const APath: string): string;
// Returns a short name for a long
functionPathGetShortPath(const APath: string): string;
// Returns a long name for a short
functionPathGetLFNPath(const APath: string): string;
// Returns True, if the path is valid
functionPathIsValid(const APath: string): Boolean;
// Creates a command line to run the program. The result of this function can be passed to CreateProcess.
functionPathProcessCommand(const AProgram: string; const AParameters: arrayof string): string;
implementation
{$A+}
{$R+}
{$Z4}
{$WARN SYMBOL_PLATFORM OFF}
uses
Windows, SysUtils;
functionKernel32: HMODULE; forward;
functionShlwAPI: HMODULE; forward;
{$IFNDEF UNICODE}
type
Unicodestring = Widestring;
{$ENDIF}
procedureCreateBuffer(out Buffer: string; const ALen: Integer); overload;
begin
SetLength(Buffer, ALen);
FillChar(Pointer(Buffer)^, ALen * SizeOf(Char), 0);
end;
procedureCreateBuffer(out Buffer: string; const APath: string); overload;
begin
CreateBuffer(Buffer, MAX_PATH);
Move(Pointer(APath)^, Pointer(Buffer)^, Length(APath) * SizeOf(Char));
end;
{$IFNDEF UNICODE}
procedureCreateBuffer(out Buffer: Unicodestring; const ALen: Integer); overload;
begin
SetLength(Buffer, ALen);
FillChar(Pointer(Buffer)^, ALen * SizeOf(WideChar), 0);
end;
procedureCreateBuffer(out Buffer: Unicodestring; const APath: string); overload;
var
Path: Unicodestring;
begin
CreateBuffer(Buffer, MAX_PATH);
Path := APath;
Move(Pointer(Path)^, Pointer(Buffer)^, Length(APath) * SizeOf(WideChar));
end;
{$ENDIF}
functionPathQuoteSpaces(const APath: string; const AForce: Boolean): string;
begin
if (not AForce) and
(Pos('', APath) <= 0) and
(Pos('"', APath) <= 0) then
begin
Result := APath;
Exit;
end;
Result := '"' + stringReplace(APath, '"', '\"', [rfReplaceAll]) + '"';
if (Length(Result) > 2) and
(Result[Length(Result) - 1] = '"') then
Insert('\', Result, Length(Result) - 1);
end;
var
FPathRelativePathTo: function(APath, AFrom: PChar; AttrFrom: DWORD; ATo: PChar; AttrTo: DWORD): BOOL; stdcall;
functionPathRelativePathTo(const AFrom, ATo: string): string;
var
Buffer, From, ToD: string;
AttrFrom, AttrTo: DWORD;
begin
ifnot Assigned(FPathRelativePathTo) then
begin
FPathRelativePathTo := GetProcAddress(ShlwAPI, {$IFDEF UNICODE}'PathRelativePathToW'{$ELSE}'PathRelativePathToA'{$ENDIF});
Win32Check(Assigned(FPathRelativePathTo));
end;
Assert(AFrom <> '');
Assert(ATo <> '');
if AFrom[Length(AFrom)] = PathDelim then
AttrFrom := FILE_ATTRIBUTE_DIRECTORY
else
AttrFrom := 0;
if ATo[Length(ATo)] = PathDelim then
AttrTo := FILE_ATTRIBUTE_DIRECTORY
else
AttrTo := 0;
From := ExcludeTrailingPathDelimiter(PathCanonicalize(AFrom));
ToD := ExcludeTrailingPathDelimiter(PathCanonicalize(ATo));
CreateBuffer(Buffer, MAX_PATH);
if FPathRelativePathTo(PChar(Buffer), PChar(From), AttrFrom, PChar(ToD), AttrTo) then
Result := PChar(Buffer)
else
Result := '';
end;
var
FGetShortPathName: function(ALong, AShort: PChar; Len: Integer): Integer; stdcall;
functionPathGetShortPath(const APath: string): string;
begin
ifnot Assigned(FGetShortPathName) then
begin
FGetShortPathName := GetProcAddress(Kernel32, {$IFDEF UNICODE}'GetShortPathNameW'{$ELSE}'GetShortPathNameA'{$ENDIF});
Win32Check(Assigned(FGetShortPathName));
end;
CreateBuffer(Result, 32768);
SetLength(Result, FGetShortPathName(PChar(APath), PChar(Result), 32768));
if Result = ''then
Result := APath;
end;
var
FGetLongPathName: function(AShort, ALong: PChar; Len: Integer): Integer; stdcall;
functionPathGetLFNPath(const APath: string): string;
begin
ifnot Assigned(FGetLongPathName) then
begin
FGetLongPathName := GetProcAddress(Kernel32, {$IFDEF UNICODE}'GetLongPathNameW'{$ELSE}'GetLongPathNameA'{$ENDIF});
Win32Check(Assigned(FGetLongPathName));
end;
CreateBuffer(Result, 32768);
SetLength(Result, FGetLongPathName(PChar(APath), PChar(Result), 32768));
if Result = ''then
Result := APath;
end;
functionPathProcessCommand(const AProgram: string; const AParameters: arrayof string): string;
var
X: Integer;
Param: string;
begin
Result := PathQuoteSpaces(AProgram);
for X := 0to High(AParameters) do
begin
if PathFileExists(AParameters[X]) then
Param := PathQuoteSpaces({$IFDEF UNICODE}PathGetShortPath({$ENDIF}AParameters[X]{$IFDEF UNICODE}){$ENDIF})
else
Param := PathQuoteSpaces(AParameters[X]);
Result := Result + '' + Param;
end;
end;
functionPathIsValid(const APath: string): Boolean;
const
UNCWPrefix = '\\?';
var
Path: string;
I: Integer;
begin
Result := False;
if APath = ''then
Exit;
// The function splits the path into parts and checks each part by calling MoveFile
// MoveFile will return either OK or ERROR_ALREADY_EXISTS for the correct parts;
// and returns other errors for reserved characters, reserved names (COM, etc.), unsupported characters to the underlying file system Result := False;
Path := APath;
repeat
I := LastDelimiter('\/', Path);
if (Path <> '') and
(
(Path[Length(Path)] = '.') or
(Path[Length(Path)] = '')
) then
Exit;
MoveFile(nil, PChar(Path));
if (GetLastError = ERROR_ALREADY_EXISTS) or
(
(GetFileAttributes(PChar(Copy(Path, I + 1, MaxInt))) = INVALID_FILE_ATTRIBUTES) and
(GetLastError = ERROR_INVALID_NAME)
) then
Exit;
if I > 0then
Path := Copy(Path, 1, I - 1);
if (I = 4) and (Path = UNCWPrefix) then
I := 0;
until I = 0;
Result := True;
end;
functionPathAppend(const APath, AMore: string): string;
var
Path, More: string;
begin
if AMore = ''then
begin
Result := APath;
Exit;
end;
Path := stringReplace(APath, '/', PathDelim, [rfReplaceAll]);
More := stringReplace(AMore, '/', PathDelim, [rfReplaceAll]);
if More[1] = PathDelim then
Result := ExcludeTrailingPathDelimiter(Path) + More
else
Result := IncludeTrailingPathDelimiter(Path) + More;
end;
functionPathCombine(const APath, AMore: string): string;
begin
Result := PathCanonicalize(PathAppend(APath, AMore));
end;
var
FPathGetCharType: function(Ch: Char): UINT; stdcall;
functionPathGetCharType(const AChar: Char): TPathCharTypes;
const
GCT_INVALID = 0;
GCT_LFNCHAR = 1;
GCT_SHORTCHAR = 2;
GCT_WILD = 4;
GCT_SEPARATOR = 8;
var
R: UINT;
begin
Result := [];
ifnot Assigned(FPathGetCharType) then
begin
FPathGetCharType := GetProcAddress(ShlwAPI, {$IFDEF UNICODE}'PathGetCharTypeW'{$ELSE}'PathGetCharTypeA'{$ENDIF});
Win32Check(Assigned(FPathGetCharType));
end;
R := FPathGetCharType(AChar);
if R = GCT_INVALID then
begin
Result := [gctInvalid];
Exit;
end;
if (R and GCT_LFNCHAR) <> 0then
Include(Result, gctLFNChar);
if (R and GCT_SEPARATOR) <> 0then
Include(Result, gctSeparator);
if (R and GCT_SHORTCHAR) <> 0then
Include(Result, gctShortChar);
if (R and GCT_WILD) <> 0then
Include(Result, gctWild);
end;
var
FPathGetDriveNumber: function(Path: PChar): Integer; stdcall;
functionPathGetDriveNumber(const APath: string): TDriveNumber;
var
R: Integer;
begin
ifnot Assigned(FPathGetDriveNumber) then
begin
FPathGetDriveNumber := GetProcAddress(ShlwAPI, {$IFDEF UNICODE}'PathGetDriveNumberW'{$ELSE}'PathGetDriveNumberA'{$ENDIF});
Win32Check(Assigned(FPathGetDriveNumber));
end;
R := FPathGetDriveNumber(PChar(APath));
if R < 0then
Result := InvalidDrive
else
Result := TDriveNumber(R);
end;
var
FPathBuildRoot: function(Root: PChar; I: Integer): PChar; stdcall;
functionPathBuildRoot(const ADrive: TDriveNumber): string;
var
Buffer: string;
begin
ifnot Assigned(FPathBuildRoot) then
begin
FPathBuildRoot := GetProcAddress(ShlwAPI, {$IFDEF UNICODE}'PathBuildRootW'{$ELSE}'PathBuildRootA'{$ENDIF});
Win32Check(Assigned(FPathBuildRoot));
end;
CreateBuffer(Buffer, 4);
Result := FPathBuildRoot(PChar(Buffer), Ord(ADrive));
end;
var
FPathCanonicalize: function(ADst, ASrc: PChar): BOOL; stdcall;
functionPathCanonicalize(const APath: string): string;
var
Buffer, Path: string;
X: Integer;
begin
ifnot Assigned(FPathCanonicalize) then
begin
FPathCanonicalize := GetProcAddress(ShlwAPI, {$IFDEF UNICODE}'PathCanonicalizeW'{$ELSE}'PathCanonicalizeA'{$ENDIF});
Win32Check(Assigned(FPathCanonicalize));
end;
CreateBuffer(Buffer, MAX_PATH);
Path := stringReplace(APath, '/', PathDelim, [rfReplaceAll]);
Win32Check(FPathCanonicalize(PChar(Buffer), PChar(Path)));
Result := PChar(Buffer);
// Remove double '\'
for X := Length(Result) downto3do
if (Result[X] = PathDelim) and
(Result[X - 1] = PathDelim) then
Delete(Result, X, 1);
end;
var
FPathSearchAndQualify: function(APath, AFullyQualifiedPath: PChar; Len: UINT): BOOL; stdcall;
functionPathSearchAndQualifyA(const APath: string): string;
var
Buffer: string;
begin
ifnot Assigned(FPathSearchAndQualify) then
begin
FPathSearchAndQualify := GetProcAddress(ShlwAPI, 'PathSearchAndQualifyA');
Win32Check(Assigned(FPathSearchAndQualify));
end;
CreateBuffer(Buffer, MAX_PATH);
Win32Check(FPathSearchAndQualify(PChar(APath), PChar(Buffer), MAX_PATH));
Result := PChar(Buffer);
end;
var
FPathFileExists: function(Path: PChar): BOOL; stdcall;
functionPathFileExists(const APath: string): Boolean;
begin
ifnot Assigned(FPathFileExists) then
begin
FPathFileExists := GetProcAddress(ShlwAPI, {$IFDEF UNICODE}'PathFileExistsW'{$ELSE}'PathFileExistsA'{$ENDIF});
Win32Check(Assigned(FPathFileExists));
end;
Result := FPathFileExists(PChar(APath));
end;
var
FPathIsDirectory: function(Path: PChar): UINT; stdcall;
functionPathIsDirectory(const APath: string): Boolean;
begin
ifnot Assigned(FPathIsDirectory) then
begin
FPathIsDirectory := GetProcAddress(ShlwAPI, {$IFDEF UNICODE}'PathIsDirectoryW'{$ELSE}'PathIsDirectoryA'{$ENDIF});
Win32Check(Assigned(FPathIsDirectory));
end;
Result := FPathIsDirectory(PChar(APath)) <> 0;
end;
var
FPathIsFileSpec: function(Path: PChar): BOOL; stdcall;
functionPathIsFileSpec(const APath: string): Boolean;
begin
ifnot Assigned(FPathIsFileSpec) then
begin
FPathIsFileSpec := GetProcAddress(ShlwAPI, {$IFDEF UNICODE}'PathIsFileSpecW'{$ELSE}'PathIsFileSpecA'{$ENDIF});
Win32Check(Assigned(FPathIsFileSpec));
end;
Result := FPathIsFileSpec(PChar(APath));
end;
var
FPathIsRelative: function(Path: PChar): BOOL; stdcall;
functionPathIsRelative(const APath: string): Boolean;
var
X: Integer;
begin
// http://stackoverflow.com/questions/26099361/is-it-a-winapi-bug-with-pathisrelative-function
X := Pos(':', APath);
if (X > 0) and
(X < Length(APath)) and
(APath[X + 1] <> PathDelim) and
(APath[X + 1] <> '/') then
begin
Result := True;
Exit;
end;
ifnot Assigned(FPathIsRelative) then
begin
FPathIsRelative := GetProcAddress(ShlwAPI, {$IFDEF UNICODE}'PathIsRelativeW'{$ELSE}'PathIsRelativeA'{$ENDIF});
Win32Check(Assigned(FPathIsRelative));
end;
Result := FPathIsRelative(PChar(APath));
end;
functionPathIsAbsolute(const APath: string): Boolean;
begin
Result := not PathIsRelative(APath);
end;
var
FKernelLib: HMODULE;
FShlwAPILib: HMODULE;
functionKernel32: HMODULE;
const
DLLName = 'kernel32.dll';
begin
if FKernelLib = 0then
begin
FKernelLib := LoadLibrary(DLLName);
Win32Check(FKernelLib <> 0);
end;
Result := FKernelLib;
end;
functionShlwAPI: HMODULE;
const
DLLName = 'shlwapi.dll';
begin
if FShlwAPILib = 0then
begin
FShlwAPILib := LoadLibrary(DLLName);
Win32Check(FShlwAPILib <> 0);
end;
Result := FShlwAPILib;
end;
end.