-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathCompressPath.dpr
More file actions
489 lines (449 loc) · 14.8 KB
/
CompressPath.dpr
File metadata and controls
489 lines (449 loc) · 14.8 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
program CompressPath;
{$APPTYPE CONSOLE}
{$R *.res}
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Classes,
System.IOUtils,
System.Win.Registry;
type
TPathCompressor = class
private
FOrgLength: Integer;
FPath: TStringList;
FPathDelphi: string;
FPathMyDocs: string;
FPathProgramFiles: string;
FPathProgramFilesX86: string;
FPathSharedDocs: string;
FRegistry: TRegistry;
FShortcuts: TStringList;
FVariables: TStringList;
function ExpandEnvironmentVars(const Value: string): string;
protected
procedure AddShortCut(const Key, Value: string);
procedure AddDelphiShortCut(const Key, RelExePath, RelDocPath: string); overload;
procedure AddOldDelphiShortCut(const Key, RelExePath, RelDocPath: string); overload;
function Compress(const Value: string): string;
function GetExistingPath(const Prefix, RelPath: string): string; overload;
function GetExistingPath(const Prefix: array of string; const RelPath: string): string; overload;
procedure InitShortCuts;
function ReadRegistry(const AName: string): string;
procedure RemoveDuplicates;
function StorePath: Integer;
procedure StoreVariables;
procedure WriteRegistry( const xName,
xValue: string;
const xIsVariable: Boolean);
property OrgLength: Integer read FOrgLength;
property Path: TStringList read FPath;
property PathDelphi: string read FPathDelphi;
property PathMyDocs: string read FPathMyDocs;
property PathProgramFiles: string read FPathProgramFiles;
property PathProgramFilesX86: string read FPathProgramFilesX86;
property PathSharedDocs: string read FPathSharedDocs;
property Registry: TRegistry read FRegistry;
property Shortcuts: TStringList read FShortcuts;
property Variables: TStringList read FVariables;
public
constructor Create;
destructor Destroy; override;
procedure Execute(out OldLength, NewLength: Integer);
function LoadPath(UserEnvironment: Boolean): Boolean;
procedure LoadShortCuts(const AFileName: string);
procedure StoreShortCuts(const AFileName: string);
procedure NotifyChanges;
end;
constructor TPathCompressor.Create;
begin
inherited Create;
FShortcuts := TStringList.Create;
FVariables := TStringList.Create;
FVariables.Sorted := true;
FVariables.Duplicates := dupIgnore;
FPath := TStringList.Create;
FPath.Delimiter := ';';
FPath.StrictDelimiter := true;
{$IFDEF DEBUG}
{ It is quite unlikely that we have write permission to HKEY_LOCAL_MACHINE when we are running from inside the IDE.
In addition it doesn't make much sense to run in DEBUG mode outside of the IDE. Hence this restriction. There are
other places where we check for DEBUG mode. In case you get unexpected results, please have a look for those. }
FRegistry := TRegistry.Create(KEY_READ);
{$ELSE}
FRegistry := TRegistry.Create();
{$ENDIF}
FPathMyDocs := TPath.GetDocumentsPath;
FPathSharedDocs := TPath.GetSharedDocumentsPath;
FPathProgramFilesX86 := GetEnvironmentVariable('ProgramFiles(x86)');
if FPathProgramFilesX86 = '' then begin
FPathProgramFiles := GetEnvironmentVariable('ProgramFiles');
FPathDelphi := FPathProgramFiles;
end
else begin
FPathProgramFiles := GetEnvironmentVariable('ProgramW6432');
FPathDelphi := FPathProgramFilesX86;
end;
InitShortCuts;
end;
destructor TPathCompressor.Destroy;
begin
FRegistry.Free;
FPath.Free;
FVariables.Free;
FShortcuts.Free;
inherited Destroy;
end;
procedure TPathCompressor.AddShortCut(const Key, Value: string);
begin
{ Shortcuts are only usefull when they contain some data. }
if Value > '' then begin
Shortcuts.Values[Key] := Value;
end;
end;
procedure TPathCompressor.AddDelphiShortCut(const Key, RelExePath, RelDocPath: string);
begin
AddShortCut(Key, GetExistingPath(PathDelphi, RelExePath));
{ Depending on the type of installation (current user or all users), the BPLs are located
in different documents folders. Here we first check inside the personal folder and
if that doesn't exist, we take the public documents folder.
}
AddShortCut(Key + 'BPL', GetExistingPath([PathMyDocs, PathSharedDocs], RelDocPath));
end;
procedure TPathCompressor.AddOldDelphiShortCut(const Key, RelExePath, RelDocPath: string);
begin
AddShortCut(Key, GetExistingPath(PathDelphi, RelExePath));
{ In older Delphi versions the BPL folder resides below the Delphi folder. }
AddShortCut(Key + 'BPL', GetExistingPath(PathDelphi, RelDocPath));
end;
function TPathCompressor.Compress(const Value: string): string;
var
S: string;
N: Integer;
L: Integer;
I: Integer;
begin
{ Find the Shortcut that will replace the longest string from the beginning of Value.
Ideally it will replace the whole string.
}
N := -1;
L := 0;
for I := 0 to Shortcuts.Count - 1 do begin
S := Shortcuts.ValueFromIndex[I];
if Value.StartsWith(S, true) and (L < S.Length) then begin
N := I;
L := S.Length;
end;
end;
if L > 0 then begin
{ Replace the Shortcut and remember to add a similar variable. }
result := Value.Remove(0, L).Insert(0, '%' + Shortcuts.Names[N] + '%');
Variables.Append(Shortcuts[N]);
end
else begin
{ Nothing to compress. }
result := Value;
end;
end;
procedure TPathCompressor.Execute(out OldLength, NewLength: Integer);
{ Returns the old and new length of the PATH variable. }
var
I: Integer;
begin
Variables.Clear;
OldLength := OrgLength;
for I := 0 to Path.Count - 1 do begin
Path[I] := Compress(Path[I]);
end;
RemoveDuplicates;
StoreVariables;
NewLength := StorePath;
end;
function TPathCompressor.ExpandEnvironmentVars(const Value: string): string;
var
buffer: TCharArray;
res: Cardinal;
begin
Result := Value;
SetLength(Buffer, 32*1024);
res := ExpandEnvironmentStrings(PChar(Value), @Buffer[0], Length(Buffer) - 1);
if res > 0 then begin
Result := PChar(@Buffer[0]);
end;
end;
function TPathCompressor.GetExistingPath(const Prefix: array of string; const
RelPath: string): string;
var
S: string;
begin
for S in Prefix do begin
Result := S + RelPath;
if TDirectory.Exists(Result) then Exit;
end;
Result := '';
end;
function TPathCompressor.GetExistingPath(const Prefix, RelPath: string): string;
begin
Result := GetExistingPath([Prefix], RelPath);
end;
procedure TPathCompressor.InitShortCuts;
begin
(*
%SYSTEMROOT% wird durch "C:\Windows" ersetzt
-> nicht machen, rückgängig
USERPROFILE wird unter den Benutzer-Variablen hinzugefügt
-> Nicht machen, löschen
Windows Umgebungs-Variablen dann nicht mehr mit "neuem" Editor sondern Textzeile?
*)
AddShortCut('SystemRoot', GetEnvironmentVariable( 'SYSTEMROOT'));
{ User Profile }
AddShortCut('USERPROFILE', GetEnvironmentVariable( 'USERPROFILE'));
{ Program Files }
AddShortCut('PF', PathProgramFiles);
AddShortCut('PF86', PathProgramFilesX86);
{ SQL Server }
AddShortCut('SQL', GetExistingPath(PathProgramFiles, '\Microsoft SQL Server'));
AddShortCut('SQL86', GetExistingPath(PathProgramFilesX86, '\Microsoft SQL Server'));
{ TODO : Add folders for missing Delphi versions}
{ Delphi 7 }
AddOldDelphiShortCut('D7', '\Borland\Delphi7', '\Borland\Delphi7\Projects\Bpl');
{ Delphi D2007+ }
AddDelphiShortCut('D2007', '\CodeGear\RAD Studio\5.0', '\RAD Studio\5.0\Bpl');
AddDelphiShortCut('D2009', '\CodeGear\RAD Studio\6.0', '\RAD Studio\6.0\Bpl');
AddDelphiShortCut('D2010', '\Embarcadero\RAD Studio\7.0', '\RAD Studio\7.0\Bpl');
AddDelphiShortCut('XE', '\Embarcadero\RAD Studio\8.0', '\RAD Studio\8.0\Bpl');
AddDelphiShortCut('XE2', '\Embarcadero\RAD Studio\9.0', '\RAD Studio\9.0\Bpl');
AddDelphiShortCut('XE3', '\Embarcadero\RAD Studio\10.0', '\RAD Studio\10.0\Bpl');
AddDelphiShortCut('XE4', '\Embarcadero\RAD Studio\11.0', '\RAD Studio\11.0\Bpl');
AddDelphiShortCut('XE5', '\Embarcadero\RAD Studio\12.0', '\RAD Studio\12.0\Bpl');
AddDelphiShortCut('XE6', '\Embarcadero\Studio\14.0', '\Embarcadero\Studio\14.0\Bpl');
AddDelphiShortCut('XE7', '\Embarcadero\Studio\15.0', '\Embarcadero\Studio\15.0\Bpl');
AddDelphiShortCut('XE8', '\Embarcadero\Studio\16.0', '\Embarcadero\Studio\16.0\Bpl');
AddDelphiShortCut('DX', '\Embarcadero\Studio\17.0', '\Embarcadero\Studio\17.0\Bpl');
AddDelphiShortCut('DX1', '\Embarcadero\Studio\18.0', '\Embarcadero\Studio\18.0\Bpl');
AddDelphiShortCut('DX2', '\Embarcadero\Studio\19.0', '\Embarcadero\Studio\19.0\Bpl');
AddDelphiShortCut('DX3', '\Embarcadero\Studio\20.0', '\Embarcadero\Studio\20.0\Bpl');
AddDelphiShortCut('DX4', '\Embarcadero\Studio\21.0', '\Embarcadero\Studio\21.0\Bpl');
AddDelphiShortCut('D11', '\Embarcadero\Studio\22.0', '\Embarcadero\Studio\22.0\Bpl');
AddDelphiShortCut('D12', '\Embarcadero\Studio\23.0', '\Embarcadero\Studio\23.0\Bpl');
AddDelphiShortCut('D13', '\Embarcadero\Studio\37.0', '\Embarcadero\Studio\37.0\Bpl');
end;
function TPathCompressor.LoadPath(UserEnvironment: Boolean): Boolean;
const
cKeyHKLM = 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment';
cKeyHKCU = 'Environment';
var
S: string;
RegKey: string;
begin
Path.Clear;
if UserEnvironment then begin
Registry.RootKey := HKEY_CURRENT_USER;
RegKey := cKeyHKCU;
end
else begin
Registry.RootKey := HKEY_LOCAL_MACHINE;
RegKey := cKeyHKLM;
end;
result := Registry.OpenKey(RegKey, false);
if result then begin
S := ReadRegistry('Path');
Path.DelimitedText := ExpandEnvironmentVars(S);
FOrgLength := S.Length;
end;
end;
procedure TPathCompressor.LoadShortCuts(const AFileName: string);
begin
Shortcuts.LoadFromFile(AFileName);
end;
procedure TPathCompressor.StoreShortCuts(const AFileName: string);
begin
Shortcuts.SaveToFile(AFileName);
end;
procedure TPathCompressor.NotifyChanges;
{ Sending a WM_SETTINGCHANGE message to all top level windows. Otherwise the new environment variables
will only be visible after logoff/logon. }
begin
{$IFDEF DEBUG}
Exit;
{$ENDIF}
SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, NativeInt(PChar('Environment')), SMTO_ABORTIFHUNG, 5000, nil);
end;
function TPathCompressor.ReadRegistry(const AName: string): string;
begin
result := Registry.ReadString(AName);
end;
procedure TPathCompressor.RemoveDuplicates;
var
lst: TStringList;
S: string;
I: Integer;
N: Integer;
begin
lst := TStringList.Create;
try
lst.Sorted := true;
lst.Duplicates := dupIgnore;
for S in Path do begin
lst.Add(S);
end;
I := 0;
while I < Path.Count do begin
if lst.Find(Path[I], N) then begin
lst.Delete(N);
Inc(I);
end
else begin
Path.Delete(I);
end;
end;
finally
lst.Free;
end;
end;
function TPathCompressor.StorePath: Integer;
var
S: string;
begin
S := Path.DelimitedText;
WriteRegistry( 'Path',
S,
False);
result := S.Length;
end;
procedure TPathCompressor.StoreVariables;
var
I: Integer;
lVariable: String;
begin
Variables.Sort;
for I := 0 to Variables.Count - 1 do
begin
lVariable := Variables.Names[ I].Trim.ToUpper;
//*** skip Windows default
if not ( lVariable.Equals( 'SYSTEMROOT') or
lVariable.Equals( 'USERPROFILE')) then
begin
WriteRegistry( Variables.Names[ I],
Variables.ValueFromIndex[ I],
True);
end;
end;
end;
procedure TPathCompressor.WriteRegistry( const xName,
xValue: string;
const xIsVariable: Boolean);
var
lExistingPath: String;
begin
if not xIsVariable or
not Registry.ValueExists( xName) then
begin
{$IFDEF DEBUG}
{ In DEBUG mode only show the changes that would be made to the registry.
}
Writeln( xName,
'=',
xValue);
Exit;
{$ENDIF}
if xValue.Contains('%') then
begin
Registry.WriteExpandString( xName,
xValue);
end
else
begin
Registry.WriteString( xName,
xValue);
end;
end
else
begin
lExistingPath := Registry.ReadString( xName);
if ( Trim( lExistingPath) <> ( xValue)) then
begin
Writeln( Format( 'Key "%s" already exists with different Path ->',
[ xName]));
Writeln( 'Value:' .PadRight( 10).PadLeft( 12) +
'"' +
lExistingPath +
'"');
Writeln( 'Default:'.PadRight( 10).PadLeft( 12) +
'"' +
xValue +
'"');
end;
end;
end;
procedure ShowHelp;
var
exeName: string;
begin
exeName := TPath.GetFileNameWithoutExtension(ParamStr(0));
Writeln('Compresses the system and user PATH variable using environment variables.');
Writeln;
Writeln(exeName, ' [/F importfile] [/X exportfile]');
Writeln;
Writeln(' /F importfile'.PadRight(20), 'load shortcuts from <importfile>');
Writeln(' /X exportfile'.PadRight(20), 'store shortcuts into <exportfile>');
Writeln;
Writeln('You must have Administrator rights to change the system PATH variable!');
Writeln;
end;
procedure Main;
var
instance: TPathCompressor;
lNew: Integer;
lOld: Integer;
shortCutFileName: string;
begin
if FindCmdLineSwitch('?') then begin
ShowHelp;
Exit;
end;
instance := TPathCompressor.Create;
try
if FindCmdLineSwitch('f', shortCutFileName) then begin
instance.LoadShortCuts(shortCutFileName);
end;
if FindCmdLineSwitch('x', shortCutFileName) then begin
instance.StoreShortCuts(shortCutFileName);
end;
Write('HKEY_LOCAL_MACHINE: ');
if instance.LoadPath(false) then begin
instance.Execute(lOld, lNew);
Writeln(lOld, ' ==> ', lNew);
end
else begin
Writeln('Could not load path. Try running as administrator.');
end;
Write('HKEY_CURRENT_USER: ');
if instance.LoadPath(true) then begin
instance.Execute(lOld, lNew);
Writeln(lOld, ' ==> ', lNew);
end
else begin
Writeln('Could not load path. Try running as administrator.');
end;
Write('notifying...');
instance.NotifyChanges;
Writeln;
finally
instance.Free;
end;
end;
begin
try
Main;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
{$IFDEF DEBUG}
{ When started from within the IDE we want to see the output. }
Write('Press <Enter> to continue...');
Readln;
{$ENDIF}
end.