PasTools.pas 33 KB

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