IEDriveInfo.pas 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  1. unit IEDriveInfo;
  2. {==================================================================
  3. Component TDriveInfo / Version 2.6 / January 2000
  4. ====================================================
  5. Description:
  6. ============
  7. Central drive management class. Provides information about all
  8. installed drives, for example wether drive is valid, disk is inserted
  9. displayname or volume size.
  10. Author:
  11. =======
  12. (c) Ingo Eckel 1999
  13. Sodener Weg 38
  14. 65812 Bad Soden
  15. Germany
  16. For detailed documentation and history see the documentation in TDriveInfo.htm.
  17. {==================================================================}
  18. {Required compiler options:}
  19. {$A+,B-,X+,H+,P+}
  20. {$WARN SYMBOL_PLATFORM OFF}
  21. interface
  22. uses
  23. Windows, Registry, SysUtils, Classes, ComCtrls, ShellApi, ShlObj, CommCtrl, Forms,
  24. BaseUtils, System.Generics.Collections, Vcl.Graphics, Winapi.Messages;
  25. const
  26. {Flags used by TDriveInfo.ReadDriveStatus and TDriveView.RefreshRootNodes:}
  27. dsValid = 0; {checks only whether drive is still valid}
  28. dsImageIndex = 1; {Fetch imageindex, if not allready fetched}
  29. dsSize = 2; {Fetch disk size and serialnumber}
  30. dsDisplayName = 4; {Fetch drives displayname}
  31. dsSynchronous = dsImageIndex or dsDisplayName;
  32. dsAll = dsSynchronous or dsSize;
  33. FirstDrive = 'A';
  34. SystemDrive = 'C';
  35. LastDrive = 'Z';
  36. FirstSpecialFolder = CSIDL_DESKTOP;
  37. LastSpecialFolder = CSIDL_PRINTHOOD;
  38. WM_USER_SHCHANGENOTIFY = WM_USER + $2000 + 13;
  39. WM_DRIVEINFO_PROCESS = WM_USER + $2000 + 18;
  40. type
  41. TDriveInfoRec = class
  42. PIDL : PItemIDList; {Fully qualyfied PIDL}
  43. Init : Boolean; {Drivestatus was updated once}
  44. Valid : Boolean; {Drivestatus is valid}
  45. ValidButHiddenByDrivePolicy: Boolean;
  46. DriveReady : Boolean; {Drive is ready}
  47. DriveType : Integer; {DRIVE_REMOVABLE, DRIVE_FIXED, DRIVE_CDROM, DRIVE_RAMDISK, DRIVE_REMOTE}
  48. DisplayName : string; {Windows displayname}
  49. PrettyName : string; {Prettyfied displayname}
  50. DriveSerial : DWORD; {Serial number of the drive}
  51. Size : Int64; {Drivesize}
  52. ImageIndex : Integer; {Drive imageIndex}
  53. DriveHandle: THandle;
  54. NotificationHandle: HDEVNOTIFY;
  55. SubscribeDriveNotifications: Boolean;
  56. end;
  57. TRealDrive = char;
  58. TSpecialFolder = FirstSpecialFolder..LastSpecialFolder;
  59. PSpecialFolderRec = ^TSpecialFolderRec;
  60. TSpecialFolderRec = record
  61. Valid: Boolean;
  62. Location: string;
  63. DisplayName: string;
  64. ImageIndex: Integer;
  65. PIDL: PItemIDList;
  66. end;
  67. TDriveNotification = (dnRefresh, dnRemoving);
  68. TDriveNotificationEvent = procedure(Notification: TDriveNotification; Drive: string) of object;
  69. TDriveInfo = class(TObject)
  70. private
  71. FData: TObjectDictionary<string, TDriveInfoRec>;
  72. FNoDrives: DWORD;
  73. FNoViewOnDrive: DWORD;
  74. FDesktop: IShellFolder;
  75. FFolders: array[TSpecialFolder] of TSpecialFolderRec;
  76. FHonorDrivePolicy: Integer;
  77. FUseABDrives: Boolean;
  78. FLoaded: Boolean;
  79. FHandlers: TList<TDriveNotificationEvent>;
  80. FChangeNotify: ULONG;
  81. function GetFolder(Folder: TSpecialFolder): PSpecialFolderRec;
  82. procedure ReadDriveBasicStatus(Drive: string);
  83. procedure ResetDrive(Drive: string);
  84. procedure SetHonorDrivePolicy(Value: Integer);
  85. function GetFirstFixedDrive: Char;
  86. procedure Load;
  87. function AddDrive(Drive: string): TDriveInfoRec;
  88. function GetDriveBitMask(Drive: string): Integer;
  89. function DoAnyValidPath(DriveType: Integer; CanBeHidden: Boolean; var Path: string): Boolean;
  90. function ReadDriveMask(Reg: TRegistry; ValueName: string): DWORD;
  91. procedure ScheduleDriveRefresh;
  92. procedure CancelDriveRefresh;
  93. procedure InternalWndProc(var Msg: TMessage);
  94. procedure InvokeHandlers(DriveNotification: TDriveNotification; Drive: string);
  95. procedure UpdateDriveNotifications(Drive: string);
  96. procedure UpdateDrivesNotifications;
  97. procedure ProcessThreadResults;
  98. constructor Create;
  99. procedure ReadAsynchronous;
  100. procedure DoReadDriveStatus(Drive: string; Flags: Integer);
  101. procedure DriveRemoving(Drive: string);
  102. public
  103. function Get(Drive: string): TDriveInfoRec;
  104. property SpecialFolder[Folder: TSpecialFolder]: PSpecialFolderRec read GetFolder;
  105. procedure NeedData;
  106. function AnyValidPath: string;
  107. function GetDriveKey(Path: string): string;
  108. function GetDriveRoot(Drive: string): string;
  109. function IsRealDrive(Drive: string): Boolean;
  110. function IsFixedDrive(Drive: string): Boolean;
  111. function GetImageIndex(Drive: string): Integer;
  112. function GetSimpleName(Drive: string): string;
  113. function GetDisplayName(Drive: string): string;
  114. function GetPrettyName(Drive: string): string;
  115. procedure ReadDriveStatus(Drive: string; Flags: Integer);
  116. procedure OverrideDrivePolicy(Drive: string);
  117. property HonorDrivePolicy: Integer read FHonorDrivePolicy write SetHonorDrivePolicy;
  118. property FirstFixedDrive: Char read GetFirstFixedDrive;
  119. property UseABDrives: Boolean read FUseABDrives write FUseABDrives;
  120. destructor Destroy; override;
  121. procedure AddHandler(Handler: TDriveNotificationEvent);
  122. procedure RemoveHandler(Handler: TDriveNotificationEvent);
  123. procedure DriveRefresh;
  124. procedure SubscribeDriveNotifications(Drive: string);
  125. end;
  126. function GetShellFileName(PIDL: PItemIDList): string; overload;
  127. function GetNetWorkName(Drive: string): string;
  128. function GetNetWorkConnected(Drive: string): Boolean;
  129. function IsRootPath(Path: string): Boolean;
  130. function GetThumbnail(Path: string; Size: TSize): TBitmap;
  131. {Central drive information object instance of TDriveInfo}
  132. var
  133. DriveInfo : TDriveInfo;
  134. resourceString
  135. ErrorInvalidDrive = '%s is a invalid drive letter.';
  136. implementation
  137. uses
  138. Math, PIDL, OperationWithTimeout, PasTools, CompThread;
  139. type
  140. PRGBQuadArray = ^TRGBQuadArray; // From graphics.pas
  141. TRGBQuadArray = array[Byte] of TRGBQuad; // From graphics.pas
  142. // Globals so that we do not have to fear that thread run after DriveInfo is released
  143. var
  144. InternalWindowHandle: HWND;
  145. ThreadLock: TRTLCriticalSection;
  146. ReadyDrives: string;
  147. type
  148. TDriveInfoThread = class(TCompThread)
  149. public
  150. constructor Create(Drives: string);
  151. protected
  152. procedure Execute; override;
  153. private
  154. FDrives: string;
  155. end;
  156. constructor TDriveInfoThread.Create(Drives: string);
  157. begin
  158. inherited Create(True);
  159. FDrives := Drives;
  160. FreeOnTerminate := True;
  161. Resume;
  162. end;
  163. procedure TDriveInfoThread.Execute;
  164. var
  165. I: Integer;
  166. FreeSpace, Size: Int64;
  167. DriveRoot: string;
  168. Drive: Char;
  169. begin
  170. if Length(FDrives) = 1 then
  171. begin
  172. Drive := FDrives[1];
  173. DriveRoot := DriveInfo.GetDriveRoot(Drive);
  174. if GetDiskFreeSpaceEx(PChar(DriveRoot), FreeSpace, Size, nil) then
  175. begin
  176. EnterCriticalSection(ThreadLock);
  177. ReadyDrives := ReadyDrives + Drive;
  178. LeaveCriticalSection(ThreadLock);
  179. end;
  180. end
  181. else
  182. begin
  183. for I := 1 to Length(FDrives) do
  184. begin
  185. TDriveInfoThread.Create(FDrives[I]);
  186. Sleep(100);
  187. end;
  188. end;
  189. end;
  190. constructor TDriveInfo.Create;
  191. begin
  192. inherited;
  193. FHonorDrivePolicy := 1;
  194. FUseABDrives := True;
  195. FLoaded := False;
  196. FData := TObjectDictionary<string, TDriveInfoRec>.Create([doOwnsValues]);
  197. FHandlers := TList<TDriveNotificationEvent>.Create;
  198. FChangeNotify := 0;
  199. end; {TDriveInfo.Create}
  200. destructor TDriveInfo.Destroy;
  201. begin
  202. Assert(FHandlers.Count = 0);
  203. FHandlers.Free;
  204. FData.Free;
  205. inherited;
  206. end; {TDriveInfo.Destroy}
  207. procedure TDriveInfo.NeedData;
  208. begin
  209. if not FLoaded then
  210. begin
  211. Load;
  212. FLoaded := True;
  213. end;
  214. ProcessThreadResults;
  215. end;
  216. procedure TDriveInfo.ProcessThreadResults;
  217. var
  218. I: Integer;
  219. Drive: Char;
  220. begin
  221. EnterCriticalSection(ThreadLock);
  222. try
  223. for I := 1 to Length(ReadyDrives) do
  224. begin
  225. Drive := ReadyDrives[I];
  226. Assert(FData.ContainsKey(Drive));
  227. FData[Drive].DriveReady := True;
  228. UpdateDriveNotifications(Drive);
  229. AppLog(Format('Drive "%s" is ready', [Drive]))
  230. end;
  231. ReadyDrives := '';
  232. finally
  233. LeaveCriticalSection(ThreadLock);
  234. end;
  235. end;
  236. function TDriveInfo.DoAnyValidPath(DriveType: Integer; CanBeHidden: Boolean; var Path: string): Boolean;
  237. var
  238. Drive: TRealDrive;
  239. DriveInfoRec: TDriveInfoRec;
  240. begin
  241. for Drive := SystemDrive to LastDrive do
  242. begin
  243. DriveInfoRec := Get(Drive);
  244. if (DriveInfoRec.Valid or
  245. (CanBeHidden and DriveInfoRec.ValidButHiddenByDrivePolicy)) and
  246. (DriveInfoRec.DriveType = DriveType) and
  247. DirectoryExists(ApiPath(GetDriveRoot(Drive))) then
  248. begin
  249. Result := True;
  250. Path := GetDriveRoot(Drive);
  251. Exit;
  252. end;
  253. end;
  254. Result := False;
  255. end;
  256. function TDriveInfo.AnyValidPath: string;
  257. begin
  258. if (not DoAnyValidPath(DRIVE_FIXED, False, Result)) and
  259. (not DoAnyValidPath(DRIVE_FIXED, True, Result)) and
  260. (not DoAnyValidPath(DRIVE_REMOTE, False, Result)) then
  261. begin
  262. raise Exception.Create(SNoValidPath);
  263. end;
  264. end;
  265. function TDriveInfo.IsRealDrive(Drive: string): Boolean;
  266. begin
  267. Result := (Length(Drive) = 1);
  268. Assert((not Result) or ((Drive[1] >= FirstDrive) and (Drive[1] <= LastDrive)));
  269. end;
  270. function TDriveInfo.IsFixedDrive(Drive: string): Boolean;
  271. begin
  272. Result := True;
  273. if IsRealDrive(Drive) and (Drive[1] < FirstFixedDrive) then Result := False;
  274. end;
  275. function TDriveInfo.GetDriveKey(Path: string): string;
  276. begin
  277. Result := ExtractFileDrive(Path);
  278. if (Length(Result) = 2) and (Result[2] = DriveDelim) then
  279. begin
  280. Result := Upcase(Result[1]);
  281. end
  282. else
  283. if IsUncPath(Path) then
  284. begin
  285. Result := LowerCase(Result);
  286. end
  287. else
  288. begin
  289. raise EConvertError.Create(Format(ErrorInvalidDrive, [Path]))
  290. end;
  291. end;
  292. function TDriveInfo.GetDriveRoot(Drive: string): string;
  293. begin
  294. if IsRealDrive(Drive) then
  295. begin
  296. Result := Drive + ':\'
  297. end
  298. else
  299. begin
  300. Assert(IsUncPath(Drive));
  301. Result := IncludeTrailingBackslash(Drive);
  302. end;
  303. end;
  304. function TDriveInfo.GetFolder(Folder: TSpecialFolder): PSpecialFolderRec;
  305. var
  306. FileInfo: TShFileInfo;
  307. Path: PChar;
  308. Flags: Word;
  309. begin
  310. NeedData;
  311. Assert((Folder >= Low(FFolders)) and (Folder <= High(FFolders)));
  312. with FFolders[Folder] do
  313. begin
  314. if not Valid then
  315. begin
  316. SpecialFolderLocation(Folder, Location, PIDL);
  317. if Assigned(PIDL) then
  318. begin
  319. Path := PChar(PIDL);
  320. Flags := SHGFI_PIDL;
  321. end
  322. else
  323. begin
  324. Path := PChar(Location);
  325. Flags := 0;
  326. end;
  327. SHGetFileInfo(Path, 0, FileInfo, SizeOf(FileInfo),
  328. SHGFI_DISPLAYNAME or SHGFI_SYSICONINDEX or SHGFI_SMALLICON or Flags);
  329. ImageIndex := FileInfo.iIcon;
  330. DisplayName := FileInfo.szDisplayName;
  331. Valid := True;
  332. end;
  333. end;
  334. Result := @FFolders[Folder];
  335. end;
  336. procedure TDriveInfo.SetHonorDrivePolicy(Value: Integer);
  337. var
  338. Drive: TRealDrive;
  339. begin
  340. if HonorDrivePolicy <> Value then
  341. begin
  342. FHonorDrivePolicy := Value;
  343. if FLoaded then
  344. begin
  345. for Drive := FirstDrive to LastDrive do
  346. begin
  347. ReadDriveBasicStatus(Drive);
  348. end;
  349. end;
  350. end;
  351. end;
  352. function TDriveInfo.GetFirstFixedDrive: Char;
  353. begin
  354. if UseABDrives then Result := FirstDrive
  355. else Result := SystemDrive;
  356. end;
  357. function TDriveInfo.GetDriveBitMask(Drive: string): Integer;
  358. begin
  359. Assert(IsRealDrive(Drive));
  360. Result := (1 shl (Ord(Drive[1]) - Ord('A')));
  361. end;
  362. procedure TDriveInfo.ReadDriveBasicStatus(Drive: string);
  363. var
  364. ValidDriveType: Boolean;
  365. InaccessibleByDrivePolicy, HiddenByDrivePolicy: Boolean;
  366. DriveBitMask: Integer;
  367. begin
  368. Assert(FData.ContainsKey(Drive));
  369. with FData[Drive] do
  370. begin
  371. DriveType := Windows.GetDriveType(PChar(GetDriveRoot(Drive)));
  372. if IsRealDrive(Drive) then DriveBitMask := GetDriveBitMask(Drive)
  373. else DriveBitMask := 0;
  374. InaccessibleByDrivePolicy :=
  375. ((HonorDrivePolicy and 2) <> 0) and ((DriveBitMask and FNoViewOnDrive) <> 0);
  376. HiddenByDrivePolicy :=
  377. ((HonorDrivePolicy and 1) <> 0) and ((DriveBitMask and FNoDrives) <> 0);
  378. ValidDriveType :=
  379. (DriveType in [DRIVE_REMOVABLE, DRIVE_FIXED, DRIVE_CDROM, DRIVE_RAMDISK, DRIVE_REMOTE]) and
  380. (not InaccessibleByDrivePolicy);
  381. ValidButHiddenByDrivePolicy := ValidDriveType and HiddenByDrivePolicy;
  382. Valid := ValidDriveType and (not HiddenByDrivePolicy);
  383. end;
  384. end;
  385. procedure TDriveInfo.ResetDrive(Drive: string);
  386. begin
  387. with FData[Drive] do
  388. begin
  389. DriveReady := False;
  390. DisplayName := '';
  391. PrettyName := '';
  392. DriveSerial := 0;
  393. Size := -1;
  394. ImageIndex := 0;
  395. DriveHandle := INVALID_HANDLE_VALUE;
  396. NotificationHandle := nil;
  397. SubscribeDriveNotifications := False;
  398. end;
  399. end;
  400. function TDriveInfo.ReadDriveMask(Reg: TRegistry; ValueName: string): DWORD;
  401. var
  402. DataInfo: TRegDataInfo;
  403. begin
  404. Result := 0;
  405. if Reg.GetDataInfo(ValueName, DataInfo) then
  406. begin
  407. if (DataInfo.RegData = rdBinary) and (DataInfo.DataSize >= SizeOf(Result)) then
  408. begin
  409. Reg.ReadBinaryData(ValueName, Result, SizeOf(Result));
  410. end
  411. else
  412. if DataInfo.RegData = rdInteger then
  413. begin
  414. Result := Reg.ReadInteger(ValueName);
  415. end;
  416. end;
  417. end;
  418. procedure TDriveInfo.Load;
  419. var
  420. Drive: TRealDrive;
  421. Reg: TRegistry;
  422. Folder: TSpecialFolder;
  423. begin
  424. AppLog('Loading drives');
  425. Reg := TRegistry.Create;
  426. FNoDrives := 0;
  427. FNoViewOnDrive := 0;
  428. try
  429. if Reg.OpenKeyReadOnly('Software\Microsoft\Windows\CurrentVersion\Policies\Explorer') then
  430. begin
  431. FNoDrives := ReadDriveMask(Reg, 'NoDrives');
  432. FNoViewOnDrive := ReadDriveMask(Reg, 'NoViewOnDrive');
  433. end;
  434. finally
  435. Reg.Free;
  436. end;
  437. AppLog(Format('NoDrives mask: %d', [Integer(FNoDrives)]));
  438. AppLog(Format('NoViewOnDrive mask: %d', [Integer(FNoViewOnDrive)]));
  439. FDesktop := nil;
  440. for Drive := FirstDrive to LastDrive do
  441. begin
  442. AddDrive(Drive);
  443. end;
  444. ReadAsynchronous;
  445. for Folder := Low(FFolders) to High(FFolders) do
  446. FFolders[Folder].Valid := False;
  447. end;
  448. procedure TDriveInfo.ReadAsynchronous;
  449. var
  450. Drive: TRealDrive;
  451. Drives: string;
  452. begin
  453. for Drive := FirstDrive to LastDrive do
  454. begin
  455. // Not using Get as that would recurse into Load
  456. if FData[Drive].Valid then
  457. Drives := Drives + Drive;
  458. end;
  459. TDriveInfoThread.Create(Drives);
  460. if Length(Drives) > 0 then
  461. begin
  462. AppLog(Format('Drives to check in the background: %s', [Drives]));
  463. TDriveInfoThread.Create(Drives);
  464. end;
  465. end;
  466. function TDriveInfo.AddDrive(Drive: string): TDriveInfoRec;
  467. begin
  468. Result := TDriveInfoRec.Create;
  469. FData.Add(Drive, Result);
  470. ResetDrive(Drive);
  471. if IsFixedDrive(Drive) or (not IsRealDrive(Drive)) then // not floppy
  472. DoReadDriveStatus(Drive, dsSynchronous)
  473. else
  474. ReadDriveBasicStatus(Drive);
  475. end;
  476. function TDriveInfo.GetImageIndex(Drive: string): Integer;
  477. begin
  478. NeedData;
  479. Result := 0;
  480. if Get(Drive).Valid then
  481. begin
  482. if Get(Drive).ImageIndex = 0 then
  483. ReadDriveStatus(Drive, dsImageIndex);
  484. Result := Get(Drive).ImageIndex;
  485. end;
  486. end; {TDriveInfo.GetImageIndex}
  487. function TDriveInfo.GetDisplayName(Drive: string): string;
  488. begin
  489. if Get(Drive).Valid then
  490. begin
  491. if Length(Get(Drive).DisplayName) = 0 then
  492. ReadDriveStatus(Drive, dsDisplayName);
  493. Result := Get(Drive).DisplayName;
  494. end
  495. else
  496. begin
  497. Result := GetSimpleName(Drive);
  498. end;
  499. end; {TDriveInfo.GetDisplayname}
  500. function TDriveInfo.GetPrettyName(Drive: string): string;
  501. begin
  502. if Get(Drive).Valid then
  503. begin
  504. if Length(Get(Drive).PrettyName) = 0 then
  505. ReadDriveStatus(Drive, dsDisplayName);
  506. Result := Get(Drive).PrettyName;
  507. end;
  508. if Length(Result) = 0 then
  509. Result := GetSimpleName(Drive);
  510. end; {TDriveInfo.GetPrettyName}
  511. function TDriveInfo.GetSimpleName(Drive: string): string;
  512. begin
  513. Result := Drive;
  514. if IsRealDrive(Result) then Result := Result + ':';
  515. end;
  516. function TDriveInfo.Get(Drive: string): TDriveInfoRec;
  517. begin
  518. NeedData;
  519. // We might want to wait for FReadyDrives to be empty before returning
  520. // (or even better do that only in DriveReady getter)
  521. if not FData.TryGetValue(Drive, Result) then
  522. begin
  523. Assert(IsUncPath(Drive));
  524. Result := AddDrive(Drive);
  525. DriveRefresh;
  526. end;
  527. end; {TDriveInfo.GetData}
  528. procedure TDriveInfo.ReadDriveStatus(Drive: string; Flags: Integer);
  529. begin
  530. // Among other, this makes sure the pending drive-ready status from the background thread are collected,
  531. // before we overwrite it with fresh status here.
  532. NeedData;
  533. DoReadDriveStatus(Drive, Flags);
  534. end;
  535. procedure TDriveInfo.DoReadDriveStatus(Drive: string; Flags: Integer);
  536. var
  537. FileInfo: TShFileInfo;
  538. DriveRoot: string;
  539. DriveID: string;
  540. CPos: Integer;
  541. Eaten: ULONG;
  542. ShAttr: ULONG;
  543. MaxFileNameLength: DWORD;
  544. FileSystemFlags: DWORD;
  545. FreeSpace: Int64;
  546. SimpleName: string;
  547. DriveInfoRec: TDriveInfoRec;
  548. S: string;
  549. begin
  550. if not Assigned(FDesktop) then
  551. SHGetDesktopFolder(FDesktop);
  552. DriveRoot := GetDriveRoot(Drive);
  553. // When this method is called, the entry always exists already
  554. Assert(FData.ContainsKey(Drive));
  555. DriveInfoRec := FData[Drive];
  556. with DriveInfoRec do
  557. begin
  558. Init := True;
  559. ReadDriveBasicStatus(Drive);
  560. if Valid then
  561. begin
  562. if (not Assigned(PIDL)) and IsFixedDrive(Drive) then
  563. begin
  564. ShAttr := 0;
  565. if DriveType = DRIVE_REMOTE then
  566. begin
  567. ShellFolderParseDisplayNameWithTimeout(
  568. FDesktop, Application.Handle, nil, PChar(DriveRoot), Eaten, PIDL, ShAttr, 2 * MSecsPerSec);
  569. end
  570. else
  571. begin
  572. FDesktop.ParseDisplayName(Application.Handle, nil, PChar(DriveRoot), Eaten, PIDL, ShAttr);
  573. end;
  574. end;
  575. {Read driveStatus:}
  576. if (Flags and dsSize) <> 0 then
  577. begin
  578. DriveReady := GetDiskFreeSpaceEx(PChar(DriveRoot), FreeSpace, Size, nil);
  579. if DriveReady then
  580. begin
  581. {Access the physical drive:}
  582. if GetVolumeInformation(PChar(DriveRoot), nil, 0,
  583. @DriveSerial, MaxFileNameLength, FileSystemFlags,
  584. nil, 0) then
  585. begin
  586. end
  587. else
  588. begin
  589. DriveSerial := 0;
  590. end;
  591. end
  592. else
  593. begin
  594. DriveSerial := 0;
  595. end;
  596. // Particularly when removing drive fails (as other app has it locked), we end up with not monitoring the
  597. // drive. When the drive is visited again in panel, it calls into here, and we take the opportunity
  598. // to resume monitoring
  599. UpdateDriveNotifications(Drive);
  600. end;
  601. {DisplayName:}
  602. if (Flags and dsDisplayName) <> 0 then
  603. begin
  604. {Fetch drives displayname:}
  605. SimpleName := GetSimpleName(Drive);
  606. if Assigned(PIDL) then DisplayName := GetShellFileName(PIDL)
  607. else
  608. begin
  609. // typical reason we do not have PIDL is that it took too long to
  610. // call ParseDisplayName, in what case calling SHGetFileInfo with
  611. // path (instead of PIDL) will take long too, avoiding that and using
  612. // fallback
  613. DisplayName := '(' + SimpleName + ')';
  614. end;
  615. if DriveType <> DRIVE_REMOTE then
  616. begin
  617. PrettyName := SimpleName + ' ' + DisplayName;
  618. S := ' (' + SimpleName + ')';
  619. CPos := Pos(S, PrettyName);
  620. if CPos > 0 then
  621. Delete(PrettyName, CPos, Length(S));
  622. end
  623. else
  624. if IsRealDrive(Drive) then
  625. begin
  626. DriveID := GetNetWorkName(Drive);
  627. PrettyName := Format('%s %s (%s)', [SimpleName, ExtractFileName(DriveID), ExtractFileDir(DriveID)]);
  628. end
  629. else
  630. begin
  631. Assert(IsUncPath(DriveRoot));
  632. PrettyName := SimpleName;
  633. end;
  634. end;
  635. {ImageIndex:}
  636. if (Flags and dsImageIndex) <> 0 then
  637. begin
  638. if Assigned(PIDL) then
  639. begin
  640. SHGetFileInfo(PChar(PIDL), 0, FileInfo, SizeOf(FileInfo), SHGFI_SYSICONINDEX or SHGFI_SMALLICON or SHGFI_PIDL)
  641. end
  642. else
  643. begin
  644. SHGetFileInfo(PChar(DriveRoot), 0, FileInfo, SizeOf(FileInfo), SHGFI_SYSICONINDEX or SHGFI_SMALLICON);
  645. end;
  646. ImageIndex := FileInfo.iIcon;
  647. end;
  648. end
  649. else
  650. begin
  651. if Assigned(PIDL) then
  652. FreePIDL(PIDL);
  653. ResetDrive(Drive);
  654. end;
  655. end;
  656. end; {TDriveInfo.ReadDriveStatus}
  657. procedure TDriveInfo.OverrideDrivePolicy(Drive: string);
  658. var
  659. Mask: DWORD;
  660. begin
  661. Assert(FData.ContainsKey(Drive));
  662. Assert(FData[Drive].ValidButHiddenByDrivePolicy);
  663. Mask := (not GetDriveBitMask(Drive));
  664. FNoDrives := FNoDrives and Mask;
  665. ReadDriveStatus(Drive, dsAll);
  666. Assert(FData[Drive].Valid);
  667. DriveRefresh;
  668. end;
  669. procedure TDriveInfo.AddHandler(Handler: TDriveNotificationEvent);
  670. var
  671. ChangeNotifyEntry: TSHChangeNotifyEntry;
  672. Dummy: string;
  673. begin
  674. if not FHandlers.Contains(Handler) then
  675. begin
  676. FHandlers.Add(Handler);
  677. if FHandlers.Count = 1 then
  678. begin
  679. // Source: petr.solin 2022-02-25
  680. if SpecialFolderLocation(CSIDL_DESKTOP, Dummy, ChangeNotifyEntry.pidl) then
  681. begin
  682. ChangeNotifyEntry.fRecursive := False;
  683. FChangeNotify :=
  684. SHChangeNotifyRegister(
  685. InternalWindowHandle, SHCNRF_ShellLevel or SHCNRF_NewDelivery,
  686. SHCNE_RENAMEFOLDER or SHCNE_MEDIAINSERTED or SHCNE_MEDIAREMOVED,
  687. WM_USER_SHCHANGENOTIFY, 1, ChangeNotifyEntry);
  688. end;
  689. UpdateDrivesNotifications;
  690. end;
  691. end;
  692. end;
  693. procedure TDriveInfo.RemoveHandler(Handler: TDriveNotificationEvent);
  694. begin
  695. if (FHandlers.Remove(Handler) >= 0) and (FHandlers.Count = 0) then
  696. begin
  697. if FChangeNotify <> 0 then
  698. begin
  699. SHChangeNotifyDeregister(FChangeNotify);
  700. FChangeNotify := 0;
  701. end;
  702. UpdateDrivesNotifications;
  703. end;
  704. end;
  705. procedure TDriveInfo.InvokeHandlers(DriveNotification: TDriveNotification; Drive: string);
  706. var
  707. Handler: TDriveNotificationEvent;
  708. begin
  709. for Handler in FHandlers do
  710. Handler(DriveNotification, Drive);
  711. end;
  712. type
  713. PDevBroadcastHdr = ^TDevBroadcastHdr;
  714. TDevBroadcastHdr = record
  715. dbch_size: DWORD;
  716. dbch_devicetype: DWORD;
  717. dbch_reserved: DWORD;
  718. end;
  719. PDevBroadcastVolume = ^TDevBroadcastVolume;
  720. TDevBroadcastVolume = record
  721. dbcv_size: DWORD;
  722. dbcv_devicetype: DWORD;
  723. dbcv_reserved: DWORD;
  724. dbcv_unitmask: DWORD;
  725. dbcv_flags: WORD;
  726. end;
  727. PDEV_BROADCAST_HANDLE = ^DEV_BROADCAST_HANDLE;
  728. DEV_BROADCAST_HANDLE = record
  729. dbch_size : DWORD;
  730. dbch_devicetype : DWORD;
  731. dbch_reserved : DWORD;
  732. dbch_handle : THandle;
  733. dbch_hdevnotify : HDEVNOTIFY ;
  734. dbch_eventguid : TGUID;
  735. dbch_nameoffset : LongInt;
  736. dbch_data : Byte;
  737. end;
  738. PPItemIDList = ^PItemIDList;
  739. const
  740. DBT_DEVTYP_HANDLE = $00000006;
  741. DBT_CONFIGCHANGED = $0018;
  742. DBT_DEVICEARRIVAL = $8000;
  743. DBT_DEVICEQUERYREMOVE = $8001;
  744. DBT_DEVICEREMOVEPENDING = $8003;
  745. DBT_DEVICEREMOVECOMPLETE = $8004;
  746. DBT_DEVTYP_VOLUME = $00000002;
  747. // WORKAROUND Declaration in Winapi.ShlObj.pas is wrong
  748. function SHChangeNotification_Lock(hChange: THandle; dwProcId: DWORD;
  749. var PPidls: PPItemIDList; var plEvent: Longint): THANDLE; stdcall;
  750. external 'shell32.dll' name 'SHChangeNotification_Lock';
  751. procedure TDriveInfo.InternalWndProc(var Msg: TMessage);
  752. var
  753. DeviceType: DWORD;
  754. UnitMask: DWORD;
  755. DeviceHandle: THandle;
  756. Drive: Char;
  757. PPIDL: PPItemIDList;
  758. Event: LONG;
  759. Lock: THandle;
  760. DrivePair: TPair<string, TDriveInfoRec>;
  761. begin
  762. with Msg do
  763. begin
  764. if Msg = WM_USER_SHCHANGENOTIFY then
  765. begin
  766. Lock := SHChangeNotification_Lock(wParam, lParam, PPIDL, Event);
  767. try
  768. if (Event = SHCNE_RENAMEFOLDER) or // = drive rename
  769. (Event = SHCNE_MEDIAINSERTED) or // also bitlocker drive unlock (also sends SHCNE_UPDATEDIR)
  770. (Event = SHCNE_MEDIAREMOVED) then
  771. begin
  772. ScheduleDriveRefresh;
  773. end;
  774. finally
  775. SHChangeNotification_Unlock(Lock);
  776. end;
  777. end
  778. else
  779. // from RegisterDeviceNotification
  780. if Msg = WM_DEVICECHANGE then
  781. begin
  782. if (wParam = DBT_CONFIGCHANGED) or
  783. (wParam = DBT_DEVICEARRIVAL) or
  784. (wParam = DBT_DEVICEREMOVECOMPLETE) then
  785. begin
  786. ScheduleDriveRefresh;
  787. end
  788. else
  789. if (wParam = DBT_DEVICEQUERYREMOVE) or
  790. (wParam = DBT_DEVICEREMOVEPENDING) then
  791. begin
  792. DeviceType := PDevBroadcastHdr(lParam)^.dbch_devicetype;
  793. // This is specifically for VeraCrypt.
  794. // For normal drives, see DBT_DEVTYP_HANDLE below
  795. // (and maybe now that we have generic implementation, this specific code for VeraCrypt might not be needed anymore)
  796. if DeviceType = DBT_DEVTYP_VOLUME then
  797. begin
  798. UnitMask := PDevBroadcastVolume(lParam)^.dbcv_unitmask;
  799. Drive := FirstDrive;
  800. while UnitMask > 0 do
  801. begin
  802. if UnitMask and $01 <> 0 then
  803. begin
  804. DriveRemoving(Drive);
  805. end;
  806. UnitMask := UnitMask shr 1;
  807. Drive := Chr(Ord(Drive) + 1);
  808. end;
  809. end
  810. else
  811. if DeviceType = DBT_DEVTYP_HANDLE then
  812. begin
  813. DeviceHandle := PDEV_BROADCAST_HANDLE(lParam)^.dbch_handle;
  814. for DrivePair in FData do
  815. if DrivePair.Value.DriveHandle = DeviceHandle then
  816. begin
  817. DriveRemoving(DrivePair.Key);
  818. end;
  819. end;
  820. end;
  821. end
  822. else
  823. if Msg = WM_TIMER then
  824. begin
  825. CancelDriveRefresh;
  826. try
  827. for Drive := FirstFixedDrive to LastDrive do
  828. ReadDriveStatus(Drive, dsSynchronous);
  829. ReadAsynchronous;
  830. DriveRefresh;
  831. except
  832. Application.HandleException(Self);
  833. end;
  834. end
  835. else
  836. if Msg = WM_DRIVEINFO_PROCESS then
  837. begin
  838. ProcessThreadResults;
  839. end;
  840. Result := DefWindowProc(InternalWindowHandle, Msg, wParam, lParam);
  841. end;
  842. end;
  843. procedure TDriveInfo.DriveRemoving(Drive: string);
  844. begin
  845. FData[Drive].DriveReady := False;
  846. UpdateDriveNotifications(Drive);
  847. AppLog(Format('Removing drive "%s"', [Drive]));
  848. InvokeHandlers(dnRemoving, Drive);
  849. end;
  850. procedure TDriveInfo.CancelDriveRefresh;
  851. begin
  852. KillTimer(InternalWindowHandle, 1);
  853. end;
  854. procedure TDriveInfo.ScheduleDriveRefresh;
  855. begin
  856. CancelDriveRefresh;
  857. // Delay refreshing drives for a sec.
  858. // Particularly with CD/DVD drives, if we query display name
  859. // immediately after receiving DBT_DEVICEARRIVAL, we do not get media label.
  860. // Actually one sec does not help usually, but we do not want to wait any longer,
  861. // because we want to add USB drives asap.
  862. // And this problem might be solved now by SHChangeNotifyRegister/SHCNE_RENAMEFOLDER.
  863. SetTimer(InternalWindowHandle, 1, MSecsPerSec, nil);
  864. end;
  865. procedure TDriveInfo.UpdateDriveNotifications(Drive: string);
  866. var
  867. NeedNotifications: Boolean;
  868. Path: string;
  869. DevBroadcastHandle: DEV_BROADCAST_HANDLE;
  870. Size: Integer;
  871. DriveInfoRec: TDriveInfoRec;
  872. begin
  873. if IsFixedDrive(Drive) then
  874. begin
  875. // Not using Get to avoid recursion
  876. DriveInfoRec := FData[Drive];
  877. NeedNotifications :=
  878. (FHandlers.Count > 0) and
  879. (DriveInfoRec.DriveType <> DRIVE_REMOTE) and
  880. DriveInfoRec.DriveReady and
  881. DriveInfoRec.SubscribeDriveNotifications;
  882. if NeedNotifications <> (DriveInfoRec.DriveHandle <> INVALID_HANDLE_VALUE) then
  883. begin
  884. Path := GetDriveRoot(Drive);
  885. if NeedNotifications then
  886. begin
  887. DriveInfoRec.DriveHandle :=
  888. CreateFile(PChar(Path), GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE, nil,
  889. OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS or FILE_ATTRIBUTE_NORMAL, 0);
  890. if DriveInfoRec.DriveHandle <> INVALID_HANDLE_VALUE then
  891. begin
  892. Size := SizeOf(DevBroadcastHandle);
  893. ZeroMemory(@DevBroadcastHandle, Size);
  894. DevBroadcastHandle.dbch_size := Size;
  895. DevBroadcastHandle.dbch_devicetype := DBT_DEVTYP_HANDLE;
  896. DevBroadcastHandle.dbch_handle := DriveInfoRec.DriveHandle;
  897. DriveInfoRec.NotificationHandle :=
  898. RegisterDeviceNotification(InternalWindowHandle, @DevBroadcastHandle, DEVICE_NOTIFY_WINDOW_HANDLE);
  899. if DriveInfoRec.NotificationHandle <> nil then
  900. begin
  901. AppLog(Format('Registered drive notification for "%s"', [Path]));
  902. end
  903. else
  904. begin
  905. CloseHandle(DriveInfoRec.DriveHandle);
  906. DriveInfoRec.DriveHandle := INVALID_HANDLE_VALUE;
  907. end;
  908. end;
  909. end
  910. else
  911. begin
  912. AppLog(Format('Unregistered drive notification for "%s"', [Path]));
  913. UnregisterDeviceNotification(DriveInfoRec.NotificationHandle);
  914. DriveInfoRec.NotificationHandle := nil;
  915. CloseHandle(DriveInfoRec.DriveHandle);
  916. DriveInfoRec.DriveHandle := INVALID_HANDLE_VALUE;
  917. end;
  918. end;
  919. end;
  920. end;
  921. procedure TDriveInfo.UpdateDrivesNotifications;
  922. var
  923. Drive: string;
  924. begin
  925. for Drive in FData.Keys do
  926. UpdateDriveNotifications(Drive);
  927. end;
  928. procedure TDriveInfo.DriveRefresh;
  929. begin
  930. InvokeHandlers(dnRefresh, '');
  931. end;
  932. procedure TDriveInfo.SubscribeDriveNotifications(Drive: string);
  933. begin
  934. Get(Drive).SubscribeDriveNotifications := True;
  935. UpdateDriveNotifications(Drive);
  936. end;
  937. // ===================
  938. function GetShellFileName(PIDL: PItemIDList): string;
  939. var
  940. SFI: TSHFileInfo;
  941. begin
  942. if SHGetFileInfo(PChar(PIDL), 0, SFI, SizeOf(TSHFileInfo), SHGFI_PIDL or SHGFI_DISPLAYNAME) <> 0 then
  943. Result := SFI.szDisplayName;
  944. end; {GetShellFileName}
  945. function GetNetWorkName(Drive: string): string;
  946. var
  947. Path: string;
  948. P: array[0..MAX_PATH] of Char;
  949. MaxLen : DWORD;
  950. begin
  951. Path := ExcludeTrailingBackslash(DriveInfo.GetDriveRoot(Drive));
  952. MaxLen := MAX_PATH;
  953. if WNetGetConnection(PChar(Path), P, MaxLen) = NO_ERROR then
  954. Result := P
  955. else
  956. Result := '';
  957. end; {GetNetWorkName}
  958. type
  959. LPBYTE = ^BYTE;
  960. LMSTR = LPWSTR;
  961. NET_API_STATUS = DWORD;
  962. _USE_INFO_1 = record
  963. ui1_local: LMSTR;
  964. ui1_remote: LMSTR;
  965. ui1_password: LMSTR;
  966. ui1_status: DWORD;
  967. ui1_asg_type: DWORD;
  968. ui1_refcount: DWORD;
  969. ui1_usecount: DWORD;
  970. end;
  971. USE_INFO_1 = _USE_INFO_1;
  972. PUSE_INFO_1 = ^USE_INFO_1;
  973. LPVOID = Pointer;
  974. const
  975. USE_OK = 0;
  976. USE_PAUSED = 1;
  977. USE_SESSLOST = 2;
  978. USE_DISCONN = 2;
  979. USE_NETERR = 3;
  980. USE_CONN = 4;
  981. USE_RECONN = 5;
  982. function NetUseGetInfo(UncServerName: LMSTR; UseName: LMSTR; Level: DWORD; var BufPtr: LPBYTE): NET_API_STATUS; stdcall; external 'netapi32.dll';
  983. function NetApiBufferFree(Buffer: Pointer): DWORD; stdcall; external 'netapi32.dll';
  984. function GetNetWorkConnected(Drive: string): Boolean;
  985. var
  986. BufPtr: LPBYTE;
  987. NetResult: Integer;
  988. ServerName: string;
  989. PServerName: PChar;
  990. Name: string;
  991. P: Integer;
  992. begin
  993. Name := '';
  994. PServerName := nil;
  995. if DriveInfo.IsRealDrive(Drive) then
  996. begin
  997. Name := Drive + ':';
  998. end
  999. else
  1000. if IsUncPath(Drive) then
  1001. begin
  1002. Name := Copy(Drive, 3, Length(Drive) - 2);
  1003. P := Pos('\', Name);
  1004. if P > 0 then
  1005. begin
  1006. ServerName := Copy(Name, P + 1, Length(Name) - P);
  1007. PServerName := PChar(ServerName);
  1008. SetLength(Name, P - 1);
  1009. end
  1010. else
  1011. begin
  1012. Assert(False);
  1013. end;
  1014. end
  1015. else
  1016. begin
  1017. Assert(False);
  1018. end;
  1019. if Name = '' then
  1020. begin
  1021. Result := False;
  1022. end
  1023. else
  1024. begin
  1025. NetResult := NetUseGetInfo(PServerName, PChar(Name), 1, BufPtr);
  1026. if NetResult = 0 then
  1027. begin
  1028. Result := (PUSE_INFO_1(BufPtr)^.ui1_status = USE_OK);
  1029. NetApiBufferFree(LPVOID(BufPtr));
  1030. end
  1031. else
  1032. begin
  1033. // NetUseGetInfo works for DFS shares only, hence when it fails
  1034. // we suppose different share type and fallback to "connected"
  1035. Result := True;
  1036. end;
  1037. end;
  1038. end;
  1039. function IsRootPath(Path: string): Boolean;
  1040. begin
  1041. Result := SameText(ExcludeTrailingBackslash(ExtractFileDrive(Path)), ExcludeTrailingBackslash(Path));
  1042. end;
  1043. function GetThumbnail(Path: string; Size: TSize): TBitmap;
  1044. var
  1045. ImageFactory: IShellItemImageFactory;
  1046. X, Y: Integer;
  1047. Row: PRGBQuadArray;
  1048. Pixel: PRGBQuad;
  1049. Alpha: Byte;
  1050. Handle: HBITMAP;
  1051. begin
  1052. Result := nil;
  1053. SHCreateItemFromParsingName(PChar(Path), nil, IShellItemImageFactory, ImageFactory);
  1054. if Assigned(ImageFactory) then
  1055. begin
  1056. if Succeeded(ImageFactory.GetImage(Size, SIIGBF_RESIZETOFIT, Handle)) then
  1057. begin
  1058. Result := TBitmap.Create;
  1059. try
  1060. Result.Handle := Handle;
  1061. Result.PixelFormat := pf32bit;
  1062. for Y := 0 to Result.Height - 1 do
  1063. begin
  1064. Row := Result.ScanLine[Y];
  1065. for X := 0 to Result.Width - 1 do
  1066. begin
  1067. Pixel := @Row[X];
  1068. Alpha := Pixel.rgbReserved;
  1069. Pixel.rgbBlue := (Pixel.rgbBlue * Alpha) div 255;
  1070. Pixel.rgbGreen := (Pixel.rgbGreen * Alpha) div 255;
  1071. Pixel.rgbRed := (Pixel.rgbRed * Alpha) div 255;
  1072. end;
  1073. end;
  1074. except
  1075. Result.Free;
  1076. raise;
  1077. end;
  1078. end;
  1079. ImageFactory := nil; // Redundant?
  1080. end;
  1081. end;
  1082. initialization
  1083. InitializeCriticalSection(ThreadLock);
  1084. if not Assigned(DriveInfo) then
  1085. begin
  1086. DriveInfo := TDriveInfo.Create;
  1087. InternalWindowHandle := Classes.AllocateHWnd(DriveInfo.InternalWndProc);
  1088. end;
  1089. finalization
  1090. if Assigned(DriveInfo) then
  1091. begin
  1092. EnterCriticalSection(ThreadLock);
  1093. Classes.DeallocateHWnd(InternalWindowHandle);
  1094. InternalWindowHandle := 0;
  1095. DriveInfo.Free;
  1096. DriveInfo := nil;
  1097. LeaveCriticalSection(ThreadLock);
  1098. end;
  1099. DeleteCriticalSection(ThreadLock);
  1100. end.