PasTools.pas 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  1. unit PasTools;
  2. interface
  3. uses
  4. Windows, Types, Classes, ComCtrls, ExtCtrls, Controls, Dialogs, Forms, Messages;
  5. function Construct(ComponentClass: TComponentClass; Owner: TComponent): TComponent;
  6. function IsVistaHard: Boolean;
  7. function IsVista: Boolean;
  8. // Prevent name conflict with C++ IsWin8.
  9. {$HPPEMIT '#define IsWin7 IsWin7Pas'}
  10. {$HPPEMIT END '#undef IsWin7'}
  11. function IsWin7: Boolean;
  12. // Prevent name conflict with C++ IsWin8.
  13. {$HPPEMIT '#define IsWin8 IsWin8Pas'}
  14. {$HPPEMIT END '#undef IsWin8'}
  15. function IsWin8: Boolean;
  16. // Prevent name conflict with C++ CutToChar.
  17. {$HPPEMIT '#define CutToChar CutToCharPas'}
  18. {$HPPEMIT END '#undef CutToChar'}
  19. function CutToChar(var Str: string; Ch: Char; Trim: Boolean): string;
  20. procedure FilterToFileTypes(Filter: string; FileTypes: TFileTypeItems);
  21. // Note that while we based our scaling on pixels-per-inch,
  22. // VCL actually scales based on font size
  23. const
  24. CM_DPICHANGED = WM_USER + $2000 + 10;
  25. WM_DPICHANGED_BEFOREPARENT = $02E2;
  26. WM_DPICHANGED_AFTERPARENT = $02E3;
  27. function HasSystemParametersInfoForPixelsPerInch: Boolean;
  28. function SystemParametersInfoForPixelsPerInch(
  29. uiAction, uiParam: UINT; pvParam: Pointer; fWinIni: UINT; dpi: UINT): BOOL;
  30. procedure GetFormScaleRatio(Form: TForm; var M, D: Integer);
  31. function GetMonitorFromControl(Control: TControl): TMonitor;
  32. function GetMonitorPixelsPerInch(Monitor: TMonitor): Integer;
  33. function GetControlPixelsPerInch(Control: TControl): Integer;
  34. function GetComponentPixelsPerInch(Component: TComponent): Integer;
  35. function LoadDimension(Dimension: Integer; PixelsPerInch: Integer; Control: TControl): Integer;
  36. function StrToDimensionDef(Str: string; PixelsPerInch: Integer; Control: TControl; Default: Integer): Integer;
  37. function SaveDimension(Dimension: Integer): Integer;
  38. function DimensionToDefaultPixelsPerInch(Dimension: Integer): Integer;
  39. function ScaleByPixelsPerInch(Dimension: Integer; Monitor: TMonitor): Integer; overload;
  40. function ScaleByPixelsPerInch(Dimension: Integer; Control: TControl): Integer; overload;
  41. function ScaleByPixelsPerInchFromSystem(Dimension: Integer; Control: TControl): Integer;
  42. function LoadPixelsPerInch(S: string; Control: TControl): Integer;
  43. function SavePixelsPerInch(Control: TControl): string;
  44. function SaveDefaultPixelsPerInch: string;
  45. function ScaleByTextHeight(Control: TControl; Dimension: Integer): Integer;
  46. function ScaleByTextHeightRunTime(Control: TControl; Dimension: Integer): Integer;
  47. function GetSystemMetricsForControl(Control: TControl; nIndex: Integer): Integer;
  48. type
  49. TImageListSize = (ilsSmall, ilsLarge);
  50. procedure NeedShellImageLists;
  51. function ShellImageListForControl(Control: TControl; Size: TImageListSize): TImageList;
  52. function ControlHasRecreationPersistenceData(Control: TControl): Boolean;
  53. function IsAppIconic: Boolean;
  54. procedure SetAppIconic(Value: Boolean);
  55. procedure SetAppMainForm(Value: TForm);
  56. procedure SetAppTerminated(Value: Boolean);
  57. procedure ForceColorChange(Control: TWinControl);
  58. function IsUncPath(Path: string): Boolean;
  59. function FileExistsFix(Path: string): Boolean;
  60. function DirectoryExistsFix(Path: string): Boolean;
  61. function SupportsDarkMode: Boolean;
  62. procedure AllowDarkModeForWindow(Control: TWinControl; Allow: Boolean); overload;
  63. procedure AllowDarkModeForWindow(Handle: THandle; Allow: Boolean); overload;
  64. procedure RefreshColorMode;
  65. procedure ResetSysDarkTheme;
  66. function GetSysDarkTheme: Boolean;
  67. type
  68. TApiPathEvent = function(Path: string): string;
  69. var
  70. OnApiPath: TApiPathEvent = nil;
  71. // Prevent name conflict with C++ ApiPath.
  72. // We would not want to call this implementation in any case anyway.
  73. {$HPPEMIT '#define ApiPath ApiPathPas'}
  74. {$HPPEMIT END '#undef ApiPath'}
  75. function ApiPath(Path: string): string;
  76. type
  77. TControlScrollBeforeUpdate = procedure(ObjectToValidate: TObject) of object;
  78. TControlScrollAfterUpdate = procedure of object;
  79. TCustomControlScrollOnDragOver = class
  80. private
  81. FOnBeforeUpdate: TControlScrollBeforeUpdate;
  82. FOnAfterUpdate: TControlScrollAfterUpdate;
  83. FDragOverTimer: TTimer;
  84. FControl: TControl;
  85. FDragOverTime: FILETIME;
  86. FLastVScrollTime: FILETIME;
  87. FVScrollCount: Integer;
  88. procedure DragOverTimer(Sender: TObject);
  89. procedure BeforeUpdate(ObjectToValidate: TObject);
  90. procedure AfterUpdate;
  91. public
  92. constructor Create(Control: TControl; ScheduleDragOver: Boolean);
  93. destructor Destroy; override;
  94. procedure StartDrag; virtual;
  95. procedure EndDrag; virtual;
  96. procedure DragOver(Point: TPoint); virtual; abstract;
  97. property OnBeforeUpdate: TControlScrollBeforeUpdate read FOnBeforeUpdate write FOnBeforeUpdate;
  98. property OnAfterUpdate: TControlScrollAfterUpdate read FOnAfterUpdate write FOnAfterUpdate;
  99. end;
  100. TTreeViewScrollOnDragOver = class(TCustomControlScrollOnDragOver)
  101. private
  102. FLastDragNode: TTreeNode;
  103. FLastHScrollTime: FILETIME;
  104. public
  105. procedure StartDrag; override;
  106. procedure DragOver(Point: TPoint); override;
  107. end;
  108. TListViewScrollOnDragOver = class(TCustomControlScrollOnDragOver)
  109. public
  110. procedure DragOver(Point: TPoint); override;
  111. end;
  112. TListBoxScrollOnDragOver = class(TCustomControlScrollOnDragOver)
  113. public
  114. procedure DragOver(Point: TPoint); override;
  115. end;
  116. implementation
  117. uses
  118. SysUtils, StdCtrls, Graphics, MultiMon, ShellAPI, Generics.Collections, CommCtrl, ImgList, Registry;
  119. const
  120. DDExpandDelay = 15000000;
  121. DDMaxSlowCount = 3;
  122. DDVScrollDelay = 2000000;
  123. DDHScrollDelay = 2000000;
  124. DDDragStartDelay = 500000;
  125. function Construct(ComponentClass: TComponentClass; Owner: TComponent): TComponent;
  126. begin
  127. Result := ComponentClass.Create(Owner);
  128. end;
  129. // detects vista, even in compatibility mode
  130. // (GetLocaleInfoEx is available since Vista only)
  131. function IsVistaHard: Boolean;
  132. begin
  133. Result := (GetProcAddress(GetModuleHandle(Kernel32), 'GetLocaleInfoEx') <> nil);
  134. end;
  135. function IsVista: Boolean;
  136. begin
  137. Result := CheckWin32Version(6, 0);
  138. end;
  139. function IsWin7: Boolean;
  140. begin
  141. Result := CheckWin32Version(6, 1);
  142. end;
  143. function IsWin8: Boolean;
  144. begin
  145. Result := CheckWin32Version(6, 2);
  146. end;
  147. function CutToChar(var Str: string; Ch: Char; Trim: Boolean): string;
  148. var
  149. P: Integer;
  150. begin
  151. P := Pos(Ch, Str);
  152. if P > 0 then
  153. begin
  154. Result := Copy(Str, 1, P-1);
  155. Delete(Str, 1, P);
  156. end
  157. else
  158. begin
  159. Result := Str;
  160. Str := '';
  161. end;
  162. if Trim then Result := SysUtils.Trim(Result);
  163. end;
  164. procedure FilterToFileTypes(Filter: string; FileTypes: TFileTypeItems);
  165. var
  166. Item: TFileTypeItem;
  167. begin
  168. while Filter <> '' do
  169. begin
  170. Item := FileTypes.Add();
  171. Item.DisplayName := CutToChar(Filter, '|', True);
  172. Item.FileMask := CutToChar(Filter, '|', True);
  173. end;
  174. end;
  175. type
  176. TGetDpiForMonitorFunc =
  177. function (hMonitor: HMONITOR; MonitorType: Integer; out DpiX, DpiY: Cardinal): HRESULT; stdcall;
  178. TGetSystemMetricsForDpiFunc =
  179. function (nIndex: Integer; Dpi: Cardinal): Integer; stdcall;
  180. TSystemParametersInfoForDpiFunc =
  181. function (uiAction, uiParam: UINT; pvParam: Pointer; fWinIni: UINT; dpi: UINT): BOOL; stdcall;
  182. const
  183. MDT_EFFECTIVE_DPI = 0;
  184. var
  185. GetDpiForMonitor: TGetDpiForMonitorFunc = nil;
  186. GetSystemMetricsForDpi: TGetSystemMetricsForDpiFunc = nil;
  187. SystemParametersInfoForDpi: TSystemParametersInfoForDpiFunc = nil;
  188. function HasSystemParametersInfoForPixelsPerInch: Boolean;
  189. begin
  190. Result := Assigned(SystemParametersInfoForDpi);
  191. end;
  192. function SystemParametersInfoForPixelsPerInch(
  193. uiAction, uiParam: UINT; pvParam: Pointer; fWinIni: UINT; dpi: UINT): BOOL;
  194. begin
  195. if HasSystemParametersInfoForPixelsPerInch then
  196. begin
  197. Result := SystemParametersInfoForDpi(uiAction, uiParam, pvParam, fWinIni, dpi);
  198. end
  199. else
  200. begin
  201. Result := SystemParametersInfo(uiAction, uiParam, pvParam, fWinIni);
  202. end;
  203. end;
  204. function GetMonitorPixelsPerInch(Monitor: TMonitor): Integer;
  205. var
  206. DpiX, DpiY: Cardinal;
  207. begin
  208. if Assigned(GetDpiForMonitor) and
  209. (GetDpiForMonitor(Monitor.Handle, MDT_EFFECTIVE_DPI, DpiX, DpiY) = S_OK) then
  210. begin
  211. Result := DpiX;
  212. end
  213. else
  214. begin
  215. Result := Screen.PixelsPerInch;
  216. end;
  217. end;
  218. function GetMonitorFromControl(Control: TControl): TMonitor;
  219. begin
  220. if Control.Parent <> nil then
  221. begin
  222. Result := GetMonitorFromControl(Control.Parent);
  223. end
  224. else
  225. if Control is TCustomForm then
  226. begin
  227. Result := TCustomForm(Control).Monitor;
  228. end
  229. else
  230. if (Control is TWinControl) and TWinControl(Control).HandleAllocated then
  231. begin
  232. Result := Screen.MonitorFromWindow(TWinControl(Control).Handle);
  233. end
  234. else
  235. begin
  236. Result := nil;
  237. end;
  238. end;
  239. function GetControlPixelsPerInch(Control: TControl): Integer;
  240. var
  241. Form: TCustomForm;
  242. Monitor: TMonitor;
  243. begin
  244. if Assigned(GetDpiForMonitor) then // optimization
  245. begin
  246. Form := GetParentForm(Control);
  247. if Assigned(Form) then
  248. begin
  249. // By default, scale according to what the form is so far rendered on.
  250. // If the monitor perceived DPI does not match its monitor DPI, it's because the WM_DPICHANGED is still pending.
  251. Result := TForm(Form).PixelsPerInch;
  252. end
  253. else
  254. begin
  255. Monitor := GetMonitorFromControl(Control);
  256. if Monitor = nil then
  257. begin
  258. Assert(False);
  259. Monitor := Screen.PrimaryMonitor;
  260. end;
  261. Result := GetMonitorPixelsPerInch(Monitor);
  262. end;
  263. end
  264. else
  265. begin
  266. Result := Screen.PixelsPerInch;
  267. end;
  268. end;
  269. function GetComponentPixelsPerInch(Component: TComponent): Integer;
  270. begin
  271. Result := GetControlPixelsPerInch(TControl(Component.Owner));
  272. end;
  273. function LoadDimension(Dimension: Integer; PixelsPerInch: Integer; Control: TControl): Integer;
  274. begin
  275. Result := MulDiv(Dimension, GetControlPixelsPerInch(Control), PixelsPerInch);
  276. end;
  277. function StrToDimensionDef(Str: string; PixelsPerInch: Integer; Control: TControl; Default: Integer): Integer;
  278. begin
  279. if TryStrToInt(Str, Result) then
  280. begin
  281. Result := LoadDimension(Result, PixelsPerInch, Control);
  282. end
  283. else
  284. begin
  285. Result := Default;
  286. end;
  287. end;
  288. function SaveDimension(Dimension: Integer): Integer;
  289. begin
  290. // noop
  291. Result := Dimension;
  292. end;
  293. function DimensionToDefaultPixelsPerInch(Dimension: Integer): Integer;
  294. begin
  295. Result := MulDiv(Dimension, USER_DEFAULT_SCREEN_DPI, Screen.PixelsPerInch);
  296. end;
  297. function ScaleByPixelsPerInch(Dimension: Integer; Monitor: TMonitor): Integer;
  298. begin
  299. Result := MulDiv(Dimension, GetMonitorPixelsPerInch(Monitor), USER_DEFAULT_SCREEN_DPI);
  300. end;
  301. function ScaleByPixelsPerInch(Dimension: Integer; Control: TControl): Integer;
  302. begin
  303. Result := MulDiv(Dimension, GetControlPixelsPerInch(Control), USER_DEFAULT_SCREEN_DPI);
  304. end;
  305. function ScaleByPixelsPerInchFromSystem(Dimension: Integer; Control: TControl): Integer;
  306. begin
  307. Result := MulDiv(Dimension, GetControlPixelsPerInch(Control), Screen.PixelsPerInch);
  308. end;
  309. function LoadPixelsPerInch(S: string; Control: TControl): Integer;
  310. begin
  311. // for backward compatibility with version that did not save the DPI,
  312. // make reasonable assumption that the configuration was saved with
  313. // the same DPI as we run now
  314. Result := StrToIntDef(S, GetControlPixelsPerInch(Control));
  315. end;
  316. function SavePixelsPerInch(Control: TControl): string;
  317. begin
  318. Result := IntToStr(GetControlPixelsPerInch(Control));
  319. end;
  320. function SaveDefaultPixelsPerInch: string;
  321. begin
  322. Result := IntToStr(USER_DEFAULT_SCREEN_DPI);
  323. end;
  324. // WORKAROUND
  325. // https://stackoverflow.com/q/9410485/850848
  326. type
  327. TFormHelper = class helper for TCustomForm
  328. public
  329. function RetrieveTextHeight: Integer;
  330. function CalculateTextHeight: Integer;
  331. end;
  332. function TFormHelper.RetrieveTextHeight: Integer;
  333. begin
  334. Result := Self.FTextHeight;
  335. end;
  336. function TFormHelper.CalculateTextHeight: Integer;
  337. begin
  338. Result := Self.GetTextHeight;
  339. end;
  340. function ScaleByTextHeightImpl(Control: TControl; Dimension: Integer; TextHeight: Integer): Integer;
  341. var
  342. Form: TCustomForm;
  343. NewTextHeight: Integer;
  344. begin
  345. // RTL_COPY (TCustomForm.ReadState)
  346. Form := ValidParentForm(Control);
  347. NewTextHeight := Form.CalculateTextHeight;
  348. if TextHeight <> NewTextHeight then
  349. begin
  350. Dimension := MulDiv(Dimension, NewTextHeight, TextHeight);
  351. end;
  352. Result := Dimension;
  353. end;
  354. const
  355. OurDesignTimeTextHeight = 13;
  356. function ScaleByTextHeight(Control: TControl; Dimension: Integer): Integer;
  357. var
  358. Form: TCustomForm;
  359. TextHeight: Integer;
  360. begin
  361. // RTL_COPY (TCustomForm.ReadState)
  362. Form := GetParentForm(Control);
  363. if Form = nil then
  364. begin
  365. // This should happen only for screen tip over dropped down menu.
  366. // The other condition is a temporary fix is for TCustomComboEdit on TCopyParamsFrame.
  367. Assert((Control.ClassName = 'TTBXPopupWindow') or ((Control.Parent <> nil) and (Control.Parent.ClassName = 'TCopyParamsFrame')) or ((Control.Parent.Parent <> nil) and (Control.Parent.Parent.ClassName = 'TCopyParamsFrame')));
  368. Result := ScaleByPixelsPerInch(Dimension, Control);
  369. end
  370. else
  371. begin
  372. TextHeight := Form.RetrieveTextHeight;
  373. // runtime form (such as TTBFloatingWindowParent)
  374. if TextHeight = 0 then
  375. begin
  376. Result := ScaleByTextHeightRunTime(Control, Dimension);
  377. end
  378. else
  379. begin
  380. // that's our design text-size, we do not expect any other value
  381. Assert(TextHeight = OurDesignTimeTextHeight);
  382. Result := ScaleByTextHeightImpl(Control, Dimension, TextHeight);
  383. end;
  384. end;
  385. end;
  386. procedure GetFormScaleRatio(Form: TForm; var M, D: Integer);
  387. begin
  388. M := Form.CalculateTextHeight;
  389. D := Form.RetrieveTextHeight;
  390. end;
  391. // this differs from ScaleByTextHeight only by enforcing
  392. // constant design-time text height
  393. function ScaleByTextHeightRunTime(Control: TControl; Dimension: Integer): Integer;
  394. begin
  395. Result := ScaleByTextHeightImpl(Control, Dimension, OurDesignTimeTextHeight);
  396. end;
  397. function GetSystemMetricsForControl(Control: TControl; nIndex: Integer): Integer;
  398. begin
  399. if Assigned(GetSystemMetricsForDpi) then
  400. begin
  401. Result := GetSystemMetricsForDpi(nIndex, GetControlPixelsPerInch(Control))
  402. end
  403. else
  404. begin
  405. Result := GetSystemMetrics(nIndex);
  406. end;
  407. end;
  408. var
  409. ShellImageLists: TDictionary<Integer, TImageList> = nil;
  410. procedure InitializeShellImageLists;
  411. type
  412. TSHGetImageList = function (iImageList: integer; const riid: TGUID; var ppv: Pointer): hResult; stdcall;
  413. const
  414. IID_IImageList: TGUID = '{46EB5926-582E-4017-9FDF-E8998DAA0950}';
  415. var
  416. Lib: THandle;
  417. ImageList: Integer;
  418. Handle: THandle;
  419. Height, Width: Integer;
  420. ShellImageList: TImageList;
  421. SHGetImageList: TSHGetImageList;
  422. HR: HRESULT;
  423. begin
  424. Lib := LoadLibrary('shell32');
  425. SHGetImageList := GetProcAddress(Lib, 'SHGetImageList');
  426. ShellImageLists := TDictionary<Integer, TImageList>.Create;
  427. for ImageList := 0 to SHIL_LAST do
  428. begin
  429. // VCL have declaration for SHGetImageList in ShellAPI, but it does not link
  430. HR := SHGetImageList(ImageList, IID_IImageList, Pointer(Handle));
  431. if (HR = S_OK) and
  432. ImageList_GetIconSize(Handle, Width, Height) then
  433. begin
  434. // We could use AddOrSetValue instead, but to be on a safe siz, we prefer e.g. SHIL_SMALL over SHIL_SYSSMALL,
  435. // while they actually can be the same
  436. if not ShellImageLists.ContainsKey(Width) then
  437. begin
  438. ShellImageList := TImageList.Create(Application);
  439. ShellImageList.Handle := Handle;
  440. ShellImageList.ShareImages := True;
  441. ShellImageList.DrawingStyle := dsTransparent;
  442. ShellImageLists.Add(Width, ShellImageList);
  443. end;
  444. end;
  445. end;
  446. end;
  447. procedure NeedShellImageLists;
  448. begin
  449. if ShellImageLists = nil then
  450. begin
  451. InitializeShellImageLists;
  452. end;
  453. end;
  454. function ShellImageListForControl(Control: TControl; Size: TImageListSize): TImageList;
  455. var
  456. ImageListPair: TPair<Integer, TImageList>;
  457. Width, ImageListWidth: Integer;
  458. Diff, BestDiff: Integer;
  459. begin
  460. // Delay load image lists, not to waste resources in console/scripting mode
  461. NeedShellImageLists;
  462. case Size of
  463. ilsSmall: Width := 16;
  464. ilsLarge: Width := 32;
  465. else Width := 0; Assert(False);
  466. end;
  467. Width := ScaleByPixelsPerInch(Width, Control);
  468. Result := nil;
  469. BestDiff := -1;
  470. for ImageListPair in ShellImageLists do
  471. begin
  472. ImageListWidth := ImageListPair.Key;
  473. if ImageListWidth <= Width then
  474. begin
  475. Diff := Width - ImageListWidth;
  476. end
  477. else
  478. begin
  479. // Prefer smaller images over larger, so for 150%, we use 100% images, not 200%
  480. Diff := ImageListWidth - Width + 1;
  481. end;
  482. if (BestDiff < 0) or (BestDiff > Diff) then
  483. begin
  484. BestDiff := Diff;
  485. Result := ImageListPair.Value;
  486. end;
  487. end;
  488. end;
  489. type
  490. TListViewHelper = class helper for TCustomListView
  491. public
  492. function HasMemStream: Boolean;
  493. end;
  494. function TListViewHelper.HasMemStream: Boolean;
  495. begin
  496. Result := Assigned(Self.FMemStream);
  497. end;
  498. type
  499. TTreeViewHelper = class helper for TCustomTreeView
  500. public
  501. function HasMemStream: Boolean;
  502. end;
  503. function TTreeViewHelper.HasMemStream: Boolean;
  504. begin
  505. Result := Assigned(Self.FMemStream);
  506. end;
  507. type
  508. TRichEditHelper = class helper for TCustomRichEdit
  509. public
  510. function HasMemStream: Boolean;
  511. end;
  512. function TRichEditHelper.HasMemStream: Boolean;
  513. begin
  514. Result := Assigned(Self.FMemStream);
  515. end;
  516. function ControlHasRecreationPersistenceData(Control: TControl): Boolean;
  517. begin
  518. // not implemented for this class as we do not use it as of now
  519. Assert(not (Control is TCustomComboBoxEx));
  520. Result :=
  521. ((Control is TCustomListView) and (Control as TCustomListView).HasMemStream) or
  522. ((Control is TCustomTreeView) and (Control as TCustomTreeView).HasMemStream) or
  523. ((Control is TCustomRichEdit) and (Control as TCustomRichEdit).HasMemStream);
  524. end;
  525. type
  526. TApplicationHelper = class helper for TApplication
  527. public
  528. function IsAppIconic: Boolean;
  529. procedure SetAppIconic(Value: Boolean);
  530. procedure SetMainForm(Value: TForm);
  531. procedure SetTerminated(Value: Boolean);
  532. end;
  533. function TApplicationHelper.IsAppIconic: Boolean;
  534. begin
  535. Result := Self.FAppIconic;
  536. end;
  537. procedure TApplicationHelper.SetAppIconic(Value: Boolean);
  538. begin
  539. Self.FAppIconic := Value;
  540. end;
  541. procedure TApplicationHelper.SetMainForm(Value: TForm);
  542. begin
  543. Self.FMainForm := Value;
  544. end;
  545. procedure TApplicationHelper.SetTerminated(Value: Boolean);
  546. begin
  547. Self.FTerminate := Value;
  548. end;
  549. function IsAppIconic: Boolean;
  550. begin
  551. Result := Application.IsAppIconic;
  552. end;
  553. procedure SetAppIconic(Value: Boolean);
  554. begin
  555. Application.SetAppIconic(Value);
  556. end;
  557. procedure SetAppMainForm(Value: TForm);
  558. begin
  559. Application.SetMainForm(Value);
  560. end;
  561. procedure SetAppTerminated(Value: Boolean);
  562. begin
  563. Application.SetTerminated(Value);
  564. end;
  565. function ApiPath(Path: string): string;
  566. begin
  567. Result := Path;
  568. if Assigned(OnApiPath) then
  569. begin
  570. Result := OnApiPath(Result);
  571. end;
  572. end;
  573. procedure ForceColorChange(Control: TWinControl);
  574. begin
  575. // particularly when changing color back to default (clWindow),
  576. // non-client area (border line) is not redrawn,
  577. // keeping previous color. force redraw here
  578. if Control.HandleAllocated then
  579. begin
  580. RedrawWindow(Control.Handle, nil, 0, RDW_INVALIDATE or RDW_FRAME);
  581. end;
  582. end;
  583. { TCustomControlScrollOnDragOver }
  584. constructor TCustomControlScrollOnDragOver.Create(Control: TControl;
  585. ScheduleDragOver: Boolean);
  586. begin
  587. FControl := Control;
  588. FOnBeforeUpdate := nil;
  589. FOnAfterUpdate := nil;
  590. if ScheduleDragOver then
  591. begin
  592. FDragOverTimer := TTimer.Create(Control);
  593. FDragOverTimer.Enabled := False;
  594. FDragOverTimer.Interval := 50;
  595. FDragOverTimer.OnTimer := DragOverTimer;
  596. end
  597. else FDragOverTimer := nil;
  598. end;
  599. destructor TCustomControlScrollOnDragOver.Destroy;
  600. begin
  601. FreeAndNil(FDragOverTimer);
  602. end;
  603. procedure TCustomControlScrollOnDragOver.DragOverTimer(Sender: TObject);
  604. var
  605. P: TPoint;
  606. begin
  607. P := FControl.ScreenToClient(Mouse.CursorPos);
  608. if (P.X >= 0) and (P.X < FControl.Width) and
  609. (P.Y >= 0) and (P.Y < FControl.Height) then
  610. begin
  611. DragOver(P);
  612. end;
  613. end;
  614. procedure TCustomControlScrollOnDragOver.StartDrag;
  615. begin
  616. GetSystemTimeAsFileTime(FDragOverTime);
  617. GetSystemTimeAsFileTime(FLastVScrollTime);
  618. FVScrollCount := 0;
  619. if Assigned(FDragOverTimer) then
  620. FDragOverTimer.Enabled := True;
  621. end;
  622. procedure TCustomControlScrollOnDragOver.EndDrag;
  623. begin
  624. if Assigned(FDragOverTimer) then
  625. FDragOverTimer.Enabled := False;
  626. end;
  627. type
  628. TPublicControl = class(TControl);
  629. procedure TCustomControlScrollOnDragOver.BeforeUpdate(ObjectToValidate: TObject);
  630. var
  631. DragImages: TDragImageList;
  632. begin
  633. if Assigned(FOnBeforeUpdate) then
  634. FOnBeforeUpdate(ObjectToValidate);
  635. DragImages := TPublicControl(FControl).GetDragImages;
  636. if Assigned(DragImages) then
  637. DragImages.HideDragImage;
  638. end;
  639. procedure TCustomControlScrollOnDragOver.AfterUpdate;
  640. var
  641. DragImages: TDragImageList;
  642. begin
  643. if Assigned(FOnAfterUpdate) then
  644. FOnAfterUpdate;
  645. DragImages := TPublicControl(FControl).GetDragImages;
  646. if Assigned(DragImages) then
  647. DragImages.ShowDragImage;
  648. end;
  649. procedure TTreeViewScrollOnDragOver.StartDrag;
  650. var
  651. KeyBoardState : TKeyBoardState;
  652. begin
  653. inherited;
  654. FLastDragNode := nil;
  655. if (GetKeyState(VK_SPACE) <> 0) and GetKeyboardState(KeyBoardState) then
  656. begin
  657. KeyBoardState[VK_SPACE] := 0;
  658. SetKeyBoardState(KeyBoardState);
  659. end;
  660. GetSystemTimeAsFileTime(FLastHScrollTime);
  661. end;
  662. { TTreeViewScrollOnDragOver }
  663. procedure TTreeViewScrollOnDragOver.DragOver(Point: TPoint);
  664. var
  665. TreeView: TCustomTreeView;
  666. NbPixels: Integer;
  667. KnowTime: TFileTime;
  668. Node: TTreeNode;
  669. TempTopItem: TTreeNode;
  670. ScrollInfo: TScrollInfo;
  671. KeyBoardState : TKeyBoardState;
  672. begin
  673. TreeView := (FControl as TCustomTreeView);
  674. Node := TreeView.GetNodeAt(Point.X, Point.Y);
  675. if Assigned(Node) then
  676. begin
  677. GetSystemTimeAsFileTime(KnowTime);
  678. if GetKeyState(VK_SPACE) = 0 then
  679. begin
  680. {Expand node after 2.5 seconds: }
  681. if not Assigned(FLastDragNode) or (FLastDragNode <> Node) then
  682. begin
  683. {not previous droptarget: start timer}
  684. GetSystemTimeAsFileTime(FDragOverTime);
  685. FLastDragNode := Node
  686. end
  687. else
  688. begin
  689. if ((Int64(KnowTime) - Int64(FDragOverTime)) > DDExpandDelay) then
  690. begin
  691. TempTopItem := TreeView.TopItem;
  692. BeforeUpdate(nil);
  693. Node.Expand(False);
  694. TreeView.TopItem := TempTopItem;
  695. TreeView.Update;
  696. AfterUpdate;
  697. FDragOverTime := KnowTime;
  698. end;
  699. end;
  700. end
  701. else
  702. begin
  703. {restart timer}
  704. GetSystemTimeAsFileTime(FDragOverTime);
  705. if GetKeyboardState(KeyBoardState) then
  706. begin
  707. KeyBoardState[VK_Space] := 0;
  708. SetKeyBoardState(KeyBoardState);
  709. end;
  710. TempTopItem := TreeView.TopItem;
  711. BeforeUpdate(Node);
  712. if Node.Expanded then
  713. begin
  714. if not TreeView.Selected.HasAsParent(Node) then
  715. Node.Collapse(False);
  716. end
  717. else Node.Expand(False);
  718. TreeView.TopItem := TempTopItem;
  719. TreeView.Update;
  720. AfterUpdate;
  721. end;
  722. NbPixels := Abs(TTreeView(FControl).Font.Height);
  723. {Vertical treescrolling:}
  724. if ((Int64(KnowTime) - Int64(FLastVScrollTime)) > DDVScrollDelay) or
  725. ((FVScrollCount > 3) and
  726. ((Int64(KnowTime) - Int64(FLastVScrollTime)) > (DDVScrollDelay Div 4))) then
  727. begin
  728. {Scroll tree up, if droptarget is topitem:}
  729. if Node = TreeView.TopItem then
  730. begin
  731. BeforeUpdate(nil);
  732. TreeView.Perform(WM_VSCROLL, SB_LINEUP, 0);
  733. AfterUpdate;
  734. GetSystemTimeAsFileTime(FLastVScrollTime);
  735. Inc(FVScrollCount);
  736. end
  737. else
  738. {Scroll tree down, if next visible item of droptarget is not visible:}
  739. begin
  740. if Point.Y + 3 * nbPixels > TreeView.Height then
  741. begin
  742. BeforeUpdate(nil);
  743. TreeView.Perform(WM_VSCROLL, SB_LINEDOWN, 0);
  744. AfterUpdate;
  745. GetSystemTimeAsFileTime(FLastVScrollTime);
  746. Inc(FVScrollCount);
  747. end
  748. else
  749. begin
  750. FVScrollCount := 0;
  751. end;
  752. end;
  753. end; {VScrollDelay}
  754. {Horizontal treescrolling:}
  755. {Scroll tree Left}
  756. if ((Int64(KnowTime) - Int64(FLastHScrollTime)) > DDHScrollDelay) then
  757. begin
  758. GetSystemTimeAsFileTime(FLastHScrollTime);
  759. ScrollInfo.cbSize := SizeOf(ScrollInfo);
  760. ScrollInfo.FMask := SIF_ALL;
  761. GetScrollInfo(TreeView.Handle, SB_HORZ, ScrollInfo);
  762. if ScrollInfo.nMin <> ScrollInfo.nMax then
  763. begin
  764. if Point.X < 50 then
  765. begin
  766. if Node.DisplayRect(True).Right + 50 < TreeView.Width then
  767. begin
  768. BeforeUpdate(nil);
  769. TreeView.Perform(WM_HSCROLL, SB_LINELEFT, 0);
  770. AfterUpdate;
  771. end;
  772. end
  773. else
  774. if Point.X > (TreeView.Width - 50) then
  775. begin
  776. if Node.DisplayRect(True).Left > 50 then
  777. begin
  778. BeforeUpdate(nil);
  779. TreeView.Perform(WM_HSCROLL, SB_LINERIGHT, 0);
  780. AfterUpdate;
  781. end;
  782. end;
  783. end;
  784. end;
  785. end;
  786. end;
  787. { TListViewScrollOnDragOver }
  788. procedure TListViewScrollOnDragOver.DragOver(Point: TPoint);
  789. var
  790. ListView: TCustomListView;
  791. KnowTime: TFileTime;
  792. NbPixels: Integer;
  793. WParam: LongInt;
  794. begin
  795. ListView := (FControl as TCustomListView);
  796. GetSystemTimeAsFileTime(KnowTime);
  797. NbPixels := Abs(TListView(ListView).Font.Height);
  798. {Vertical scrolling, if viewstyle = vsReport:}
  799. if (TListView(ListView).ViewStyle = vsReport) and Assigned(ListView.TopItem) and
  800. (((Int64(KnowTime) - Int64(FLastVScrollTime)) > DDVScrollDelay) or
  801. ((FVScrollCount > DDMaxSlowCount) and
  802. ((Int64(KnowTime) - Int64(FLastVScrollTime)) > (DDVScrollDelay div 4)))) then
  803. begin
  804. if (Point.Y - 3 * nbPixels <= 0) and (ListView.TopItem.Index > 0) then WParam := SB_LINEUP
  805. else
  806. if (Point.Y + 3 * nbPixels > ListView.Height) then WParam := SB_LINEDOWN
  807. else WParam := -1;
  808. if WParam >= 0 then
  809. begin
  810. BeforeUpdate(nil);
  811. ListView.Perform(WM_VSCROLL, WParam, 0);
  812. if FVScrollCount > DDMaxSlowCount then
  813. ListView.Perform(WM_VSCROLL, WParam, 0);
  814. if FVScrollCount > DDMaxSlowCount * 3 then
  815. ListView.Perform(WM_VSCROLL, WParam, 0);
  816. ListView.Update;
  817. AfterUpdate;
  818. GetSystemTimeAsFileTime(FLastVScrollTime);
  819. Inc(FVScrollCount);
  820. end
  821. else FVScrollCount := 0;
  822. end;
  823. end;
  824. { TListBoxScrollOnDragOver }
  825. procedure TListBoxScrollOnDragOver.DragOver(Point: TPoint);
  826. var
  827. ListBox: TListBox;
  828. KnowTime: TFileTime;
  829. NbPixels: Integer;
  830. WParam: LongInt;
  831. begin
  832. ListBox := (FControl as TListBox);
  833. GetSystemTimeAsFileTime(KnowTime);
  834. NbPixels := Abs(ListBox.Font.Height);
  835. {Vertical scrolling, if viewstyle = vsReport:}
  836. if (ListBox.Items.Count > 0) and
  837. (((Int64(KnowTime) - Int64(FLastVScrollTime)) > DDVScrollDelay) or
  838. ((FVScrollCount > DDMaxSlowCount) and
  839. ((Int64(KnowTime) - Int64(FLastVScrollTime)) > (DDVScrollDelay div 4)))) then
  840. begin
  841. if (Point.Y - 3 * nbPixels <= 0) and (ListBox.TopIndex > 0) then WParam := SB_LINEUP
  842. else
  843. if (Point.Y + 3 * nbPixels > ListBox.Height) then WParam := SB_LINEDOWN
  844. else WParam := -1;
  845. if WParam >= 0 then
  846. begin
  847. BeforeUpdate(nil);
  848. ListBox.Perform(WM_VSCROLL, WParam, 0);
  849. if FVScrollCount > DDMaxSlowCount then
  850. ListBox.Perform(WM_VSCROLL, WParam, 0);
  851. if FVScrollCount > DDMaxSlowCount * 3 then
  852. ListBox.Perform(WM_VSCROLL, WParam, 0);
  853. ListBox.Update;
  854. AfterUpdate;
  855. GetSystemTimeAsFileTime(FLastVScrollTime);
  856. Inc(FVScrollCount);
  857. end
  858. else FVScrollCount := 0;
  859. end;
  860. end;
  861. function IsUncPath(Path: string): Boolean;
  862. begin
  863. Result := (Copy(Path, 1, 2) = '\\') or (Copy(Path, 1, 2) = '//');
  864. end;
  865. const ERROR_CANT_ACCESS_FILE = 1920;
  866. function DoExists(R: Boolean; Path: string): Boolean;
  867. var
  868. Error: Integer;
  869. begin
  870. Result := R;
  871. if not Result then
  872. begin
  873. Error := GetLastError();
  874. if (Error = ERROR_CANT_ACCESS_FILE) or // returned when resolving symlinks in %LOCALAPPDATA%\Microsoft\WindowsApps
  875. (Error = ERROR_ACCESS_DENIED) then // returned for %USERPROFILE%\Application Data symlink
  876. begin
  877. Result := DirectoryExists(ApiPath(ExtractFileDir(Path)));
  878. end;
  879. end;
  880. end;
  881. function FileExistsFix(Path: string): Boolean;
  882. begin
  883. // WORKAROUND
  884. SetLastError(ERROR_SUCCESS);
  885. Result := DoExists(FileExists(ApiPath(Path)), Path);
  886. end;
  887. function DirectoryExistsFix(Path: string): Boolean;
  888. begin
  889. // WORKAROUND
  890. SetLastError(ERROR_SUCCESS);
  891. Result := DoExists(DirectoryExists(ApiPath(Path)), Path);
  892. end;
  893. type TPreferredAppMode = (pamDefault, pamAllowDark, pamForceDark, pamForceLight, pamMax);
  894. var
  895. AAllowDarkModeForWindow: function(hWnd: HWND; Allow: BOOL): BOOL; stdcall;
  896. ARefreshImmersiveColorPolicyState: procedure; stdcall;
  897. ASetPreferredAppMode: function(AppMode: TPreferredAppMode): TPreferredAppMode; stdcall;
  898. function SupportsDarkMode: Boolean;
  899. begin
  900. Result := Assigned(AAllowDarkModeForWindow) and Assigned(ARefreshImmersiveColorPolicyState);
  901. end;
  902. procedure AllowDarkModeForWindow(Control: TWinControl; Allow: Boolean);
  903. begin
  904. Assert(Control.HandleAllocated);
  905. if SupportsDarkMode and Control.HandleAllocated then
  906. begin
  907. AAllowDarkModeForWindow(Control.Handle, Allow);
  908. end;
  909. end;
  910. procedure AllowDarkModeForWindow(Handle: THandle; Allow: Boolean);
  911. begin
  912. if SupportsDarkMode then
  913. begin
  914. AAllowDarkModeForWindow(Handle, Allow);
  915. end;
  916. end;
  917. procedure RefreshColorMode;
  918. begin
  919. if SupportsDarkMode then
  920. begin
  921. ARefreshImmersiveColorPolicyState;
  922. end;
  923. end;
  924. var
  925. SysDarkTheme: Integer;
  926. procedure ResetSysDarkTheme;
  927. begin
  928. SysDarkTheme := -1;
  929. end;
  930. function DoGetSysDarkTheme(RootKey: HKEY): Integer;
  931. const
  932. ThemesPersonalizeKey = 'Software\Microsoft\Windows\CurrentVersion\Themes\Personalize';
  933. AppsUseLightThemeValue = 'AppsUseLightTheme';
  934. var
  935. Registry: TRegistry;
  936. begin
  937. Registry := TRegistry.Create;
  938. try
  939. Registry.RootKey := RootKey;
  940. Result := -1;
  941. if Registry.OpenKeyReadOnly(ThemesPersonalizeKey) and
  942. Registry.ValueExists(AppsUseLightThemeValue) then
  943. begin
  944. if Registry.ReadBool(AppsUseLightThemeValue) then Result := 0
  945. else Result := 1;
  946. end;
  947. finally
  948. Registry.Free;
  949. end;
  950. end;
  951. function GetSysDarkTheme: Boolean;
  952. begin
  953. if SysDarkTheme < 0 then
  954. begin
  955. SysDarkTheme := DoGetSysDarkTheme(HKEY_CURRENT_USER);
  956. if SysDarkTheme < 0 then
  957. begin
  958. SysDarkTheme := DoGetSysDarkTheme(HKEY_LOCAL_MACHINE);
  959. if SysDarkTheme < 0 then
  960. begin
  961. SysDarkTheme := 0;
  962. end;
  963. end;
  964. end;
  965. Result := (SysDarkTheme > 0);
  966. end;
  967. var
  968. Lib: THandle;
  969. OSVersionInfo: TOSVersionInfoEx;
  970. initialization
  971. Lib := LoadLibrary('shcore');
  972. if Lib <> 0 then
  973. begin
  974. GetDpiForMonitor := GetProcAddress(Lib, 'GetDpiForMonitor');
  975. end;
  976. Lib := LoadLibrary('user32');
  977. if Lib <> 0 then
  978. begin
  979. GetSystemMetricsForDpi := GetProcAddress(Lib, 'GetSystemMetricsForDpi');
  980. SystemParametersInfoForDpi := GetProcAddress(Lib, 'SystemParametersInfoForDpi');
  981. end;
  982. AAllowDarkModeForWindow := nil;
  983. ARefreshImmersiveColorPolicyState := nil;
  984. ASetPreferredAppMode := nil;
  985. OSVersionInfo.dwOSVersionInfoSize := SizeOf(OSVersionInfo);
  986. if GetVersionEx(OSVersionInfo) and (OSVersionInfo.dwBuildNumber >= 17763) then
  987. begin
  988. Lib := GetModuleHandle('uxtheme');
  989. if Lib <> 0 then
  990. begin
  991. AAllowDarkModeForWindow := GetProcAddress(Lib, MakeIntResource(133));
  992. ARefreshImmersiveColorPolicyState := GetProcAddress(Lib, MakeIntResource(104));
  993. if OSVersionInfo.dwBuildNumber >= 18334 then
  994. begin
  995. ASetPreferredAppMode := GetProcAddress(Lib, MakeIntResource(135));
  996. end;
  997. if SupportsDarkMode then
  998. begin
  999. // Both SetPreferredAppMode and RefreshImmersiveColorPolicyState is needed for
  1000. // dark list view headers and dark list view and tree view scrollbars
  1001. if Assigned(ASetPreferredAppMode) then
  1002. begin
  1003. ASetPreferredAppMode(pamAllowDark);
  1004. end;
  1005. ARefreshImmersiveColorPolicyState;
  1006. end;
  1007. end;
  1008. end;
  1009. ResetSysDarkTheme;
  1010. finalization
  1011. // No need to release individual image lists as they are owned by Application object.
  1012. FreeAndNil(ShellImageLists);
  1013. end.