-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTrayMenu.MainForm.pas
More file actions
357 lines (311 loc) · 9.8 KB
/
TrayMenu.MainForm.pas
File metadata and controls
357 lines (311 loc) · 9.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
unit TrayMenu.MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, Menus, ImgList, ShlObj;
type
TFileInfo = record
Description: string;
IconIndex: integer;
end;
TMainForm = class(TForm)
TrayIcon: TTrayIcon;
PopupMenu: TPopupMenu;
est11: TMenuItem;
PopupIcons: TImageList;
DirectoryWatcherTimer: TTimer;
procedure FormCreate(Sender: TObject);
procedure TrayIconMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormDestroy(Sender: TObject);
procedure PopupMenuPopup(Sender: TObject);
procedure DirectoryWatcherTimerTimer(Sender: TObject);
protected
FRootPath: string;
procedure ParseCommandLine;
protected
FPopupMenuDirty: boolean;
procedure ReloadMenu;
procedure ReloadSubmenu(AParent: TMenuItem; const APath: string);
procedure SortSubmenu(AParent: TMenuItem);
function CompareMenuItems(A, B: TMenuItem): integer;
protected
procedure TryReadInfo(const AFilename: string; out AInfo: TFileInfo);
function GetShellLink(const AFilename: string): IShellLink;
function CopyIcon(const AIcon: HICON): integer;
protected
FHDir: THandle;
FHDirBuf: array[0..1024-1] of byte;
FHDirOverlapped: TOverlapped;
procedure SetupDirectoryWatcher;
procedure CleanupDirectoryWatcher;
procedure DirectoryWatcherRearm;
end;
TDirMenuItem = class(TMenuItem)
end;
TLinkMenuItem = class(TMenuItem)
protected
FFilename: string;
public
constructor Create(AOwner: TComponent; const AFilename: string); reintroduce;
procedure Click; override;
end;
var
MainForm: TMainForm;
implementation
uses SystemUtils, FilenameUtils, CommCtrl, ActiveX, ShellApi;
{$R *.dfm}
procedure TMainForm.FormCreate(Sender: TObject);
begin
inherited;
CoInitialize(nil);
OleInitialize(nil);
FRootPath := GetSpecialFolderPath(CSIDL_APPDATA)+'\TrayMenu'; //by default
ParseCommandLine;
ReloadMenu;
SetupDirectoryWatcher;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
CleanupDirectoryWatcher;
end;
type
EBadUsage = class(Exception);
procedure TMainForm.ParseCommandLine;
var i: integer;
s: string;
begin
i := 1;
while i < ParamCount do begin
s := AnsiLowerCase(Trim(ParamStr(i)));
if s='' then begin
Inc(i);
continue;
end;
if s='/path' then begin
Inc(i);
if i > ParamCount then
raise EBadUsage.Create('/path requires specifying path');
Self.FRootPath := CanonicalizePath(ParamStr(i), GetCurrentDir);
end;
raise EBadUsage.Create('Unknown parameter: "'+s+'"');
Inc(i);
end;
end;
procedure TMainForm.SetupDirectoryWatcher;
var res: integer;
begin
FHDir := CreateFile(PChar(Self.FRootPath), FILE_LIST_DIRECTORY, //or GENERIC_READ
FILE_SHARE_READ or FILE_SHARE_WRITE or FILE_SHARE_DELETE, nil,
OPEN_EXISTING, FILE_FLAG_OVERLAPPED or FILE_FLAG_BACKUP_SEMANTICS, 0);
if FHDir = INVALID_HANDLE_VALUE then FHDir := 0;
if FHDir = 0 then begin
res := GetLastError;
OutputDebugString('Cannot open target path with backup semantics, change notifications will be unavailable');
OutputDebugString(PChar('GetLastError='+IntToStr(res)));
exit;
end;
DirectoryWatcherRearm;
end;
procedure TMainForm.CleanupDirectoryWatcher;
begin
if FHDir <> 0 then begin
CancelIo(FHDir);
CloseHandle(FHDir);
end;
end;
//Do not call directly, done automatically
procedure TMainForm.DirectoryWatcherRearm;
var res: integer;
dwBytes: dword;
begin
if Self.FHDir = 0 then exit; //can't anything
FillChar(FHDirOverlapped, SizeOf(FHDirOverlapped), 0);
//Would be better to assign a completion routine but those don't run without
//us doing SleepEx or WaitForMessagesEx somewhere
if not ReadDirectoryChangesW(Self.FHDir, @FHDirBuf[0], SizeOf(FHDirBuf),
true, //monitor children
FILE_NOTIFY_CHANGE_FILE_NAME or FILE_NOTIFY_CHANGE_DIR_NAME or
FILE_NOTIFY_CHANGE_ATTRIBUTES or FILE_NOTIFY_CHANGE_SIZE or
FILE_NOTIFY_CHANGE_LAST_WRITE or FILE_NOTIFY_CHANGE_CREATION,
@dwBytes,
@FHDirOverlapped, nil) then
begin
res := GetLastError;
OutputDebugString('Cannot rearm change notifications, further change notifications will be unavailable');
OutputDebugString(PChar('GetLastError='+IntToStr(res)));
//Can't do much on error, won't get any more notifications, sad
end;
end;
procedure TMainForm.DirectoryWatcherTimerTimer(Sender: TObject);
var dwBytes: dword;
begin
if Self.FHDir = 0 then exit;
if GetOverlappedResult(Self.FHDir, Self.FHDirOverlapped, dwBytes, false) then begin
FPopupMenuDirty := true;
DirectoryWatcherRearm;
end;
end;
procedure TMainForm.PopupMenuPopup(Sender: TObject);
begin
if FPopupMenuDirty then
ReloadMenu;
end;
procedure TMainForm.ReloadMenu;
begin
FPopupMenuDirty := false;
PopupIcons.Clear;
ReloadSubmenu(PopupMenu.Items, FRootPath);
end;
procedure TMainForm.ReloadSubmenu(AParent: TMenuItem; const APath: string);
var sr: TSearchRec;
res: integer;
item: TMenuItem;
info: TFileInfo;
begin
AParent.Clear;
if APath = '' then exit;
res := SysUtils.FindFirst(APath+'\*.*', faAnyFile, sr);
while res = 0 do begin
if (sr.Name='') or (sr.Name='.') or (sr.Name='..') then begin
res := SysUtils.FindNext(sr);
continue;
end;
if (sr.Name[1]='.') or (sr.Attr and faHidden <> 0) then begin
res := SysUtils.FindNext(sr);
continue;
end;
if sr.Attr and faDirectory <> 0 then begin
item := TDirMenuItem.Create(Self.PopupMenu);
item.Caption := sr.Name;
TryReadInfo(APath+'\'+sr.Name, info);
item.ImageIndex := info.IconIndex;
AParent.Add(item);
ReloadSubmenu(item, APath+'\'+sr.Name);
end else begin
item := TLinkMenuItem.Create(Self.PopupMenu, APath+'\'+sr.Name);
item.Caption := ChangeFileExt(sr.Name, '');
TryReadInfo(APath+'\'+sr.Name, info);
item.Hint := info.Description;
item.ImageIndex := info.IconIndex;
AParent.Add(item);
end;
res := SysUtils.FindNext(sr);
end;
SysUtils.FindClose(sr);
SortSubmenu(AParent);
end;
procedure TMainForm.SortSubmenu(AParent: TMenuItem);
var i, j: integer;
item: TMenuItem;
begin
i := 0;
while i < AParent.Count-1 do begin
j := i-1;
while j >= 0 do begin
if CompareMenuItems(AParent.Items[j], AParent.Items[i]) <= 0 then begin
if j<i-1 then begin
item := AParent.Items[i];
AParent.Remove(item);
AParent.Insert(j+1, item);
end;
break;
end;
Dec(j);
end;
if j < 0 then begin
item := AParent.Items[i];
AParent.Remove(item);
AParent.Insert(0, item);
end;
Inc(i);
end;
end;
function TMainForm.CompareMenuItems(A, B: TMenuItem): integer;
var AD, BD: boolean;
begin
AD := (A is TDirMenuItem);
BD := (B is TDirMenuItem);
if AD <> BD then begin
if AD then
Result := -1
else
Result := +1;
exit;
end;
Result := CompareText(A.Caption, B.Caption);
end;
procedure TMainForm.TryReadInfo(const AFilename: string; out AInfo: TFileInfo);
var psl: IShellLink;
shInfo: SHFILEINFO;
res: integer;
begin
AInfo.Description := '';
AInfo.IconIndex := -1;
//If this is a link, we can query its link description
psl := Self.GetShellLink(AFilename);
if psl <> nil then begin
SetLength(AInfo.Description, MAX_PATH+1);
if SUCCEEDED(psl.GetDescription(PChar(AInfo.Description), MAX_PATH)) then
SetLength(AInfo.Description, StrLen(PChar(AInfo.Description))) //trim
else
AInfo.Description := '';
end;
//For files and folders we can query their explorer icons + type descriptions
res := ShellApi.SHGetFileInfo(PChar(AFilename), 0, shInfo, SizeOf(shInfo), SHGFI_TYPENAME or SHGFI_SMALLICON or SHGFI_SYSICONINDEX);
if res <> 0 then begin
if AInfo.Description='' then
AInfo.Description := shInfo.szTypeName;
//Icon from hIcon has [link] overlay, we prefer to get the system index and query directly
if shInfo.hIcon <> 0 then
DestroyIcon(shInfo.hIcon);
if (AInfo.IconIndex < 0) and (shInfo.iIcon <> 0) then begin
shInfo.hIcon := ImageList_GetIcon(res, shInfo.iIcon, ILD_NORMAL);
if shInfo.hIcon = 0 then
shInfo.hIcon := GetLastError;
AInfo.IconIndex := Self.CopyIcon(shInfo.hIcon);
DestroyIcon(shInfo.hIcon);
end;
end;
end;
function TMainForm.GetShellLink(const AFilename: string): IShellLink;
var ppf: IPersistFile;
begin
Result := nil;
if FAILED(CoCreateInstance(CLSID_ShellLink, nil, CLSCTX_INPROC_SERVER, IID_IShellLink, Result)) then
exit;
if FAILED(Result.QueryInterface(IPersistFile, ppf))
or FAILED(ppf.Load(PChar(AFilename), STGM_READ)) then begin
Result := nil;
exit;
end;
end;
function TMainForm.CopyIcon(const AIcon: HICON): integer;
var icon: TIcon;
begin
icon := TIcon.Create;
icon.Handle := AIcon;
Result := PopupIcons.AddIcon(icon);
end;
procedure TMainForm.TrayIconMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then begin
SetForegroundWindow(Application.Handle);
Application.ProcessMessages;
PopupMenu.AutoPopup := False;
PopupMenu.PopupComponent := TrayIcon;
PopupMenu.Popup(X, Y);
end;
end;
constructor TLinkMenuItem.Create(AOwner: TComponent; const AFilename: string);
begin
inherited Create(AOwner);
Self.FFilename := AFilename;
end;
procedure TLinkMenuItem.Click;
begin
inherited;
ShellExecute(0, PChar('open'), PChar(Self.FFilename), nil, nil, SW_SHOW);
end;
end.