/
VCLCommon.cpp
2956 lines (2782 loc) · 95.8 KB
/
VCLCommon.cpp
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
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "WinInterface.h"
#include "VCLCommon.h"
#include <Common.h>
#include <TextsWin.h>
#include <RemoteFiles.h>
#include <GUITools.h>
#include <Tools.h>
#include <CustomWinConfiguration.h>
#include <CoreMain.h>
#include <Vcl.StdActns.hpp>
#include <PasswordEdit.hpp>
#include <FileCtrl.hpp>
#include <PathLabel.hpp>
#include <PasTools.hpp>
#include <StrUtils.hpp>
#include <Vcl.Imaging.pngimage.hpp>
#include <Math.hpp>
#include <TB2ExtItems.hpp>
#include <TBXExtItems.hpp>
#include <IEListView.hpp>
#include <WinApi.h>
#include <vssym32.h>
//---------------------------------------------------------------------------
const UnicodeString LinkAppLabelMark(TraceInitStr(L" \x00BB"));
//---------------------------------------------------------------------------
#pragma package(smart_init)
//---------------------------------------------------------------------------
void __fastcall FixListColumnWidth(TListView * TListView, int Index)
{
if (Index < 0)
{
Index = TListView->Columns->Count + Index;
}
TListView->Column[Index]->Tag = 1;
}
//---------------------------------------------------------------------------
static int __fastcall GetColumnTextWidth(TListView * ListView, int ColumnPadding, const UnicodeString & Text)
{
return
ColumnPadding +
ListView->Canvas->TextExtent(Text).Width;
}
//---------------------------------------------------------------------------
void __fastcall AutoSizeListColumnsWidth(TListView * ListView, int ColumnToShrinkIndex)
{
// Preallocate handle to precreate columns, otherwise our changes may get
// overwritten once the handle is created.
// This should actually get called only once the handle are allocated.
// Otherwise we end up recreating the handles,
// what may cause a flicker of the currently focused window title.
ListView->HandleNeeded();
SendMessage(ListView->Handle, WM_SETREDRAW, false, 0);
try
{
int ColumnPadding = 2 * ScaleByTextHeightRunTime(ListView, 6);
int ColumnShrinkMinWidth = ScaleByTextHeightRunTime(ListView, 60);
int ResizableWidth = 0;
int NonResizableWidth = 0;
int LastResizable = -1;
for (int Index = 0; Index < ListView->Columns->Count; Index++)
{
TListColumn * Column = ListView->Columns->Items[Index];
int CaptionWidth = GetColumnTextWidth(ListView, ColumnPadding, Column->Caption);
int OrigWidth = -1;
bool NonResizable = (Column->Tag != 0);
if (NonResizable) // optimization
{
OrigWidth = ListView_GetColumnWidth(ListView->Handle, Index);
}
int Width;
// LVSCW_AUTOSIZE does not work for OwnerData list views
if (!ListView->OwnerData)
{
ListView_SetColumnWidth(ListView->Handle, Index, LVSCW_AUTOSIZE);
Width = ListView_GetColumnWidth(ListView->Handle, Index);
}
else
{
Width = 0;
for (int ItemIndex = 0; ItemIndex < ListView->Items->Count; ItemIndex++)
{
TListItem * Item = ListView->Items->Item[ItemIndex];
UnicodeString Text;
if (Index == 0)
{
Text = Item->Caption;
}
// Particularly EditorListView3 on Preferences dialog does not have all subitems filled for internal editor
else if (Index <= Item->SubItems->Count)
{
Text = Item->SubItems->Strings[Index - 1];
}
int TextWidth = GetColumnTextWidth(ListView, ColumnPadding, Text);
if (TextWidth > Width)
{
Width = TextWidth;
}
}
}
Width = Max(Width, CaptionWidth);
// Never shrink the non-resizable columns
if (NonResizable && (Width < OrigWidth))
{
Width = OrigWidth;
}
Column->Width = Width;
if (NonResizable)
{
NonResizableWidth += Width;
}
else
{
LastResizable = Index;
ResizableWidth += Width;
}
}
DebugAssert(LastResizable >= 0);
int ClientWidth = ListView->ClientWidth;
int RowCount = ListView->Items->Count;
if ((ListView->VisibleRowCount < RowCount) &&
(ListView->Width - ListView->ClientWidth < GetSystemMetricsForControl(ListView, SM_CXVSCROLL)))
{
ClientWidth -= GetSystemMetricsForControl(ListView, SM_CXVSCROLL);
}
if (DebugAlwaysTrue(NonResizableWidth < ClientWidth))
{
int Remaining = ClientWidth - NonResizableWidth;
bool ProportionalResize = true;
bool Shrinking = (Remaining < ResizableWidth);
// If columns are too wide to fit and we have dedicated shrink column, shrink it
if (Shrinking &&
(ColumnToShrinkIndex >= 0))
{
TListColumn * ColumnToShrink = ListView->Columns->Items[ColumnToShrinkIndex];
int ColumnToShrinkCaptionWidth = GetColumnTextWidth(ListView, ColumnPadding, ColumnToShrink->Caption);
int ColumnToShrinkMinWidth = Max(ColumnShrinkMinWidth, ColumnToShrinkCaptionWidth);
// This falls back to proprotional shrinking when the shrink column would fall below min width.
// Question is whether we should not shrink to min width instead.
if ((ResizableWidth - ColumnToShrink->Width) < (Remaining - ColumnToShrinkMinWidth))
{
int ColumnToShrinkWidth = Remaining - (ResizableWidth - ColumnToShrink->Width);
ColumnToShrink->Width = ColumnToShrinkWidth;
ProportionalResize = false;
}
}
if (ProportionalResize)
{
for (int Index = 0; Index <= LastResizable; Index++)
{
TListColumn * Column = ListView->Columns->Items[Index];
if (Column->Tag == 0)
{
int Width = ListView_GetColumnWidth(ListView->Handle, Index);
int AutoWidth = Width;
if (Index < LastResizable)
{
Width = (Remaining * Width) / ResizableWidth;
}
else
{
Width = Remaining;
}
int CaptionWidth = GetColumnTextWidth(ListView, ColumnPadding, Column->Caption);
Width = Max(Width, CaptionWidth);
Width = Max(Width, Min(ColumnShrinkMinWidth, AutoWidth));
Column->Width = Width;
Remaining -= Min(Width, Remaining);
}
}
DebugAssert(Remaining == 0);
}
}
}
__finally
{
SendMessage(ListView->Handle, WM_SETREDRAW, true, 0);
// As recommended by documentation for WM_SETREDRAW.
// Without this, session list on Import dialog stops working after the list is reloaded while visible
// (i.e. when chaing import source)
RedrawWindow(ListView->Handle, NULL, NULL, RDW_ERASE | RDW_FRAME | RDW_INVALIDATE | RDW_ALLCHILDREN);
}
}
//---------------------------------------------------------------------------
static void __fastcall SetParentColor(TControl * Control)
{
TColor Color = clBtnFace;
if (UseThemes)
{
bool OnTabSheet = false;
TWinControl * Parent = Control->Parent;
while ((Parent != NULL) && !OnTabSheet)
{
TTabSheet * TabSheet = dynamic_cast<TTabSheet *>(Parent);
OnTabSheet = (TabSheet != NULL) && TabSheet->TabVisible;
Parent = Parent->Parent;
}
if (OnTabSheet)
{
HTHEME Theme = OpenThemeData(NULL, L"tab");
if (Theme != NULL)
{
COLORREF RGB;
// XP with classic theme: Does not get past OpenThemeData, clBtnFace is exact color
// XP with XP theme: not the exact color (probably same as clBtnFace), but close
// Vista - ok
// 2016 without desktop - ok
// 7 with classic and high contrast themes: Do not get past OpenThemeData, clBtnFace is exact color
// 7 with 7 and basic themes - ok
// 10 with high contrast themes - ok (note the difference to 7 with high contract themes)
// 10 - ok
if (GetThemeColor(Theme, TABP_AEROWIZARDBODY, TIS_NORMAL, TMT_FILLCOLOR, &RGB) == S_OK)
{
Color = static_cast<TColor>(RGB);
}
CloseThemeData(Theme);
}
}
}
((TEdit*)Control)->Color = Color;
}
//---------------------------------------------------------------------------
void __fastcall EnableControl(TControl * Control, bool Enable)
{
if (Control->Enabled != Enable)
{
TWinControl * WinControl = dynamic_cast<TWinControl *>(Control);
if ((WinControl != NULL) &&
(WinControl->ControlCount > 0))
{
for (int Index = 0; Index < WinControl->ControlCount; Index++)
{
EnableControl(WinControl->Controls[Index], Enable);
}
}
Control->Enabled = Enable;
}
if ((dynamic_cast<TCustomEdit *>(Control) != NULL) ||
(dynamic_cast<TCustomComboBox *>(Control) != NULL) ||
(dynamic_cast<TCustomListView *>(Control) != NULL) ||
(dynamic_cast<TCustomTreeView *>(Control) != NULL))
{
if (Enable)
{
((TEdit*)Control)->Color = clWindow;
}
else
{
// This does not work for list view with
// LVS_EX_DOUBLEBUFFER (TCustomDirView).
// It automatically gets gray background.
// Though on Windows 7, the control has to be disabled
// only after it is showing already (see TCustomScpExplorerForm::UpdateControls())
((TEdit*)Control)->Color = clBtnFace;
}
}
};
//---------------------------------------------------------------------------
void __fastcall DoReadOnlyControl(TControl * Control, bool ReadOnly, bool Color);
//---------------------------------------------------------------------------
void __fastcall ReadOnlyAndEnabledControl(TControl * Control, bool ReadOnly, bool Enabled)
{
// Change color only in only one of EnableControl and DoReadOnlyControl to prevent flicker
if (ReadOnly)
{
DebugAssert(dynamic_cast<TWinControl *>(Control)->ControlCount == 0);
// As EnableControl, but with no color change
Control->Enabled = Enabled;
DoReadOnlyControl(Control, ReadOnly, true);
}
else
{
DoReadOnlyControl(Control, ReadOnly, false);
EnableControl(Control, Enabled);
}
}
//---------------------------------------------------------------------------
static void __fastcall ReadOnlyEditContextPopup(void * /*Data*/, TObject * Sender, const TPoint & MousePos, bool & Handled)
{
TEdit * Edit = static_cast<TEdit *>(Sender);
if (Edit->ReadOnly)
{
MenuPopup(Sender, MousePos, Handled);
}
}
//---------------------------------------------------------------------------
void __fastcall DoReadOnlyControl(TControl * Control, bool ReadOnly, bool Color)
{
if (dynamic_cast<TCustomEdit *>(Control) != NULL)
{
TEdit * Edit = static_cast<TEdit *>(Control);
Edit->ReadOnly = ReadOnly;
TMemo * Memo = dynamic_cast<TMemo *>(Control);
if (ReadOnly)
{
if (Color)
{
SetParentColor(Control);
}
if (Memo != NULL)
{
// Is true by default and makes the control swallow not only
// returns but also escapes.
// See also MemoKeyDown
Memo->WantReturns = false;
}
if ((Edit->PopupMenu == NULL) && (dynamic_cast<TPasswordEdit *>(Control) == NULL))
{
std::unique_ptr<TPopupMenu> PopupMenu(new TPopupMenu(Edit));
TMenuItem * Item;
Item = new TMenuItem(PopupMenu.get());
PopupMenu->Items->Add(Item);
Item->Action = new TEditCopy(Item);
Item->Caption = LoadStr(EDIT_COPY);
Item->ShortCut = ShortCut(L'C', TShiftState() << ssCtrl);
Item = new TMenuItem(PopupMenu.get());
PopupMenu->Items->Add(Item);
Item->Action = new TEditSelectAll(Item);
Item->Caption = LoadStr(EDIT_SELECT_ALL);
Item->ShortCut = ShortCut(L'A', TShiftState() << ssCtrl);
Edit->PopupMenu = PopupMenu.release();
Edit->OnContextPopup = MakeMethod<TContextPopupEvent>(NULL, ReadOnlyEditContextPopup);
}
}
else
{
if (Color)
{
Edit->Color = clWindow;
}
// not supported atm, we need to persist previous value of WantReturns
DebugAssert(Memo == NULL);
if ((Edit->PopupMenu != NULL) && (Edit->PopupMenu->Owner == Edit))
{
delete Edit->PopupMenu;
}
}
}
else if ((dynamic_cast<TCustomComboBox *>(Control) != NULL) ||
(dynamic_cast<TCustomTreeView *>(Control) != NULL))
{
EnableControl(Control, !ReadOnly);
}
else
{
DebugFail();
}
}
//---------------------------------------------------------------------------
void __fastcall ReadOnlyControl(TControl * Control, bool ReadOnly)
{
DoReadOnlyControl(Control, ReadOnly, true);
}
//---------------------------------------------------------------------------
int CalculateCheckBoxWidth(TControl * Control, const UnicodeString & Caption)
{
return
ScaleByTextHeight(Control, 13 + 3 + 8) + // checkbox, padding and buffer
GetParentForm(Control)->Canvas->TextWidth(StripHotkey(Caption));
}
//---------------------------------------------------------------------------
void AutoSizeCheckBox(TCheckBox * CheckBox)
{
CheckBox->Width = CalculateCheckBoxWidth(CheckBox, CheckBox->Caption);
}
//---------------------------------------------------------------------------
// Some of MainFormLike code can now be obsolete, thanks to Application->OnGetMainFormHandle.
static TForm * MainLikeForm = NULL;
//---------------------------------------------------------------------------
TForm * __fastcall GetMainForm()
{
TForm * Result;
if (MainLikeForm != NULL)
{
Result = MainLikeForm;
}
else
{
Result = Application->MainForm;
}
return Result;
}
//---------------------------------------------------------------------------
bool __fastcall IsMainFormHidden()
{
bool Result = false;
TForm * MainForm = GetMainForm();
if (MainForm != NULL)
{
Result =
!MainForm->Visible ||
(MainForm->Perform(WM_IS_HIDDEN, 0, 0) == 1);
}
// we do not expect this to return true when MainLikeForm is set
DebugAssert(!Result || (MainLikeForm == NULL));
return Result;
}
//---------------------------------------------------------------------------
bool __fastcall IsMainFormLike(TCustomForm * Form)
{
return
(GetMainForm() == Form) ||
// this particularly happens if error occurs while main
// window is being shown (e.g. non existent local directory when opening
// explorer)
IsMainFormHidden();
}
//---------------------------------------------------------------------------
UnicodeString __fastcall FormatMainFormCaption(const UnicodeString & Caption, const UnicodeString & SessionName)
{
UnicodeString Suffix = AppName;
if (!SessionName.IsEmpty())
{
Suffix = SessionName + TitleSeparator + Suffix;
}
UnicodeString Result = Caption;
if (Result.IsEmpty())
{
Result = Suffix;
}
else
{
Suffix = TitleSeparator + Suffix;
if (!EndsStr(Suffix, Result))
{
Result += Suffix;
}
}
return Result;
}
//---------------------------------------------------------------------------
UnicodeString __fastcall FormatFormCaption(
TCustomForm * Form, const UnicodeString & Caption, const UnicodeString & SessionName)
{
UnicodeString Result = Caption;
if (IsMainFormLike(Form))
{
Result = FormatMainFormCaption(Result, SessionName);
}
return Result;
}
//---------------------------------------------------------------------------
class TPublicWinControl : public TWinControl
{
friend TWndMethod __fastcall ControlWndProc(TWinControl * Control);
friend void __fastcall InstallPathWordBreakProc(TWinControl * Control);
};
//---------------------------------------------------------------------------
TWndMethod __fastcall ControlWndProc(TWinControl * Control)
{
TPublicWinControl * PublicWinControl = static_cast<TPublicWinControl *>(Control);
return &PublicWinControl->WndProc;
}
//---------------------------------------------------------------------
class TPublicControl : public TControl
{
friend void __fastcall RealignControl(TControl * Control);
friend void __fastcall DoFormWindowProc(TCustomForm * Form, TWndMethod WndProc, TMessage & Message);
friend TCanvas * CreateControlCanvas(TControl * Control);
};
//---------------------------------------------------------------------
class TPublicForm : public TForm
{
friend void __fastcall ChangeFormPixelsPerInch(TForm * Form, int PixelsPerInch);
friend void __fastcall ShowAsModal(TForm * Form, void *& Storage, bool BringToFront, bool TriggerModalStarted);
friend void __fastcall HideAsModal(TForm * Form, void *& Storage);
friend void __fastcall ShowFormNoActivate(TForm * Form);
};
//---------------------------------------------------------------------------
void __fastcall RealignControl(TControl * Control)
{
TPublicControl * PublicControl = static_cast<TPublicControl *>(Control);
PublicControl->RequestAlign();
}
//---------------------------------------------------------------------------
static Forms::TMonitor * LastMonitor = NULL;
//---------------------------------------------------------------------------
static int __fastcall GetTextHeightAtPixelsPerInch(TForm * Form, int PixelsPerInch)
{
std::unique_ptr<TCanvas> Canvas(new TCanvas());
Canvas->Handle = GetDC(0);
Canvas->Font->Assign(Form->Font);
Canvas->Font->PixelsPerInch = PixelsPerInch; // Must be set BEFORE size
Canvas->Font->Size = Form->Font->Size;
// VCLCOPY: this is what TCustomForm.GetTextHeight does
return Canvas->TextHeight(L"0");
}
//---------------------------------------------------------------------------
class TRescaleComponent : public TComponent
{
public:
__fastcall TRescaleComponent(TRescaleEvent AOnRescale, TObject * AToken, bool AOwnsToken) :
TComponent(NULL)
{
OnRescale = AOnRescale;
Token = AToken;
OwnsToken = AOwnsToken;
}
virtual __fastcall ~TRescaleComponent()
{
if (OwnsToken)
{
delete Token;
}
}
TRescaleEvent OnRescale;
TObject * Token;
bool OwnsToken;
};
//---------------------------------------------------------------------------
void __fastcall SetRescaleFunction(
TComponent * Component, TRescaleEvent OnRescale, TObject * Token, bool OwnsToken)
{
TRescaleComponent * RescaleComponent = new TRescaleComponent(OnRescale, Token, OwnsToken);
RescaleComponent->Name = TRescaleComponent::QualifiedClassName();
Component->InsertComponent(RescaleComponent);
}
//---------------------------------------------------------------------------
static void __fastcall ChangeControlScale(TControl * Control, int M, int D)
{
// VCLCOPY This is what TCustomListView.ChangeScale does,
// but it does that for initial loading only, when ScalingFlags includes sfWidth.
// But ScalingFlags is reset in TControl.ChangeScale (seems like a bug).
TCustomListView * CustomListView = dynamic_cast<TCustomListView *>(Control);
if (CustomListView != NULL)
{
TListView * ListView = reinterpret_cast<TListView *>(CustomListView);
for (int Index = 0; Index < ListView->Columns->Count; Index++)
{
TListColumn * Column = ListView->Columns->Items[Index];
if ((Column->Width != LVSCW_AUTOSIZE) &&
(Column->Width != LVSCW_AUTOSIZE_USEHEADER))
{
Column->Width = MulDiv(Column->Width, M, D);
}
}
}
TCustomCombo * CustomCombo = dynamic_cast<TCustomCombo *>(Control);
if (CustomCombo != NULL)
{
// WORKAROUND
// Some combo boxes (e.g. path box on Copy dialog) visualize selection after rescaling, even when not focused
if (!CustomCombo->Focused())
{
CustomCombo->SelLength = 0;
}
}
for (int Index = 0; Index < Control->ComponentCount; Index++)
{
TComponent * Component = Control->Components[Index];
TControl * ChildControl = dynamic_cast<TControl *>(Component);
if (ChildControl != NULL)
{
ChangeControlScale(ChildControl, M, D);
}
TRescaleComponent * RescaleComponent =
dynamic_cast<TRescaleComponent *>(Component->FindComponent(TRescaleComponent::QualifiedClassName()));
if (RescaleComponent != NULL)
{
RescaleComponent->OnRescale(Component, RescaleComponent->Token);
}
}
Control->Perform(CM_DPICHANGED, M, D);
}
//---------------------------------------------------------------------------
typedef std::pair<int, int> TRatio;
typedef std::map<TRatio, TRatio > TRatioMap;
//---------------------------------------------------------------------------
class TFormRescaleComponent : public TComponent
{
public:
__fastcall TFormRescaleComponent() :
TComponent(NULL)
{
ImplicitRescaleAdded = false;
Rescaling = false;
}
bool Rescaling;
bool ImplicitRescaleAdded;
TRatioMap RatioMap;
};
//---------------------------------------------------------------------------
static TFormRescaleComponent * GetFormRescaleComponent(TForm * Form)
{
TFormRescaleComponent * FormRescaleComponent =
dynamic_cast<TFormRescaleComponent *>(Form->FindComponent(TFormRescaleComponent::QualifiedClassName()));
if (FormRescaleComponent == NULL)
{
FormRescaleComponent = new TFormRescaleComponent();
FormRescaleComponent->Name = TFormRescaleComponent::QualifiedClassName();
Form->InsertComponent(FormRescaleComponent);
}
return FormRescaleComponent;
}
//---------------------------------------------------------------------------
void __fastcall RecordFormImplicitRescale(TForm * Form)
{
if (Form->Scaled)
{
TFormRescaleComponent * FormRescaleComponent = GetFormRescaleComponent(Form);
if (!FormRescaleComponent->ImplicitRescaleAdded)
{
TRatio Ratio;
GetFormScaleRatio(Form, Ratio.first, Ratio.second);
TRatio RescaleKeyRatio(Form->PixelsPerInch, USER_DEFAULT_SCREEN_DPI);
FormRescaleComponent->RatioMap[RescaleKeyRatio] = Ratio;
FormRescaleComponent->ImplicitRescaleAdded = true;
}
}
}
//---------------------------------------------------------------------------
static void GetFormRescaleRatio(TForm * Form, int PixelsPerInch, int & M, int & D)
{
TFormRescaleComponent * FormRescaleComponent = GetFormRescaleComponent(Form);
TRatio ReverseRescaleKeyRatio(Form->PixelsPerInch, PixelsPerInch);
if (FormRescaleComponent->RatioMap.count(ReverseRescaleKeyRatio) > 0)
{
M = FormRescaleComponent->RatioMap[ReverseRescaleKeyRatio].second;
D = FormRescaleComponent->RatioMap[ReverseRescaleKeyRatio].first;
}
else
{
M = GetTextHeightAtPixelsPerInch(Form, PixelsPerInch);
D = GetTextHeightAtPixelsPerInch(Form, Form->PixelsPerInch);
}
TRatio RescaleKeyRatio(PixelsPerInch, Form->PixelsPerInch);
FormRescaleComponent->RatioMap[RescaleKeyRatio] = TRatio(M, D);
}
//---------------------------------------------------------------------------
static void __fastcall ChangeFormPixelsPerInch(TForm * Form, int PixelsPerInch)
{
RecordFormImplicitRescale(Form);
TFormRescaleComponent * FormRescaleComponent = GetFormRescaleComponent(Form);
if ((Form->PixelsPerInch != PixelsPerInch) && // optimization
!FormRescaleComponent->Rescaling)
{
AppLogFmt(L"Scaling window %s", (Form->Caption));
TAutoFlag RescalingFlag(FormRescaleComponent->Rescaling);
int M, D;
GetFormRescaleRatio(Form, PixelsPerInch, M, D);
Form->PixelsPerInch = PixelsPerInch;
TPublicForm * PublicCustomForm = static_cast<TPublicForm *>(Form);
// WORKAROUND
// TCustomForm.ChangeScale scales contraints only after rescaling the size,
// so the unscaled constraints apply to the new size
// (e.g. with TLoginDialog)
std::unique_ptr<TSizeConstraints> Constraints(new TSizeConstraints(NULL));
Constraints->Assign(PublicCustomForm->Constraints);
std::unique_ptr<TSizeConstraints> NoConstraints(new TSizeConstraints(NULL));
PublicCustomForm->Constraints = NoConstraints.get();
// Does not seem to have any effect
PublicCustomForm->DisableAlign();
try
{
int PrevFontHeight = Form->Font->Height;
PublicCustomForm->ChangeScale(M, D);
// Re-rescale by Height as it has higher granularity, hence lower risk of loosing precision due to rounding
Form->Font->Height = MulDiv(PrevFontHeight, M, D);
ChangeControlScale(Form, M, D);
Constraints->MinWidth = MulDiv(Constraints->MinWidth, M, D);
Constraints->MaxWidth = MulDiv(Constraints->MaxWidth, M, D);
Constraints->MinHeight = MulDiv(Constraints->MinHeight, M, D);
Constraints->MaxHeight = MulDiv(Constraints->MaxHeight, M, D);
PublicCustomForm->Constraints = Constraints.get();
}
__finally
{
PublicCustomForm->EnableAlign();
}
}
}
//---------------------------------------------------------------------------
static void __fastcall FormShowingChanged(TForm * Form, TWndMethod WndProc, TMessage & Message)
{
if (IsMainFormLike(Form))
{
if (Form->Showing)
{
if (Application->MainForm != Form)
{
MainLikeForm = Form;
// When main form is hidden, no taskbar button for it is shown and
// this window does not become main window, so there won't be no taskbar
// icon created automatically (by VCL). So we force it manually here.
// This particularly happen for all windows/dialogs of command-line
// operations (e.g. /synchronize) after CreateScpExplorer() happens.
// Also CM_SHOWINGCHANGED happens twice, and the WS_EX_APPWINDOW flag
// from the first call is not preserved, re-applying on the second call too.
// TODO: What about minimize to tray?
int Style = GetWindowLong(Form->Handle, GWL_EXSTYLE);
if (FLAGCLEAR(Style, WS_EX_APPWINDOW))
{
Style |= WS_EX_APPWINDOW;
SetWindowLong(Form->Handle, GWL_EXSTYLE, Style);
}
}
if (Form->Perform(WM_MANAGES_CAPTION, 0, 0) == 0)
{
Form->Caption = FormatFormCaption(Form, Form->Caption);
}
SendMessage(Form->Handle, WM_SETICON, ICON_BIG, reinterpret_cast<long>(Application->Icon->Handle));
}
else
{
if (MainLikeForm == Form)
{
// Do not bother with hiding the WS_EX_APPWINDOW flag
// as the window is closing anyway.
MainLikeForm = NULL;
}
}
}
// Part of following code (but actually not all, TODO), has to happen
// for all windows when VCL main window is hidden (particularly the last branch).
// This is different from above brach, that should happen only for top-level visible window.
if ((Application->MainForm == Form) ||
// this particularly happens if error occurs while main
// window is being shown (e.g. non existent local directory when opening
// explorer)
((Application->MainForm != NULL) && !Application->MainForm->Visible))
{
if (!Form->Showing)
{
// when closing main form, remember its monitor,
// so that the next form is shown on the same one
LastMonitor = Form->Monitor;
}
else if ((LastMonitor != NULL) && (LastMonitor != Form->Monitor) &&
Form->Showing)
{
// would actually always be poScreenCenter, see _SafeFormCreate
if ((Form->Position == poMainFormCenter) ||
(Form->Position == poOwnerFormCenter) ||
(Form->Position == poScreenCenter))
{
// this would typically be a standalone message box (e.g. /UninstallCleanup or /Update)
// If DPI changes (as the form moves to a monitor with a non-system DPI),
// we have to re-center as the form size changed too.
int PixelsPerInch;
do
{
PixelsPerInch = Form->PixelsPerInch;
// taken from TCustomForm::SetWindowToMonitor
Form->SetBounds(LastMonitor->Left + ((LastMonitor->Width - Form->Width) / 2),
LastMonitor->Top + ((LastMonitor->Height - Form->Height) / 2),
Form->Width, Form->Height);
Form->Position = poDesigned;
}
while (PixelsPerInch != Form->PixelsPerInch);
}
else if ((Form->Position != poDesigned) &&
(Form->Position != poDefaultPosOnly))
{
// we do not expect any other positioning
DebugFail();
}
}
// otherwise it would not get centered
else if ((Form->Position == poMainFormCenter) ||
(Form->Position == poOwnerFormCenter))
{
Form->Position = poScreenCenter;
}
}
if (Form->Showing)
{
// At least on single monitor setup, monitor DPI is 100% but system DPI is higher,
// WM_DPICHANGED is not sent. But VCL scales the form using system DPI.
// Also we have to do this always for implicitly placed forms (poDefaultPosOnly), like TEditorForm,
// as they never get the WM_DPICHANGED.
// Call this before WndProc below, i.e. before OnShow event (particularly important for the TEditorForm::FormShow).
// GetControlPixelsPerInch would return Form.PixelsPerInch, but we want to get a new DPI of the form monitor.
ChangeFormPixelsPerInch(Form, GetMonitorPixelsPerInch(GetMonitorFromControl(Form)));
}
bool WasFormCenter =
(Form->Position == poMainFormCenter) ||
(Form->Position == poOwnerFormCenter);
WndProc(Message);
// Make sure dialogs are shown on-screen even if center of the main window
// is off-screen. Occurs e.g. if you move the main window so that
// only window title is visible above taksbar.
if (Form->Showing && WasFormCenter && (Form->Position == poDesigned))
{
TRect Rect;
// Reading Form.Left/Form.Top instead here does not work, likely due to some
// bug, when querying TProgressForm opened from TEditorForm (reloading remote file)
GetWindowRect(Form->Handle, &Rect);
int Left = Rect.Left;
int Top = Rect.Top;
TRect WorkArea = Form->Monitor->WorkareaRect;
if (Left + Rect.Width() > WorkArea.Right)
{
Left = WorkArea.Right - Rect.Width();
}
if (Left < WorkArea.Left)
{
Left = WorkArea.Left;
}
if (Top + Rect.Height() > WorkArea.Bottom)
{
Top = WorkArea.Bottom - Rect.Height();
}
if (Top < WorkArea.Top)
{
Top = WorkArea.Top;
}
if ((Left != Rect.Left) ||
(Top != Rect.Top))
{
SetWindowPos(Form->Handle, 0, Left, Top, Rect.Width(), Rect.Height(),
SWP_NOZORDER + SWP_NOACTIVATE);
}
}
}
//---------------------------------------------------------------------------
static TCustomForm * WindowPrintForm = NULL;
static DWORD WindowPrintPrevClick = 0;
static unsigned int WindowPrintClickCount = 0;
//---------------------------------------------------------------------------
void __fastcall CountClicksForWindowPrint(TForm * Form)
{
if ((WinConfiguration != NULL) && WinConfiguration->AllowWindowPrint)
{
DWORD Tick = GetTickCount();
if (WindowPrintForm != Form)
{
WindowPrintForm = Form;
WindowPrintClickCount = 0;
}
if (WindowPrintPrevClick < Tick - 500)
{
WindowPrintClickCount = 0;
}
WindowPrintClickCount++;
WindowPrintPrevClick = Tick;
if (WindowPrintClickCount == 3)
{
WindowPrintClickCount = 0;
TInstantOperationVisualizer Visualizer;
// get the device context of the screen
HDC ScreenDC = CreateDC(L"DISPLAY", NULL, NULL, NULL);
// and a device context to put it in
HDC MemoryDC = CreateCompatibleDC(ScreenDC);
try
{
bool Sizable = (Form->BorderStyle == bsSizeable);
int Frame = GetSystemMetrics(Sizable ? SM_CXSIZEFRAME : SM_CXFIXEDFRAME) - 1;
int Width = Form->Width - 2*Frame;
int Height = Form->Height - Frame;
// maybe worth checking these are positive values
HBITMAP Bitmap = CreateCompatibleBitmap(ScreenDC, Width, Height);
try
{
// get a new bitmap
HBITMAP OldBitmap = static_cast<HBITMAP>(SelectObject(MemoryDC, Bitmap));
BitBlt(MemoryDC, 0, 0, Width, Height, ScreenDC, Form->Left + Frame, Form->Top, SRCCOPY);
Bitmap = static_cast<HBITMAP>(SelectObject(MemoryDC, OldBitmap));
OpenClipboard(NULL);
try
{
EmptyClipboard();
SetClipboardData(CF_BITMAP, Bitmap);
}
__finally
{
CloseClipboard();
}
}
__finally
{
DeleteObject(Bitmap);
}
}
__finally
{
DeleteDC(MemoryDC);
DeleteDC(ScreenDC);
}
}
}
}
//---------------------------------------------------------------------------
inline void __fastcall DoFormWindowProc(TCustomForm * Form, TWndMethod WndProc,
TMessage & Message)
{
TForm * AForm = dynamic_cast<TForm *>(Form);
DebugAssert(AForm != NULL);
if ((Message.Msg == WM_SYSCOMMAND) &&
(Message.WParam == SC_CONTEXTHELP))
{
FormHelp(Form);
Message.Result = 1;
}
else if (Message.Msg == CM_SHOWINGCHANGED)
{
FormShowingChanged(AForm, WndProc, Message);
}
else if (Message.Msg == WM_SETICON)
{
// WORKAROUND: Swallow VCL attempt to clear the icon from TCustomForm.WMDestroy.
// The clearing still happens to be visualised before the form is hidden.
// On resizable forms, the icon gets replaced by the default application icon,
// on the other forms, the icon disappears and window caption is shifted left.
if (Message.LParam != 0)
{
WndProc(Message);
}
}
else if (Message.Msg == WM_GETDPISCALEDSIZE)
{
WndProc(Message);
int M, D;
GetFormRescaleRatio(AForm, LOWORD(Message.WParam), M, D);
SIZE & Size = *(reinterpret_cast<SIZE *>(Message.LParam));
Size.cx = MulDiv(Size.cx, M, D);
Size.cy = MulDiv(Size.cy, M, D);
Message.Result = TRUE;
}
else if (Message.Msg == WM_DPICHANGED)
{
ChangeFormPixelsPerInch(AForm, LOWORD(Message.WParam));
WndProc(Message);
}
else if ((Message.Msg == WM_LBUTTONDOWN) || (Message.Msg == WM_LBUTTONDBLCLK))
{
CountClicksForWindowPrint(AForm);
WndProc(Message);
}
else
{
WndProc(Message);
}
}