-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMaxLogic.vcl.highDpi.pas
More file actions
1146 lines (969 loc) · 33.4 KB
/
Copy pathMaxLogic.vcl.highDpi.pas
File metadata and controls
1146 lines (969 loc) · 33.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
unit maxLogic.vcl.highDpi;
{
to review:
https://web.archive.org/web/20130106235952/http://msdn.microsoft.com/en-us/library/windows/desktop/dd464660%28v=vs.85%29.aspx
http://zarko-gajic.iz.hr/making-the-glyph-property-high-dpi-aware-for-tbitbtn-and-tspeedbutton/
http://zarko-gajic.iz.hr/resizing-delphis-timagelist-bitmaps-to-fit-high-dpi-scaling-size-for-menus-toolbars-trees-etc/
http://zarko-gajic.iz.hr/delphi-high-dpi-road-ensuring-your-ui-looks-correctly/
http://stackoverflow.com/questions/17614566/how-to-display-a-tbitmap-with-alpha-channel-on-timage-correctly
https://zarko-gajic.iz.hr/delphi-high-dpi-road-ensuring-your-ui-looks-correctly/
}
{
Version: 2.3
History:
2026-07-19: replace the unsafe TImage.DestRect detour with per-image DPI materialization through TImageCollection and TVirtualImageList
2024-02-14: add support for TImageCollection and TVirtualImageList to move glyphs and images there on app startup for all forms to enable high dpi support for legacy applications
2022-06-22: remove threading + remove monitor dpi dependancy, use TControl.ScaleFactor
added more RTTI based replacement to support a wider array of components
2022-06-09: the newer versions of delphi have new properties for controls like ScaleFactor and methods like ScaleValue(), that superseedes methods that were used in this unit.
2017-02-18: first implementation
Description:
adjusts some bitmaps for high DPI.
it is quite simple it resises glyphs in:
TImageList, TBitBtn, TSpeedButton, TImage
}
interface
uses
winApi.Windows, system.Classes, system.SysUtils, vcl.Controls, vcl.StdCtrls, vcl.ExtCtrls, Graphics, vcl.Forms,
Buttons, ComCtrls, vcl.ImgList,
system.syncObjs, generics.collections, Messages,
vcl.BaseImageCollection, vcl.ImageCollection, vcl.VirtualImageList,
maxLogic.GraphicUtils,
System.Generics.Defaults, System.Types;
type
// forward declarations
THighDpiMarker = class; // will be attached to any form that is adjusted
THighDpiAdjuster = class; // the main class that performs the adjustments
TStrProc = reference to procedure(const s: string);
THighDpiAdjuster = class
public
class var OnLog: TStrProc;
class procedure log(const s: string); overload;
class procedure log(const s: String; C: TComponent); overload;
private type
// a Glyph in TBitBtn or TSpeedbutton and similar can have multiple elements, up to 4 on a single bitmap... we need to split this up
TGlyphCollectionItem = class
public
PropPrefix: string;
Image: TBitmap;
ImageName: string;
Index: integer;
constructor Create(aIndex: integer);
destructor Destroy; override;
end;
TGlyphCollection = class
private
fTransparentColor: TColor;
fHasTransparentColor: boolean;
fMainGlyph: TBitmap;
procedure applyTransparency(aBmp: TBitmap);
public
Items: TObjectList<TGlyphCollectionItem>;
constructor Create(aParent: THighDpiAdjuster; aGlyph: TGraphic; aNumGlyphs: integer);
destructor Destroy; override;
procedure EnsureDisabledImagePresent(aVirtualImageList: TVirtualImageList);
end;
private
class var fSingelton: THighDpiAdjuster;
class constructor CreateClass;
class destructor DestroyClass;
private
fDataModule: TDataModule;
fImageCollection: TImageCollection;
fOrgOnActiveFormChange: TNotifyEvent;
fOrgOnActiveFormChangeAssigned: boolean;
fMaxComponentCount: integer;
function AddToImageCol(aGraphic: TGraphic; out aImageName: String): boolean;
function CreateVirtualImgList(aOwner: TComponent; aMarker: THighDpiMarker; aWidth, aHeight: integer): TVirtualImageList;
function GetOrCreateVirtualImgList(aOwner: TComponent; aMarker: THighDpiMarker; aWidth, aHeight: integer): TVirtualImageList;
function AdjustTImageList(aImageList: TImageList): TVirtualImageList;
procedure AdjustTImage(aImage: TImage);
function RedirectImageListReferenceToVirtualImage(c: TComponent): boolean;
function AdjustUsingRttiLookingForGlyphAndImageName(c: TComponent): boolean;
// returns a sha256 hash as hex string
function CalcHash(aGraphic: TGraphic): RawByteString;
procedure screenOnActiveFormChange(Sender: TObject);
public
constructor Create;
destructor Destroy; override;
procedure AdjustComponent(aComponent: TComponent; aAlreadyProcessedDic: TDictionary<TComponent, boolean>);
// thread safe
class function Singelton: THighDpiAdjuster;
// will adjust all components and controls on a form
class procedure AdjustForm(AfORM: TCustomForm);
// this will mark the component and all its children as non scalable by this class
class procedure MarkAsNonScalable(c: TComponent);
// this method will register itself to the screen.onActiveFormChange event
class procedure EnableAutoAdjusting;
// marker related, mostly for internal use
class function GetMarker(c: TComponent): THighDpiMarker;
class function GetOrAddMarker(c: TComponent): THighDpiMarker; overload;
class function GetOrAddMarker(c: TComponent; out aIsNew: boolean): THighDpiMarker; overload;
public
property ImageCollection: TImageCollection read fImageCollection;
end;
THighDpiMarker = class(TComponent)
private
FdoNotScale: boolean;
procedure SetdoNotScale(const Value: boolean);
public
VirtualImageList: TVirtualImageList; // used for TImageList
// this will check the DoNotScale flag and it will compare the screen dpi with the last adjustment
function CanScale: boolean;
property doNotScale: boolean read FdoNotScale write SetdoNotScale;
end;
TTImageMarker = class(THighDpiMarker)
private
ImageName: string;
ImageSize: TPoint; // used for TImage
RenderedImageHash: AnsiString;
WasAutoSized: boolean;
public
// returns nil if none was found
class function GetMarker(aComponent: TComponent): TTImageMarker; static;
class function GetOrCreateMarker(aComponent: TComponent; out aIsNew: boolean): TTImageMarker; static;
end;
TFormChangeScaleTrigger = class(TComponent)
private
fLastPixelsperInch: integer;
protected
fOrgMonitorDpiChangedEvent: TMonitorDpiChangedEvent;
procedure FormOnAfterMonitorDpiChanged(Sender: TObject; OldDPI: integer; NewDPI: integer);
public
// checks if that form already has a TFormChangeScaleTrigger instance
class function has(AfORM: TCustomForm): boolean;
class function get(AfORM: TCustomForm; out aMarker: TFormChangeScaleTrigger): boolean;
constructor Create(aOwner: TCustomForm); reintroduce;
destructor Destroy; override;
property LastPixelsperInch: integer read fLastPixelsperInch;
end;
// those methods helps to recalculate a value that was stored (in a config or somewhere else) with a different scaleFactor then the one currently used by the control
function ReScaleValue(const aValue: double; aControl: TControl; const aOldScaleFactor: Single): double; overload;
function ReScaleValue(const aValue: integer; aControl: TControl; const aOldScaleFactor: Single): integer; overload;
function ReScaleValue(const aValue: int64; aControl: TControl; const aOldScaleFactor: Single): int64; overload;
// when we save scaleFactors as strings, we might loose some detail, so we assume all scale factor not different by more then 0.001 are the same
function sameScaleFactor(const v1, v2: Single): boolean;
function TryScale(aOwner: TComponent; const p: TPoint): TPoint;
implementation
uses
maxLogic.QuickPixel,
System.Math, System.StrUtils,
AutoFree, maxLogic.RTTIHelper, System.Hash,
pngImage, System.Rtti, Maxlogic.GdiUtils;
type
OpenControl = class(TControl)
published
property OnResize;
property Color;
end;
OpenForm = class(TCustomForm)
published
property OnAfterMonitorDpiChanged;
end;
OpenVirtualImageList = class(TVirtualImageList)
end;
function TryScale(aOwner: TComponent; const p: TPoint): TPoint;
var
lDone: boolean;
begin
Result := p;
lDone := False;
while (not lDone) and (aOwner <> nil) do
begin
lDone := True;
if aOwner is TControl then
Result := (aOwner as TControl).ScaleValue(p)
else if aOwner is TForm then
Result := (aOwner as TForm).ScaleValue(p)
else if aOwner is TFrame then
Result := (aOwner as TFrame).ScaleValue(p)
else
begin
lDone := False;
aOwner := aOwner.Owner;
end;
end;
end;
{ THighDpiAdjuster }
class procedure THighDpiAdjuster.AdjustForm(AfORM: TCustomForm);
begin
if assigned(application)
and (not application.Terminated)
and assigned(AfORM)
and (not (csDestroying in AfORM.ComponentState)) then
begin
Singelton.AdjustComponent(AfORM, nil);
AfORM.Invalidate;
Singelton.fImageCollection.Change;
end;
end;
class function THighDpiAdjuster.GetMarker(c: TComponent): THighDpiMarker;
var
X: integer;
begin
Result := nil;
for X := c.ComponentCount - 1 downto 0 do
if c.Components[X] is THighDpiMarker then
exit(THighDpiMarker(c.Components[X]));
end;
class constructor THighDpiAdjuster.CreateClass;
begin
fSingelton := nil;
end;
function THighDpiAdjuster.GetOrCreateVirtualImgList(aOwner: TComponent;
aMarker: THighDpiMarker; aWidth, aHeight: integer): TVirtualImageList;
var
lComponentName: string;
lComponent: TComponent;
begin
Result := nil;
lComponentName := 'MaxLogicHighDpiVirtualImageList_' + aWidth.ToString + 'x' + aHeight.ToString;
lComponent := aOwner.FindComponent(lComponentName);
if lComponent = nil then
begin
Result := CreateVirtualImgList(aOwner, aMarker, aWidth, aHeight);
Result.Name := lComponentName;
end
else
begin
Result := lComponent as TVirtualImageList;
if aMarker <> nil then
aMarker.VirtualImageList := Result;
end;
end;
class procedure THighDpiAdjuster.log(const s: String; C: TComponent);
var
n: String;
begin
if c = nil then
n:= 'NIL'
else begin
n:= c.Name+':'+c.ClassName;
while c.Owner <> nil do
begin
c:= c.Owner;
n:= c.Name+':'+c.ClassName + '->' +n;
end;
end;
Log(Format(s, [n]));
end;
class procedure THighDpiAdjuster.log(const s: string);
begin
if assigned(OnLog) then
OnLog(s);
end;
function THighDpiAdjuster.CreateVirtualImgList(aOwner: TComponent;
aMarker: THighDpiMarker; aWidth, aHeight: integer): TVirtualImageList;
var
p: TPoint;
begin
Result := TVirtualImageList.Create(aOwner);
if aMarker <> nil then
aMarker.VirtualImageList := Result;
Result.PreserveItems := True;
Result.ImageCollection := fImageCollection;
p := TryScale(aOwner, point(aWidth, aHeight));
Result.Width := p.X;
Result.Height := p.y;
Result.ColorDepth := TColorDepth.cd32Bit;
// Result.DrawWWingStyle:= TDrawingStyle.dsTransparent;
// Result.BkGColor := TRGB.Create(255,0,255).ToColor;
// Result.BlendColor := clNone;
// Result.Masked := True;
end;
class function THighDpiAdjuster.GetOrAddMarker(c: TComponent): THighDpiMarker;
var
lIsNew: boolean;
begin
Result := GetOrAddMarker(c, lIsNew);
end;
class function THighDpiAdjuster.GetOrAddMarker(c: TComponent; out aIsNew: boolean): THighDpiMarker;
begin
Result := GetMarker(c);
aIsNew := not assigned(Result);
if not assigned(Result) then
Result := THighDpiMarker.Create(c);
end;
function THighDpiAdjuster.AdjustTImageList(aImageList: TImageList): TVirtualImageList;
var
lMarker: THighDpiMarker;
lIsNew: Boolean;
lBitmap: TBitmap;
lGlyphBitmap: TBitmap;
lSrcQP: TQuickPixel;
lDstQP: TQuickPixel;
lImagesPerRow, lImagesPerColumn: Integer;
lSrcRect: TRect;
lPt: TPoint;
lImageName: string;
lVL: TVirtualImageList;
begin
Result := nil;
// Basic sanity checks
if (aImageList = nil) or (aImageList.Count = 0) then
Exit;
if (aImageList.Width <= 0) or (aImageList.Height <= 0) then
Exit; // prevents division by zero and invalid bitmap sizing
lMarker := GetOrAddMarker(aImageList, lIsNew);
if (not lIsNew) and Assigned(lMarker.VirtualImageList) then
Exit(lMarker.VirtualImageList); // already processed
// Source sheet copy
gc(lBitmap, TBitmap.Create);
if not maxLogic.QuickPixel.CopyBmp(aImageList.GetImageBitmap, lBitmap) then
Exit;
if (lBitmap.Width <= 0) or (lBitmap.Height <= 0) then
Exit; // prevents division by zero and invalid rects
Log('THighDpiAdjuster.AdjustTImageList: %s', aImageList);
lVL := CreateVirtualImgList(aImageList.Owner, lMarker, aImageList.Width, aImageList.Height);
Result := lMarker.VirtualImageList;
// Prepare quick-pixel helpers and a per-glyph work bitmap
gc(lSrcQP, TQuickPixel.Create(lBitmap));
// Ensure transparency before slicing, if a bg color is set
aImageList.BkColor := clFuchsia;
if aImageList.BkColor <> clNone then
lSrcQP.TransparencyToAlphaChannel(aImageList.BkColor);
// Safe, non-zero values (Max(1, �)) to avoid div-by-zero in mod/div
lImagesPerRow := System.Math.Max(1, lBitmap.Width div aImageList.Width);
lImagesPerColumn := System.Math.Max(1, lBitmap.Height div aImageList.Height);
// Independent per-glyph bitmap
gc(lGlyphBitmap, TBitmap.Create);
lGlyphBitmap.Assign(lBitmap);
lGlyphBitmap.FreeImage; // detach from source
lGlyphBitmap.SetSize(aImageList.Width, aImageList.Height);
gc(lDstQP, TQuickPixel.Create(lGlyphBitmap));
lSrcRect := Rect(0, 0, aImageList.Width, aImageList.Height);
for var lGlyphIndex := 0 to aImageList.Count - 1 do
begin
if lGlyphIndex <> 0 then
begin
// Calculate the offset of the glyph on the sheet
lPt.X := (lGlyphIndex mod lImagesPerRow) * lGlyphBitmap.Width;
lPt.Y := (lGlyphIndex div lImagesPerRow) * lGlyphBitmap.Height;
// Optional: clamp to source bounds to be extra safe
if (lPt.X + lSrcRect.Width > lBitmap.Width) or
(lPt.Y + lSrcRect.Height > lBitmap.Height) then
begin
// Out-of-bounds slice -> stop or continue; here we stop silently
Break;
end;
lSrcRect.Location := lPt;
end;
// Copy from sheet to per-glyph bitmap
lDstQP.CopyRect(Point(0, 0), lSrcQP, lSrcRect);
if AddToImageCol(lGlyphBitmap, lImageName) then
lVL.Add(lImageName, lImageName, False);
end;
end;
function THighDpiAdjuster.AdjustUsingRttiLookingForGlyphAndImageName(
c: TComponent): boolean;
var
lImagesObj, lGlyphObj: TObject;
lGlyph: TGraphic;
lNumGlyphs: integer;
lBitmaps: array[0..3] of TBitmap;
lNames: array[0..3] of string;
vl: TVirtualImageList;
lImageName: string;
lImages: TGlyphCollection;
lBmp: TBitmap;
lGarbo: iGarbo;
lOrgEnabled: boolean;
lSuccess: boolean;
begin
Result := False;
lSuccess := False;
// those are required
if not (TRttiHelper.has(c, 'ImageName')
and TRttiHelper.has(c, 'Images')
and TRttiHelper.has(c, 'ImageIndex')
and TRttiHelper.has(c, 'Glyph')
) then
exit;
lImagesObj := TRttiHelper.ReadObjectProperty(c, 'Images');
if (lImagesObj <> nil) and (lImagesObj is TVirtualImageList) then
exit; // already using virtual image list
lGlyphObj := TRttiHelper.ReadObjectProperty(c, 'Glyph');
if (lGlyphObj = nil) then
exit;
lGlyph := lGlyphObj as TGraphic;
{
Glyph can provide up to four images within a single bitmap. All images must be the same size and next to each other in a horizontal row. TSpeedButton displays one of these images depending on the state of the button.
Image position Button state Description
First | Up | This image appears when the button is unselected. If no other images exist in the bitmap, this image is used for all states.
Second | Disabled | This image usually appears dimmed to indicate that the button can't be selected.
Third | Clicked | This image appears when the button is clicked. If GroupIndex is 0, the Up image reappears when the user releases the mouse button.
Fourth | Down | This image appears when the button stays down indicating that it remains selected.
If only one image is present, TSpeedButton attempts to represent the other states by altering the image slightly for each state, although the Down state is always the same as the Up state.
If the bitmap contains multiple images, specify the number of images in the bitmap with the NumGlyphs property.
Note: The lower left pixel of the bitmap is reserved for the "transparent" color. Any pixel in the bitmap that matches the lower left pixel will be transparent.
The new Controls have the following extra properties
DisabledImageIndex
DisabledImageName
HotImageIndex
HotImageName
ImageIndex
ImageName
PressedImageIndex
PressedImageName
SelectedImageIndex
SelectedImageName
}
lNumGlyphs := 0;
if TRttiHelper.has(c, 'NumGlyphs') then
lNumGlyphs := StrToIntDef(TRttiHelper.ReadProperty(c, 'NumGlyphs'), 0);
gc(lImages, TGlyphCollection.Create(self, lGlyph, lNumGlyphs));
if (not assigned(lImages.Items)) or (lImages.Items.Count = 0) then
exit;
Log('THighDpiAdjuster.AdjustUsingRttiLookingForGlyphAndImageName: %s', c);
vl := GetOrCreateVirtualImgList(c.Owner, nil,
lImages.Items[0].Image.Width,
lGlyph.Height);
lImages.EnsureDisabledImagePresent(vl);
vl.BeginUpdate;
try
for var lItem in lImages.Items do
begin
// lImageName := 'GLYPH_' + CalcHash(lItem.Image);
if AddToImageCol(lItem.Image, lImageName) then
begin
lItem.ImageName := lImageName;
vl.add(lImageName, lImageName, False);
lSuccess := True;
end;
end;
if not lSuccess then
exit;
// set the properties
TRttiHelper.WriteProperty(c, 'Glyph', nil);
TRttiHelper.WriteProperty(c, 'Images', vl);
for var lItem in lImages.Items do
TRttiHelper.WriteProperty(c, lItem.PropPrefix + 'ImageName', lItem.ImageName);
Result := True;
finally
vl.EndUpdate;
end;
end;
procedure THighDpiAdjuster.AdjustComponent(aComponent: TComponent; aAlreadyProcessedDic: TDictionary<TComponent, boolean>);
var
lMarker: THighDpiMarker;
c: TComponent;
lGarbo: iGarbo;
lControl: TWinControl;
lFormMarker: TFormChangeScaleTrigger;
lForm: TCustomForm;
begin
c := aComponent;
if (c is TFormChangeScaleTrigger) or (c is THighDpiMarker) then
exit;
lGarbo := nil;
if aAlreadyProcessedDic = nil then
begin
fMaxComponentCount := Max(1000, fMaxComponentCount);
aAlreadyProcessedDic := TDictionary<TComponent, boolean>.Create(fMaxComponentCount);
lGarbo := gc(aAlreadyProcessedDic);
end
else if aAlreadyProcessedDic.containskey(c) then
exit;
aAlreadyProcessedDic.add(c, True);
lMarker := GetMarker(c);
if assigned(lMarker) and (not lMarker.CanScale) then
exit;
if c is TCustomForm then
begin
lForm := c as TCustomForm;
if not TFormChangeScaleTrigger.has(lForm) then
TFormChangeScaleTrigger.Create(lForm);
end;
if c is TImage then
AdjustTImage(TImage(c))
else if (c is TImageList) and (not (c is TVirtualImageList)) then
AdjustTImageList(c as TImageList)
else
begin
if not AdjustUsingRttiLookingForGlyphAndImageName(c) then
RedirectImageListReferenceToVirtualImage(c);
end;
for var X := 0 to c.ComponentCount - 1 do
AdjustComponent(c.Components[X], aAlreadyProcessedDic);
if c is TWinControl then
begin
lControl := c as TWinControl;
for var X := 0 to lControl.ControlCount - 1 do
AdjustComponent(lControl.Controls[X], aAlreadyProcessedDic);
end;
// update the max count, so we have a better preset next time
if lGarbo <> nil then
fMaxComponentCount := Max(fMaxComponentCount, aAlreadyProcessedDic.Count);
end;
procedure THighDpiAdjuster.AdjustTImage(aImage: TImage);
var
g: TGarbos;
lBitmap: TBitmap;
lCurrentHash: RawByteString;
lImageIndex: Integer;
lImageName: string;
lMarker: TTImageMarker;
lIsNew: boolean;
lSize: TPoint;
lVirtualImageList: TVirtualImageList;
begin
// if there is no image or if it is already stretched... then just do nothing
if (aImage.Picture.Graphic = nil) or aImage.Stretch then
exit;
lMarker := TTImageMarker.GetOrCreateMarker(aImage, lIsNew);
if (not lMarker.CanScale) then
exit;
lCurrentHash := CalcHash(aImage.Picture.Graphic);
if lIsNew or (lCurrentHash <> lMarker.RenderedImageHash) then
begin
if not AddToImageCol(aImage.Picture.Graphic, lImageName) then
exit;
lMarker.ImageName := lImageName;
lMarker.ImageSize := Point(
aImage.Picture.Graphic.Width, aImage.Picture.Graphic.Height);
if lMarker.VirtualImageList <> nil then
lMarker.VirtualImageList.Clear;
end;
// let images that auto scaled manage themself
if aImage.autosize or (lMarker.WasAutoSized) then
begin
aImage.autosize := False;
lSize := aImage.ScaleValue(lMarker.ImageSize);
aImage.Width := lSize.X;
aImage.Height := lSize.y;
aImage.Stretch := True;
aImage.Proportional := True;
lMarker.WasAutoSized := True;
exit;
end;
lSize := aImage.ScaleValue(lMarker.ImageSize);
if lMarker.VirtualImageList = nil then
lVirtualImageList := CreateVirtualImgList(
aImage, lMarker, lMarker.ImageSize.X, lMarker.ImageSize.Y)
else begin
lVirtualImageList := lMarker.VirtualImageList;
end;
lVirtualImageList.Width := lSize.X;
lVirtualImageList.Height := lSize.Y;
lImageIndex := lVirtualImageList.GetIndexByName(lMarker.ImageName);
if lImageIndex < 0 then
begin
lVirtualImageList.Add(lMarker.ImageName, lMarker.ImageName, False);
lImageIndex := lVirtualImageList.GetIndexByName(lMarker.ImageName);
end;
if lImageIndex < 0 then
exit;
GC(lBitmap, TBitmap.Create, g);
if not lVirtualImageList.GetBitmap(lImageIndex, lBitmap) then
exit;
aImage.Picture.Assign(lBitmap);
lMarker.RenderedImageHash := CalcHash(aImage.Picture.Graphic);
aImage.Invalidate; // force repaint
end;
function THighDpiAdjuster.AddToImageCol(aGraphic: TGraphic; out aImageName: String): Boolean;
var
lIndex: integer;
lImageElement: TImageCollectionItem;
lBmp: TBitmap;
lGarbo: iGarbo;
begin
Result := True;
aImageName:= string(Self.CalcHash(aGraphic));
Log('THighDpiAdjuster.AddToImageCol("'+aImageName+'")');
lIndex := fImageCollection.GetIndexByName(aImageName);
Log(' lIndex: '+lIndex.ToString);
if lIndex <> -1 then
begin
// do not add it if it is already there
{lImageElement := fImageCollection.Images[lIndex];
try
lImageElement.SourceImages[0].Image.Assign(aGraphic);
except
Result := False;
end;}
end else begin
lImageElement := fImageCollection.Images.add;
Log(' ImagesCount: '+fImageCollection.Images.Count.ToString);
lImageElement.Name := aImageName;
var ImageCollectionSourceItem := lImageElement.SourceImages.add;
try
ImageCollectionSourceItem.Image.Assign(aGraphic);
except
on e: Exception do
begin
Log(' Exception '+e.classname+': '+e.Message);
Result := False;
end;
end;
// remove the invalid item...
if not Result then
if Assigned(lImageElement) then
begin
lIndex := fImageCollection.GetIndexByName(aImageName);
if lIndex <> -1 then
fImageCollection.Images.Delete(lIndex);
end;
end;
Log(' GetUserObjectCount: '+IntToStr(GetUserObjectCount));
Log(' GetGDIObjectCount : '+IntToStr(GetGDIObjectCount));
end;
function THighDpiAdjuster.CalcHash(aGraphic: TGraphic): RawByteString;
var
lStream: TMemoryStream;
lHashValue: Integer;
begin
gc(lStream, TMemoryStream.Create);
aGraphic.SaveToStream(lStream);
lStream.Position := 0;
// as hex
Result:= RawByteString(THashBobJenkins.GetHashValue(lStream.Memory^, lStream.Size, 0).ToHexString);
end;
constructor THighDpiAdjuster.Create;
begin
inherited;
fDataModule := TDataModule.Create(nil);
fImageCollection := TImageCollection.Create(fDataModule);
end;
destructor THighDpiAdjuster.Destroy;
begin
fDataModule.Free;
try
if assigned(application)
and assigned(Screen)
and (not application.Terminated) then
begin
Screen.OnActiveFormChange := self.fOrgOnActiveFormChange;
self.fOrgOnActiveFormChange := nil;
end;
except
// do nothing
end;
inherited;
end;
class procedure THighDpiAdjuster.EnableAutoAdjusting;
begin
if not Singelton.fOrgOnActiveFormChangeAssigned then
begin
Singelton.fOrgOnActiveFormChangeAssigned := True;
Singelton.fOrgOnActiveFormChange := Screen.OnActiveFormChange;
Screen.OnActiveFormChange := Singelton.screenOnActiveFormChange;
end;
end;
class destructor THighDpiAdjuster.DestroyClass;
begin
FreeAndNil(fSingelton);
end;
class function THighDpiAdjuster.Singelton: THighDpiAdjuster;
var
lInstance: THighDpiAdjuster;
begin
if not assigned(fSingelton) then
begin
lInstance := THighDpiAdjuster.Create;
if TInterlocked.CompareExchange<THighDpiAdjuster>(fSingelton, lInstance, nil) <> nil then
FreeAndNil(lInstance)
end;
Result := fSingelton;
end;
procedure THighDpiAdjuster.screenOnActiveFormChange(Sender: TObject);
var
lForm: TForm;
begin
if assigned(application)
and assigned(Screen)
and (not application.Terminated)
and (Screen.activeform <> nil) then
begin
lForm := Screen.activeform;
if (not (csDestroying in lForm.ComponentState)) then
begin
if not TFormChangeScaleTrigger.has(lForm) then
AdjustForm(lForm);
if assigned(fOrgOnActiveFormChange) then
fOrgOnActiveFormChange(Sender);
end;
end;
end;
class procedure THighDpiAdjuster.MarkAsNonScalable(c: TComponent);
var
m: THighDpiMarker;
begin
m := GetOrAddMarker(c);
m.doNotScale := True;
end;
function THighDpiAdjuster.RedirectImageListReferenceToVirtualImage(
c: TComponent): boolean;
var
lObj: TObject;
lImageList: TImageList;
lVirtualImageList: TVirtualImageList;
lTypeName: string;
begin
Result := False;
// only TCustomImageList are supported
// some controls like TBalloonHint use directly TImageList
lTypeName := TRttiHelper.GetPropertyTypeName(c, 'Images');
if (lTypeName = '')
or (not System.StrUtils.MatchText(lTypeName, ['TCustomImageList', 'TVirtualImageList'])) then
exit;
lObj := TRttiHelper.ReadObjectProperty(c, 'Images');
if (lObj = nil) or (not (lObj is TImageList)) then
exit;
lImageList := lObj as TImageList;
lVirtualImageList := AdjustTImageList(lImageList);
TRttiHelper.WriteProperty(c, 'Images', lVirtualImageList);
Result := True;
end;
{ THighDpiMarker }
procedure THighDpiMarker.SetdoNotScale(const Value: boolean);
begin
FdoNotScale := Value;
end;
function THighDpiMarker.CanScale: boolean;
begin
Result := (doNotScale = False)
end;
{ Others }
function ReScaleValue(const aValue: double; aControl: TControl; const aOldScaleFactor: Single): double;
var
v: double;
begin
if sameScaleFactor(aControl.ScaleFactor, aOldScaleFactor) then
Result := aValue
else
begin
v := aValue / aOldScaleFactor;
Result := aControl.ScaleValue(v);
end;
end;
function ReScaleValue(const aValue: int64; aControl: TControl; const aOldScaleFactor: Single): int64; overload;
begin
Result:= ReScaleValue(Integer(aValue), aControl, aOldScaleFactor);
end;
function ReScaleValue(const aValue: integer; aControl: TControl; const aOldScaleFactor: Single): integer;
var
f1, f2: double;
begin
if sameScaleFactor(aControl.ScaleFactor, aOldScaleFactor) then
Result := aValue
else
begin
f1 := aValue;
f2 := ReScaleValue(f1, aControl, aOldScaleFactor);
Result := Round(f2);
end;
end;
function sameScaleFactor(const v1, v2: Single): boolean;
var
f: Single;
begin
f := v1 - v2;
if f < 0 then
f := f * -1;
if f < 0.001 then
Result := True
else
Result := False;
end;
{ TFormChangeScaleTrigger }
constructor TFormChangeScaleTrigger.Create(aOwner: TCustomForm);
begin
inherited Create(aOwner);
fOrgMonitorDpiChangedEvent := OpenForm(aOwner).OnAfterMonitorDpiChanged;
OpenForm(aOwner).OnAfterMonitorDpiChanged := FormOnAfterMonitorDpiChanged;
fLastPixelsperInch := OpenForm(aOwner).PixelsPerInch;
end;
destructor TFormChangeScaleTrigger.Destroy;
begin
if assigned(Owner) and (Owner is TCustomForm) then
begin
OpenForm(Owner).OnAfterMonitorDpiChanged := fOrgMonitorDpiChangedEvent;
fOrgMonitorDpiChangedEvent := nil;
end;
inherited;
end;
procedure TFormChangeScaleTrigger.FormOnAfterMonitorDpiChanged(
Sender: TObject; OldDPI, NewDPI: integer);
begin
try
if assigned(fOrgMonitorDpiChangedEvent) then
fOrgMonitorDpiChangedEvent(Sender, OldDPI, NewDPI);
finally
if assigned(THighDpiAdjuster.fSingelton)
and assigned(application)
and (not application.Terminated)
and assigned(self.Owner)
and (not (csDestroying in self.Owner.ComponentState)) then
THighDpiAdjuster.AdjustForm(Owner as TCustomForm);
end;
end;
class function TFormChangeScaleTrigger.has(AfORM: TCustomForm): boolean;
var
lMarker: TFormChangeScaleTrigger;
begin
Result := get(AfORM, lMarker);
end;
class function TFormChangeScaleTrigger.get(AfORM: TCustomForm; out aMarker: TFormChangeScaleTrigger): boolean;
var
X: integer;
begin
Result := False;
for X := AfORM.ComponentCount - 1 downto 0 do
if AfORM.Components[X] is TFormChangeScaleTrigger then
begin
aMarker := AfORM.Components[X] as TFormChangeScaleTrigger;
exit(True);
end;
end;
{ THighDpiAdjuster.TGlyphCollectionItem }
constructor THighDpiAdjuster.TGlyphCollectionItem.Create;
begin
inherited Create;
Image := TBitmap.Create;
Image.pixelformat := pf32bit;
Index := aIndex;
end;
destructor THighDpiAdjuster.TGlyphCollectionItem.Destroy;
begin
Image.Free;
inherited;
end;
{ THighDpiAdjuster.TGlyphCollection }
procedure THighDpiAdjuster.TGlyphCollection.applyTransparency(
aBmp: TBitmap);
var
qp: TQuickPixel;
begin
TQuickPixel.MaskToAlphaChannel(aBmp);
end;
constructor THighDpiAdjuster.TGlyphCollection.Create(
aParent: THighDpiAdjuster;
aGlyph: TGraphic;
aNumGlyphs: integer);
var
lIndex: integer;
lMaskColor: TColor;
w: integer;
lItem: TGlyphCollectionItem;
lPrefix, lName: string;