DriveView.pas 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071
  1. unit DriveView;
  2. {==================================================================
  3. Component TDriveView / Version 2.6, January 2000
  4. ==================================================================
  5. Description:
  6. ============
  7. Displays the the directory structure of all drives as treeview
  8. with shell icons. Complete drag&Drop support for files and
  9. directories.
  10. Author:
  11. =======
  12. (c) Ingo Eckel 1998, 1999
  13. Sodener Weg 38
  14. 65812 Bad Soden
  15. Germany
  16. Modifications (for WinSCP):
  17. ===========================
  18. (c) Martin Prikryl 2004
  19. V2.6:
  20. - Shows "shared"-symbol with directories
  21. - Delphi5 compatible
  22. For detailed documentation and history see TDriveView.htm.
  23. {==================================================================}
  24. interface
  25. { Define ENHVALIDATE to scan all existing directories on a detected filesystem change:}
  26. {.$DEFINE ENHVALIDATE}
  27. {Required compiler options for TDriveView:}
  28. {$A+,B-,X+,H+,P+}
  29. {$WARN SYMBOL_PLATFORM OFF}
  30. uses
  31. Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, ComObj,
  32. Dialogs, ComCtrls, ShellApi, CommCtrl, ExtCtrls, ActiveX, ShlObj,
  33. DirView, ShellDialogs, DragDrop, DragDropFilesEx, FileChanges, FileOperator,
  34. DiscMon, IEDriveInfo, IEListView, BaseUtils, CustomDirView,
  35. CustomDriveView, System.Generics.Collections, CompThread;
  36. const
  37. msThreadChangeDelay = 50;
  38. ErrorNodeNA = '%s: Node not assigned';
  39. {Flags used by TDriveView.RefreshRootNodes:}
  40. dvdsFloppy = 8; {Include floppy drives}
  41. dvdsRereadAllways = 16; {Refresh drivestatus in any case}
  42. WM_USER_SUBDIRREADER = WM_USER_SHCHANGENOTIFY + 1;
  43. type
  44. EInvalidDirName = class(Exception);
  45. ENodeNotAssigned = class(Exception);
  46. TDriveStatus = class
  47. Scanned: Boolean; {Drive allready scanned?}
  48. Verified: Boolean; {Drive completly scanned?}
  49. RootNode: TTreeNode; {Rootnode to drive}
  50. RootNodeIndex: Integer;
  51. DiscMonitor: TDiscMonitor; {Monitor thread}
  52. ChangeTimer: TTimer; {Change timer for the monitor thread}
  53. DefaultDir: string; {Current directory}
  54. end;
  55. TDriveStatusPair = TPair<string, TDriveStatus>;
  56. TScanDirInfo = record
  57. SearchNewDirs: Boolean;
  58. StartNode: TTreeNode;
  59. DriveType: Integer;
  60. end;
  61. PScanDirInfo = ^TScanDirInfo;
  62. TDriveView = class;
  63. TSubDirReaderSchedule = class
  64. Node: TTreeNode;
  65. Path: string;
  66. Deleted: Boolean;
  67. Processed: Boolean;
  68. end;
  69. TNodeData = class
  70. private
  71. FDirName: string;
  72. FAttr: Integer;
  73. FScanned: Boolean;
  74. FData: Pointer;
  75. FIsRecycleBin: Boolean;
  76. FIconEmpty: Boolean;
  77. FSchedule: TSubDirReaderSchedule;
  78. public
  79. DelayedSrec: TSearchRec;
  80. DelayedExclude: TStringList;
  81. constructor Create;
  82. destructor Destroy; override;
  83. property DirName: string read FDirName write FDirName;
  84. property Attr: Integer read FAttr write FAttr;
  85. property Scanned: Boolean read FScanned write FScanned;
  86. property Data: Pointer read FData write FData;
  87. property IsRecycleBin: Boolean read FIsRecycleBin;
  88. property IconEmpty: Boolean read FIconEmpty write FIconEmpty;
  89. property Schedule: TSubDirReaderSchedule read FSchedule write FSchedule;
  90. end;
  91. TDriveTreeNode = class(TTreeNode)
  92. procedure Assign(Source: TPersistent); override;
  93. end;
  94. TSubDirReaderThread = class(TCompThread)
  95. public
  96. destructor Destroy; override;
  97. procedure Terminate; override;
  98. protected
  99. constructor Create(DriveView: TDriveView);
  100. procedure Add(Node: TTreeNode; Path: string);
  101. procedure Delete(Node: TTreeNode);
  102. function Detach: Integer;
  103. procedure Reattach(Count: Integer);
  104. procedure Execute; override;
  105. private
  106. FDriveView: TDriveView;
  107. FEvent: THandle;
  108. FQueue: TStack<TSubDirReaderSchedule>;
  109. FResults: TQueue<TSubDirReaderSchedule>;
  110. FSection: TRTLCriticalSection;
  111. FTimer: TTimer;
  112. FWindowHandle: HWND;
  113. procedure TriggerEvent;
  114. procedure ScheduleProcess;
  115. procedure Process;
  116. function ProcessResult: Boolean;
  117. procedure Timer(Sender: TObject);
  118. procedure WndProc(var Msg: TMessage);
  119. end;
  120. TDriveView = class(TCustomDriveView)
  121. private
  122. FDriveStatus: TObjectDictionary<string, TDriveStatus>;
  123. FConfirmDelete: Boolean;
  124. FConfirmOverwrite: Boolean;
  125. FWatchDirectory: Boolean;
  126. FDirectory: string;
  127. FShowVolLabel: Boolean;
  128. FVolDisplayStyle: TVolumeDisplayStyle;
  129. FChangeFlag: Boolean;
  130. FLastDir: string;
  131. FValidateFlag: Boolean;
  132. FSysColorChangePending: Boolean;
  133. FCreating: Boolean;
  134. FForceRename: Boolean;
  135. FRenameNode: TTreeNode;
  136. FLastRenameName: string;
  137. FPrevSelected: TTreeNode;
  138. FPrevSelectedIndex: Integer;
  139. FChangeTimerSuspended: Integer;
  140. FSubDirReaderThread: TSubDirReaderThread;
  141. FDelayedNodes: TStringList;
  142. FDelayedNodeTimer: TTimer;
  143. {Additional events:}
  144. FOnDisplayContextMenu: TNotifyEvent;
  145. FOnNeedHiddenDirectories: TNotifyEvent;
  146. {used components:}
  147. FDirView: TDirView;
  148. FFileOperator: TFileOperator;
  149. FChangeInterval: Cardinal;
  150. {Drag&drop:}
  151. FLastPathCut: string;
  152. {Drag&drop helper functions:}
  153. procedure SignalDirDelete(Sender: TObject; Files: TStringList);
  154. function GetSubDir(var SRec: TSearchRec): Boolean;
  155. function FindFirstSubDir(Path: string; var SRec: TSearchRec): Boolean;
  156. function FindNextSubDir(var SRec: TSearchRec): Boolean;
  157. procedure ReadSubDirs(Node: TTreeNode);
  158. procedure CancelDelayedNode(Node: TTreeNode);
  159. procedure DelayedNodeTimer(Sender: TObject);
  160. function ReadSubDirsBatch(Node: TTreeNode; var SRec: TSearchRec; CheckInterval, Limit: Integer): Boolean;
  161. procedure UpdateDelayedNodeTimer;
  162. {Callback-functions used by iteratesubtree:}
  163. function CallBackValidateDir(var Node: TTreeNode; Data: Pointer): Boolean;
  164. procedure DeleteNode(Node: TTreeNode);
  165. { Notification procedures used by component TDiscMonitor: }
  166. procedure ChangeDetected(Sender: TObject; const Directory: string;
  167. var SubdirsChanged: Boolean);
  168. procedure ChangeInvalid(Sender: TObject; const Directory: string; const ErrorStr: string);
  169. {Notification procedure used by component TTimer:}
  170. procedure ChangeTimerOnTimer(Sender: TObject);
  171. protected
  172. procedure SetSelected(Node: TTreeNode);
  173. procedure SetWatchDirectory(Value: Boolean);
  174. procedure SetShowVolLabel(ShowIt: Boolean);
  175. procedure SetDirView(Value: TDirView);
  176. procedure SetDirectory(Value: string); override;
  177. function DoScanDir(FromNode: TTreeNode): Boolean;
  178. procedure AddChildNode(ParentNode: TTreeNode; ParentPath: string; SRec: TSearchRec);
  179. procedure CreateWatchThread(Drive: string);
  180. function NodeWatched(Node: TTreeNode): Boolean;
  181. procedure TerminateWatchThread(Drive: string);
  182. function WatchThreadActive: Boolean; overload;
  183. function WatchThreadActive(Drive: string): Boolean; overload;
  184. procedure SubscribeDriveNotifications(Drive: string);
  185. procedure DriveRemoved(Drive: string);
  186. procedure DriveRemoving(Drive: string);
  187. procedure RefreshRootNodes(Floppy: Boolean = False);
  188. procedure DriveNotification(Notification: TDriveNotification; Drive: string);
  189. function DirAttrMask: Integer;
  190. function CreateDriveStatus: TDriveStatus;
  191. procedure ValidateDirectoryEx(Node: TTreeNode; Recurse: TRecursiveScan;
  192. NewDirs: Boolean); override;
  193. procedure RebuildTree; override;
  194. procedure SetLastPathCut(Path: string);
  195. function GetCanUndoCopyMove: Boolean; virtual;
  196. procedure CreateWnd; override;
  197. procedure DestroyWnd; override;
  198. procedure Edit(const Item: TTVItem); override;
  199. procedure WMUserRename(var Message: TMessage); message WM_USER_RENAME;
  200. procedure CMRecreateWnd(var Msg: TMessage); message CM_RECREATEWND;
  201. procedure CMSysColorChange(var Message: TMessage); message CM_SYSCOLORCHANGE;
  202. function GetCustomDirView: TCustomDirView; override;
  203. procedure SetCustomDirView(Value: TCustomDirView); override;
  204. function NodePath(Node: TTreeNode): string; override;
  205. function NodeIsRecycleBin(Node: TTreeNode): Boolean; override;
  206. function NodePathExists(Node: TTreeNode): Boolean; override;
  207. function NodeColor(Node: TTreeNode): TColor; override;
  208. function FindPathNode(Path: string): TTreeNode; override;
  209. function DoFindNodeToPath(Path: string; ExistingOnly: Boolean): TTreeNode;
  210. function CreateNode: TTreeNode; override;
  211. function DDSourceEffects: TDropEffectSet; override;
  212. procedure DDChooseEffect(KeyState: Integer; var Effect: Integer; PreferredEffect: Integer); override;
  213. function DragCompleteFileList: Boolean; override;
  214. function DDExecute: TDragResult; override;
  215. public
  216. property Images;
  217. property StateImages;
  218. property Items stored False;
  219. property Selected Write SetSelected stored False;
  220. property DragImageList: TDragImageList read FDragImageList;
  221. property CanUndoCopyMove: Boolean read GetCanUndoCopyMove;
  222. property DDFileOperator: TFileOperator read FFileOperator;
  223. property LastPathCut: string read FLastPathCut write SetLastPathCut;
  224. function UndoCopyMove: Boolean; dynamic;
  225. procedure EmptyClipboard; dynamic;
  226. function CopyToClipBoard(Node: TTreeNode): Boolean; dynamic;
  227. function CutToClipBoard(Node: TTreeNode): Boolean; dynamic;
  228. function CanPasteFromClipBoard: Boolean; dynamic;
  229. function PasteFromClipBoard(TargetPath: string = ''): Boolean; dynamic;
  230. procedure PerformDragDropFileOperation(Node: TTreeNode; Effect: Integer); override;
  231. {Drive handling:}
  232. function GetDriveStatus(Drive: string): TDriveStatus;
  233. function GetDriveTypetoNode(Node: TTreeNode): Integer; {Returns DRIVE_CDROM etc..}
  234. function GetDriveToNode(Node: TTreeNode): string;
  235. function GetDriveText(Drive: string): string;
  236. procedure ScanDrive(Drive: string);
  237. function GetDrives: TStrings;
  238. {Node handling:}
  239. procedure SetImageIndex(Node: TTreeNode); virtual;
  240. function FindNodeToPath(Path: string): TTreeNode;
  241. function TryFindNodeToPath(Path: string): TTreeNode;
  242. function RootNode(Node: TTreeNode): TTreeNode;
  243. function GetDirName(Node: TTreeNode): string;
  244. function GetDisplayName(Node: TTreeNode): string;
  245. function NodePathName(Node: TTreeNode): string; override;
  246. constructor Create(AOwner: TComponent); override;
  247. destructor Destroy; override;
  248. {Menu-handling:}
  249. procedure DisplayContextMenu(Node: TTreeNode; Point: TPoint); override;
  250. procedure DisplayPropertiesMenu(Node: TTreeNode); override;
  251. {Watchthread handling:}
  252. procedure StartWatchThread;
  253. procedure StopWatchThread;
  254. procedure SuspendChangeTimer;
  255. procedure ResumeChangeTimer;
  256. procedure StartAllWatchThreads;
  257. procedure StopAllWatchThreads;
  258. procedure ValidateCurrentDirectoryIfNotMonitoring;
  259. (* Modified Events: *)
  260. procedure GetImageIndex(Node: TTreeNode); override;
  261. function CanEdit(Node: TTreeNode): Boolean; override;
  262. function CanChange(Node: TTreeNode): Boolean; override;
  263. function CanExpand(Node: TTreeNode): Boolean; override;
  264. procedure Delete(Node: TTreeNode); override;
  265. procedure Loaded; override;
  266. procedure KeyPress(var Key: Char); override;
  267. procedure Change(Node: TTreeNode); override;
  268. published
  269. {Additional properties:}
  270. {Current selected directory:}
  271. property Directory;
  272. {Confirm deleting directories:}
  273. property ConfirmDelete: Boolean read FConfirmDelete write FConfirmDelete default True;
  274. {Confirm overwriting directories:}
  275. property ConfirmOverwrite: Boolean read FConfirmOverwrite write FConfirmOverwrite default True;
  276. {Enable automatic update on filesystem changes:}
  277. property WatchDirectory: Boolean read FWatchDirectory write SetWatchDirectory default False;
  278. {Linked component TDirView:}
  279. property DirView: TDirView read FDirView write SetDirView;
  280. {Show the volume labels of drives:}
  281. property ShowVolLabel: Boolean read FShowVolLabel write SetShowVolLabel default True;
  282. {Additional events:}
  283. property OnDisplayContextMenu: TNotifyEvent read FOnDisplayContextMenu
  284. write FOnDisplayContextMenu;
  285. property OnBusy;
  286. property DDLinkOnExeDrag;
  287. property TargetPopUpMenu;
  288. property OnDDDragEnter;
  289. property OnDDDragLeave;
  290. property OnDDDragOver;
  291. property OnDDDrop;
  292. property OnDDQueryContinueDrag;
  293. property OnDDGiveFeedback;
  294. property OnDDDragDetect;
  295. property OnDDProcessDropped;
  296. property OnDDError;
  297. property OnDDExecuted;
  298. property OnDDFileOperation;
  299. property OnDDFileOperationExecuted;
  300. property Align;
  301. property Anchors;
  302. property AutoExpand;
  303. property BiDiMode;
  304. property BorderStyle;
  305. property BorderWidth;
  306. property ChangeDelay;
  307. property Color;
  308. property Ctl3D;
  309. property Constraints;
  310. property DoubleBuffered;
  311. {Delphi's drag&drop is not compatible with the OLE windows drag&drop:}
  312. property DragKind;
  313. property DragCursor;
  314. property DragMode Default dmAutomatic;
  315. property OnDragDrop;
  316. property OnDragOver;
  317. property Enabled;
  318. property Font;
  319. property HideSelection;
  320. property HotTrack;
  321. property Indent;
  322. property ParentBiDiMode;
  323. property ParentColor;
  324. property ParentCtl3D;
  325. property ParentDoubleBuffered;
  326. property ParentFont;
  327. property ParentShowHint;
  328. property PopupMenu;
  329. property ReadOnly;
  330. property RightClickSelect;
  331. property RowSelect;
  332. property ShowButtons;
  333. property ShowHint;
  334. property ShowLines;
  335. property TabOrder;
  336. property TabStop default True;
  337. property ToolTips;
  338. property Visible;
  339. property OnChange;
  340. property OnChanging;
  341. property OnClick;
  342. property OnCollapsing;
  343. property OnCollapsed;
  344. property OnCompare;
  345. property OnDblClick;
  346. property OnDeletion;
  347. property OnEdited;
  348. property OnEditing;
  349. property OnEndDock;
  350. property OnEndDrag;
  351. property OnEnter;
  352. property OnExit;
  353. property OnExpanding;
  354. property OnExpanded;
  355. property OnGetImageIndex;
  356. property OnGetSelectedIndex;
  357. property OnKeyDown;
  358. property OnKeyPress;
  359. property OnKeyUp;
  360. property OnMouseDown;
  361. property OnMouseMove;
  362. property OnMouseUp;
  363. property OnStartDock;
  364. property OnStartDrag;
  365. property OnNeedHiddenDirectories: TNotifyEvent read FOnNeedHiddenDirectories write FOnNeedHiddenDirectories;
  366. end;
  367. var
  368. DriveViewLoadingTooLongLimit: Integer = 0;
  369. procedure Register;
  370. implementation
  371. uses
  372. PasTools, UITypes, SyncObjs, IOUtils, System.DateUtils;
  373. type
  374. PInt = ^Integer;
  375. procedure Register;
  376. begin
  377. RegisterComponents('DriveDir', [TDriveView]);
  378. end; {Register}
  379. constructor TNodeData.Create;
  380. begin
  381. inherited;
  382. FAttr := 0;
  383. FScanned := False;
  384. FDirName := '';
  385. FIsRecycleBin := False;
  386. FIconEmpty := True;
  387. FSchedule := nil;
  388. DelayedExclude := nil;
  389. end; {TNodeData.Create}
  390. destructor TNodeData.Destroy;
  391. begin
  392. Assert(not Assigned(FSchedule));
  393. SetLength(FDirName, 0);
  394. inherited;
  395. end; {TNodeData.Destroy}
  396. { TSubDirReaderThread }
  397. constructor TSubDirReaderThread.Create(DriveView: TDriveView);
  398. begin
  399. inherited Create(True);
  400. FDriveView := DriveView;
  401. FSection.Initialize;
  402. FEvent := CreateEvent(nil, False, False, nil);
  403. FQueue := TStack<TSubDirReaderSchedule>.Create;
  404. FResults := TQueue<TSubDirReaderSchedule>.Create;
  405. FTimer := TTimer.Create(FDriveView);
  406. FTimer.Enabled := False;
  407. FTimer.Interval := 200;
  408. FTimer.OnTimer := Timer;
  409. FWindowHandle := AllocateHWnd(WndProc);
  410. end;
  411. destructor TSubDirReaderThread.Destroy;
  412. procedure DestroyScheduleList(List: TEnumerable<TSubDirReaderSchedule>);
  413. var
  414. Schedule: TSubDirReaderSchedule;
  415. begin
  416. for Schedule in List do
  417. begin
  418. if not Schedule.Deleted then
  419. TNodeData(Schedule.Node.Data).Schedule := nil;
  420. Schedule.Free;
  421. end;
  422. List.Destroy;
  423. end;
  424. begin
  425. inherited;
  426. DeallocateHWnd(FWindowHandle);
  427. DestroyScheduleList(FQueue);
  428. DestroyScheduleList(FResults);
  429. CloseHandle(FEvent);
  430. FTimer.Destroy;
  431. FSection.Destroy;
  432. end;
  433. procedure TSubDirReaderThread.WndProc(var Msg: TMessage);
  434. begin
  435. if Msg.Msg = WM_USER_SUBDIRREADER then
  436. ScheduleProcess
  437. else
  438. Msg.Result := DefWindowProc(FWindowHandle, Msg.Msg, Msg.wParam, Msg.lParam);
  439. end;
  440. procedure TSubDirReaderThread.Process;
  441. var
  442. Started: DWORD;
  443. Elapsed: Integer;
  444. Later: Boolean;
  445. begin
  446. Started := GetTickCount;
  447. Later := False;
  448. while (not Later) and ProcessResult do
  449. begin
  450. Elapsed := GetTickCount - Started;
  451. Later := (Elapsed < 0) or (Elapsed > 20);
  452. end;
  453. if not Later then
  454. FTimer.Enabled := False;
  455. end;
  456. procedure TSubDirReaderThread.Timer(Sender: TObject);
  457. begin
  458. Process;
  459. end;
  460. procedure TSubDirReaderThread.Add(Node: TTreeNode; Path: string);
  461. var
  462. NodeData: TNodeData;
  463. Schedule: TSubDirReaderSchedule;
  464. begin
  465. if Suspended then
  466. Resume;
  467. FSection.Enter;
  468. try
  469. NodeData := TNodeData(Node.Data);
  470. Assert(not Assigned(NodeData.Schedule));
  471. Schedule := TSubDirReaderSchedule.Create;
  472. Schedule.Node := Node;
  473. Schedule.Path := Path;
  474. Schedule.Deleted := False;
  475. Schedule.Processed := False;
  476. FQueue.Push(Schedule);
  477. NodeData.Schedule := Schedule;
  478. finally
  479. FSection.Leave;
  480. end;
  481. TriggerEvent;
  482. end;
  483. procedure TSubDirReaderThread.Delete(Node: TTreeNode);
  484. var
  485. NodeData: TNodeData;
  486. begin
  487. FSection.Enter;
  488. try
  489. NodeData := TNodeData(Node.Data);
  490. if Assigned(NodeData.Schedule) then
  491. begin
  492. NodeData.Schedule.Deleted := True;
  493. NodeData.Schedule := nil;
  494. end;
  495. finally
  496. FSection.Leave;
  497. end;
  498. TriggerEvent;
  499. end;
  500. function TSubDirReaderThread.Detach: Integer;
  501. procedure DetachList(List: TEnumerable<TSubDirReaderSchedule>);
  502. var
  503. Schedule: TSubDirReaderSchedule;
  504. begin
  505. for Schedule in List do
  506. begin
  507. if Schedule.Deleted then Schedule.Free
  508. else
  509. begin
  510. Assert(Schedule.Processed = (List = FResults));
  511. Schedule.Node := nil;
  512. Inc(Result);
  513. end;
  514. end;
  515. end;
  516. begin
  517. // block thread while handle is being recreated
  518. FSection.Enter;
  519. try
  520. Result := 0;
  521. DetachList(FQueue);
  522. DetachList(FResults);
  523. FQueue.Clear;
  524. FResults.Clear;
  525. except
  526. FSection.Leave;
  527. raise;
  528. end;
  529. end;
  530. procedure TSubDirReaderThread.Reattach(Count: Integer);
  531. var
  532. Node: TTreeNode;
  533. Schedule: TSubDirReaderSchedule;
  534. begin
  535. try
  536. if Count > 0 then
  537. begin
  538. Node := FDriveView.Items.GetFirstNode;
  539. while Assigned(Node) do
  540. begin
  541. Schedule := TNodeData(Node.Data).Schedule;
  542. if Assigned(Schedule) then
  543. begin
  544. Assert(not Assigned(Schedule.Node));
  545. Schedule.Node := Node;
  546. if not Schedule.Processed then
  547. FQueue.Push(Schedule)
  548. else
  549. FResults.Enqueue(Schedule);
  550. Assert(Count > 0);
  551. // Can be optimized to stop once Count = 0
  552. Dec(Count);
  553. end;
  554. Node := Node.GetNext;
  555. end;
  556. if Count = 0 then Assert(False); // shut up
  557. end;
  558. finally
  559. FSection.Leave;
  560. end;
  561. TriggerEvent;
  562. ScheduleProcess;
  563. end;
  564. procedure TSubDirReaderThread.Terminate;
  565. begin
  566. inherited;
  567. TriggerEvent;
  568. end;
  569. procedure TSubDirReaderThread.TriggerEvent;
  570. begin
  571. SetEvent(FEvent);
  572. end;
  573. function TSubDirReaderThread.ProcessResult: Boolean;
  574. var
  575. Node: TTreeNode;
  576. NodeData: TNodeData;
  577. Schedule: TSubDirReaderSchedule;
  578. begin
  579. FSection.Enter;
  580. try
  581. Result := (FResults.Count > 0);
  582. if Result then
  583. begin
  584. Schedule := FResults.Dequeue;
  585. if not Schedule.Deleted then
  586. begin
  587. Assert(Schedule.Processed);
  588. Node := Schedule.Node;
  589. Node.HasChildren := False;
  590. NodeData := TNodeData(Node.Data);
  591. NodeData.Scanned := not Node.HasChildren; // = True
  592. Assert(NodeData.Schedule = Schedule);
  593. NodeData.Schedule := nil;
  594. end;
  595. Schedule.Free;
  596. end;
  597. finally
  598. FSection.Leave;
  599. end;
  600. end;
  601. procedure TSubDirReaderThread.ScheduleProcess;
  602. begin
  603. // process the first batch immediatelly, to make it more likely that the first seen subdirectories
  604. // will immediatelly show correct status
  605. Process;
  606. FTimer.Enabled := True;
  607. end;
  608. procedure TSubDirReaderThread.Execute;
  609. var
  610. SRec: TSearchRec;
  611. HasSubDirs: Boolean;
  612. NodeData: TNodeData;
  613. Schedule: TSubDirReaderSchedule;
  614. DelayStart, DelayStartStep: Integer;
  615. begin
  616. DelayStart := 3000;
  617. DelayStartStep := 100;
  618. while (DelayStart > 0) and (not Terminated) do
  619. begin
  620. Sleep(DelayStartStep);
  621. Dec(DelayStart, DelayStartStep)
  622. end;
  623. while not Terminated do
  624. begin
  625. WaitForSingleObject(FEvent, INFINITE);
  626. while not Terminated do
  627. begin
  628. FSection.Enter;
  629. try
  630. if FQueue.Count = 0 then
  631. begin
  632. Break;
  633. end
  634. else
  635. begin
  636. Schedule := FQueue.Pop;
  637. if Schedule.Deleted then
  638. begin
  639. Schedule.Free;
  640. // Can be optimized to loop within locked critical section until first non-deleted schedule is found
  641. Continue;
  642. end;
  643. Assert(not Schedule.Processed);
  644. end
  645. finally
  646. FSection.Leave;
  647. end;
  648. HasSubDirs := FDriveView.FindFirstSubDir(IncludeTrailingBackslash(Schedule.Path) + '*.*', SRec);
  649. FindClose(SRec);
  650. FSection.Enter;
  651. try
  652. if Schedule.Deleted then
  653. begin
  654. Schedule.Free;
  655. end
  656. else
  657. begin
  658. Schedule.Processed := True;
  659. if not HasSubDirs then // optimization
  660. begin
  661. FResults.Enqueue(Schedule);
  662. if FResults.Count = 1 then
  663. PostMessage(FWindowHandle, WM_USER_SUBDIRREADER, 0, 0);
  664. end
  665. else
  666. begin
  667. // can happen only if the tree handle is just being recreated
  668. if Assigned(Schedule.Node) then
  669. begin
  670. NodeData := TNodeData(Schedule.Node.Data);
  671. NodeData.Schedule := nil;
  672. end;
  673. Schedule.Free;
  674. end;
  675. end;
  676. finally
  677. FSection.Leave;
  678. end;
  679. end;
  680. end;
  681. end;
  682. { TDriveTreeNode }
  683. // Not sure if this is ever used (possibly only then "assigning" tree view to another instance, what never do).
  684. // It is NOT used when recreating a tree view handle - for that a node is serialized and deserialized,
  685. // including a pointer to TNodeData. See csRecreating condition in TDriveView.Delete.
  686. procedure TDriveTreeNode.Assign(Source: TPersistent);
  687. var
  688. SourceData: TNodeData;
  689. NewData: TNodeData;
  690. begin
  691. Assert(False);
  692. inherited Assign(Source);
  693. if not Deleting and (Source is TTreeNode) then
  694. begin
  695. SourceData := TNodeData(TTreeNode(Source).Data);
  696. NewData := TNodeData.Create();
  697. NewData.DirName := SourceData.DirName;
  698. NewData.Attr := SourceData.Attr;
  699. NewData.Scanned := SourceData.Scanned;
  700. NewData.Data := SourceData.Data;
  701. NewData.FIsRecycleBin := SourceData.FIsRecycleBin;
  702. NewData.IconEmpty := SourceData.IconEmpty;
  703. TTreeNode(Source).Data := NewData;
  704. end;
  705. end;
  706. { TDriveView }
  707. constructor TDriveView.Create(AOwner: TComponent);
  708. var
  709. Drive: TRealDrive;
  710. begin
  711. inherited;
  712. FCreating := True;
  713. FDriveStatus := TObjectDictionary<string, TDriveStatus>.Create([doOwnsValues]);
  714. FChangeInterval := MSecsPerSec;
  715. for Drive := FirstDrive to LastDrive do
  716. begin
  717. FDriveStatus.Add(Drive, CreateDriveStatus);
  718. end;
  719. FFileOperator := TFileOperator.Create(Self);
  720. FSubDirReaderThread := TSubDirReaderThread.Create(Self);
  721. FDelayedNodes := TStringList.Create;
  722. FDelayedNodeTimer := TTimer.Create(Self);
  723. UpdateDelayedNodeTimer;
  724. FDelayedNodeTimer.Interval := 250;
  725. FDelayedNodeTimer.OnTimer := DelayedNodeTimer;
  726. FShowVolLabel := True;
  727. FChangeFlag := False;
  728. FLastDir := EmptyStr;
  729. FValidateFlag := False;
  730. FSysColorChangePending := False;
  731. FConfirmDelete := True;
  732. FDirectory := EmptyStr;
  733. FForceRename := False;
  734. FLastRenameName := '';
  735. FRenameNode := nil;
  736. FPrevSelected := nil;
  737. FPrevSelectedIndex := -1;
  738. FChangeTimerSuspended := 0;
  739. FConfirmOverwrite := True;
  740. FLastPathCut := '';
  741. FStartPos.X := -1;
  742. FStartPos.Y := -1;
  743. FDragPos := FStartPos;
  744. DriveInfo.AddHandler(DriveNotification);
  745. with FDragDropFilesEx do
  746. begin
  747. ShellExtensions.DragDropHandler := True;
  748. end;
  749. end; {Create}
  750. destructor TDriveView.Destroy;
  751. var
  752. DriveStatusPair: TDriveStatusPair;
  753. begin
  754. DriveInfo.RemoveHandler(DriveNotification);
  755. for DriveStatusPair in FDriveStatus do
  756. begin
  757. with DriveStatusPair.Value do
  758. begin
  759. if Assigned(DiscMonitor) then
  760. FreeAndNil(DiscMonitor);
  761. if Assigned(ChangeTimer) then
  762. FreeAndNil(ChangeTimer);
  763. end;
  764. end;
  765. FDriveStatus.Free;
  766. if Assigned(FFileOperator) then
  767. FFileOperator.Free;
  768. FSubDirReaderThread.Free;
  769. Assert(FDelayedNodes.Count = 0);
  770. FreeAndNil(FDelayedNodes);
  771. inherited Destroy;
  772. end; {Destroy}
  773. function TDriveView.CreateDriveStatus: TDriveStatus;
  774. begin
  775. Result := TDriveStatus.Create;
  776. with Result do
  777. begin
  778. Scanned := False;
  779. Verified := False;
  780. RootNode := nil;
  781. RootNodeIndex := -1;
  782. DiscMonitor := nil;
  783. DefaultDir := EmptyStr;
  784. {ChangeTimer: }
  785. ChangeTimer := TTimer.Create(Self);
  786. ChangeTimer.Interval := 0;
  787. ChangeTimer.Enabled := False;
  788. ChangeTimer.OnTimer := ChangeTimerOnTimer;
  789. end;
  790. end;
  791. procedure TDriveView.DriveRemoving(Drive: string);
  792. begin
  793. DriveRemoved(Drive);
  794. TerminateWatchThread(Drive);
  795. end;
  796. procedure TDriveView.CreateWnd;
  797. var
  798. DriveStatus: TDriveStatus;
  799. begin
  800. inherited;
  801. FDragDropFilesEx.SourceEffects := [deCopy, deMove, deLink];
  802. FDragDropFilesEx.TargetEffects := [deCopy, deMove, deLink];
  803. if FPrevSelectedIndex >= 0 then
  804. begin
  805. FPrevSelected := Items[FPrevSelectedIndex];
  806. FPrevSelectedIndex := -1;
  807. end;
  808. for DriveStatus in FDriveStatus.Values do
  809. with DriveStatus do
  810. begin
  811. if RootNodeIndex >= 0 then
  812. begin
  813. RootNode := Items[RootNodeIndex];
  814. RootNodeIndex := -1;
  815. end;
  816. end;
  817. UpdateDelayedNodeTimer;
  818. end; {CreateWnd}
  819. procedure TDriveView.DestroyWnd;
  820. var
  821. DriveStatus: TDriveStatus;
  822. I: Integer;
  823. begin
  824. FDelayedNodeTimer.Enabled := False;
  825. for I := 0 to FDelayedNodes.Count - 1 do
  826. FDelayedNodes.Objects[I] := nil;
  827. if not (csRecreating in ControlState) then
  828. begin
  829. FSubDirReaderThread.Terminate;
  830. FSubDirReaderThread.WaitFor;
  831. end
  832. else
  833. if CreateWndRestores and (Items.Count > 0) then
  834. begin
  835. FPrevSelectedIndex := -1;
  836. if Assigned(FPrevSelected) then
  837. begin
  838. FPrevSelectedIndex := FPrevSelected.AbsoluteIndex;
  839. FPrevSelected := nil;
  840. end;
  841. for DriveStatus in FDriveStatus.Values do
  842. with DriveStatus do
  843. begin
  844. RootNodeIndex := -1;
  845. if Assigned(RootNode) then
  846. begin
  847. RootNodeIndex := RootNode.AbsoluteIndex;
  848. RootNode := nil;
  849. end;
  850. end;
  851. end;
  852. inherited;
  853. end;
  854. function TDriveView.NodeColor(Node: TTreeNode): TColor;
  855. begin
  856. Result := clDefaultItemColor;
  857. with TNodeData(Node.Data) do
  858. if not Node.Selected then
  859. begin
  860. {Colored display of compressed directories:}
  861. if (Attr and FILE_ATTRIBUTE_COMPRESSED) <> 0 then
  862. begin
  863. if SupportsDarkMode and DarkMode then Result := clSkyBlue
  864. else Result := clBlue;
  865. end
  866. else
  867. {Dimmed display, if hidden-atrribut set:}
  868. if FDimmHiddenDirs and ((Attr and FILE_ATTRIBUTE_HIDDEN) <> 0) then
  869. Result := clGrayText
  870. end;
  871. end;
  872. function TDriveView.GetCustomDirView: TCustomDirView;
  873. begin
  874. Result := DirView;
  875. end;
  876. procedure TDriveView.SetCustomDirView(Value: TCustomDirView);
  877. begin
  878. DirView := Value as TDirView;
  879. end;
  880. function TDriveView.NodePath(Node: TTreeNode): string;
  881. var
  882. ParentNode: TTreeNode;
  883. begin
  884. if not Assigned(Node) then
  885. raise ENodeNotAssigned.Create(Format(ErrorNodeNA, ['GetDirPath']));
  886. Result := GetDirName(Node);
  887. Node := Node.Parent;
  888. while Assigned(Node) do
  889. begin
  890. ParentNode := Node.Parent;
  891. if Assigned(ParentNode) then
  892. Result := GetDirName(Node) + '\' + Result
  893. else
  894. Result := GetDirName(Node) + Result;
  895. Node := ParentNode;
  896. end;
  897. if IsRootPath(Result) then
  898. Result := ExcludeTrailingBackslash(Result);
  899. end;
  900. {NodePathName: Returns the complete path to Node with trailing backslash on rootnodes:
  901. C:\ ,C:\WINDOWS, C:\WINDOWS\SYSTEM }
  902. function TDriveView.NodePathName(Node: TTreeNode): string;
  903. begin
  904. Result := NodePath(Node);
  905. if IsRootPath(Result) then
  906. Result := IncludeTrailingBackslash(Result);
  907. end; {NodePathName}
  908. function TDriveView.NodeIsRecycleBin(Node: TTreeNode): Boolean;
  909. begin
  910. Result := TNodeData(Node.Data).IsRecycleBin;
  911. end;
  912. function TDriveView.NodePathExists(Node: TTreeNode): Boolean;
  913. begin
  914. Result := DirectoryExists(ApiPath(NodePathName(Node)));
  915. end;
  916. function TDriveView.CanEdit(Node: TTreeNode): Boolean;
  917. begin
  918. Result := inherited CanEdit(Node) or FForceRename;
  919. if Result then
  920. begin
  921. Result := Assigned(Node.Parent) and
  922. (not TNodeData(Node.Data).IsRecycleBin) and
  923. (not ReadOnly) and
  924. (FDragDropFilesEx.DragDetectStatus <> ddsDrag) and
  925. ((TNodeData(Node.Data).Attr and (faReadOnly or faSysFile)) = 0) and
  926. (UpperCase(Node.Text) = UpperCase(GetDirName(Node)));
  927. end;
  928. FForceRename := False;
  929. end; {CanEdit}
  930. procedure TDriveView.Edit(const Item: TTVItem);
  931. var
  932. Node: TTreeNode;
  933. Info: string;
  934. i: Integer;
  935. begin
  936. Node := GetNodeFromHItem(Item);
  937. if (Length(Item.pszText) > 0) and (Item.pszText <> Node.Text) then
  938. begin
  939. if StrContains(coInvalidDosChars, Item.pszText) then
  940. begin
  941. Info := coInvalidDosChars;
  942. for i := Length(Info) downto 1 do
  943. System.Insert(Space, Info, i);
  944. if Length(Item.pszText) > 0 then
  945. raise EInvalidDirName.Create(SErrorInvalidName + Space + Info);
  946. Exit;
  947. end;
  948. StopWatchThread;
  949. if Assigned(DirView) then
  950. DirView.StopWatchThread;
  951. with FFileOperator do
  952. begin
  953. Flags := FileOperatorDefaultFlags + [foNoConfirmation];
  954. Operation := foRename;
  955. OperandFrom.Clear;
  956. OperandTo.Clear;
  957. OperandFrom.Add(NodePath(Node));
  958. OperandTo.Add(IncludeTrailingBackslash(NodePath(Node.Parent)) + Item.pszText);
  959. end;
  960. try
  961. if FFileOperator.Execute then
  962. begin
  963. Node.Text := Item.pszText;
  964. TNodeData(Node.Data).DirName := Item.pszText;
  965. SortChildren(Node.Parent, False);
  966. inherited;
  967. end
  968. else
  969. begin
  970. if FileOrDirExists(IncludeTrailingBackslash(NodePath(Node.Parent)) + Item.pszText) then
  971. Info := SErrorRenameFileExists + Item.pszText
  972. else
  973. Info := SErrorRenameFile + Item.pszText;
  974. MessageBeep(MB_ICONHAND);
  975. if MessageDlg(FormatLastOSError(Info), mtError, [mbOK, mbAbort], 0) = mrOK then
  976. begin
  977. FLastRenameName := Item.pszText;
  978. FRenameNode := Node;
  979. PostMessage(Self.Handle, WM_USER_RENAME, 0, 0);
  980. end;
  981. end;
  982. finally
  983. StartWatchThread;
  984. if Assigned(DirView) then
  985. begin
  986. DirView.Reload2;
  987. DirView.StartWatchThread;
  988. end;
  989. end;
  990. end;
  991. end; {Edit}
  992. procedure TDriveView.WMUserRename(var Message: TMessage);
  993. begin
  994. if Assigned(FRenameNode) then
  995. begin
  996. FForceRename := True;
  997. TreeView_EditLabel(Handle, FRenameNode.ItemID);
  998. SetWindowText(TreeView_GetEditControl(Self.Handle), PChar(FLastRenameName));
  999. FRenameNode := nil;
  1000. end;
  1001. end; {WMUserRename}
  1002. function TDriveView.CanExpand(Node: TTreeNode): Boolean;
  1003. var
  1004. SubNode: TTreeNode;
  1005. Drive: string;
  1006. SaveCursor: TCursor;
  1007. begin
  1008. Result := inherited CanExpand(Node);
  1009. Drive := GetDriveToNode(Node);
  1010. if Node.HasChildren then
  1011. begin
  1012. if (not Assigned(Node.Parent)) and
  1013. (not GetDriveStatus(Drive).Scanned) and
  1014. DriveInfo.IsFixedDrive(Drive) then
  1015. begin
  1016. SubNode := Node.GetFirstChild;
  1017. if not Assigned(SubNode) then
  1018. begin
  1019. ScanDrive(Drive);
  1020. SubNode := Node.GetFirstChild;
  1021. Node.HasChildren := Assigned(SubNode);
  1022. Result := Node.HasChildren;
  1023. if not Assigned(GetDriveStatus(Drive).DiscMonitor) then
  1024. CreateWatchThread(Drive);
  1025. end;
  1026. end
  1027. else
  1028. begin
  1029. SaveCursor := Screen.Cursor;
  1030. Screen.Cursor := crHourGlass;
  1031. try
  1032. if (not TNodeData(Node.Data).Scanned) and DoScanDir(Node) then
  1033. begin
  1034. ReadSubDirs(Node);
  1035. end;
  1036. finally
  1037. Screen.Cursor := SaveCursor;
  1038. end;
  1039. end;
  1040. end;
  1041. end; {CanExpand}
  1042. procedure TDriveView.GetImageIndex(Node: TTreeNode);
  1043. begin
  1044. if TNodeData(Node.Data).IconEmpty then
  1045. SetImageIndex(Node);
  1046. inherited;
  1047. end; {GetImageIndex}
  1048. procedure TDriveView.Loaded;
  1049. begin
  1050. inherited;
  1051. {Create the drive nodes:}
  1052. RefreshRootNodes(True);
  1053. {Set the initial directory:}
  1054. if (Length(FDirectory) > 0) and DirectoryExists(ApiPath(FDirectory)) then
  1055. Directory := FDirectory;
  1056. FCreating := False;
  1057. end; {Loaded}
  1058. function TDriveView.CreateNode: TTreeNode;
  1059. begin
  1060. Result := TDriveTreeNode.Create(Items);
  1061. end;
  1062. procedure TDriveView.Delete(Node: TTreeNode);
  1063. var
  1064. NodeData: TNodeData;
  1065. begin
  1066. if Node = FPrevSelected then
  1067. FPrevSelected := nil;
  1068. NodeData := nil;
  1069. if Assigned(Node) and Assigned(Node.Data) then
  1070. NodeData := TNodeData(Node.Data);
  1071. Node.Data := nil;
  1072. inherited;
  1073. if Assigned(NodeData) and not (csRecreating in ControlState) then
  1074. begin
  1075. FSubDirReaderThread.Delete(Node);
  1076. if Assigned(NodeData.DelayedExclude) then
  1077. begin
  1078. CancelDelayedNode(Node);
  1079. FDelayedNodes.Delete(FDelayedNodes.IndexOfObject(Node));
  1080. UpdateDelayedNodeTimer;
  1081. end;
  1082. NodeData.Destroy;
  1083. end;
  1084. end; {OnDelete}
  1085. procedure TDriveView.KeyPress(var Key: Char);
  1086. begin
  1087. inherited;
  1088. if Assigned(Selected) then
  1089. begin
  1090. if Pos(Key, coInvalidDosChars) <> 0 then
  1091. begin
  1092. Beep;
  1093. Key := #0;
  1094. end;
  1095. end;
  1096. end; {KeyPress}
  1097. function TDriveView.CanChange(Node: TTreeNode): Boolean;
  1098. var
  1099. Path: string;
  1100. Drive: string;
  1101. begin
  1102. Result := inherited CanChange(Node);
  1103. if not Reading and not (csRecreating in ControlState) then
  1104. begin
  1105. if Result and Assigned(Node) then
  1106. begin
  1107. Path := NodePathName(Node);
  1108. if Path <> FLastDir then
  1109. begin
  1110. Drive := DriveInfo.GetDriveKey(Path);
  1111. DriveInfo.ReadDriveStatus(Drive, dsSize or dsImageIndex);
  1112. if not DriveInfo.Get(Drive).DriveReady then
  1113. begin
  1114. MessageDlg(Format(SDriveNotReady, [Drive]), mtError, [mbOK], 0);
  1115. Result := False;
  1116. end
  1117. else
  1118. try
  1119. CheckCanOpenDirectory(Path);
  1120. except
  1121. Application.HandleException(Self);
  1122. Result := False;
  1123. end;
  1124. end;
  1125. end;
  1126. if Result and (csDestroying in ComponentState) then
  1127. begin
  1128. Result := False;
  1129. end;
  1130. if Result and
  1131. (not FCanChange) and
  1132. Assigned(Node) and
  1133. Assigned(Node.Data) and
  1134. Assigned(Selected) and
  1135. Assigned(Selected.Data) then
  1136. begin
  1137. DropTarget := Node;
  1138. Result := False;
  1139. end
  1140. else
  1141. begin
  1142. DropTarget := nil;
  1143. end;
  1144. end;
  1145. end; {CanChange}
  1146. procedure TDriveView.Change(Node: TTreeNode);
  1147. var
  1148. Drive: string;
  1149. OldSerial: DWORD;
  1150. NewDir: string;
  1151. PrevDrive: string;
  1152. begin
  1153. if not Reading and not (csRecreating in ControlState) then
  1154. begin
  1155. if Assigned(Node) then
  1156. begin
  1157. NewDir := NodePathName(Node);
  1158. if NewDir <> FLastDir then
  1159. begin
  1160. Drive := DriveInfo.GetDriveKey(NewDir);
  1161. if Length(FLastDir) > 0 then
  1162. PrevDrive := DriveInfo.GetDriveKey(FLastDir)
  1163. else
  1164. PrevDrive := '';
  1165. FChangeFlag := True;
  1166. FLastDir := NewDir;
  1167. OldSerial := DriveInfo.Get(Drive).DriveSerial;
  1168. DriveInfo.ReadDriveStatus(Drive, dsSize or dsImageIndex);
  1169. with DriveInfo.Get(Drive) do
  1170. begin
  1171. if Assigned(FDirView) and (FDirView.Path <> NewDir) then
  1172. FDirView.Path := NewDir;
  1173. if DriveReady then
  1174. begin
  1175. if not DirectoryExists(ApiPath(NewDir)) then
  1176. begin
  1177. ValidateDirectory(GetDriveStatus(Drive).RootNode);
  1178. Exit;
  1179. end;
  1180. GetDriveStatus(Drive).DefaultDir := IncludeTrailingBackslash(NewDir);
  1181. if PrevDrive <> Drive then
  1182. begin
  1183. if (PrevDrive <> '') and
  1184. (DriveInfo.Get(PrevDrive).DriveType = DRIVE_REMOVABLE) then
  1185. begin
  1186. TerminateWatchThread(PrevDrive);
  1187. end;
  1188. {Drive serial has changed or is missing: allways reread the drive:}
  1189. if (DriveSerial <> OldSerial) or (DriveSerial = 0) then
  1190. begin
  1191. if TNodeData(GetDriveStatus(Drive).RootNode.Data).Scanned then
  1192. ScanDrive(Drive);
  1193. end;
  1194. end;
  1195. StartWatchThread;
  1196. end
  1197. else {Drive not ready:}
  1198. begin
  1199. GetDriveStatus(Drive).RootNode.DeleteChildren;
  1200. GetDriveStatus(Drive).DefaultDir := EmptyStr;
  1201. end;
  1202. end;
  1203. end;
  1204. if (not Assigned(FPrevSelected)) or (not FPrevSelected.HasAsParent(Node)) then
  1205. Node.Expand(False);
  1206. FPrevSelected := Node;
  1207. ValidateCurrentDirectoryIfNotMonitoring;
  1208. end;
  1209. end;
  1210. inherited;
  1211. end; {Change}
  1212. procedure TDriveView.SetImageIndex(Node: TTreeNode);
  1213. var
  1214. FileInfo: TShFileInfo;
  1215. Drive, NodePath: string;
  1216. begin
  1217. if Assigned(Node) and TNodeData(Node.Data).IconEmpty then
  1218. begin
  1219. NodePath := NodePathName(Node);
  1220. Drive := DriveInfo.GetDriveKey(NodePath);
  1221. if not Assigned(Node.Parent) then
  1222. begin
  1223. with DriveInfo.Get(Drive) do
  1224. begin
  1225. if ImageIndex = 0 then
  1226. begin
  1227. DriveInfo.ReadDriveStatus(Drive, dsImageIndex);
  1228. Node.ImageIndex := DriveInfo.Get(Drive).ImageIndex;
  1229. end
  1230. else Node.ImageIndex := ImageIndex;
  1231. Node.SelectedIndex := Node.ImageIndex;
  1232. end;
  1233. end
  1234. else
  1235. begin
  1236. if DriveInfo.Get(Drive).DriveType = DRIVE_REMOTE then
  1237. begin
  1238. Node.ImageIndex := StdDirIcon;
  1239. Node.SelectedIndex := StdDirSelIcon;
  1240. end
  1241. else
  1242. begin
  1243. try
  1244. SHGetFileInfo(PChar(NodePath), 0, FileInfo, SizeOf(FileInfo),
  1245. SHGFI_SYSICONINDEX or SHGFI_SMALLICON);
  1246. if (FileInfo.iIcon < Images.Count) and (FileInfo.iIcon > 0) then
  1247. begin
  1248. Node.ImageIndex := FileInfo.iIcon;
  1249. SHGetFileInfo(PChar(NodePath), 0, FileInfo, SizeOf(FileInfo),
  1250. SHGFI_SYSICONINDEX or SHGFI_SMALLICON or SHGFI_OPENICON);
  1251. Node.SelectedIndex := FileInfo.iIcon;
  1252. end
  1253. else
  1254. begin
  1255. Node.ImageIndex := StdDirIcon;
  1256. Node.SelectedIndex := StdDirSelIcon;
  1257. end;
  1258. except
  1259. Node.ImageIndex := StdDirIcon;
  1260. Node.SelectedIndex := StdDirSelIcon;
  1261. end;
  1262. end;
  1263. end;
  1264. end; {IconEmpty}
  1265. TNodeData(Node.Data).IconEmpty := False;
  1266. end; {SetImageIndex}
  1267. function TDriveView.GetDriveText(Drive: string): string;
  1268. begin
  1269. if FShowVolLabel and (Length(DriveInfo.GetPrettyName(Drive)) > 0) then
  1270. begin
  1271. case FVolDisplayStyle of
  1272. doPrettyName: Result := DriveInfo.GetPrettyName(Drive);
  1273. doDisplayName: Result := DriveInfo.GetDisplayName(Drive);
  1274. end; {Case}
  1275. end
  1276. else
  1277. begin
  1278. Result := DriveInfo.GetSimpleName(Drive);
  1279. end;
  1280. end; {GetDriveText}
  1281. function CompareDrive(List: TStringList; Index1, Index2: Integer): Integer;
  1282. var
  1283. Drive1, Drive2: string;
  1284. RealDrive1, RealDrive2: Boolean;
  1285. begin
  1286. Drive1 := List[Index1];
  1287. Drive2 := List[Index2];
  1288. RealDrive1 := DriveInfo.IsRealDrive(Drive1);
  1289. RealDrive2 := DriveInfo.IsRealDrive(Drive2);
  1290. if RealDrive1 = RealDrive2 then
  1291. begin
  1292. Result := CompareText(Drive1, Drive2);
  1293. end
  1294. else
  1295. if RealDrive1 and (not RealDrive2) then
  1296. begin
  1297. Result := -1;
  1298. end
  1299. else
  1300. begin
  1301. Result := 1;
  1302. end;
  1303. end;
  1304. function TDriveView.GetDrives: TStrings;
  1305. var
  1306. DriveStatusPair: TDriveStatusPair;
  1307. Drives: TStringList;
  1308. begin
  1309. Drives := TStringList.Create;
  1310. { We could iterate only .Keys here, but that crashes IDE for some reason }
  1311. for DriveStatusPair in FDriveStatus do
  1312. begin
  1313. Drives.Add(DriveStatusPair.Key);
  1314. end;
  1315. Drives.CustomSort(CompareDrive);
  1316. Result := Drives;
  1317. end;
  1318. procedure TDriveView.DriveRemoved(Drive: string);
  1319. var
  1320. NewDrive: Char;
  1321. begin
  1322. if (Directory <> '') and (Directory[1] = Drive) then
  1323. begin
  1324. if DriveInfo.IsRealDrive(Drive) then NewDrive := Drive[1]
  1325. else NewDrive := SystemDrive;
  1326. repeat
  1327. if NewDrive < SystemDrive then NewDrive := SystemDrive
  1328. else
  1329. if NewDrive = SystemDrive then NewDrive := LastDrive
  1330. else Dec(NewDrive);
  1331. DriveInfo.ReadDriveStatus(NewDrive, dsSize or dsImageIndex);
  1332. if NewDrive = Drive then
  1333. begin
  1334. Break;
  1335. end;
  1336. if DriveInfo.Get(NewDrive).Valid and DriveInfo.Get(NewDrive).DriveReady and Assigned(GetDriveStatus(NewDrive).RootNode) then
  1337. begin
  1338. Directory := NodePathName(GetDriveStatus(NewDrive).RootNode);
  1339. break;
  1340. end;
  1341. until False;
  1342. if not Assigned(Selected) then
  1343. begin
  1344. Directory := NodePathName(GetDriveStatus(SystemDrive).RootNode);
  1345. end;
  1346. end;
  1347. end;
  1348. procedure TDriveView.DriveNotification(Notification: TDriveNotification; Drive: string);
  1349. begin
  1350. case Notification of
  1351. dnRefresh:
  1352. RefreshRootNodes;
  1353. dnRemoving:
  1354. // Lame way to reduce rick, we modify the treee while it's being updated already.
  1355. // It might be better to post an update message to the message loop.
  1356. if WatchThreadActive(Drive) then
  1357. DriveRemoving(Drive);
  1358. end;
  1359. end;
  1360. procedure TDriveView.RefreshRootNodes(Floppy: Boolean);
  1361. var
  1362. Drives: TStrings;
  1363. NewText: string;
  1364. SaveCursor: TCursor;
  1365. WasValid: Boolean;
  1366. NodeData: TNodeData;
  1367. DriveStatus: TDriveStatus;
  1368. NextDriveNode: TTreeNode;
  1369. Index: Integer;
  1370. Drive: string;
  1371. begin
  1372. SaveCursor := Screen.Cursor;
  1373. Screen.Cursor := crHourGlass;
  1374. Drives := nil;
  1375. try
  1376. Drives := GetDrives;
  1377. NextDriveNode := nil;
  1378. for Index := Drives.Count - 1 downto 0 do
  1379. begin
  1380. Drive := Drives[Index];
  1381. DriveStatus := GetDriveStatus(Drive);
  1382. if Floppy or DriveInfo.IsFixedDrive(Drive) then
  1383. begin
  1384. with DriveInfo.Get(Drive) do
  1385. begin
  1386. WasValid := Assigned(DriveStatus.RootNode);
  1387. end;
  1388. with DriveInfo.Get(Drive), DriveStatus do
  1389. begin
  1390. if Valid then
  1391. begin
  1392. if not WasValid then
  1393. {New drive has arrived: insert new rootnode:}
  1394. begin
  1395. { Create root directory node }
  1396. NodeData := TNodeData.Create;
  1397. NodeData.DirName := DriveInfo.GetDriveRoot(Drive);
  1398. if Assigned(NextDriveNode) then
  1399. RootNode := Items.InsertObject(NextDriveNode, '', NodeData)
  1400. else
  1401. RootNode := Items.AddObject(nil, '', NodeData);
  1402. RootNode.Text := GetDisplayName(RootNode);
  1403. RootNode.HasChildren := True;
  1404. Scanned := False;
  1405. Verified := False;
  1406. end
  1407. else
  1408. if RootNode.ImageIndex <> DriveInfo.Get(Drive).ImageIndex then
  1409. begin {WasValid = True}
  1410. RootNode.ImageIndex := DriveInfo.Get(Drive).ImageIndex;
  1411. RootNode.SelectedIndex := DriveInfo.Get(Drive).ImageIndex;
  1412. end;
  1413. if Assigned(RootNode) then
  1414. begin
  1415. NewText := GetDisplayName(RootNode);
  1416. if RootNode.Text <> NewText then
  1417. RootNode.Text := NewText;
  1418. end;
  1419. end
  1420. else
  1421. if WasValid then
  1422. {Drive has been removed => delete rootnode:}
  1423. begin
  1424. DriveRemoved(Drive);
  1425. Scanned := False;
  1426. Verified := False;
  1427. RootNode.Delete;
  1428. RootNode := nil;
  1429. end;
  1430. end;
  1431. end;
  1432. if Assigned(DriveStatus.RootNode) then
  1433. NextDriveNode := DriveStatus.RootNode;
  1434. end;
  1435. finally
  1436. Screen.Cursor := SaveCursor;
  1437. Drives.Free;
  1438. end;
  1439. end; {RefreshRootNodes}
  1440. procedure TDriveView.AddChildNode(ParentNode: TTreeNode; ParentPath: string; SRec: TSearchRec);
  1441. var
  1442. NewNode: TTreeNode;
  1443. NodeData: TNodeData;
  1444. begin
  1445. NodeData := TNodeData.Create;
  1446. NodeData.Attr := SRec.Attr;
  1447. NodeData.DirName := SRec.Name;
  1448. NodeData.FIsRecycleBin :=
  1449. (SRec.Attr and faSysFile <> 0) and
  1450. (not Assigned(ParentNode.Parent)) and
  1451. (SameText(SRec.Name, 'RECYCLED') or
  1452. SameText(SRec.Name, 'RECYCLER') or
  1453. SameText(SRec.Name, '$RECYCLE.BIN'));
  1454. NodeData.Scanned := False;
  1455. NewNode := Self.Items.AddChildObject(ParentNode, '', NodeData);
  1456. NewNode.Text := GetDisplayName(NewNode);
  1457. NewNode.HasChildren := True;
  1458. if GetDriveTypeToNode(ParentNode) <> DRIVE_REMOTE then
  1459. FSubDirReaderThread.Add(NewNode, IncludeTrailingBackslash(ParentPath) + SRec.Name);
  1460. end; {AddChildNode}
  1461. function TDriveView.GetDriveStatus(Drive: string): TDriveStatus;
  1462. begin
  1463. if not FDriveStatus.TryGetValue(Drive, Result) then
  1464. begin
  1465. Result := CreateDriveStatus;
  1466. FDriveStatus.Add(Drive, Result);
  1467. end;
  1468. end; {GetDriveStatus}
  1469. function TDriveView.DoScanDir(FromNode: TTreeNode): Boolean;
  1470. begin
  1471. Result := not TNodeData(FromNode.Data).IsRecycleBin;
  1472. end; {DoScanDir}
  1473. function TDriveView.DirAttrMask: Integer;
  1474. begin
  1475. Result := faDirectory or faSysFile;
  1476. if ShowHiddenDirs then
  1477. Result := Result or faHidden;
  1478. end;
  1479. procedure TDriveView.ScanDrive(Drive: string);
  1480. begin {ScanDrive}
  1481. with Self.Items do
  1482. begin
  1483. ValidateDirectory(FindNodeToPath(DriveInfo.GetDriveRoot(Drive)));
  1484. GetDriveStatus(Drive).Scanned := True;
  1485. GetDriveStatus(Drive).Verified := False;
  1486. end;
  1487. end; {ScanDrive}
  1488. function TDriveView.DoFindNodeToPath(Path: string; ExistingOnly: Boolean): TTreeNode;
  1489. var
  1490. SelectionHierarchy: array of TTreeNode;
  1491. SelectionHierarchyHeight: Integer;
  1492. function SearchSubDirs(ParentNode: TTreeNode; Path: string; Level: Integer): TTreeNode; forward;
  1493. function ExtractFirstName(S: string): string;
  1494. var
  1495. I: Integer;
  1496. begin
  1497. I := Pos('\', S);
  1498. if I = 0 then
  1499. I := Length(S);
  1500. Result := System.Copy(S, 1, I);
  1501. end;
  1502. function DoSearchSubDirs(ParentNode: TTreeNode; Path: string; Level: Integer): TTreeNode;
  1503. var
  1504. Node: TTreeNode;
  1505. Dir: string;
  1506. begin
  1507. {Extract first directory from path:}
  1508. Dir := ExtractFirstName(Path);
  1509. System.Delete(Path, 1, Length(Dir));
  1510. if Dir[Length(Dir)] = '\' then
  1511. SetLength(Dir, Pred(Length(Dir)));
  1512. // Optimization. Avoid iterating possibly thousands of nodes,
  1513. // when the node we are looking for is the selected node or its ancestor.
  1514. // This is often the case, when navigating under node that has lot of siblings.
  1515. // Typically, when navigating in user's profile folder, and there are many [thousands] other user profile folders.
  1516. if (SelectionHierarchyHeight > 0) and
  1517. // Change of selection might indicate that the tree was rebuilt meanwhile and
  1518. // the references in SelectionHierarchy might not be valid anymore
  1519. (Selected = SelectionHierarchy[SelectionHierarchyHeight - 1]) and
  1520. (Level < SelectionHierarchyHeight) and
  1521. (Uppercase(GetDirName(SelectionHierarchy[Level])) = Dir) then
  1522. begin
  1523. Result := SelectionHierarchy[Level];
  1524. end
  1525. else
  1526. begin
  1527. // Paths have diverted
  1528. SelectionHierarchyHeight := 0;
  1529. Node := ParentNode.GetFirstChild;
  1530. if (not Assigned(Node)) and (not ExistingOnly) then
  1531. begin
  1532. ValidateDirectoryEx(ParentNode, rsRecursiveExisting, True);
  1533. Node := ParentNode.GetFirstChild;
  1534. end;
  1535. Result := nil;
  1536. while (not Assigned(Result)) and Assigned(Node) do
  1537. begin
  1538. if UpperCase(GetDirName(Node)) = Dir then
  1539. begin
  1540. Result := Node;
  1541. end
  1542. else
  1543. begin
  1544. Node := ParentNode.GetNextChild(Node);
  1545. end;
  1546. end;
  1547. end;
  1548. if Assigned(Result) and (Length(Path) > 0) then
  1549. begin
  1550. Result := SearchSubDirs(Result, Path, Level + 1);
  1551. end;
  1552. end;
  1553. function SearchSubDirs(ParentNode: TTreeNode; Path: string; Level: Integer): TTreeNode;
  1554. var
  1555. ParentPath, SubPath: string;
  1556. SRec: TSearchRec;
  1557. ParentNodeData: TNodeData;
  1558. begin
  1559. Result := nil;
  1560. if Length(Path) > 0 then
  1561. begin
  1562. ParentNodeData := TNodeData(ParentNode.Data);
  1563. if (not ParentNodeData.Scanned) and (not ExistingOnly) then
  1564. begin
  1565. ReadSubDirs(ParentNode);
  1566. end;
  1567. // Factored out of DoSearchSubDirs is remnant of Bug 956 superceded by Bug 1320
  1568. Result := DoSearchSubDirs(ParentNode, Path, Level);
  1569. if (not Assigned(Result)) and (not ExistingOnly) then
  1570. begin
  1571. ParentPath := NodePath(ParentNode);
  1572. if DirectoryExists(ApiPath(IncludeTrailingBackslash(ParentPath) + Path)) then
  1573. begin
  1574. SubPath := IncludeTrailingBackslash(ParentPath) + ExcludeTrailingBackslash(ExtractFirstName(Path));
  1575. if FindFirstSubDir(SubPath, SRec) then
  1576. begin
  1577. AddChildNode(ParentNode, ParentPath, SRec);
  1578. if Assigned(ParentNodeData.DelayedExclude) then
  1579. ParentNodeData.DelayedExclude.Add(SRec.Name);
  1580. SortChildren(ParentNode, False);
  1581. FindClose(SRec);
  1582. end;
  1583. Result := DoSearchSubDirs(ParentNode, Path, Level);
  1584. end;
  1585. end;
  1586. end;
  1587. end; {SearchSubDirs}
  1588. var
  1589. Drive: string;
  1590. P, I: Integer;
  1591. RootNode, Node: TTreeNode;
  1592. begin {FindNodeToPath}
  1593. Result := nil;
  1594. if Length(Path) < 3 then
  1595. Exit;
  1596. // Particularly when used by TDirView to delegate browsing to
  1597. // hidden drive view, the handle may not be created
  1598. HandleNeeded;
  1599. Drive := DriveInfo.GetDriveKey(Path);
  1600. // Likely a network drive
  1601. if (not Assigned(GetDriveStatus(Drive).RootNode)) and
  1602. // Side effect of this is drive refresh that adds the network drive to the trees
  1603. DriveInfo.Get(Drive).ValidButHiddenByDrivePolicy then
  1604. begin
  1605. // This refreshes the drives again
  1606. DriveInfo.OverrideDrivePolicy(Drive);
  1607. end;
  1608. // if not assigned now, it must be that the drive already existed in DriveInfo, but it didn't make it to this view
  1609. // (possible a network drive opened in another panel before)
  1610. if not Assigned(GetDriveStatus(Drive).RootNode) then
  1611. begin
  1612. // Refresh the view drives to add the new drive and also explorer's drive drop down.
  1613. // Overkill, as we know exactly what drive to add (so not need to check all drives)
  1614. DriveInfo.DriveRefresh;
  1615. end;
  1616. if Assigned(GetDriveStatus(Drive).RootNode) then
  1617. begin
  1618. if DriveInfo.IsRealDrive(Drive) then
  1619. begin
  1620. System.Delete(Path, 1, 3);
  1621. end
  1622. else
  1623. if IsUncPath(Path) then
  1624. begin
  1625. System.Delete(Path, 1, 2);
  1626. P := Pos('\', Path);
  1627. if P = 0 then
  1628. begin
  1629. Path := '';
  1630. end
  1631. else
  1632. begin
  1633. System.Delete(Path, 1, P);
  1634. P := Pos('\', Path);
  1635. if P = 0 then
  1636. begin
  1637. Path := '';
  1638. end
  1639. else
  1640. begin
  1641. System.Delete(Path, 1, P);
  1642. end;
  1643. end;
  1644. end
  1645. else
  1646. begin
  1647. raise EConvertError.Create(Format(ErrorInvalidDrive, [Path]))
  1648. end;
  1649. if Length(Path) > 0 then
  1650. begin
  1651. if (not GetDriveStatus(Drive).Scanned) and (not ExistingOnly) then
  1652. begin
  1653. ScanDrive(Drive);
  1654. end;
  1655. Node := Selected;
  1656. RootNode := GetDriveStatus(Drive).RootNode;
  1657. if not Assigned(Node) then
  1658. begin
  1659. SelectionHierarchyHeight := 0;
  1660. end
  1661. else
  1662. begin
  1663. SelectionHierarchyHeight := Node.Level + 1;
  1664. SetLength(SelectionHierarchy, SelectionHierarchyHeight);
  1665. for I := SelectionHierarchyHeight - 1 downto 0 do
  1666. begin
  1667. SelectionHierarchy[I] := Node;
  1668. Node := Node.Parent;
  1669. end;
  1670. Assert(Selected = SelectionHierarchy[SelectionHierarchyHeight - 1]);
  1671. // Different drive - nothing to optimize
  1672. if RootNode <> SelectionHierarchy[0] then
  1673. SelectionHierarchyHeight := 0;
  1674. end;
  1675. Result := SearchSubDirs(RootNode, UpperCase(Path), 1);
  1676. end
  1677. else Result := GetDriveStatus(Drive).RootNode;
  1678. end;
  1679. end; {FindNodetoPath}
  1680. function TDriveView.FindNodeToPath(Path: string): TTreeNode;
  1681. begin
  1682. Result := DoFindNodeToPath(Path, False);
  1683. end;
  1684. function TDriveView.TryFindNodeToPath(Path: string): TTreeNode;
  1685. begin
  1686. Result := DoFindNodeToPath(Path, True);
  1687. end;
  1688. function TDriveView.GetSubDir(var SRec: TSearchRec): Boolean;
  1689. begin
  1690. Result := True;
  1691. while Result and
  1692. ((SRec.Name = '.' ) or
  1693. (SRec.Name = '..') or
  1694. ((SRec.Attr and faDirectory) = 0)) do
  1695. begin
  1696. if FindNext(SRec) <> 0 then
  1697. begin
  1698. Result := False;
  1699. end;
  1700. end;
  1701. end;
  1702. function TDriveView.FindFirstSubDir(Path: string; var SRec: TSearchRec): Boolean;
  1703. begin
  1704. Result := (FindFirstEx(ApiPath(Path), DirAttrMask, SRec, FIND_FIRST_EX_LARGE_FETCH_PAS, FindExSearchLimitToDirectories) = 0);
  1705. if Result then
  1706. begin
  1707. Result := GetSubDir(SRec);
  1708. if not Result then FindClose(SRec);
  1709. end;
  1710. end;
  1711. function TDriveView.FindNextSubDir(var SRec: TSearchRec): Boolean;
  1712. begin
  1713. Result := (FindNext(SRec) = 0) and GetSubDir(SRec);
  1714. end;
  1715. function TDriveView.ReadSubDirsBatch(Node: TTreeNode; var SRec: TSearchRec; CheckInterval, Limit: Integer): Boolean;
  1716. var
  1717. Start: TDateTime;
  1718. Cont: Boolean;
  1719. Path: string;
  1720. Count: Integer;
  1721. DelayedExclude: TStringList;
  1722. begin
  1723. Start := Now;
  1724. Path := NodePath(Node);
  1725. Result := True;
  1726. Count := 0;
  1727. DelayedExclude := TNodeData(Node.Data).DelayedExclude;
  1728. // At least from SetDirectory > DoFindNodeToPath and CanExpand, this is not called within BeginUpdate/EndUpdate block.
  1729. // But in any case, adding it here makes expanding (which calls CanExpand) noticeably slower, when there are lot of nodes,
  1730. // because EndUpdate triggers TVN_GETDISPINFO for all nodes in the tree.
  1731. repeat
  1732. if (not Assigned(DelayedExclude)) or
  1733. (DelayedExclude.IndexOf(SRec.Name) < 0) then
  1734. begin
  1735. AddChildNode(Node, Path, SRec);
  1736. Inc(Count);
  1737. end;
  1738. Cont := FindNextSubDir(SRec);
  1739. // There are two other directory reading loops, where this is not checked
  1740. if Cont and
  1741. ((Count mod CheckInterval) = 0) and
  1742. (Limit > 0) and
  1743. (MilliSecondsBetween(Now, Start) > Limit) then
  1744. begin
  1745. Result := False;
  1746. Cont := False;
  1747. end
  1748. until not Cont;
  1749. if Result then
  1750. FindClose(Srec);
  1751. end;
  1752. procedure TDriveView.DelayedNodeTimer(Sender: TObject);
  1753. var
  1754. Node: TTreeNode;
  1755. NodeData: TNodeData;
  1756. begin
  1757. Assert(FDelayedNodes.Count > 0);
  1758. if FDelayedNodes.Count > 0 then
  1759. begin
  1760. // Control was recreated
  1761. if not Assigned(FDelayedNodes.Objects[0]) then
  1762. begin
  1763. FDelayedNodes.Objects[0] := TryFindNodeToPath(FDelayedNodes.Strings[0]);
  1764. end;
  1765. Node := TTreeNode(FDelayedNodes.Objects[0]);
  1766. if not Assigned(Node) then
  1767. begin
  1768. FDelayedNodes.Delete(0);
  1769. end
  1770. else
  1771. begin
  1772. NodeData := TNodeData(Node.Data);
  1773. if ReadSubDirsBatch(Node, NodeData.DelayedSrec, 10, 50) then
  1774. begin
  1775. FreeAndNil(NodeData.DelayedExclude);
  1776. FDelayedNodes.Delete(0);
  1777. SortChildren(Node, False);
  1778. end;
  1779. end;
  1780. end;
  1781. UpdateDelayedNodeTimer;
  1782. end;
  1783. procedure TDriveView.UpdateDelayedNodeTimer;
  1784. begin
  1785. FDelayedNodeTimer.Enabled := HandleAllocated and (FDelayedNodes.Count > 0);
  1786. end;
  1787. procedure TDriveView.ReadSubDirs(Node: TTreeNode);
  1788. var
  1789. SRec: TSearchRec;
  1790. NodeData: TNodeData;
  1791. Path: string;
  1792. CheckInterval, Limit: Integer;
  1793. begin
  1794. NodeData := TNodeData(Node.Data);
  1795. Path := NodePath(Node);
  1796. if not FindFirstSubDir(IncludeTrailingBackslash(Path) + '*.*', SRec) then
  1797. begin
  1798. Node.HasChildren := False;
  1799. end
  1800. else
  1801. begin
  1802. CheckInterval := 100;
  1803. Limit := DriveViewLoadingTooLongLimit * 1000;
  1804. if not Showing then
  1805. begin
  1806. Limit := Limit div 10;
  1807. CheckInterval := CheckInterval div 10;
  1808. end;
  1809. if not ReadSubDirsBatch(Node, SRec, CheckInterval, Limit) then
  1810. begin
  1811. NodeData.DelayedSrec := SRec;
  1812. NodeData.DelayedExclude := TStringList.Create;
  1813. NodeData.DelayedExclude.CaseSensitive := False;
  1814. NodeData.DelayedExclude.Sorted := True;
  1815. FDelayedNodes.AddObject(Path, Node);
  1816. Assert(FDelayedNodes.Count < 20); // if more, something went likely wrong
  1817. UpdateDelayedNodeTimer;
  1818. end;
  1819. SortChildren(Node, False);
  1820. end;
  1821. NodeData.Scanned := True;
  1822. Application.ProcessMessages;
  1823. end; {ReadSubDirs}
  1824. procedure TDriveView.CancelDelayedNode(Node: TTreeNode);
  1825. var
  1826. NodeData: TNodeData;
  1827. begin
  1828. NodeData := TNodeData(Node.Data);
  1829. FindClose(NodeData.DelayedSrec);
  1830. FreeAndNil(NodeData.DelayedExclude);
  1831. end;
  1832. procedure TDriveView.DeleteNode(Node: TTreeNode);
  1833. var
  1834. ValidNode: TTreeNode;
  1835. begin
  1836. if Assigned(Selected) and Assigned(Node.Parent) and
  1837. ((Selected = Node) or Selected.HasAsParent(Node)) then
  1838. begin
  1839. ValidNode := Node.Parent;
  1840. while (not NodePathExists(ValidNode)) and Assigned(ValidNode.Parent) do
  1841. ValidNode := ValidNode.Parent;
  1842. Selected := ValidNode;
  1843. end;
  1844. if DropTarget = Node then
  1845. DropTarget := nil;
  1846. Node.Delete;
  1847. end;
  1848. function TDriveView.CallBackValidateDir(var Node: TTreeNode; Data: Pointer): Boolean;
  1849. var
  1850. WorkNode: TTreeNode;
  1851. DelNode: TTreeNode;
  1852. SRec: TSearchRec;
  1853. SrecList: TStringList;
  1854. SubDirList: TStringList;
  1855. R: Boolean;
  1856. Index: Integer;
  1857. NewDirFound: Boolean;
  1858. ParentDir: string;
  1859. NodeData: TNodeData;
  1860. ScanDirInfo: PScanDirInfo;
  1861. begin {CallBackValidateDir}
  1862. Result := True;
  1863. if (not Assigned(Node)) or (not Assigned(Node.Data)) then
  1864. Exit;
  1865. NewDirFound := False;
  1866. ScanDirInfo := PScanDirInfo(Data);
  1867. {Check, if directory still exists: (but not with root directory) }
  1868. if Assigned(Node.Parent) and (ScanDirInfo^.StartNode = Node) and
  1869. (not NodePathExists(Node)) then
  1870. begin
  1871. DeleteNode(Node);
  1872. Node := nil;
  1873. Exit;
  1874. end;
  1875. WorkNode := Node.GetFirstChild;
  1876. NodeData := TNodeData(Node.Data);
  1877. if NodeData.Scanned and Assigned(WorkNode) then
  1878. {if node was already scanned: check wether the existing subnodes are still alive
  1879. and add all new subdirectories as subnodes:}
  1880. begin
  1881. if DoScanDir(Node) then
  1882. begin
  1883. ParentDir := IncludeTrailingBackslash(NodePath(Node));
  1884. {Build list of existing subnodes:}
  1885. SubDirList := TStringList.Create;
  1886. SubDirList.CaseSensitive := True; // We want to reflect changes in subfolder name case
  1887. while Assigned(WorkNode) do
  1888. begin
  1889. SubDirList.Add(TNodeData(WorkNode.Data).DirName);
  1890. WorkNode := Node.GetNextChild(WorkNode);
  1891. end;
  1892. // Nodes are sorted using natural sorting, while TStringList.Find uses simple sorting
  1893. SubDirList.Sort;
  1894. SRecList := TStringList.Create;
  1895. SRecList.CaseSensitive := True;
  1896. R := FindFirstSubDir(ParentDir + '*.*', SRec);
  1897. while R do
  1898. begin
  1899. SrecList.Add(Srec.Name);
  1900. if not SubDirList.Find(Srec.Name, Index) then
  1901. {Subnode does not exists: add it:}
  1902. begin
  1903. AddChildNode(Node, ParentDir, SRec);
  1904. NewDirFound := True;
  1905. end;
  1906. R := FindNextSubDir(Srec);
  1907. end;
  1908. FindClose(Srec);
  1909. Sreclist.Sort;
  1910. {Remove not existing subnodes:}
  1911. WorkNode := Node.GetFirstChild;
  1912. while Assigned(WorkNode) do
  1913. begin
  1914. if not Assigned(WorkNode.Data) or
  1915. not SrecList.Find(TNodeData(WorkNode.Data).DirName, Index) then
  1916. begin
  1917. DelNode := WorkNode;
  1918. WorkNode := Node.GetNextChild(WorkNode);
  1919. DeleteNode(DelNode);
  1920. end
  1921. else
  1922. begin
  1923. if (SrecList[Index] <> TNodeData(WorkNode.Data).DirName) then
  1924. begin
  1925. {Case of directory letters has changed:}
  1926. TNodeData(WorkNode.Data).DirName := SrecList[Index];
  1927. WorkNode.Text := SrecList[Index];
  1928. end;
  1929. WorkNode := Node.GetNextChild(WorkNode);
  1930. end;
  1931. end;
  1932. SrecList.Free;
  1933. SubDirList.Free;
  1934. {Sort subnodes:}
  1935. if NewDirFound then
  1936. SortChildren(Node, False);
  1937. end;
  1938. end
  1939. else
  1940. {Node was not already scanned:}
  1941. if (ScanDirInfo^.SearchNewDirs or
  1942. NodeData.Scanned or
  1943. (Node = ScanDirInfo^.StartNode)) and
  1944. DoScanDir(Node) then
  1945. begin
  1946. ReadSubDirs(Node);
  1947. end;
  1948. end; {CallBackValidateDir}
  1949. procedure TDriveView.RebuildTree;
  1950. var
  1951. Drive: string;
  1952. begin
  1953. for Drive in FDriveStatus.Keys do
  1954. with GetDriveStatus(Drive) do
  1955. if Assigned(RootNode) and Scanned then
  1956. ValidateDirectory(RootNode);
  1957. end;
  1958. procedure TDriveView.ValidateCurrentDirectoryIfNotMonitoring;
  1959. begin
  1960. if Assigned(Selected) and
  1961. not Assigned(GetDriveStatus(GetDriveToNode(Selected)).DiscMonitor) then
  1962. begin
  1963. ValidateDirectory(Selected);
  1964. end;
  1965. end;
  1966. procedure TDriveView.ValidateDirectoryEx(Node: TTreeNode; Recurse: TRecursiveScan;
  1967. NewDirs: Boolean);
  1968. var
  1969. Info: PScanDirInfo;
  1970. SelDir: string;
  1971. SaveCursor: TCursor;
  1972. RestartWatchThread: Boolean;
  1973. SaveCanChange: Boolean;
  1974. CurrentPath: string;
  1975. Drive: string;
  1976. begin
  1977. if Assigned(Node) and Assigned(Node.Data) and
  1978. (not FValidateFlag) and DoScanDir(Node) then
  1979. begin
  1980. SelDir := Directory;
  1981. SaveCursor := Screen.Cursor;
  1982. if Self.Focused and (Screen.Cursor <> crHourGlass) then
  1983. Screen.Cursor := crHourGlass;
  1984. CurrentPath := NodePath(Node);
  1985. Drive := DriveInfo.GetDriveKey(CurrentPath);
  1986. if not Assigned(Node.Parent) then
  1987. GetDriveStatus(Drive).ChangeTimer.Enabled := False;
  1988. RestartWatchThread := WatchThreadActive;
  1989. try
  1990. if WatchThreadActive then
  1991. StopWatchThread;
  1992. FValidateFlag := True;
  1993. FSysColorChangePending := False;
  1994. New(Info);
  1995. Info^.StartNode := Node;
  1996. Info^.SearchNewDirs := NewDirs;
  1997. Info^.DriveType := DriveInfo.Get(Drive).DriveType;
  1998. SaveCanChange := FCanChange;
  1999. FCanChange := True;
  2000. FChangeFlag := False;
  2001. Items.BeginUpdate;
  2002. try
  2003. IterateSubTree(Node, CallBackValidateDir, Recurse, coScanStartNode, Info);
  2004. finally
  2005. Items.EndUpdate;
  2006. end;
  2007. FValidateFlag := False;
  2008. if (not Assigned(Selected)) and (Length(SelDir) > 0) then
  2009. Directory := ExtractFileDrive(SelDir);
  2010. if (SelDir <> Directory) and (not FChangeFlag) then
  2011. Change(Selected);
  2012. FCanChange := SaveCanChange;
  2013. Dispose(Info);
  2014. finally
  2015. if RestartWatchThread and FWatchDirectory and not WatchThreadActive then
  2016. StartWatchThread;
  2017. if Screen.Cursor <> SaveCursor then
  2018. Screen.Cursor := SaveCursor;
  2019. if FSysColorChangePending then
  2020. begin
  2021. FSysColorChangePending := False;
  2022. if HandleAllocated then Perform(CM_SYSCOLORCHANGE, 0, 0);
  2023. end;
  2024. end;
  2025. end;
  2026. end; {ValidateDirectoryEx}
  2027. function TDriveView.GetDriveTypeToNode(Node: TTreeNode): Integer;
  2028. begin
  2029. Assert(Assigned(Node));
  2030. Result := DriveInfo.Get(GetDriveToNode(Node)).DriveType;
  2031. end; {GetDriveTypeToNode}
  2032. procedure TDriveView.CreateWatchThread(Drive: string);
  2033. begin
  2034. if csDesigning in ComponentState then
  2035. Exit;
  2036. if (not Assigned(GetDriveStatus(Drive).DiscMonitor)) and
  2037. FWatchDirectory and
  2038. (DriveInfo.Get(Drive).DriveType <> DRIVE_REMOTE) then
  2039. begin
  2040. with GetDriveStatus(Drive) do
  2041. begin
  2042. DiscMonitor := TDiscMonitor.Create(Self);
  2043. DiscMonitor.ChangeDelay := msThreadChangeDelay;
  2044. DiscMonitor.SubTree := True;
  2045. DiscMonitor.Filters := [moDirName];
  2046. DiscMonitor.OnChange := ChangeDetected;
  2047. DiscMonitor.OnInvalid := ChangeInvalid;
  2048. DiscMonitor.SetDirectory(DriveInfo.GetDriveRoot(Drive));
  2049. DiscMonitor.Open;
  2050. end;
  2051. SubscribeDriveNotifications(Drive);
  2052. end;
  2053. end; {CreateWatchThread}
  2054. procedure TDriveView.SetWatchDirectory(Value: Boolean);
  2055. begin
  2056. if FWatchDirectory <> Value then
  2057. begin
  2058. FWatchDirectory := Value;
  2059. if (not (csDesigning in ComponentState)) and Value then
  2060. StartAllWatchThreads
  2061. else
  2062. StopAllWatchThreads;
  2063. end;
  2064. end; {SetAutoScan}
  2065. procedure TDriveView.SetDirView(Value: TDirView);
  2066. begin
  2067. if Assigned(FDirView) then
  2068. FDirView.DriveView := nil;
  2069. FDirView := Value;
  2070. if Assigned(FDirView) then
  2071. FDirView.DriveView := Self;
  2072. end; {SetDirView}
  2073. function TDriveView.NodeWatched(Node: TTreeNode): Boolean;
  2074. var
  2075. Drive: string;
  2076. begin
  2077. Drive := GetDriveToNode(Node);
  2078. Result := WatchThreadActive(Drive);
  2079. end; {NodeWatched}
  2080. procedure TDriveView.ChangeInvalid(Sender: TObject; const Directory: string;
  2081. const ErrorStr: string);
  2082. var
  2083. Drive: string;
  2084. begin
  2085. Drive := DriveInfo.GetDriveKey((Sender as TDiscMonitor).Directories[0]);
  2086. with GetDriveStatus(Drive) do
  2087. begin
  2088. DiscMonitor.Close;
  2089. end;
  2090. end; {DirWatchChangeInvalid}
  2091. procedure TDriveView.ChangeDetected(Sender: TObject; const Directory: string;
  2092. var SubdirsChanged: Boolean);
  2093. var
  2094. DirChanged: string;
  2095. begin
  2096. if Sender is TDiscMonitor then
  2097. begin
  2098. DirChanged := (Sender as TDiscMonitor).Directories[0];
  2099. if Length(DirChanged) > 0 then
  2100. begin
  2101. with GetDriveStatus(DriveInfo.GetDriveKey(DirChanged)) do
  2102. begin
  2103. ChangeTimer.Interval := 0;
  2104. ChangeTimer.Interval := FChangeInterval;
  2105. ChangeTimer.Enabled := True;
  2106. end;
  2107. end;
  2108. end;
  2109. end; {DirWatchChangeDetected}
  2110. procedure TDriveView.ChangeTimerOnTimer(Sender: TObject);
  2111. var
  2112. DriveStatusPair: TDriveStatusPair;
  2113. begin
  2114. if (FChangeTimerSuspended = 0) and (Sender is TTimer) then
  2115. begin
  2116. for DriveStatusPair in FDriveStatus do
  2117. begin
  2118. if DriveStatusPair.Value.ChangeTimer = Sender then
  2119. begin
  2120. // Messages are processed during ValidateDirectory, so we may detect another change while
  2121. // updating the directory. Prevent the recursion.
  2122. // But retry the update afterwards (by reenabling the timer in ChangeDetected)
  2123. SuspendChangeTimer;
  2124. try
  2125. with DriveStatusPair.Value.ChangeTimer do
  2126. begin
  2127. Interval := 0;
  2128. Enabled := False;
  2129. end;
  2130. if Assigned(DriveStatusPair.Value.RootNode) then
  2131. begin
  2132. {Check also collapsed (invisible) subdirectories:}
  2133. ValidateDirectory(DriveStatusPair.Value.RootNode);
  2134. end;
  2135. finally
  2136. ResumeChangeTimer;
  2137. end;
  2138. end;
  2139. end;
  2140. end;
  2141. end; {ChangeTimerOnTimer}
  2142. procedure TDriveView.SubscribeDriveNotifications(Drive: string);
  2143. begin
  2144. // As previously, subscribe drive notification only once the drive is at least once visited.
  2145. // Shouldn't do much harm to subscribe always, but just in case.
  2146. DriveInfo.SubscribeDriveNotifications(Drive);
  2147. end;
  2148. procedure TDriveView.StartWatchThread;
  2149. var
  2150. Drive: string;
  2151. begin
  2152. if (csDesigning in ComponentState) or
  2153. not Assigned(Selected) or
  2154. not fWatchDirectory then Exit;
  2155. Drive := GetDriveToNode(Selected);
  2156. with GetDriveStatus(Drive) do
  2157. begin
  2158. if not Assigned(DiscMonitor) then
  2159. CreateWatchThread(Drive);
  2160. if Assigned(DiscMonitor) and not DiscMonitor.Enabled then
  2161. DiscMonitor.Enabled := True;
  2162. end;
  2163. SubscribeDriveNotifications(Drive);
  2164. end; {StartWatchThread}
  2165. procedure TDriveView.StopWatchThread;
  2166. var
  2167. Drive: string;
  2168. begin
  2169. if Assigned(Selected) then
  2170. begin
  2171. Drive := GetDriveToNode(Selected);
  2172. with GetDriveStatus(Drive) do
  2173. if Assigned(DiscMonitor) then
  2174. DiscMonitor.Enabled := False;
  2175. end;
  2176. end; {StopWatchThread}
  2177. procedure TDriveView.SuspendChangeTimer;
  2178. begin
  2179. Inc(FChangeTimerSuspended);
  2180. end;
  2181. procedure TDriveView.ResumeChangeTimer;
  2182. begin
  2183. Assert(FChangeTimerSuspended > 0);
  2184. Dec(FChangeTimerSuspended);
  2185. end;
  2186. procedure TDriveView.TerminateWatchThread(Drive: string);
  2187. begin
  2188. with GetDriveStatus(Drive) do
  2189. if Assigned(DiscMonitor) then
  2190. begin
  2191. DiscMonitor.Free;
  2192. DiscMonitor := nil;
  2193. end;
  2194. end; {StopWatchThread}
  2195. procedure TDriveView.StartAllWatchThreads;
  2196. var
  2197. DriveStatusPair: TDriveStatusPair;
  2198. Drive: string;
  2199. begin
  2200. if (csDesigning in ComponentState) or (not FWatchDirectory) then
  2201. Exit;
  2202. for DriveStatusPair in FDriveStatus do
  2203. with DriveStatusPair.Value do
  2204. if Scanned then
  2205. begin
  2206. if not Assigned(DiscMonitor) then
  2207. CreateWatchThread(DriveStatusPair.Key);
  2208. if Assigned(DiscMonitor) and (not DiscMonitor.Active) then
  2209. begin
  2210. DiscMonitor.Open;
  2211. SubscribeDriveNotifications(DriveStatusPair.Key);
  2212. end;
  2213. end;
  2214. if Assigned(Selected) then
  2215. begin
  2216. Drive := GetDriveToNode(Selected);
  2217. if not DriveInfo.IsFixedDrive(Drive) then
  2218. begin
  2219. StartWatchThread;
  2220. end;
  2221. end;
  2222. end; {StartAllWatchThreads}
  2223. procedure TDriveView.StopAllWatchThreads;
  2224. var
  2225. DriveStatusPair: TDriveStatusPair;
  2226. begin
  2227. if (csDesigning in ComponentState) or (not FWatchDirectory) then
  2228. Exit;
  2229. for DriveStatusPair in FDriveStatus do
  2230. with DriveStatusPair.Value do
  2231. begin
  2232. if Assigned(DiscMonitor) then
  2233. begin
  2234. DiscMonitor.Close;
  2235. end;
  2236. end;
  2237. end; {StopAllWatchThreads}
  2238. function TDriveView.WatchThreadActive(Drive: string): Boolean;
  2239. begin
  2240. Result := FWatchDirectory and
  2241. Assigned(GetDriveStatus(Drive).DiscMonitor) and
  2242. GetDriveStatus(Drive).DiscMonitor.Active and
  2243. GetDriveStatus(Drive).DiscMonitor.Enabled;
  2244. end; {WatchThreadActive}
  2245. function TDriveView.WatchThreadActive: Boolean;
  2246. var
  2247. Drive: string;
  2248. begin
  2249. if not Assigned(Selected) then
  2250. begin
  2251. Result := False;
  2252. Exit;
  2253. end;
  2254. Drive := GetDriveToNode(Selected);
  2255. Result := WatchThreadActive(Drive);
  2256. end; {WatchThreadActive}
  2257. function TDriveView.FindPathNode(Path: string): TTreeNode;
  2258. var
  2259. PossiblyHiddenPath: string;
  2260. Attrs: Integer;
  2261. begin
  2262. if Assigned(FOnNeedHiddenDirectories) and
  2263. (not ShowHiddenDirs) and
  2264. DirectoryExistsFix(Path) then // do not even bother if the path does not exist
  2265. begin
  2266. PossiblyHiddenPath := ExcludeTrailingPathDelimiter(Path);
  2267. while (PossiblyHiddenPath <> '') and
  2268. (not IsRootPath(PossiblyHiddenPath)) do // Drives have hidden attribute
  2269. begin
  2270. Attrs := FileGetAttr(PossiblyHiddenPath, False);
  2271. if (Attrs and faHidden) = faHidden then
  2272. begin
  2273. if Assigned(FOnNeedHiddenDirectories) then
  2274. begin
  2275. FOnNeedHiddenDirectories(Self);
  2276. end;
  2277. Break;
  2278. end
  2279. else
  2280. begin
  2281. PossiblyHiddenPath := ExtractFileDir(PossiblyHiddenPath);
  2282. end;
  2283. end;
  2284. end;
  2285. {Find existing path or parent path of not existing path:}
  2286. repeat
  2287. Result := FindNodeToPath(Path);
  2288. if not Assigned(Result) then
  2289. Path := ExtractFilePath(ExcludeTrailingBackslash(Path));
  2290. until Assigned(Result) or (Length(Path) < 3);
  2291. end;
  2292. procedure TDriveView.SetDirectory(Value: string);
  2293. begin
  2294. Value := IncludeTrailingBackslash(Value);
  2295. FDirectory := Value;
  2296. inherited;
  2297. if Assigned(Selected) and (not Assigned(Selected.Parent)) then
  2298. begin
  2299. if not GetDriveStatus(GetDriveToNode(Selected)).Scanned then
  2300. ScanDrive(GetDriveToNode(Selected));
  2301. end;
  2302. end; {SetDirectory}
  2303. function TDriveView.GetDirName(Node: TTreeNode): string;
  2304. begin
  2305. if Assigned(Node) and Assigned(Node.Data) then
  2306. Result := TNodeData(Node.Data).DirName
  2307. else
  2308. Result := '';
  2309. end; {GetDirName}
  2310. {GetDrive: returns the drive of the Node.}
  2311. function TDriveView.GetDriveToNode(Node: TTreeNode): string;
  2312. var
  2313. Path: string;
  2314. begin
  2315. if (not Assigned (Node)) or (not Assigned(Node.Data)) then
  2316. raise ENodeNotAssigned.Create(Format(ErrorNodeNA, ['GetDrive']));
  2317. Path := NodePath(Node);
  2318. Result := DriveInfo.GetDriveKey(Path);
  2319. end; {GetDrive}
  2320. {RootNode: returns the rootnode to the Node:}
  2321. function TDriveView.RootNode(Node: TTreeNode): TTreeNode;
  2322. begin
  2323. Result := Node;
  2324. if not Assigned(Node) then
  2325. raise ENodeNotAssigned.Create(Format(ErrorNodeNA, ['RootNode']));
  2326. while Assigned(Result.Parent) do
  2327. Result := Result.Parent;
  2328. end; {RootNode}
  2329. function TDriveView.GetDisplayName(Node: TTreeNode): string;
  2330. begin
  2331. Result := '';
  2332. if (not Assigned(Node)) or (not Assigned(Node.Data)) then
  2333. raise ENodeNotAssigned.Create(Format(ErrorNodeNA, ['GetDisplayName']));
  2334. if not Assigned(Node.Parent) then Result := GetDriveText(GetDriveToNode(Node))
  2335. else
  2336. begin
  2337. Result := GetDirName(Node);
  2338. end;
  2339. end; {GetDisplayName}
  2340. procedure TDriveView.SetShowVolLabel(ShowIt: Boolean);
  2341. begin
  2342. if ShowIt = FShowVolLabel then
  2343. Exit;
  2344. FShowVolLabel := ShowIt;
  2345. RefreshRootNodes(True);
  2346. end; {SetShowVolLabel}
  2347. procedure TDriveView.DisplayContextMenu(Node: TTreeNode; Point: TPoint);
  2348. var
  2349. Verb: string;
  2350. DirWatched: Boolean;
  2351. begin
  2352. DirWatched := NodeWatched(Node) and WatchThreadActive;
  2353. Assert(Node <> nil);
  2354. if Node <> Selected then
  2355. DropTarget := Node;
  2356. Verb := EmptyStr;
  2357. if Assigned(FOnDisplayContextMenu) then
  2358. FOnDisplayContextMenu(Self);
  2359. ShellDisplayContextMenu(FParentForm.Handle, Point, NodePathName(Node),
  2360. CanEdit(Node), Verb, False);
  2361. if Verb = shcRename then Node.EditText
  2362. else
  2363. if Verb = shcCut then
  2364. begin
  2365. LastClipBoardOperation := cboCut;
  2366. LastPathCut := NodePathName(Node);
  2367. end
  2368. else
  2369. if Verb = shcCopy then LastClipBoardOperation := cboCopy
  2370. else
  2371. if Verb = shcPaste then
  2372. PasteFromClipBoard(NodePathName(Node));
  2373. DropTarget := nil;
  2374. if not DirWatched then
  2375. ValidateDirectory(Node);
  2376. end; {DisplayContextMenu (2)}
  2377. procedure TDriveView.DisplayPropertiesMenu(Node: TTreeNode);
  2378. begin
  2379. Assert(Assigned(Node));
  2380. ShellExecuteContextCommand(FParentForm.Handle, shcProperties, NodePathName(Node));
  2381. end; {ContextMenu}
  2382. procedure TDriveView.SetSelected(Node: TTreeNode);
  2383. begin
  2384. if Node <> Selected then
  2385. begin
  2386. FChangeFlag := False;
  2387. FCanChange := True;
  2388. inherited Selected := Node;
  2389. if not FChangeFlag then
  2390. Change(Selected);
  2391. end;
  2392. end; {SetSelected}
  2393. {Called by TFileDeleteThread, when a file deletion was detected by the D&D receiving application:}
  2394. procedure TDriveView.SignalDirDelete(Sender: TObject; Files: TStringList);
  2395. begin
  2396. if Files.Count > 0 then
  2397. ValidateDirectory(FindNodeToPath(Files[0]));
  2398. end; {SignalDirDelete}
  2399. function TDriveView.DDSourceEffects: TDropEffectSet;
  2400. begin
  2401. if not Assigned(FDragNode.Parent) then
  2402. Result := [deLink]
  2403. else
  2404. Result := [deLink, deCopy, deMove];
  2405. end;
  2406. procedure TDriveView.DDChooseEffect(KeyState: Integer; var Effect: Integer; PreferredEffect: Integer);
  2407. begin
  2408. if DropTarget = nil then Effect := DROPEFFECT_NONE
  2409. else
  2410. if (KeyState and (MK_CONTROL or MK_SHIFT) = 0) and (PreferredEffect = 0) then
  2411. begin
  2412. if FDragDrive <> '' then
  2413. begin
  2414. if FExeDrag and DriveInfo.IsFixedDrive(GetDriveToNode(DropTarget)) and DriveInfo.IsFixedDrive(FDragDrive) then
  2415. begin
  2416. Effect := DROPEFFECT_LINK;
  2417. end
  2418. else
  2419. if (Effect = DROPEFFECT_COPY) and
  2420. (SameText(FDragDrive, GetDriveToNode(DropTarget)) and
  2421. (FDragDropFilesEx.AvailableDropEffects and DROPEFFECT_MOVE <> 0)) then
  2422. begin
  2423. Effect := DROPEFFECT_MOVE;
  2424. end;
  2425. end;
  2426. end;
  2427. inherited;
  2428. end;
  2429. function TDriveView.DragCompleteFileList: Boolean;
  2430. begin
  2431. Result := (GetDriveTypeToNode(FDragNode) <> DRIVE_REMOVABLE);
  2432. end;
  2433. function TDriveView.DDExecute: TDragResult;
  2434. var
  2435. WatchThreadOK: Boolean;
  2436. DragParentPath: string;
  2437. DragPath: string;
  2438. begin
  2439. WatchThreadOK := WatchThreadActive;
  2440. Result := FDragDropFilesEx.Execute(nil);
  2441. if (Result = drMove) and (not WatchThreadOK) then
  2442. begin
  2443. DragPath := NodePathName(FDragNode);
  2444. if Assigned(FDragNode.Parent) then
  2445. DragParentPath := NodePathName(FDragNode.Parent)
  2446. else
  2447. DragParentPath := DragPath;
  2448. if Assigned(FDragNode.Parent) or (DragParentPath <> NodePathName(Selected.Parent)) then
  2449. begin
  2450. FDragNode := FindNodeToPath(DragPath);
  2451. if Assigned(FDragNode) then
  2452. begin
  2453. FDragFileList.Clear;
  2454. FDragFileList.Add(DragPath);
  2455. TFileDeleteThread.Create(FDragFileList, MaxWaitTimeOut, SignalDirDelete);
  2456. end;
  2457. end;
  2458. end;
  2459. end;
  2460. procedure TDriveView.PerformDragDropFileOperation(Node: TTreeNode; Effect: Integer);
  2461. var
  2462. Index: Integer;
  2463. SourcePath: string;
  2464. SourceParentPath: string;
  2465. SourceIsDirectory: Boolean;
  2466. SaveCursor: TCursor;
  2467. SourceNode, TargetNode: TTreeNode;
  2468. TargetPath: string;
  2469. IsRecycleBin: Boolean;
  2470. begin
  2471. TargetPath := NodePathName(Node);
  2472. IsRecycleBin := NodeIsRecycleBin(Node);
  2473. if FDragDropFilesEx.FileList.Count = 0 then
  2474. Exit;
  2475. SaveCursor := Screen.Cursor;
  2476. Screen.Cursor := crHourGlass;
  2477. SourcePath := EmptyStr;
  2478. try
  2479. if (Effect = DROPEFFECT_COPY) or (Effect = DROPEFFECT_MOVE) then
  2480. begin
  2481. StopAllWatchThreads;
  2482. if Assigned(FDirView) then
  2483. FDirView.StopWatchThread;
  2484. if Assigned(DropSourceControl) and
  2485. (DropSourceControl is TDirView) and
  2486. (DropSourceControl <> FDirView) then
  2487. begin
  2488. TDirView(DropSourceControl).StopWatchThread;
  2489. end;
  2490. if DropFiles(
  2491. DragDropFilesEx, Effect, FFileOperator, TargetPath, false, IsRecycleBin, ConfirmDelete, ConfirmOverwrite, False,
  2492. Self, OnDDFileOperation, SourcePath, SourceIsDirectory) then
  2493. begin
  2494. if Assigned(FOnDDFileOperationExecuted) then
  2495. FOnDDFileOperationExecuted(Self, Effect, SourcePath, TargetPath);
  2496. end;
  2497. ClearDragFileList(FDragDropFilesEx.FileList);
  2498. // TDirView.PerformDragDropFileOperation validates the SourcePath and that actually seems correct
  2499. SourceParentPath := ExtractFilePath(ExcludeTrailingBackslash(SourcePath));
  2500. end
  2501. else
  2502. if Effect = DROPEFFECT_LINK then
  2503. { Create Link requested: }
  2504. begin
  2505. for Index := 0 to FDragDropFilesEx.FileList.Count - 1 do
  2506. begin
  2507. if not DropLink(PFDDListItem(FDragDropFilesEx.FileList[Index]), TargetPath) then
  2508. begin
  2509. DDError(DDCreateShortCutError);
  2510. end;
  2511. end;
  2512. end;
  2513. if Effect = DROPEFFECT_MOVE then
  2514. Items.BeginUpdate;
  2515. {Update source directory, if move-operation was performed:}
  2516. if ((Effect = DROPEFFECT_MOVE) or IsRecycleBin) then
  2517. begin
  2518. // See comment in corresponding operation in TDirView.PerformDragDropFileOperation
  2519. SourceNode := TryFindNodeToPath(SourceParentPath);
  2520. if Assigned(SourceNode) then
  2521. ValidateDirectory(SourceNode);
  2522. end;
  2523. {Update subdirectories of target directory:}
  2524. TargetNode := FindNodeToPath(TargetPath);
  2525. if Assigned(TargetNode) then
  2526. ValidateDirectory(TargetNode)
  2527. else
  2528. ValidateDirectory(GetDriveStatus(DriveInfo.GetDriveKey(TargetPath)).RootNode);
  2529. if Effect = DROPEFFECT_MOVE then
  2530. Items.EndUpdate;
  2531. {Update linked component TDirView:}
  2532. if Assigned(FDirView) and (not FDirView.WatchThreadActive) then
  2533. begin
  2534. case Effect of
  2535. DROPEFFECT_COPY,
  2536. DROPEFFECT_LINK:
  2537. if (IncludeTrailingBackslash(TargetPath) = IncludeTrailingBackslash(DirView.Path)) then
  2538. FDirView.Reload2;
  2539. DROPEFFECT_MOVE:
  2540. if (IncludeTrailingBackslash(TargetPath) = IncludeTrailingBackslash(DirView.Path)) or
  2541. (IncludeTrailingBackslash(SourceParentPath) = IncludeTrailingBackslash(DirView.Path)) then
  2542. begin
  2543. if FDirView <> DropSourceControl then FDirView.Reload2;
  2544. end;
  2545. end; {Case}
  2546. end;
  2547. {Update the DropSource control, if files are moved and it is a TDirView:}
  2548. if (Effect = DROPEFFECT_MOVE) and (DropSourceControl is TDirView) then
  2549. begin
  2550. TDirView(DropSourceControl).ValidateSelectedFiles;
  2551. end;
  2552. finally
  2553. FFileOperator.OperandFrom.Clear;
  2554. FFileOperator.OperandTo.Clear;
  2555. StartAllWatchThreads;
  2556. if Assigned(FDirView) and (not FDirView.WatchThreadActive) then
  2557. FDirView.StartWatchThread;
  2558. if Assigned(DropSourceControl) and (DropSourceControl is TDirView) and
  2559. (not TDirView(DropSourceControl).WatchThreadActive) then
  2560. TDirView(DropSourceControl).StartWatchThread;
  2561. Screen.Cursor := SaveCursor;
  2562. end;
  2563. end; {PerformDragDropFileOperation}
  2564. function TDriveView.GetCanUndoCopyMove: Boolean;
  2565. begin
  2566. Result := Assigned(FFileOperator) and FFileOperator.CanUndo;
  2567. end; {CanUndoCopyMove}
  2568. function TDriveView.UndoCopyMove: Boolean;
  2569. var
  2570. LastTarget: string;
  2571. LastSource: string;
  2572. begin
  2573. Result := False;
  2574. if FFileOperator.CanUndo then
  2575. begin
  2576. Lasttarget := FFileOperator.LastOperandTo[0];
  2577. LastSource := FFileOperator.LastOperandFrom[0];
  2578. StopAllWatchThreads;
  2579. Result := FFileOperator.UndoExecute;
  2580. ValidateDirectory(FindNodeToPath(ExtractFilePath(LastTarget)));
  2581. ValidateDirectory(FindNodeToPath(ExtractFilePath(LastSource)));
  2582. StartAllWatchThreads;
  2583. if Assigned(FDirView) then
  2584. with FDirView do
  2585. if not WatchThreadActive then
  2586. begin
  2587. if (IncludeTrailingBackslash(ExtractFilePath(LastTarget)) = IncludeTrailingBackslash(Path)) or
  2588. (IncludeTrailingBackslash(ExtractFilePath(LastSource)) = IncludeTrailingBackslash(Path)) then
  2589. Reload2;
  2590. end;
  2591. end;
  2592. end; {UndoCopyMove}
  2593. {Clipboard operations:}
  2594. procedure TDriveView.SetLastPathCut(Path: string);
  2595. var
  2596. Node: TTreeNode;
  2597. begin
  2598. if FLastPathCut <> Path then
  2599. begin
  2600. Node := FindNodeToPath(FLastPathCut);
  2601. if Assigned(Node) then
  2602. begin
  2603. FLastPathCut := Path;
  2604. Node.Cut := False;
  2605. end;
  2606. Node := FindNodeToPath(Path);
  2607. if Assigned(Node) then
  2608. begin
  2609. FLastPathCut := Path;
  2610. Node.Cut := True;
  2611. end;
  2612. end;
  2613. end; {SetLastNodeCut}
  2614. procedure TDriveView.EmptyClipboard;
  2615. begin
  2616. if Windows.OpenClipBoard(0) then
  2617. begin
  2618. Windows.EmptyClipBoard;
  2619. Windows.CloseClipBoard;
  2620. LastPathCut := '';
  2621. LastClipBoardOperation := cboNone;
  2622. if Assigned(FDirView) then
  2623. FDirView.EmptyClipboard;
  2624. end;
  2625. end; {EmptyClipBoard}
  2626. function TDriveView.CopyToClipBoard(Node: TTreeNode): Boolean;
  2627. begin
  2628. Result := Assigned(Selected);
  2629. if Result then
  2630. begin
  2631. EmptyClipBoard;
  2632. ClearDragFileList(FDragDropFilesEx.FileList);
  2633. AddToDragFileList(FDragDropFilesEx.FileList, Selected);
  2634. Result := FDragDropFilesEx.CopyToClipBoard;
  2635. LastClipBoardOperation := cboCopy;
  2636. end;
  2637. end; {CopyToClipBoard}
  2638. function TDriveView.CutToClipBoard(Node: TTreeNode): Boolean;
  2639. begin
  2640. Result := Assigned(Node) and Assigned(Node.Parent) and CopyToClipBoard(Node);
  2641. if Result then
  2642. begin
  2643. LastPathCut := NodePathName(Node);
  2644. LastClipBoardOperation := cboCut;
  2645. end;
  2646. end; {CutToClipBoard}
  2647. function TDriveView.CanPasteFromClipBoard: Boolean;
  2648. begin
  2649. Result := False;
  2650. if Assigned(Selected) and Windows.OpenClipboard(0) then
  2651. begin
  2652. Result := IsClipboardFormatAvailable(CF_HDROP);
  2653. Windows.CloseClipBoard;
  2654. end;
  2655. end; {CanPasteFromClipBoard}
  2656. function TDriveView.PasteFromClipBoard(TargetPath: String = ''): Boolean;
  2657. begin
  2658. ClearDragFileList(FDragDropFilesEx.FileList);
  2659. Result := False;
  2660. if CanPasteFromClipBoard and {MP}FDragDropFilesEx.GetFromClipBoard{/MP}
  2661. then
  2662. begin
  2663. if TargetPath = '' then
  2664. TargetPath := NodePathName(Selected);
  2665. case LastClipBoardOperation of
  2666. cboCopy,
  2667. cboNone:
  2668. begin
  2669. PerformDragDropFileOperation(Selected, DROPEFFECT_COPY);
  2670. if Assigned(FOnDDExecuted) then
  2671. FOnDDExecuted(Self, DROPEFFECT_COPY);
  2672. end;
  2673. cboCut:
  2674. begin
  2675. PerformDragDropFileOperation(Selected, DROPEFFECT_MOVE);
  2676. if Assigned(FOnDDExecuted) then
  2677. FOnDDExecuted(Self, DROPEFFECT_MOVE);
  2678. EmptyClipBoard;
  2679. end;
  2680. end;
  2681. Result := True;
  2682. end;
  2683. end; {PasteFromClipBoard}
  2684. procedure TDriveView.CMRecreateWnd(var Msg: TMessage);
  2685. var
  2686. ScheduledCount: Integer;
  2687. begin
  2688. ScheduledCount := FSubDirReaderThread.Detach;
  2689. try
  2690. inherited;
  2691. finally
  2692. FSubDirReaderThread.Reattach(ScheduledCount);
  2693. end;
  2694. end;
  2695. procedure TDriveView.CMSysColorChange(var Message: TMessage);
  2696. begin
  2697. if not FValidateFlag then
  2698. begin
  2699. inherited;
  2700. end
  2701. else
  2702. begin
  2703. // Do not recreate the handle, if we are just iterating nodes, at that invalidates the node objects.
  2704. // This is not perfect, as the handle can be recreated for other reasons.
  2705. // But system color change is by far the most common case.
  2706. FSysColorChangePending := True;
  2707. end;
  2708. end;
  2709. end.