IEDriveInfo.pas 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  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. else
  509. begin
  510. Result := GetSimpleName(Drive);
  511. end;
  512. end; {TDriveInfo.GetPrettyName}
  513. function TDriveInfo.GetSimpleName(Drive: string): string;
  514. begin
  515. Result := Drive;
  516. if IsRealDrive(Result) then Result := Result + ':';
  517. end;
  518. function TDriveInfo.Get(Drive: string): TDriveInfoRec;
  519. begin
  520. NeedData;
  521. // We might want to wait for FReadyDrives to be empty before returning
  522. // (or even better do that only in DriveReady getter)
  523. if not FData.TryGetValue(Drive, Result) then
  524. begin
  525. Assert(IsUncPath(Drive));
  526. Result := AddDrive(Drive);
  527. DriveRefresh;
  528. end;
  529. end; {TDriveInfo.GetData}
  530. procedure TDriveInfo.ReadDriveStatus(Drive: string; Flags: Integer);
  531. begin
  532. // Among other, this makes sure the pending drive-ready status from the background thread are collected,
  533. // before we overwrite it with fresh status here.
  534. NeedData;
  535. DoReadDriveStatus(Drive, Flags);
  536. end;
  537. procedure TDriveInfo.DoReadDriveStatus(Drive: string; Flags: Integer);
  538. var
  539. FileInfo: TShFileInfo;
  540. DriveRoot: string;
  541. DriveID: string;
  542. CPos: Integer;
  543. Eaten: ULONG;
  544. ShAttr: ULONG;
  545. MaxFileNameLength: DWORD;
  546. FileSystemFlags: DWORD;
  547. FreeSpace: Int64;
  548. SimpleName: string;
  549. DriveInfoRec: TDriveInfoRec;
  550. S: string;
  551. begin
  552. if not Assigned(FDesktop) then
  553. SHGetDesktopFolder(FDesktop);
  554. DriveRoot := GetDriveRoot(Drive);
  555. // When this method is called, the entry always exists already
  556. Assert(FData.ContainsKey(Drive));
  557. DriveInfoRec := FData[Drive];
  558. with DriveInfoRec do
  559. begin
  560. Init := True;
  561. ReadDriveBasicStatus(Drive);
  562. if Valid then
  563. begin
  564. if (not Assigned(PIDL)) and IsFixedDrive(Drive) then
  565. begin
  566. ShAttr := 0;
  567. if DriveType = DRIVE_REMOTE then
  568. begin
  569. ShellFolderParseDisplayNameWithTimeout(
  570. FDesktop, Application.Handle, nil, PChar(DriveRoot), Eaten, PIDL, ShAttr, 2 * MSecsPerSec);
  571. end
  572. else
  573. begin
  574. FDesktop.ParseDisplayName(Application.Handle, nil, PChar(DriveRoot), Eaten, PIDL, ShAttr);
  575. end;
  576. end;
  577. {Read driveStatus:}
  578. if (Flags and dsSize) <> 0 then
  579. begin
  580. DriveReady := GetDiskFreeSpaceEx(PChar(DriveRoot), FreeSpace, Size, nil);
  581. if DriveReady then
  582. begin
  583. {Access the physical drive:}
  584. if GetVolumeInformation(PChar(DriveRoot), nil, 0,
  585. @DriveSerial, MaxFileNameLength, FileSystemFlags,
  586. nil, 0) then
  587. begin
  588. end
  589. else
  590. begin
  591. DriveSerial := 0;
  592. end;
  593. end
  594. else
  595. begin
  596. DriveSerial := 0;
  597. end;
  598. // Particularly when removing drive fails (as other app has it locked), we end up with not monitoring the
  599. // drive. When the drive is visited again in panel, it calls into here, and we take the opportunity
  600. // to resume monitoring
  601. UpdateDriveNotifications(Drive);
  602. end;
  603. {DisplayName:}
  604. if (Flags and dsDisplayName) <> 0 then
  605. begin
  606. {Fetch drives displayname:}
  607. SimpleName := GetSimpleName(Drive);
  608. if Assigned(PIDL) then DisplayName := GetShellFileName(PIDL)
  609. else
  610. begin
  611. // typical reason we do not have PIDL is that it took too long to
  612. // call ParseDisplayName, in what case calling SHGetFileInfo with
  613. // path (instead of PIDL) will take long too, avoiding that and using
  614. // fallback
  615. DisplayName := '(' + SimpleName + ')';
  616. end;
  617. if DriveType <> DRIVE_REMOTE then
  618. begin
  619. PrettyName := SimpleName + ' ' + DisplayName;
  620. S := ' (' + SimpleName + ')';
  621. CPos := Pos(S, PrettyName);
  622. if CPos > 0 then
  623. Delete(PrettyName, CPos, Length(S));
  624. end
  625. else
  626. if IsRealDrive(Drive) then
  627. begin
  628. DriveID := GetNetWorkName(Drive);
  629. PrettyName := Format('%s %s (%s)', [SimpleName, ExtractFileName(DriveID), ExtractFileDir(DriveID)]);
  630. end
  631. else
  632. begin
  633. Assert(IsUncPath(DriveRoot));
  634. PrettyName := SimpleName;
  635. end;
  636. end;
  637. {ImageIndex:}
  638. if (Flags and dsImageIndex) <> 0 then
  639. begin
  640. if Assigned(PIDL) then
  641. begin
  642. SHGetFileInfo(PChar(PIDL), 0, FileInfo, SizeOf(FileInfo), SHGFI_SYSICONINDEX or SHGFI_SMALLICON or SHGFI_PIDL)
  643. end
  644. else
  645. begin
  646. SHGetFileInfo(PChar(DriveRoot), 0, FileInfo, SizeOf(FileInfo), SHGFI_SYSICONINDEX or SHGFI_SMALLICON);
  647. end;
  648. ImageIndex := FileInfo.iIcon;
  649. end;
  650. end
  651. else
  652. begin
  653. if Assigned(PIDL) then
  654. FreePIDL(PIDL);
  655. ResetDrive(Drive);
  656. end;
  657. end;
  658. end; {TDriveInfo.ReadDriveStatus}
  659. procedure TDriveInfo.OverrideDrivePolicy(Drive: string);
  660. var
  661. Mask: DWORD;
  662. begin
  663. Assert(FData.ContainsKey(Drive));
  664. Assert(FData[Drive].ValidButHiddenByDrivePolicy);
  665. Mask := (not GetDriveBitMask(Drive));
  666. FNoDrives := FNoDrives and Mask;
  667. ReadDriveStatus(Drive, dsAll);
  668. Assert(FData[Drive].Valid);
  669. DriveRefresh;
  670. end;
  671. procedure TDriveInfo.AddHandler(Handler: TDriveNotificationEvent);
  672. var
  673. ChangeNotifyEntry: TSHChangeNotifyEntry;
  674. Dummy: string;
  675. begin
  676. if not FHandlers.Contains(Handler) then
  677. begin
  678. FHandlers.Add(Handler);
  679. if FHandlers.Count = 1 then
  680. begin
  681. // Source: petr.solin 2022-02-25
  682. if SpecialFolderLocation(CSIDL_DESKTOP, Dummy, ChangeNotifyEntry.pidl) then
  683. begin
  684. ChangeNotifyEntry.fRecursive := False;
  685. FChangeNotify :=
  686. SHChangeNotifyRegister(
  687. InternalWindowHandle, SHCNRF_ShellLevel or SHCNRF_NewDelivery,
  688. SHCNE_RENAMEFOLDER or SHCNE_MEDIAINSERTED or SHCNE_MEDIAREMOVED,
  689. WM_USER_SHCHANGENOTIFY, 1, ChangeNotifyEntry);
  690. end;
  691. UpdateDrivesNotifications;
  692. end;
  693. end;
  694. end;
  695. procedure TDriveInfo.RemoveHandler(Handler: TDriveNotificationEvent);
  696. begin
  697. if (FHandlers.Remove(Handler) >= 0) and (FHandlers.Count = 0) then
  698. begin
  699. if FChangeNotify <> 0 then
  700. begin
  701. SHChangeNotifyDeregister(FChangeNotify);
  702. FChangeNotify := 0;
  703. end;
  704. UpdateDrivesNotifications;
  705. end;
  706. end;
  707. procedure TDriveInfo.InvokeHandlers(DriveNotification: TDriveNotification; Drive: string);
  708. var
  709. Handler: TDriveNotificationEvent;
  710. begin
  711. for Handler in FHandlers do
  712. Handler(DriveNotification, Drive);
  713. end;
  714. type
  715. PDevBroadcastHdr = ^TDevBroadcastHdr;
  716. TDevBroadcastHdr = record
  717. dbch_size: DWORD;
  718. dbch_devicetype: DWORD;
  719. dbch_reserved: DWORD;
  720. end;
  721. PDevBroadcastVolume = ^TDevBroadcastVolume;
  722. TDevBroadcastVolume = record
  723. dbcv_size: DWORD;
  724. dbcv_devicetype: DWORD;
  725. dbcv_reserved: DWORD;
  726. dbcv_unitmask: DWORD;
  727. dbcv_flags: WORD;
  728. end;
  729. PDEV_BROADCAST_HANDLE = ^DEV_BROADCAST_HANDLE;
  730. DEV_BROADCAST_HANDLE = record
  731. dbch_size : DWORD;
  732. dbch_devicetype : DWORD;
  733. dbch_reserved : DWORD;
  734. dbch_handle : THandle;
  735. dbch_hdevnotify : HDEVNOTIFY ;
  736. dbch_eventguid : TGUID;
  737. dbch_nameoffset : LongInt;
  738. dbch_data : Byte;
  739. end;
  740. PPItemIDList = ^PItemIDList;
  741. const
  742. DBT_DEVTYP_HANDLE = $00000006;
  743. DBT_CONFIGCHANGED = $0018;
  744. DBT_DEVICEARRIVAL = $8000;
  745. DBT_DEVICEQUERYREMOVE = $8001;
  746. DBT_DEVICEREMOVEPENDING = $8003;
  747. DBT_DEVICEREMOVECOMPLETE = $8004;
  748. DBT_DEVTYP_VOLUME = $00000002;
  749. // WORKAROUND Declaration in Winapi.ShlObj.pas is wrong
  750. function SHChangeNotification_Lock(hChange: THandle; dwProcId: DWORD;
  751. var PPidls: PPItemIDList; var plEvent: Longint): THANDLE; stdcall;
  752. external 'shell32.dll' name 'SHChangeNotification_Lock';
  753. procedure TDriveInfo.InternalWndProc(var Msg: TMessage);
  754. var
  755. DeviceType: DWORD;
  756. UnitMask: DWORD;
  757. DeviceHandle: THandle;
  758. Drive: Char;
  759. PPIDL: PPItemIDList;
  760. Event: LONG;
  761. Lock: THandle;
  762. DrivePair: TPair<string, TDriveInfoRec>;
  763. begin
  764. with Msg do
  765. begin
  766. if Msg = WM_USER_SHCHANGENOTIFY then
  767. begin
  768. Lock := SHChangeNotification_Lock(wParam, lParam, PPIDL, Event);
  769. try
  770. if (Event = SHCNE_RENAMEFOLDER) or // = drive rename
  771. (Event = SHCNE_MEDIAINSERTED) or // also bitlocker drive unlock (also sends SHCNE_UPDATEDIR)
  772. (Event = SHCNE_MEDIAREMOVED) then
  773. begin
  774. ScheduleDriveRefresh;
  775. end;
  776. finally
  777. SHChangeNotification_Unlock(Lock);
  778. end;
  779. end
  780. else
  781. // from RegisterDeviceNotification
  782. if Msg = WM_DEVICECHANGE then
  783. begin
  784. if (wParam = DBT_CONFIGCHANGED) or
  785. (wParam = DBT_DEVICEARRIVAL) or
  786. (wParam = DBT_DEVICEREMOVECOMPLETE) then
  787. begin
  788. ScheduleDriveRefresh;
  789. end
  790. else
  791. if (wParam = DBT_DEVICEQUERYREMOVE) or
  792. (wParam = DBT_DEVICEREMOVEPENDING) then
  793. begin
  794. DeviceType := PDevBroadcastHdr(lParam)^.dbch_devicetype;
  795. // This is specifically for VeraCrypt.
  796. // For normal drives, see DBT_DEVTYP_HANDLE below
  797. // (and maybe now that we have generic implementation, this specific code for VeraCrypt might not be needed anymore)
  798. if DeviceType = DBT_DEVTYP_VOLUME then
  799. begin
  800. UnitMask := PDevBroadcastVolume(lParam)^.dbcv_unitmask;
  801. Drive := FirstDrive;
  802. while UnitMask > 0 do
  803. begin
  804. if UnitMask and $01 <> 0 then
  805. begin
  806. DriveRemoving(Drive);
  807. end;
  808. UnitMask := UnitMask shr 1;
  809. Drive := Chr(Ord(Drive) + 1);
  810. end;
  811. end
  812. else
  813. if DeviceType = DBT_DEVTYP_HANDLE then
  814. begin
  815. DeviceHandle := PDEV_BROADCAST_HANDLE(lParam)^.dbch_handle;
  816. for DrivePair in FData do
  817. if DrivePair.Value.DriveHandle = DeviceHandle then
  818. begin
  819. DriveRemoving(DrivePair.Key);
  820. end;
  821. end;
  822. end;
  823. end
  824. else
  825. if Msg = WM_TIMER then
  826. begin
  827. CancelDriveRefresh;
  828. try
  829. for Drive := FirstFixedDrive to LastDrive do
  830. ReadDriveStatus(Drive, dsSynchronous);
  831. ReadAsynchronous;
  832. DriveRefresh;
  833. except
  834. Application.HandleException(Self);
  835. end;
  836. end
  837. else
  838. if Msg = WM_DRIVEINFO_PROCESS then
  839. begin
  840. ProcessThreadResults;
  841. end;
  842. Result := DefWindowProc(InternalWindowHandle, Msg, wParam, lParam);
  843. end;
  844. end;
  845. procedure TDriveInfo.DriveRemoving(Drive: string);
  846. begin
  847. FData[Drive].DriveReady := False;
  848. UpdateDriveNotifications(Drive);
  849. AppLog(Format('Removing drive "%s"', [Drive]));
  850. InvokeHandlers(dnRemoving, Drive);
  851. end;
  852. procedure TDriveInfo.CancelDriveRefresh;
  853. begin
  854. KillTimer(InternalWindowHandle, 1);
  855. end;
  856. procedure TDriveInfo.ScheduleDriveRefresh;
  857. begin
  858. CancelDriveRefresh;
  859. // Delay refreshing drives for a sec.
  860. // Particularly with CD/DVD drives, if we query display name
  861. // immediately after receiving DBT_DEVICEARRIVAL, we do not get media label.
  862. // Actually one sec does not help usually, but we do not want to wait any longer,
  863. // because we want to add USB drives asap.
  864. // And this problem might be solved now by SHChangeNotifyRegister/SHCNE_RENAMEFOLDER.
  865. SetTimer(InternalWindowHandle, 1, MSecsPerSec, nil);
  866. end;
  867. procedure TDriveInfo.UpdateDriveNotifications(Drive: string);
  868. var
  869. NeedNotifications: Boolean;
  870. Path: string;
  871. DevBroadcastHandle: DEV_BROADCAST_HANDLE;
  872. Size: Integer;
  873. DriveInfoRec: TDriveInfoRec;
  874. begin
  875. if IsFixedDrive(Drive) then
  876. begin
  877. // Not using Get to avoid recursion
  878. DriveInfoRec := FData[Drive];
  879. NeedNotifications :=
  880. (FHandlers.Count > 0) and
  881. (DriveInfoRec.DriveType <> DRIVE_REMOTE) and
  882. DriveInfoRec.DriveReady and
  883. DriveInfoRec.SubscribeDriveNotifications;
  884. if NeedNotifications <> (DriveInfoRec.DriveHandle <> INVALID_HANDLE_VALUE) then
  885. begin
  886. Path := GetDriveRoot(Drive);
  887. if NeedNotifications then
  888. begin
  889. DriveInfoRec.DriveHandle :=
  890. CreateFile(PChar(Path), GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE, nil,
  891. OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS or FILE_ATTRIBUTE_NORMAL, 0);
  892. if DriveInfoRec.DriveHandle <> INVALID_HANDLE_VALUE then
  893. begin
  894. Size := SizeOf(DevBroadcastHandle);
  895. ZeroMemory(@DevBroadcastHandle, Size);
  896. DevBroadcastHandle.dbch_size := Size;
  897. DevBroadcastHandle.dbch_devicetype := DBT_DEVTYP_HANDLE;
  898. DevBroadcastHandle.dbch_handle := DriveInfoRec.DriveHandle;
  899. DriveInfoRec.NotificationHandle :=
  900. RegisterDeviceNotification(InternalWindowHandle, @DevBroadcastHandle, DEVICE_NOTIFY_WINDOW_HANDLE);
  901. if DriveInfoRec.NotificationHandle <> nil then
  902. begin
  903. AppLog(Format('Registered drive notification for "%s"', [Path]));
  904. end
  905. else
  906. begin
  907. CloseHandle(DriveInfoRec.DriveHandle);
  908. DriveInfoRec.DriveHandle := INVALID_HANDLE_VALUE;
  909. end;
  910. end;
  911. end
  912. else
  913. begin
  914. AppLog(Format('Unregistered drive notification for "%s"', [Path]));
  915. UnregisterDeviceNotification(DriveInfoRec.NotificationHandle);
  916. DriveInfoRec.NotificationHandle := nil;
  917. CloseHandle(DriveInfoRec.DriveHandle);
  918. DriveInfoRec.DriveHandle := INVALID_HANDLE_VALUE;
  919. end;
  920. end;
  921. end;
  922. end;
  923. procedure TDriveInfo.UpdateDrivesNotifications;
  924. var
  925. Drive: string;
  926. begin
  927. for Drive in FData.Keys do
  928. UpdateDriveNotifications(Drive);
  929. end;
  930. procedure TDriveInfo.DriveRefresh;
  931. begin
  932. InvokeHandlers(dnRefresh, '');
  933. end;
  934. procedure TDriveInfo.SubscribeDriveNotifications(Drive: string);
  935. begin
  936. Get(Drive).SubscribeDriveNotifications := True;
  937. UpdateDriveNotifications(Drive);
  938. end;
  939. // ===================
  940. function GetShellFileName(PIDL: PItemIDList): string;
  941. var
  942. SFI: TSHFileInfo;
  943. begin
  944. if SHGetFileInfo(PChar(PIDL), 0, SFI, SizeOf(TSHFileInfo), SHGFI_PIDL or SHGFI_DISPLAYNAME) <> 0 then
  945. Result := SFI.szDisplayName;
  946. end; {GetShellFileName}
  947. function GetNetWorkName(Drive: string): string;
  948. var
  949. Path: string;
  950. P: array[0..MAX_PATH] of Char;
  951. MaxLen : DWORD;
  952. begin
  953. Path := ExcludeTrailingBackslash(DriveInfo.GetDriveRoot(Drive));
  954. MaxLen := MAX_PATH;
  955. if WNetGetConnection(PChar(Path), P, MaxLen) = NO_ERROR then
  956. Result := P
  957. else
  958. Result := '';
  959. end; {GetNetWorkName}
  960. type
  961. LPBYTE = ^BYTE;
  962. LMSTR = LPWSTR;
  963. NET_API_STATUS = DWORD;
  964. _USE_INFO_1 = record
  965. ui1_local: LMSTR;
  966. ui1_remote: LMSTR;
  967. ui1_password: LMSTR;
  968. ui1_status: DWORD;
  969. ui1_asg_type: DWORD;
  970. ui1_refcount: DWORD;
  971. ui1_usecount: DWORD;
  972. end;
  973. USE_INFO_1 = _USE_INFO_1;
  974. PUSE_INFO_1 = ^USE_INFO_1;
  975. LPVOID = Pointer;
  976. const
  977. USE_OK = 0;
  978. USE_PAUSED = 1;
  979. USE_SESSLOST = 2;
  980. USE_DISCONN = 2;
  981. USE_NETERR = 3;
  982. USE_CONN = 4;
  983. USE_RECONN = 5;
  984. function NetUseGetInfo(UncServerName: LMSTR; UseName: LMSTR; Level: DWORD; var BufPtr: LPBYTE): NET_API_STATUS; stdcall; external 'netapi32.dll';
  985. function NetApiBufferFree(Buffer: Pointer): DWORD; stdcall; external 'netapi32.dll';
  986. function GetNetWorkConnected(Drive: string): Boolean;
  987. var
  988. BufPtr: LPBYTE;
  989. NetResult: Integer;
  990. ServerName: string;
  991. PServerName: PChar;
  992. Name: string;
  993. P: Integer;
  994. begin
  995. Name := '';
  996. PServerName := nil;
  997. if DriveInfo.IsRealDrive(Drive) then
  998. begin
  999. Name := Drive + ':';
  1000. end
  1001. else
  1002. if IsUncPath(Drive) then
  1003. begin
  1004. Name := Copy(Drive, 3, Length(Drive) - 2);
  1005. P := Pos('\', Name);
  1006. if P > 0 then
  1007. begin
  1008. ServerName := Copy(Name, P + 1, Length(Name) - P);
  1009. PServerName := PChar(ServerName);
  1010. SetLength(Name, P - 1);
  1011. end
  1012. else
  1013. begin
  1014. Assert(False);
  1015. end;
  1016. end
  1017. else
  1018. begin
  1019. Assert(False);
  1020. end;
  1021. if Name = '' then
  1022. begin
  1023. Result := False;
  1024. end
  1025. else
  1026. begin
  1027. NetResult := NetUseGetInfo(PServerName, PChar(Name), 1, BufPtr);
  1028. if NetResult = 0 then
  1029. begin
  1030. Result := (PUSE_INFO_1(BufPtr)^.ui1_status = USE_OK);
  1031. NetApiBufferFree(LPVOID(BufPtr));
  1032. end
  1033. else
  1034. begin
  1035. // NetUseGetInfo works for DFS shares only, hence when it fails
  1036. // we suppose different share type and fallback to "connected"
  1037. Result := True;
  1038. end;
  1039. end;
  1040. end;
  1041. function IsRootPath(Path: string): Boolean;
  1042. begin
  1043. Result := SameText(ExcludeTrailingBackslash(ExtractFileDrive(Path)), ExcludeTrailingBackslash(Path));
  1044. end;
  1045. function GetThumbnail(Path: string; Size: TSize): TBitmap;
  1046. var
  1047. ImageFactory: IShellItemImageFactory;
  1048. X, Y: Integer;
  1049. Row: PRGBQuadArray;
  1050. Pixel: PRGBQuad;
  1051. Alpha: Byte;
  1052. Handle: HBITMAP;
  1053. begin
  1054. Result := nil;
  1055. SHCreateItemFromParsingName(PChar(Path), nil, IShellItemImageFactory, ImageFactory);
  1056. if Assigned(ImageFactory) then
  1057. begin
  1058. if Succeeded(ImageFactory.GetImage(Size, SIIGBF_RESIZETOFIT, Handle)) then
  1059. begin
  1060. Result := TBitmap.Create;
  1061. try
  1062. Result.Handle := Handle;
  1063. Result.PixelFormat := pf32bit;
  1064. for Y := 0 to Result.Height - 1 do
  1065. begin
  1066. Row := Result.ScanLine[Y];
  1067. for X := 0 to Result.Width - 1 do
  1068. begin
  1069. Pixel := @Row[X];
  1070. Alpha := Pixel.rgbReserved;
  1071. Pixel.rgbBlue := (Pixel.rgbBlue * Alpha) div 255;
  1072. Pixel.rgbGreen := (Pixel.rgbGreen * Alpha) div 255;
  1073. Pixel.rgbRed := (Pixel.rgbRed * Alpha) div 255;
  1074. end;
  1075. end;
  1076. except
  1077. Result.Free;
  1078. raise;
  1079. end;
  1080. end;
  1081. ImageFactory := nil; // Redundant?
  1082. end;
  1083. end;
  1084. initialization
  1085. InitializeCriticalSection(ThreadLock);
  1086. if not Assigned(DriveInfo) then
  1087. begin
  1088. DriveInfo := TDriveInfo.Create;
  1089. InternalWindowHandle := Classes.AllocateHWnd(DriveInfo.InternalWndProc);
  1090. end;
  1091. finalization
  1092. if Assigned(DriveInfo) then
  1093. begin
  1094. EnterCriticalSection(ThreadLock);
  1095. Classes.DeallocateHWnd(InternalWindowHandle);
  1096. InternalWindowHandle := 0;
  1097. DriveInfo.Free;
  1098. DriveInfo := nil;
  1099. LeaveCriticalSection(ThreadLock);
  1100. end;
  1101. DeleteCriticalSection(ThreadLock);
  1102. end.