VCLCommon.cpp 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "WinInterface.h"
  5. #include "VCLCommon.h"
  6. #include <Common.h>
  7. #include <TextsWin.h>
  8. #include <RemoteFiles.h>
  9. #include <GUITools.h>
  10. #include <Tools.h>
  11. #include <CustomWinConfiguration.h>
  12. #include <Vcl.StdActns.hpp>
  13. #include <PasswordEdit.hpp>
  14. #include <FileCtrl.hpp>
  15. #include <PathLabel.hpp>
  16. #include <PasTools.hpp>
  17. #include <StrUtils.hpp>
  18. #include <Vcl.Imaging.pngimage.hpp>
  19. #include <Math.hpp>
  20. #include <TB2ExtItems.hpp>
  21. #include <TBXExtItems.hpp>
  22. #include <IEListView.hpp>
  23. #include <WinApi.h>
  24. #include <vssym32.h>
  25. //---------------------------------------------------------------------------
  26. const UnicodeString LinkAppLabelMark(TraceInitStr(L" \x00BB"));
  27. //---------------------------------------------------------------------------
  28. #pragma package(smart_init)
  29. //---------------------------------------------------------------------------
  30. void __fastcall FixListColumnWidth(TListView * TListView, int Index)
  31. {
  32. if (Index < 0)
  33. {
  34. Index = TListView->Columns->Count + Index;
  35. }
  36. TListView->Column[Index]->Tag = 1;
  37. }
  38. //---------------------------------------------------------------------------
  39. static int __fastcall GetColumnTextWidth(TListView * ListView, int ColumnPadding, const UnicodeString & Text)
  40. {
  41. return
  42. ColumnPadding +
  43. ListView->Canvas->TextExtent(Text).Width;
  44. }
  45. //---------------------------------------------------------------------------
  46. void __fastcall AutoSizeListColumnsWidth(TListView * ListView, int ColumnToShrinkIndex)
  47. {
  48. // Preallocate handle to precreate columns, otherwise our changes may get
  49. // overwritten once the handle is created.
  50. // This should actually get called only once the handle are allocated.
  51. // Otherwise we end up recreating the handles,
  52. // what may cause a flicker of the currently focused window title.
  53. ListView->HandleNeeded();
  54. SendMessage(ListView->Handle, WM_SETREDRAW, false, 0);
  55. try
  56. {
  57. int ColumnPadding = 2 * ScaleByTextHeightRunTime(ListView, 6);
  58. int ColumnShrinkMinWidth = ScaleByTextHeightRunTime(ListView, 60);
  59. int ResizableWidth = 0;
  60. int NonResizableWidth = 0;
  61. int LastResizable = -1;
  62. for (int Index = 0; Index < ListView->Columns->Count; Index++)
  63. {
  64. TListColumn * Column = ListView->Columns->Items[Index];
  65. int CaptionWidth = GetColumnTextWidth(ListView, ColumnPadding, Column->Caption);
  66. int OrigWidth = -1;
  67. bool NonResizable = (Column->Tag != 0);
  68. if (NonResizable) // optimization
  69. {
  70. OrigWidth = ListView_GetColumnWidth(ListView->Handle, Index);
  71. }
  72. int Width;
  73. // LVSCW_AUTOSIZE does not work for OwnerData list views
  74. if (!ListView->OwnerData)
  75. {
  76. ListView_SetColumnWidth(ListView->Handle, Index, LVSCW_AUTOSIZE);
  77. Width = ListView_GetColumnWidth(ListView->Handle, Index);
  78. }
  79. else
  80. {
  81. Width = 0;
  82. for (int ItemIndex = 0; ItemIndex < ListView->Items->Count; ItemIndex++)
  83. {
  84. TListItem * Item = ListView->Items->Item[ItemIndex];
  85. UnicodeString Text;
  86. if (Index == 0)
  87. {
  88. Text = Item->Caption;
  89. }
  90. // Particularly EditorListView3 on Preferences dialog does not have all subitems filled for internal editor
  91. else if (Index <= Item->SubItems->Count)
  92. {
  93. Text = Item->SubItems->Strings[Index - 1];
  94. }
  95. int TextWidth = GetColumnTextWidth(ListView, ColumnPadding, Text);
  96. if (TextWidth > Width)
  97. {
  98. Width = TextWidth;
  99. }
  100. }
  101. }
  102. Width = Max(Width, CaptionWidth);
  103. // Never shrink the non-resizable columns
  104. if (NonResizable && (Width < OrigWidth))
  105. {
  106. Width = OrigWidth;
  107. }
  108. Column->Width = Width;
  109. if (NonResizable)
  110. {
  111. NonResizableWidth += Width;
  112. }
  113. else
  114. {
  115. LastResizable = Index;
  116. ResizableWidth += Width;
  117. }
  118. }
  119. DebugAssert(LastResizable >= 0);
  120. int ClientWidth = ListView->ClientWidth;
  121. int RowCount = ListView->Items->Count;
  122. if ((ListView->VisibleRowCount < RowCount) &&
  123. (ListView->Width - ListView->ClientWidth < GetSystemMetricsForControl(ListView, SM_CXVSCROLL)))
  124. {
  125. ClientWidth -= GetSystemMetricsForControl(ListView, SM_CXVSCROLL);
  126. }
  127. if (DebugAlwaysTrue(NonResizableWidth < ClientWidth))
  128. {
  129. int Remaining = ClientWidth - NonResizableWidth;
  130. bool ProportionalResize = true;
  131. bool Shrinking = (Remaining < ResizableWidth);
  132. // If columns are too wide to fit and we have dedicated shrink column, shrink it
  133. if (Shrinking &&
  134. (ColumnToShrinkIndex >= 0))
  135. {
  136. TListColumn * ColumnToShrink = ListView->Columns->Items[ColumnToShrinkIndex];
  137. int ColumnToShrinkCaptionWidth = GetColumnTextWidth(ListView, ColumnPadding, ColumnToShrink->Caption);
  138. int ColumnToShrinkMinWidth = Max(ColumnShrinkMinWidth, ColumnToShrinkCaptionWidth);
  139. // This falls back to proprotional shrinking when the shrink column would fall below min width.
  140. // Question is whether we should not shrink to min width instead.
  141. if ((ResizableWidth - ColumnToShrink->Width) < (Remaining - ColumnToShrinkMinWidth))
  142. {
  143. int ColumnToShrinkWidth = Remaining - (ResizableWidth - ColumnToShrink->Width);
  144. ColumnToShrink->Width = ColumnToShrinkWidth;
  145. ProportionalResize = false;
  146. }
  147. }
  148. if (ProportionalResize)
  149. {
  150. for (int Index = 0; Index <= LastResizable; Index++)
  151. {
  152. TListColumn * Column = ListView->Columns->Items[Index];
  153. if (Column->Tag == 0)
  154. {
  155. int Width = ListView_GetColumnWidth(ListView->Handle, Index);
  156. int AutoWidth = Width;
  157. if (Index < LastResizable)
  158. {
  159. Width = (Remaining * Width) / ResizableWidth;
  160. }
  161. else
  162. {
  163. Width = Remaining;
  164. }
  165. int CaptionWidth = GetColumnTextWidth(ListView, ColumnPadding, Column->Caption);
  166. Width = Max(Width, CaptionWidth);
  167. Width = Max(Width, Min(ColumnShrinkMinWidth, AutoWidth));
  168. Column->Width = Width;
  169. Remaining -= Min(Width, Remaining);
  170. }
  171. }
  172. DebugAssert(Remaining == 0);
  173. }
  174. }
  175. }
  176. __finally
  177. {
  178. SendMessage(ListView->Handle, WM_SETREDRAW, true, 0);
  179. // As recommended by documentation for WM_SETREDRAW.
  180. // Without this, session list on Import dialog stops working after the list is reloaded while visible
  181. // (i.e. when chaing import source)
  182. RedrawWindow(ListView->Handle, NULL, NULL, RDW_ERASE | RDW_FRAME | RDW_INVALIDATE | RDW_ALLCHILDREN);
  183. }
  184. }
  185. //---------------------------------------------------------------------------
  186. static void __fastcall SetParentColor(TControl * Control)
  187. {
  188. TColor Color = clBtnFace;
  189. if (UseThemes)
  190. {
  191. bool OnTabSheet = false;
  192. TWinControl * Parent = Control->Parent;
  193. while ((Parent != NULL) && !OnTabSheet)
  194. {
  195. TTabSheet * TabSheet = dynamic_cast<TTabSheet *>(Parent);
  196. OnTabSheet = (TabSheet != NULL) && TabSheet->TabVisible;
  197. Parent = Parent->Parent;
  198. }
  199. if (OnTabSheet)
  200. {
  201. HTHEME Theme = OpenThemeData(NULL, L"tab");
  202. if (Theme != NULL)
  203. {
  204. COLORREF RGB;
  205. // XP with classic theme: Does not get past OpenThemeData, clBtnFace is exact color
  206. // XP with XP theme: not the exact color (probably same as clBtnFace), but close
  207. // Vista - ok
  208. // 2016 without desktop - ok
  209. // 7 with classic and high contrast themes: Do not get past OpenThemeData, clBtnFace is exact color
  210. // 7 with 7 and basic themes - ok
  211. // 10 with high contrast themes - ok (note the difference to 7 with high contract themes)
  212. // 10 - ok
  213. if (GetThemeColor(Theme, TABP_AEROWIZARDBODY, TIS_NORMAL, TMT_FILLCOLOR, &RGB) == S_OK)
  214. {
  215. Color = static_cast<TColor>(RGB);
  216. }
  217. CloseThemeData(Theme);
  218. }
  219. }
  220. }
  221. ((TEdit*)Control)->Color = Color;
  222. }
  223. //---------------------------------------------------------------------------
  224. void __fastcall EnableControl(TControl * Control, bool Enable)
  225. {
  226. if (Control->Enabled != Enable)
  227. {
  228. TWinControl * WinControl = dynamic_cast<TWinControl *>(Control);
  229. if ((WinControl != NULL) &&
  230. (WinControl->ControlCount > 0))
  231. {
  232. for (int Index = 0; Index < WinControl->ControlCount; Index++)
  233. {
  234. EnableControl(WinControl->Controls[Index], Enable);
  235. }
  236. }
  237. Control->Enabled = Enable;
  238. }
  239. if ((dynamic_cast<TCustomEdit *>(Control) != NULL) ||
  240. (dynamic_cast<TCustomComboBox *>(Control) != NULL) ||
  241. (dynamic_cast<TCustomListView *>(Control) != NULL) ||
  242. (dynamic_cast<TCustomTreeView *>(Control) != NULL))
  243. {
  244. if (Enable)
  245. {
  246. ((TEdit*)Control)->Color = clWindow;
  247. }
  248. else
  249. {
  250. // This does not work for list view with
  251. // LVS_EX_DOUBLEBUFFER (TCustomDirView).
  252. // It automatically gets gray background.
  253. // Though on Windows 7, the control has to be disabled
  254. // only after it is showing already (see TCustomScpExplorerForm::UpdateControls())
  255. ((TEdit*)Control)->Color = clBtnFace;
  256. }
  257. }
  258. };
  259. //---------------------------------------------------------------------------
  260. void __fastcall ReadOnlyAndEnabledControl(TControl * Control, bool ReadOnly, bool Enabled)
  261. {
  262. if (dynamic_cast<TCustomEdit *>(Control) != NULL)
  263. {
  264. DebugAssert(dynamic_cast<TWinControl *>(Control)->ControlCount == 0);
  265. DebugAssert(dynamic_cast<TMemo *>(Control) == NULL);
  266. if (ReadOnly)
  267. {
  268. Control->Enabled = Enabled;
  269. ReadOnlyControl(Control, true);
  270. }
  271. else
  272. {
  273. // ReadOnlyControl(..., false) would set color to clWindow,
  274. // but we want to reflect the Enabled state and avoid flicker.
  275. ((TEdit*)Control)->ReadOnly = false;
  276. EnableControl(Control, Enabled);
  277. }
  278. }
  279. else
  280. {
  281. DebugFail();
  282. }
  283. }
  284. //---------------------------------------------------------------------------
  285. static void __fastcall ReadOnlyEditContextPopup(void * /*Data*/, TObject * Sender, const TPoint & MousePos, bool & Handled)
  286. {
  287. MenuPopup(Sender, MousePos, Handled);
  288. }
  289. //---------------------------------------------------------------------------
  290. void __fastcall ReadOnlyControl(TControl * Control, bool ReadOnly)
  291. {
  292. if (dynamic_cast<TCustomEdit *>(Control) != NULL)
  293. {
  294. TEdit * Edit = static_cast<TEdit *>(Control);
  295. Edit->ReadOnly = ReadOnly;
  296. TMemo * Memo = dynamic_cast<TMemo *>(Control);
  297. if (ReadOnly)
  298. {
  299. SetParentColor(Control);
  300. if (Memo != NULL)
  301. {
  302. // Is true by default and makes the control swallow not only
  303. // returns but also escapes.
  304. // See also MemoKeyDown
  305. Memo->WantReturns = false;
  306. }
  307. if ((Edit->PopupMenu == NULL) && (dynamic_cast<TPasswordEdit *>(Control) == NULL))
  308. {
  309. std::unique_ptr<TPopupMenu> PopupMenu(new TPopupMenu(Edit));
  310. TMenuItem * Item;
  311. Item = new TMenuItem(PopupMenu.get());
  312. PopupMenu->Items->Add(Item);
  313. Item->Action = new TEditCopy(Item);
  314. Item->Caption = LoadStr(EDIT_COPY);
  315. Item->ShortCut = ShortCut(L'C', TShiftState() << ssCtrl);
  316. Item = new TMenuItem(PopupMenu.get());
  317. PopupMenu->Items->Add(Item);
  318. Item->Action = new TEditSelectAll(Item);
  319. Item->Caption = LoadStr(EDIT_SELECT_ALL);
  320. Item->ShortCut = ShortCut(L'A', TShiftState() << ssCtrl);
  321. Edit->PopupMenu = PopupMenu.release();
  322. Edit->OnContextPopup = MakeMethod<TContextPopupEvent>(NULL, ReadOnlyEditContextPopup);
  323. }
  324. }
  325. else
  326. {
  327. Edit->Color = clWindow;
  328. // not supported atm, we need to persist previous value of WantReturns
  329. DebugAssert(Memo == NULL);
  330. if ((Edit->PopupMenu != NULL) && (Edit->PopupMenu->Owner == Edit))
  331. {
  332. delete Edit->PopupMenu;
  333. }
  334. }
  335. }
  336. else if ((dynamic_cast<TCustomComboBox *>(Control) != NULL) ||
  337. (dynamic_cast<TCustomTreeView *>(Control) != NULL))
  338. {
  339. EnableControl(Control, !ReadOnly);
  340. }
  341. else
  342. {
  343. DebugFail();
  344. }
  345. }
  346. //---------------------------------------------------------------------------
  347. static TForm * MainLikeForm = NULL;
  348. //---------------------------------------------------------------------------
  349. TForm * __fastcall GetMainForm()
  350. {
  351. TForm * Result;
  352. if (MainLikeForm != NULL)
  353. {
  354. Result = MainLikeForm;
  355. }
  356. else
  357. {
  358. Result = Application->MainForm;
  359. }
  360. return Result;
  361. }
  362. //---------------------------------------------------------------------------
  363. bool __fastcall IsMainFormHidden()
  364. {
  365. bool Result = (GetMainForm() != NULL) && !GetMainForm()->Visible;
  366. // we do not expect this to return true when MainLikeForm is set
  367. DebugAssert(!Result || (MainLikeForm == NULL));
  368. return Result;
  369. }
  370. //---------------------------------------------------------------------------
  371. bool __fastcall IsMainFormLike(TCustomForm * Form)
  372. {
  373. return
  374. (GetMainForm() == Form) ||
  375. // this particularly happens if error occurs while main
  376. // window is being shown (e.g. non existent local directory when opening
  377. // explorer)
  378. IsMainFormHidden();
  379. }
  380. //---------------------------------------------------------------------------
  381. UnicodeString __fastcall FormatMainFormCaption(const UnicodeString & Caption)
  382. {
  383. UnicodeString Result = Caption;
  384. if (Result.IsEmpty())
  385. {
  386. Result = AppName;
  387. }
  388. else
  389. {
  390. UnicodeString Suffix = L" - " + AppName;
  391. if (!EndsStr(Suffix, Result))
  392. {
  393. Result += Suffix;
  394. }
  395. }
  396. return Result;
  397. }
  398. //---------------------------------------------------------------------------
  399. UnicodeString __fastcall FormatFormCaption(TCustomForm * Form, const UnicodeString & Caption)
  400. {
  401. UnicodeString Result = Caption;
  402. if (IsMainFormLike(Form))
  403. {
  404. Result = FormatMainFormCaption(Result);
  405. }
  406. return Result;
  407. }
  408. //---------------------------------------------------------------------------
  409. class TPublicWinControl : public TWinControl
  410. {
  411. friend TWndMethod __fastcall ControlWndProc(TWinControl * Control);
  412. friend void __fastcall InstallPathWordBreakProc(TWinControl * Control);
  413. };
  414. //---------------------------------------------------------------------------
  415. TWndMethod __fastcall ControlWndProc(TWinControl * Control)
  416. {
  417. TPublicWinControl * PublicWinControl = static_cast<TPublicWinControl *>(Control);
  418. return &PublicWinControl->WndProc;
  419. }
  420. //---------------------------------------------------------------------
  421. class TPublicControl : public TControl
  422. {
  423. friend void __fastcall RealignControl(TControl * Control);
  424. friend void __fastcall DoFormWindowProc(TCustomForm * Form, TWndMethod WndProc, TMessage & Message);
  425. };
  426. //---------------------------------------------------------------------
  427. class TPublicForm : public TForm
  428. {
  429. friend void __fastcall ChangeFormPixelsPerInch(TForm * Form, int PixelsPerInch);
  430. friend void __fastcall ShowAsModal(TForm * Form, void *& Storage, bool BringToFront);
  431. friend void __fastcall HideAsModal(TForm * Form, void *& Storage);
  432. friend void __fastcall ShowFormNoActivate(TForm * Form);
  433. };
  434. //---------------------------------------------------------------------------
  435. void __fastcall RealignControl(TControl * Control)
  436. {
  437. TPublicControl * PublicControl = static_cast<TPublicControl *>(Control);
  438. PublicControl->RequestAlign();
  439. }
  440. //---------------------------------------------------------------------------
  441. static Forms::TMonitor * LastMonitor = NULL;
  442. //---------------------------------------------------------------------------
  443. static int __fastcall GetTextHeightAtPixelsPerInch(TForm * Form, int PixelsPerInch)
  444. {
  445. std::unique_ptr<TCanvas> Canvas(new TCanvas());
  446. Canvas->Handle = GetDC(0);
  447. Canvas->Font->Assign(Form->Font);
  448. Canvas->Font->PixelsPerInch = PixelsPerInch; // Must be set BEFORE size
  449. Canvas->Font->Size = Form->Font->Size;
  450. // VCLCOPY: this is what TCustomForm.GetTextHeight does
  451. return Canvas->TextHeight(L"0");
  452. }
  453. //---------------------------------------------------------------------------
  454. class TRescaleComponent : public TComponent
  455. {
  456. public:
  457. __fastcall TRescaleComponent(TRescaleEvent AOnRescale, TObject * AToken, bool AOwnsToken) :
  458. TComponent(NULL)
  459. {
  460. OnRescale = AOnRescale;
  461. Token = AToken;
  462. OwnsToken = AOwnsToken;
  463. }
  464. virtual __fastcall ~TRescaleComponent()
  465. {
  466. if (OwnsToken)
  467. {
  468. delete Token;
  469. }
  470. }
  471. TRescaleEvent OnRescale;
  472. TObject * Token;
  473. bool OwnsToken;
  474. };
  475. //---------------------------------------------------------------------------
  476. void __fastcall SetRescaleFunction(
  477. TComponent * Component, TRescaleEvent OnRescale, TObject * Token, bool OwnsToken)
  478. {
  479. TRescaleComponent * RescaleComponent = new TRescaleComponent(OnRescale, Token, OwnsToken);
  480. RescaleComponent->Name = TRescaleComponent::QualifiedClassName();
  481. Component->InsertComponent(RescaleComponent);
  482. }
  483. //---------------------------------------------------------------------------
  484. static void __fastcall ChangeControlScale(TControl * Control, int M, int D)
  485. {
  486. // VCLCOPY This is what TCustomListView.ChangeScale does,
  487. // but it does that for initial loading only, when ScalingFlags includes sfWidth.
  488. // But ScalingFlags is reset in TControl.ChangeScale (seems like a bug).
  489. TCustomListView * CustomListView = dynamic_cast<TCustomListView *>(Control);
  490. if (CustomListView != NULL)
  491. {
  492. TListView * ListView = reinterpret_cast<TListView *>(CustomListView);
  493. for (int Index = 0; Index < ListView->Columns->Count; Index++)
  494. {
  495. TListColumn * Column = ListView->Columns->Items[Index];
  496. if ((Column->Width != LVSCW_AUTOSIZE) &&
  497. (Column->Width != LVSCW_AUTOSIZE_USEHEADER))
  498. {
  499. Column->Width = MulDiv(Column->Width, M, D);
  500. }
  501. }
  502. }
  503. TCustomCombo * CustomCombo = dynamic_cast<TCustomCombo *>(Control);
  504. if (CustomCombo != NULL)
  505. {
  506. // WORKAROUND
  507. // Some combo boxes (e.g. path box on Copy dialog) visualize selection after rescaling, even when not focused
  508. if (!CustomCombo->Focused())
  509. {
  510. CustomCombo->SelLength = 0;
  511. }
  512. }
  513. for (int Index = 0; Index < Control->ComponentCount; Index++)
  514. {
  515. TComponent * Component = Control->Components[Index];
  516. TControl * ChildControl = dynamic_cast<TControl *>(Component);
  517. if (ChildControl != NULL)
  518. {
  519. ChangeControlScale(ChildControl, M, D);
  520. }
  521. TRescaleComponent * RescaleComponent =
  522. dynamic_cast<TRescaleComponent *>(Component->FindComponent(TRescaleComponent::QualifiedClassName()));
  523. if (RescaleComponent != NULL)
  524. {
  525. RescaleComponent->OnRescale(Component, RescaleComponent->Token);
  526. }
  527. }
  528. Control->Perform(CM_DPICHANGED, M, D);
  529. }
  530. //---------------------------------------------------------------------------
  531. typedef std::pair<int, int> TRatio;
  532. typedef std::map<TRatio, TRatio > TRatioMap;
  533. //---------------------------------------------------------------------------
  534. class TFormRescaleComponent : public TComponent
  535. {
  536. public:
  537. __fastcall TFormRescaleComponent() :
  538. TComponent(NULL)
  539. {
  540. ImplicitRescaleAdded = false;
  541. Rescaling = false;
  542. }
  543. bool Rescaling;
  544. bool ImplicitRescaleAdded;
  545. TRatioMap RatioMap;
  546. };
  547. //---------------------------------------------------------------------------
  548. static TFormRescaleComponent * GetFormRescaleComponent(TForm * Form)
  549. {
  550. TFormRescaleComponent * FormRescaleComponent =
  551. dynamic_cast<TFormRescaleComponent *>(Form->FindComponent(TFormRescaleComponent::QualifiedClassName()));
  552. if (FormRescaleComponent == NULL)
  553. {
  554. FormRescaleComponent = new TFormRescaleComponent();
  555. FormRescaleComponent->Name = TFormRescaleComponent::QualifiedClassName();
  556. Form->InsertComponent(FormRescaleComponent);
  557. }
  558. return FormRescaleComponent;
  559. }
  560. //---------------------------------------------------------------------------
  561. void __fastcall RecordFormImplicitRescale(TForm * Form)
  562. {
  563. if (Form->Scaled)
  564. {
  565. TFormRescaleComponent * FormRescaleComponent = GetFormRescaleComponent(Form);
  566. if (!FormRescaleComponent->ImplicitRescaleAdded)
  567. {
  568. TRatio Ratio;
  569. GetFormScaleRatio(Form, Ratio.first, Ratio.second);
  570. TRatio RescaleKeyRatio(Form->PixelsPerInch, USER_DEFAULT_SCREEN_DPI);
  571. FormRescaleComponent->RatioMap[RescaleKeyRatio] = Ratio;
  572. FormRescaleComponent->ImplicitRescaleAdded = true;
  573. }
  574. }
  575. }
  576. //---------------------------------------------------------------------------
  577. static void GetFormRescaleRatio(TForm * Form, int PixelsPerInch, int & M, int & D)
  578. {
  579. TFormRescaleComponent * FormRescaleComponent = GetFormRescaleComponent(Form);
  580. TRatio ReverseRescaleKeyRatio(Form->PixelsPerInch, PixelsPerInch);
  581. if (FormRescaleComponent->RatioMap.count(ReverseRescaleKeyRatio) > 0)
  582. {
  583. M = FormRescaleComponent->RatioMap[ReverseRescaleKeyRatio].second;
  584. D = FormRescaleComponent->RatioMap[ReverseRescaleKeyRatio].first;
  585. }
  586. else
  587. {
  588. M = GetTextHeightAtPixelsPerInch(Form, PixelsPerInch);
  589. D = GetTextHeightAtPixelsPerInch(Form, Form->PixelsPerInch);
  590. }
  591. TRatio RescaleKeyRatio(PixelsPerInch, Form->PixelsPerInch);
  592. FormRescaleComponent->RatioMap[RescaleKeyRatio] = TRatio(M, D);
  593. }
  594. //---------------------------------------------------------------------------
  595. static void __fastcall ChangeFormPixelsPerInch(TForm * Form, int PixelsPerInch)
  596. {
  597. RecordFormImplicitRescale(Form);
  598. TFormRescaleComponent * FormRescaleComponent = GetFormRescaleComponent(Form);
  599. if ((Form->PixelsPerInch != PixelsPerInch) && // optimization
  600. !FormRescaleComponent->Rescaling)
  601. {
  602. TAutoFlag RescalingFlag(FormRescaleComponent->Rescaling);
  603. int M, D;
  604. GetFormRescaleRatio(Form, PixelsPerInch, M, D);
  605. Form->PixelsPerInch = PixelsPerInch;
  606. TPublicForm * PublicCustomForm = static_cast<TPublicForm *>(Form);
  607. // WORKAROUND
  608. // TCustomForm.ChangeScale scales contraints only after rescaling the size,
  609. // so the unscaled constraints apply to the new size
  610. // (e.g. with TLoginDialog)
  611. std::unique_ptr<TSizeConstraints> Constraints(new TSizeConstraints(NULL));
  612. Constraints->Assign(PublicCustomForm->Constraints);
  613. std::unique_ptr<TSizeConstraints> NoConstraints(new TSizeConstraints(NULL));
  614. PublicCustomForm->Constraints = NoConstraints.get();
  615. // Does not seem to have any effect
  616. PublicCustomForm->DisableAlign();
  617. try
  618. {
  619. int PrevFontHeight = Form->Font->Height;
  620. PublicCustomForm->ChangeScale(M, D);
  621. // Re-rescale by Height as it has higher granularity, hence lower risk of loosing precision due to rounding
  622. Form->Font->Height = MulDiv(PrevFontHeight, M, D);
  623. ChangeControlScale(Form, M, D);
  624. Constraints->MinWidth = MulDiv(Constraints->MinWidth, M, D);
  625. Constraints->MaxWidth = MulDiv(Constraints->MaxWidth, M, D);
  626. Constraints->MinHeight = MulDiv(Constraints->MinHeight, M, D);
  627. Constraints->MaxHeight = MulDiv(Constraints->MaxHeight, M, D);
  628. PublicCustomForm->Constraints = Constraints.get();
  629. }
  630. __finally
  631. {
  632. PublicCustomForm->EnableAlign();
  633. }
  634. }
  635. }
  636. //---------------------------------------------------------------------------
  637. static void __fastcall FormShowingChanged(TForm * Form, TWndMethod WndProc, TMessage & Message)
  638. {
  639. if (IsMainFormLike(Form))
  640. {
  641. if (Form->Showing)
  642. {
  643. if (Application->MainForm != Form)
  644. {
  645. MainLikeForm = Form;
  646. // When main form is hidden, no taskbar button for it is shown and
  647. // this window does not become main window, so there won't be no taskbar
  648. // icon created automatically (by VCL). So we force it manually here.
  649. // This particularly happen for all windows/dialogs of command-line
  650. // operations (e.g. /synchronize) after CreateScpExplorer() happens.
  651. // Also CM_SHOWINGCHANGED happens twice, and the WS_EX_APPWINDOW flag
  652. // from the first call is not preserved, re-applying on the second call too.
  653. // TODO: What about minimize to tray?
  654. int Style = GetWindowLong(Form->Handle, GWL_EXSTYLE);
  655. if (FLAGCLEAR(Style, WS_EX_APPWINDOW))
  656. {
  657. Style |= WS_EX_APPWINDOW;
  658. SetWindowLong(Form->Handle, GWL_EXSTYLE, Style);
  659. }
  660. }
  661. if (Form->Perform(WM_MANAGES_CAPTION, 0, 0) == 0)
  662. {
  663. Form->Caption = FormatFormCaption(Form, Form->Caption);
  664. }
  665. SendMessage(Form->Handle, WM_SETICON, ICON_BIG, reinterpret_cast<long>(Application->Icon->Handle));
  666. }
  667. else
  668. {
  669. if (MainLikeForm == Form)
  670. {
  671. // Do not bother with hiding the WS_EX_APPWINDOW flag
  672. // as the window is closing anyway.
  673. MainLikeForm = NULL;
  674. }
  675. }
  676. }
  677. // Part of following code (but actually not all, TODO), has to happen
  678. // for all windows when VCL main window is hidden (particularly the last branch).
  679. // This is different from above brach, that should happen only for top-level visible window.
  680. if ((Application->MainForm == Form) ||
  681. // this particularly happens if error occurs while main
  682. // window is being shown (e.g. non existent local directory when opening
  683. // explorer)
  684. ((Application->MainForm != NULL) && !Application->MainForm->Visible))
  685. {
  686. if (!Form->Showing)
  687. {
  688. // when closing main form, remember its monitor,
  689. // so that the next form is shown on the same one
  690. LastMonitor = Form->Monitor;
  691. }
  692. else if ((LastMonitor != NULL) && (LastMonitor != Form->Monitor) &&
  693. Form->Showing)
  694. {
  695. // would actually always be poScreenCenter, see _SafeFormCreate
  696. if ((Form->Position == poMainFormCenter) ||
  697. (Form->Position == poOwnerFormCenter) ||
  698. (Form->Position == poScreenCenter))
  699. {
  700. // this would typically be a standalone message box (e.g. /UninstallCleanup or /Update)
  701. // If DPI changes (as the form moves to a monitor with a non-system DPI),
  702. // we have to re-center as the form size changed too.
  703. int PixelsPerInch;
  704. do
  705. {
  706. PixelsPerInch = Form->PixelsPerInch;
  707. // taken from TCustomForm::SetWindowToMonitor
  708. Form->SetBounds(LastMonitor->Left + ((LastMonitor->Width - Form->Width) / 2),
  709. LastMonitor->Top + ((LastMonitor->Height - Form->Height) / 2),
  710. Form->Width, Form->Height);
  711. Form->Position = poDesigned;
  712. }
  713. while (PixelsPerInch != Form->PixelsPerInch);
  714. }
  715. else if ((Form->Position != poDesigned) &&
  716. (Form->Position != poDefaultPosOnly))
  717. {
  718. // we do not expect any other positioning
  719. DebugFail();
  720. }
  721. }
  722. // otherwise it would not get centered
  723. else if ((Form->Position == poMainFormCenter) ||
  724. (Form->Position == poOwnerFormCenter))
  725. {
  726. Form->Position = poScreenCenter;
  727. }
  728. }
  729. if (Form->Showing)
  730. {
  731. // At least on single monitor setup, monitor DPI is 100% but system DPI is higher,
  732. // WM_DPICHANGED is not sent. But VCL scales the form using system DPI.
  733. // Also we have to do this always for implicitly placed forms (poDefaultPosOnly), like TEditorForm,
  734. // as thay never get the WM_DPICHANGED.
  735. // Call this before WndProc below, i.e. before OnShow event (particularly important for the TEditorForm::FormShow.
  736. // GetControlPixelsPerInch would return Form.PixelsPerInch, but we want to get a new DPI of the form monitor.
  737. ChangeFormPixelsPerInch(Form, GetMonitorPixelsPerInch(GetMonitorFromControl(Form)));
  738. }
  739. bool WasFormCenter =
  740. (Form->Position == poMainFormCenter) ||
  741. (Form->Position == poOwnerFormCenter);
  742. WndProc(Message);
  743. // Make sure dialogs are shown on-screen even if center of the main window
  744. // is off-screen. Occurs e.g. if you move the main window so that
  745. // only window title is visible above taksbar.
  746. if (Form->Showing && WasFormCenter && (Form->Position == poDesigned))
  747. {
  748. TRect Rect;
  749. // Reading Form.Left/Form.Top instead here does not work, likely due to some
  750. // bug, when querying TProgressForm opened from TEditorForm (reloading remote file)
  751. GetWindowRect(Form->Handle, &Rect);
  752. int Left = Rect.Left;
  753. int Top = Rect.Top;
  754. TRect WorkArea = Form->Monitor->WorkareaRect;
  755. if (Left + Rect.Width() > WorkArea.Right)
  756. {
  757. Left = WorkArea.Right - Rect.Width();
  758. }
  759. if (Left < WorkArea.Left)
  760. {
  761. Left = WorkArea.Left;
  762. }
  763. if (Top + Rect.Height() > WorkArea.Bottom)
  764. {
  765. Top = WorkArea.Bottom - Rect.Height();
  766. }
  767. if (Top < WorkArea.Top)
  768. {
  769. Top = WorkArea.Top;
  770. }
  771. if ((Left != Rect.Left) ||
  772. (Top != Rect.Top))
  773. {
  774. SetWindowPos(Form->Handle, 0, Left, Top, Rect.Width(), Rect.Height(),
  775. SWP_NOZORDER + SWP_NOACTIVATE);
  776. }
  777. }
  778. }
  779. //---------------------------------------------------------------------------
  780. inline void __fastcall DoFormWindowProc(TCustomForm * Form, TWndMethod WndProc,
  781. TMessage & Message)
  782. {
  783. TForm * AForm = dynamic_cast<TForm *>(Form);
  784. DebugAssert(AForm != NULL);
  785. if ((Message.Msg == WM_SYSCOMMAND) &&
  786. (Message.WParam == SC_CONTEXTHELP))
  787. {
  788. FormHelp(Form);
  789. Message.Result = 1;
  790. }
  791. else if (Message.Msg == CM_SHOWINGCHANGED)
  792. {
  793. FormShowingChanged(AForm, WndProc, Message);
  794. }
  795. else if (Message.Msg == WM_SETICON)
  796. {
  797. // WORKAROUND: Swallow VCL attempt to clear the icon from TCustomForm.WMDestroy.
  798. // The clearing still happens to be visualised before the form is hidden.
  799. // On resizable forms, the icon gets replaced by the default application icon,
  800. // on the other forms, the icon disappears and window caption is shifted left.
  801. if (Message.LParam != 0)
  802. {
  803. WndProc(Message);
  804. }
  805. }
  806. else if (Message.Msg == WM_GETDPISCALEDSIZE)
  807. {
  808. WndProc(Message);
  809. int M, D;
  810. GetFormRescaleRatio(AForm, LOWORD(Message.WParam), M, D);
  811. SIZE & Size = *(reinterpret_cast<SIZE *>(Message.LParam));
  812. Size.cx = MulDiv(Size.cx, M, D);
  813. Size.cy = MulDiv(Size.cy, M, D);
  814. Message.Result = TRUE;
  815. }
  816. else if (Message.Msg == WM_DPICHANGED)
  817. {
  818. ChangeFormPixelsPerInch(AForm, LOWORD(Message.WParam));
  819. WndProc(Message);
  820. }
  821. else
  822. {
  823. WndProc(Message);
  824. }
  825. }
  826. //---------------------------------------------------------------------------
  827. static void __fastcall FormWindowProc(void * Data, TMessage & Message)
  828. {
  829. TCustomForm * Form = static_cast<TCustomForm *>(Data);
  830. DoFormWindowProc(Form, ControlWndProc(Form), Message);
  831. }
  832. //---------------------------------------------------------------------------
  833. void __fastcall InitializeSystemSettings()
  834. {
  835. }
  836. //---------------------------------------------------------------------------
  837. void __fastcall FinalizeSystemSettings()
  838. {
  839. }
  840. //---------------------------------------------------------------------------
  841. #ifdef _DEBUG
  842. void __fastcall VerifyControl(TControl * Control)
  843. {
  844. // If at this time the control has allocated persistence data that are used
  845. // for delayed handle recreation, we are at potential risk, as the future
  846. // de-persistence may overwrite meanwhile changed data.
  847. // For instance it may happen with list view that DPI scaling gets lost.
  848. // This for example happens when the list view has both design time
  849. // ReadOnly = true and some items set. We cannot usually explicitly
  850. // check for the presence of items as while the listview does not have
  851. // a handle allocated, item count querying does not work
  852. // (see also a check below)
  853. if (ControlHasRecreationPersistenceData(Control))
  854. {
  855. // Though if RTL bidi mode is set, the controls are recreated always,
  856. // as we cannot really prevent it. So we force creation here.
  857. DebugAssert(Application->BiDiMode != bdLeftToRight);
  858. TWinControl * WinControl = dynamic_cast<TWinControl *>(Control);
  859. // It must be TWinControl if ControlHasRecreationPersistenceData returned true
  860. if (DebugAlwaysTrue(WinControl != NULL))
  861. {
  862. WinControl->HandleNeeded();
  863. }
  864. }
  865. TCustomListView * ListView = dynamic_cast<TCustomListView *>(Control);
  866. if (ListView != NULL)
  867. {
  868. // As of now the HandleAllocated check is pointless as
  869. // ListView->Items->Count returns 0 when the handle is not allocated yet.
  870. // But we want to know if the implementation ever changes to allocate the handle
  871. // on the call. Because we do not want to allocate a handle here as
  872. // that would change the debug mode behavior from release behavior,
  873. // possibly hiding away some problems.
  874. DebugAssert(!ListView->HandleAllocated() || (ListView->Items->Count == 0));
  875. }
  876. }
  877. #endif
  878. //---------------------------------------------------------------------------
  879. void __fastcall ApplySystemSettingsOnControl(TControl * Control)
  880. {
  881. #ifdef _DEBUG
  882. VerifyControl(Control);
  883. #endif
  884. // WORKAROUND
  885. // VCL does not scale status par panels (while for instance it does
  886. // scale list view headers). Remove this if they ever "fix" this.
  887. // Neither they scale the status bar size if UseSystemFont is true.
  888. // they claim it should scale with font size, but it does not,
  889. // probably because they eat WM_SIZE in TCustomStatusBar.WMSize.
  890. // (used to be issue 83599 on Embarcadero QC, when it was still online)
  891. // Check TCustomStatusBar.ChangeScale() for changes.
  892. // For TBX status bars, this is implemented in TTBXCustomStatusBar.ChangeScale
  893. TStatusBar * StatusBar = dynamic_cast<TStatusBar *>(Control);
  894. if (StatusBar != NULL)
  895. {
  896. // We should have UseSystemFont and bottom alignment set for all status bars.
  897. if (DebugAlwaysTrue(StatusBar->UseSystemFont) &&
  898. DebugAlwaysTrue(StatusBar->Align == alBottom))
  899. {
  900. StatusBar->Height = ScaleByTextHeight(StatusBar, StatusBar->Height);
  901. }
  902. for (int Index = 0; Index < StatusBar->Panels->Count; Index++)
  903. {
  904. TStatusPanel * Panel = StatusBar->Panels->Items[Index];
  905. Panel->Width = ScaleByTextHeight(StatusBar, Panel->Width);
  906. }
  907. }
  908. TCustomListView * ListView = dynamic_cast<TCustomListView *>(Control);
  909. TCustomIEListView * IEListView = dynamic_cast<TCustomIEListView *>(Control);
  910. // For IEListView, this is (somewhat) handled in the TCustomListViewColProperties
  911. if ((ListView != NULL) && (IEListView == NULL))
  912. {
  913. TListView * PublicListView = reinterpret_cast<TListView *>(ListView);
  914. for (int Index = 0; Index < PublicListView->Columns->Count; Index++)
  915. {
  916. TListColumn * Column = ListView->Column[Index];
  917. Column->MaxWidth = ScaleByTextHeight(ListView, Column->MaxWidth);
  918. Column->MinWidth = ScaleByTextHeight(ListView, Column->MinWidth);
  919. }
  920. }
  921. // WORKAROUND for lack of public API for mimicking Explorer-style mouse selection
  922. // See https://stackoverflow.com/q/15750842/850848
  923. if (IEListView != NULL)
  924. {
  925. // It should not be a problem to call the LVM_QUERYINTERFACE
  926. // on earlier versions of Windows. It should be noop.
  927. if (IsWin7())
  928. {
  929. IListView_Win7 * ListViewIntf = NULL;
  930. SendMessage(IEListView->Handle, LVM_QUERYINTERFACE, reinterpret_cast<WPARAM>(&IID_IListView_Win7), reinterpret_cast<LPARAM>(&ListViewIntf));
  931. if (DebugAlwaysTrue(ListViewIntf != NULL))
  932. {
  933. ListViewIntf->SetSelectionFlags(1, 1);
  934. ListViewIntf->Release();
  935. }
  936. }
  937. }
  938. TWinControl * WinControl = dynamic_cast<TWinControl *>(Control);
  939. if (WinControl != NULL)
  940. {
  941. for (int Index = 0; Index < WinControl->ControlCount; Index++)
  942. {
  943. ApplySystemSettingsOnControl(WinControl->Controls[Index]);
  944. }
  945. }
  946. }
  947. //---------------------------------------------------------------------------
  948. // Settings that must be set as soon as possible.
  949. void __fastcall UseSystemSettingsPre(TCustomForm * Control)
  950. {
  951. LocalSystemSettings(Control);
  952. TWndMethod WindowProc;
  953. ((TMethod*)&WindowProc)->Data = Control;
  954. ((TMethod*)&WindowProc)->Code = FormWindowProc;
  955. Control->WindowProc = WindowProc;
  956. if (Control->HelpKeyword.IsEmpty())
  957. {
  958. // temporary help keyword to enable F1 key in all forms
  959. Control->HelpKeyword = L"start";
  960. }
  961. ApplySystemSettingsOnControl(Control);
  962. };
  963. //---------------------------------------------------------------------------
  964. static void FlipAnchors(TControl * Control)
  965. {
  966. // WORKAROUND VCL flips the Align, but not the Anchors
  967. TAnchors Anchors = Control->Anchors;
  968. if (Anchors.Contains(akLeft) != Anchors.Contains(akRight))
  969. {
  970. if (Anchors.Contains(akLeft))
  971. {
  972. Anchors << akRight;
  973. Anchors >> akLeft;
  974. }
  975. else
  976. {
  977. Anchors << akLeft;
  978. Anchors >> akRight;
  979. }
  980. }
  981. Control->Anchors = Anchors;
  982. TWinControl * WinControl = dynamic_cast<TWinControl *>(Control);
  983. if (WinControl != NULL)
  984. {
  985. for (int Index = 0; Index < WinControl->ControlCount; Index++)
  986. {
  987. FlipAnchors(WinControl->Controls[Index]);
  988. }
  989. }
  990. }
  991. //---------------------------------------------------------------------------
  992. // Settings that must be set only after whole form is constructed
  993. void __fastcall UseSystemSettingsPost(TCustomForm * Control)
  994. {
  995. // When showing an early error message
  996. if (WinConfiguration != NULL)
  997. {
  998. UnicodeString FlipStr = LoadStr(FLIP_CHILDREN);
  999. int FlipChildrenFlag =
  1000. AdjustLocaleFlag(FlipStr, WinConfiguration->FlipChildrenOverride, false, true, false);
  1001. if (static_cast<bool>(FlipChildrenFlag))
  1002. {
  1003. Control->FlipChildren(true);
  1004. FlipAnchors(Control);
  1005. }
  1006. }
  1007. ResetSystemSettings(Control);
  1008. };
  1009. //---------------------------------------------------------------------------
  1010. void __fastcall UseSystemSettings(TCustomForm * Control)
  1011. {
  1012. UseSystemSettingsPre(Control);
  1013. UseSystemSettingsPost(Control);
  1014. };
  1015. //---------------------------------------------------------------------------
  1016. void __fastcall ResetSystemSettings(TCustomForm * /*Control*/)
  1017. {
  1018. // noop
  1019. }
  1020. //---------------------------------------------------------------------------
  1021. struct TShowAsModalStorage
  1022. {
  1023. void * FocusWindowList;
  1024. HWND FocusActiveWindow;
  1025. TFocusState FocusState;
  1026. TCursor SaveCursor;
  1027. int SaveCount;
  1028. };
  1029. //---------------------------------------------------------------------------
  1030. void __fastcall ShowAsModal(TForm * Form, void *& Storage, bool BringToFront)
  1031. {
  1032. SetCorrectFormParent(Form);
  1033. CancelDrag();
  1034. if (GetCapture() != 0) SendMessage(GetCapture(), WM_CANCELMODE, 0, 0);
  1035. ReleaseCapture();
  1036. (static_cast<TPublicForm*>(Form))->FFormState << fsModal;
  1037. TShowAsModalStorage * AStorage = new TShowAsModalStorage;
  1038. AStorage->FocusActiveWindow = GetActiveWindow();
  1039. AStorage->FocusState = SaveFocusState();
  1040. Screen->SaveFocusedList->Insert(0, Screen->FocusedForm);
  1041. Screen->FocusedForm = Form;
  1042. AStorage->SaveCursor = Screen->Cursor;
  1043. // This is particularly used when displaing progress window
  1044. // while downloading via temporary folder
  1045. // (the mouse cursor is yet hidden at this point).
  1046. // While the code was added to workaround the above problem,
  1047. // it is taken from TCustomForm.ShowModal and
  1048. // should have been here ever since.
  1049. Screen->Cursor = crDefault;
  1050. AStorage->SaveCount = Screen->CursorCount;
  1051. AStorage->FocusWindowList = DisableTaskWindows(0);
  1052. // VCLCOPY (TCustomForm::Show)
  1053. Form->Visible = true;
  1054. if (BringToFront)
  1055. {
  1056. Form->BringToFront();
  1057. }
  1058. SendMessage(Form->Handle, CM_ACTIVATE, 0, 0);
  1059. Storage = AStorage;
  1060. }
  1061. //---------------------------------------------------------------------------
  1062. void __fastcall HideAsModal(TForm * Form, void *& Storage)
  1063. {
  1064. DebugAssert((static_cast<TPublicForm*>(Form))->FFormState.Contains(fsModal));
  1065. TShowAsModalStorage * AStorage = static_cast<TShowAsModalStorage *>(Storage);
  1066. Storage = NULL;
  1067. SendMessage(Form->Handle, CM_DEACTIVATE, 0, 0);
  1068. if (GetActiveWindow() != Form->Handle)
  1069. {
  1070. AStorage->FocusActiveWindow = 0;
  1071. }
  1072. Form->Hide();
  1073. if (Screen->CursorCount == AStorage->SaveCount)
  1074. {
  1075. Screen->Cursor = AStorage->SaveCursor;
  1076. }
  1077. else
  1078. {
  1079. Screen->Cursor = crDefault;
  1080. }
  1081. EnableTaskWindows(AStorage->FocusWindowList);
  1082. if (Screen->SaveFocusedList->Count > 0)
  1083. {
  1084. Screen->FocusedForm = static_cast<TCustomForm *>(Screen->SaveFocusedList->First());
  1085. Screen->SaveFocusedList->Remove(Screen->FocusedForm);
  1086. }
  1087. else
  1088. {
  1089. Screen->FocusedForm = NULL;
  1090. }
  1091. if (AStorage->FocusActiveWindow != 0)
  1092. {
  1093. SetActiveWindow(AStorage->FocusActiveWindow);
  1094. }
  1095. RestoreFocusState(AStorage->FocusState);
  1096. (static_cast<TPublicForm*>(Form))->FFormState >> fsModal;
  1097. delete AStorage;
  1098. }
  1099. //---------------------------------------------------------------------------
  1100. bool __fastcall ReleaseAsModal(TForm * Form, void *& Storage)
  1101. {
  1102. bool Result = (Storage != NULL);
  1103. if (Result)
  1104. {
  1105. HideAsModal(Form, Storage);
  1106. }
  1107. return Result;
  1108. }
  1109. //---------------------------------------------------------------------------
  1110. bool __fastcall SelectDirectory(UnicodeString & Path, const UnicodeString Prompt,
  1111. bool PreserveFileName)
  1112. {
  1113. bool Result;
  1114. unsigned int ErrorMode;
  1115. ErrorMode = SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);
  1116. try
  1117. {
  1118. UnicodeString Directory;
  1119. UnicodeString FileName;
  1120. if (!PreserveFileName || DirectoryExists(ApiPath(Path)))
  1121. {
  1122. Directory = Path;
  1123. }
  1124. else
  1125. {
  1126. Directory = ExtractFilePath(Path);
  1127. FileName = ExtractFileName(Path);
  1128. }
  1129. Result = SelectDirectory(Prompt, L"", Directory);
  1130. if (Result)
  1131. {
  1132. Path = Directory;
  1133. if (!FileName.IsEmpty())
  1134. {
  1135. Path = IncludeTrailingBackslash(Path) + FileName;
  1136. }
  1137. }
  1138. }
  1139. __finally
  1140. {
  1141. SetErrorMode(ErrorMode);
  1142. }
  1143. return Result;
  1144. }
  1145. //---------------------------------------------------------------------------
  1146. bool __fastcall ListViewAnyChecked(TListView * ListView, bool Checked)
  1147. {
  1148. bool AnyChecked = false;
  1149. for (int Index = 0; Index < ListView->Items->Count; Index++)
  1150. {
  1151. if (ListView->Items->Item[Index]->Checked == Checked)
  1152. {
  1153. AnyChecked = true;
  1154. break;
  1155. }
  1156. }
  1157. return AnyChecked;
  1158. }
  1159. //---------------------------------------------------------------------------
  1160. void __fastcall ListViewCheckAll(TListView * ListView,
  1161. TListViewCheckAll CheckAll)
  1162. {
  1163. bool Check;
  1164. if (CheckAll == caToggle)
  1165. {
  1166. Check = ListViewAnyChecked(ListView, false);
  1167. }
  1168. else
  1169. {
  1170. Check = (CheckAll == caCheck);
  1171. }
  1172. for (int Index = 0; Index < ListView->Items->Count; Index++)
  1173. {
  1174. ListView->Items->Item[Index]->Checked = Check;
  1175. }
  1176. }
  1177. //---------------------------------------------------------------------------
  1178. void __fastcall ComboAutoSwitchInitialize(TComboBox * ComboBox)
  1179. {
  1180. int PrevIndex = ComboBox->ItemIndex;
  1181. ComboBox->Items->BeginUpdate();
  1182. try
  1183. {
  1184. ComboBox->Clear();
  1185. ComboBox->Items->Add(LoadStr(AUTO_SWITCH_AUTO));
  1186. ComboBox->Items->Add(LoadStr(AUTO_SWITCH_OFF));
  1187. ComboBox->Items->Add(LoadStr(AUTO_SWITCH_ON));
  1188. }
  1189. __finally
  1190. {
  1191. ComboBox->Items->EndUpdate();
  1192. }
  1193. DebugAssert(PrevIndex < ComboBox->Items->Count);
  1194. ComboBox->ItemIndex = PrevIndex;
  1195. }
  1196. //---------------------------------------------------------------------------
  1197. void __fastcall ComboAutoSwitchLoad(TComboBox * ComboBox, TAutoSwitch Value)
  1198. {
  1199. ComboBox->ItemIndex = 2 - Value;
  1200. if (ComboBox->ItemIndex < 0)
  1201. {
  1202. ComboBox->ItemIndex = 0;
  1203. }
  1204. }
  1205. //---------------------------------------------------------------------------
  1206. TAutoSwitch __fastcall ComboAutoSwitchSave(TComboBox * ComboBox)
  1207. {
  1208. return (TAutoSwitch)(2 - ComboBox->ItemIndex);
  1209. }
  1210. //---------------------------------------------------------------------------
  1211. void __fastcall CheckBoxAutoSwitchLoad(TCheckBox * CheckBox, TAutoSwitch Value)
  1212. {
  1213. switch (Value)
  1214. {
  1215. case asOn:
  1216. CheckBox->State = cbChecked;
  1217. break;
  1218. case asOff:
  1219. CheckBox->State = cbUnchecked;
  1220. break;
  1221. default:
  1222. CheckBox->State = cbGrayed;
  1223. break;
  1224. }
  1225. }
  1226. //---------------------------------------------------------------------------
  1227. TAutoSwitch __fastcall CheckBoxAutoSwitchSave(TCheckBox * CheckBox)
  1228. {
  1229. switch (CheckBox->State)
  1230. {
  1231. case cbChecked:
  1232. return asOn;
  1233. case cbUnchecked:
  1234. return asOff;
  1235. default:
  1236. return asAuto;
  1237. }
  1238. }
  1239. //---------------------------------------------------------------------------
  1240. static const wchar_t PathWordDelimiters[] = L"\\/ ;,.";
  1241. //---------------------------------------------------------------------------
  1242. static bool IsPathWordDelimiter(wchar_t Ch)
  1243. {
  1244. return (wcschr(PathWordDelimiters, Ch) != NULL);
  1245. }
  1246. //---------------------------------------------------------------------------
  1247. // Windows algorithm is as follows (tested on W2k):
  1248. // right:
  1249. // is_delimiter(current)
  1250. // false:
  1251. // right(left(current) + 1)
  1252. // true:
  1253. // right(right(current) + 1)
  1254. // left:
  1255. // right(left(current) + 1)
  1256. int CALLBACK PathWordBreakProc(wchar_t * Ch, int Current, int Len, int Code)
  1257. {
  1258. int Result;
  1259. UnicodeString ACh(Ch, Len);
  1260. if (Code == WB_ISDELIMITER)
  1261. {
  1262. // we return negacy of what WinAPI docs says
  1263. Result = !IsPathWordDelimiter(ACh[Current + 1]);
  1264. }
  1265. else if (Code == WB_LEFT)
  1266. {
  1267. // skip consecutive delimiters
  1268. while ((Current > 0) &&
  1269. IsPathWordDelimiter(ACh[Current]))
  1270. {
  1271. Current--;
  1272. }
  1273. Result = ACh.SubString(1, Current - 1).LastDelimiter(PathWordDelimiters);
  1274. }
  1275. else if (Code == WB_RIGHT)
  1276. {
  1277. if (Current == 0)
  1278. {
  1279. // will be called again with Current == 1
  1280. Result = 0;
  1281. }
  1282. else
  1283. {
  1284. const wchar_t * P = wcspbrk(ACh.c_str() + Current - 1, PathWordDelimiters);
  1285. if (P == NULL)
  1286. {
  1287. Result = Len;
  1288. }
  1289. else
  1290. {
  1291. Result = P - ACh.c_str() + 1;
  1292. // skip consecutive delimiters
  1293. while ((Result < Len) &&
  1294. IsPathWordDelimiter(ACh[Result + 1]))
  1295. {
  1296. Result++;
  1297. }
  1298. }
  1299. }
  1300. }
  1301. else
  1302. {
  1303. DebugFail();
  1304. Result = 0;
  1305. }
  1306. return Result;
  1307. }
  1308. //---------------------------------------------------------------------------
  1309. static void __fastcall PathEditKeyPress(void * /*Data*/, TObject * Sender, char & Key)
  1310. {
  1311. // Ctrl+Backspace
  1312. // Have to use OnKeyPress as the Ctrl+Backspace is handled in WM_CHAR as any other char,
  1313. // so we have to swallow it here to prevent it getting inserted to the text
  1314. if (Key == '\x7F')
  1315. {
  1316. Key = '\0';
  1317. TCustomEdit * Edit = dynamic_cast<TCustomEdit *>(Sender);
  1318. TCustomComboBox * ComboBox = dynamic_cast<TCustomComboBox *>(Sender);
  1319. TWinControl * WinControl = DebugNotNull(dynamic_cast<TWinControl *>(Sender));
  1320. if (((Edit != NULL) && (Edit->SelLength == 0)) ||
  1321. ((ComboBox != NULL) && (ComboBox->SelLength == 0)))
  1322. {
  1323. // See TCustomMaskEdit.SetCursor
  1324. TKeyboardState KeyState;
  1325. GetKeyboardState(KeyState);
  1326. TKeyboardState NewKeyState;
  1327. memset(NewKeyState, 0, sizeof(NewKeyState));
  1328. NewKeyState[VK_CONTROL] = 0x81;
  1329. NewKeyState[VK_SHIFT] = 0x81;
  1330. SetKeyboardState(NewKeyState);
  1331. SendMessage(WinControl->Handle, WM_KEYDOWN, VK_LEFT, 1);
  1332. NewKeyState[VK_SHIFT] = 0;
  1333. NewKeyState[VK_CONTROL] = 0;
  1334. SetKeyboardState(NewKeyState);
  1335. SendMessage(WinControl->Handle, WM_KEYDOWN, VK_DELETE, 1);
  1336. SetKeyboardState(KeyState);
  1337. }
  1338. }
  1339. }
  1340. //---------------------------------------------------------------------------
  1341. class TPublicCustomCombo : public TCustomCombo
  1342. {
  1343. friend void __fastcall InstallPathWordBreakProc(TWinControl * Control);
  1344. };
  1345. //---------------------------------------------------------------------------
  1346. void __fastcall InstallPathWordBreakProc(TWinControl * Control)
  1347. {
  1348. // Since we are setting Application->ModalPopupMode = pmAuto,
  1349. // this has to be called from OnShow, not from constructor anymore,
  1350. // to have any effect
  1351. HWND Wnd;
  1352. if (dynamic_cast<TCustomCombo*>(Control) != NULL)
  1353. {
  1354. TPublicCustomCombo * Combo =
  1355. static_cast<TPublicCustomCombo *>(dynamic_cast<TCustomCombo *>(Control));
  1356. Combo->HandleNeeded();
  1357. Wnd = Combo->EditHandle;
  1358. }
  1359. else
  1360. {
  1361. Wnd = Control->Handle;
  1362. }
  1363. SendMessage(Wnd, EM_SETWORDBREAKPROC, 0, (LPARAM)(EDITWORDBREAKPROC)PathWordBreakProc);
  1364. TPublicWinControl * PublicWinControl = static_cast<TPublicWinControl *>(Control);
  1365. if (DebugAlwaysTrue(PublicWinControl->OnKeyDown == NULL))
  1366. {
  1367. PublicWinControl->OnKeyPress = MakeMethod<TKeyPressEvent>(NULL, PathEditKeyPress);
  1368. }
  1369. }
  1370. //---------------------------------------------------------------------------
  1371. static void __fastcall RemoveHiddenControlsFromOrder(TControl ** ControlsOrder, int & Count)
  1372. {
  1373. int Shift = 0;
  1374. for (int Index = 0; Index < Count; Index++)
  1375. {
  1376. if (ControlsOrder[Index]->Visible)
  1377. {
  1378. ControlsOrder[Index - Shift] = ControlsOrder[Index];
  1379. }
  1380. else
  1381. {
  1382. Shift++;
  1383. }
  1384. }
  1385. Count -= Shift;
  1386. }
  1387. //---------------------------------------------------------------------------
  1388. void __fastcall SetVerticalControlsOrder(TControl ** ControlsOrder, int Count)
  1389. {
  1390. RemoveHiddenControlsFromOrder(ControlsOrder, Count);
  1391. if (Count > 0)
  1392. {
  1393. TWinControl * CommonParent = ControlsOrder[0]->Parent;
  1394. CommonParent->DisableAlign();
  1395. try
  1396. {
  1397. int Top = 0;
  1398. for (int Index = 0; Index < Count; Index++)
  1399. {
  1400. DebugAssert(ControlsOrder[Index]->Parent == CommonParent);
  1401. if ((Index == 0) || (Top > ControlsOrder[Index]->Top))
  1402. {
  1403. Top = ControlsOrder[Index]->Top;
  1404. }
  1405. }
  1406. for (int Index = 0; Index < Count; Index++)
  1407. {
  1408. TControl * Control = ControlsOrder[Index];
  1409. Control->Top = Top;
  1410. if (((Control->Align == alTop) || (Control->Align == alBottom)) ||
  1411. ((Index == Count - 1) || (ControlsOrder[Index + 1]->Align == alBottom)))
  1412. {
  1413. Top += Control->Height;
  1414. }
  1415. }
  1416. }
  1417. __finally
  1418. {
  1419. CommonParent->EnableAlign();
  1420. }
  1421. }
  1422. }
  1423. //---------------------------------------------------------------------------
  1424. void __fastcall SetHorizontalControlsOrder(TControl ** ControlsOrder, int Count)
  1425. {
  1426. RemoveHiddenControlsFromOrder(ControlsOrder, Count);
  1427. if (Count > 0)
  1428. {
  1429. TWinControl * CommonParent = ControlsOrder[0]->Parent;
  1430. CommonParent->DisableAlign();
  1431. try
  1432. {
  1433. int Left = 0;
  1434. for (int Index = 0; Index < Count; Index++)
  1435. {
  1436. DebugAssert(ControlsOrder[Index]->Parent == CommonParent);
  1437. if ((Index == 0) || (Left > ControlsOrder[Index]->Left))
  1438. {
  1439. Left = ControlsOrder[Index]->Left;
  1440. }
  1441. }
  1442. for (int Index = 0; Index < Count; Index++)
  1443. {
  1444. TControl * Control = ControlsOrder[Index];
  1445. Control->Left = Left;
  1446. if (((Control->Align == alLeft) || (Control->Align == alRight)) ||
  1447. ((Index == Count - 1) || (ControlsOrder[Index + 1]->Align == alRight)))
  1448. {
  1449. Left += Control->Width;
  1450. }
  1451. // vertical alignment has priority, so alBottom-aligned controls start
  1452. // at the very left, even if there are any alLeft/alRight controls.
  1453. // for the reason this code is not necessary in SetVerticalControlsOrder.
  1454. // we could exit the loop as well here.
  1455. if ((Index == Count - 1) || (ControlsOrder[Index + 1]->Align == alBottom))
  1456. {
  1457. Left = 0;
  1458. }
  1459. }
  1460. }
  1461. __finally
  1462. {
  1463. CommonParent->EnableAlign();
  1464. }
  1465. }
  1466. }
  1467. //---------------------------------------------------------------------------
  1468. void __fastcall MakeNextInTabOrder(TWinControl * Control, TWinControl * After)
  1469. {
  1470. if (After->TabOrder > Control->TabOrder)
  1471. {
  1472. After->TabOrder = Control->TabOrder;
  1473. }
  1474. else if (After->TabOrder < Control->TabOrder - 1)
  1475. {
  1476. After->TabOrder = static_cast<TTabOrder>(Control->TabOrder - 1);
  1477. }
  1478. }
  1479. //---------------------------------------------------------------------------
  1480. void __fastcall CutFormToDesktop(TForm * Form)
  1481. {
  1482. DebugAssert(Form->Monitor != NULL);
  1483. TRect Workarea = Form->Monitor->WorkareaRect;
  1484. if (Form->Top + Form->Height > Workarea.Bottom)
  1485. {
  1486. Form->Height = Workarea.Bottom - Form->Top;
  1487. }
  1488. if (Form->Left + Form->Width >= Workarea.Right)
  1489. {
  1490. Form->Width = Workarea.Right - Form->Left;
  1491. }
  1492. }
  1493. //---------------------------------------------------------------------------
  1494. void __fastcall UpdateFormPosition(TCustomForm * Form, TPosition Position)
  1495. {
  1496. if ((Position == poScreenCenter) ||
  1497. (Position == poOwnerFormCenter) ||
  1498. (Position == poMainFormCenter))
  1499. {
  1500. TCustomForm * CenterForm = NULL;
  1501. if ((Position == poOwnerFormCenter) ||
  1502. (Position == poMainFormCenter))
  1503. {
  1504. CenterForm = Application->MainForm;
  1505. if ((Position == poOwnerFormCenter) &&
  1506. (dynamic_cast<TCustomForm*>(Form->Owner) != NULL))
  1507. {
  1508. CenterForm = dynamic_cast<TCustomForm*>(Form->Owner);
  1509. }
  1510. }
  1511. TRect Bounds = Form->BoundsRect;
  1512. int X, Y;
  1513. if (CenterForm != NULL)
  1514. {
  1515. X = ((((TForm *)CenterForm)->Width - Bounds.Width()) / 2) +
  1516. ((TForm *)CenterForm)->Left;
  1517. Y = ((((TForm *)CenterForm)->Height - Bounds.Height()) / 2) +
  1518. ((TForm *)CenterForm)->Top;
  1519. }
  1520. else
  1521. {
  1522. X = (Form->Monitor->Width - Bounds.Width()) / 2;
  1523. Y = (Form->Monitor->Height - Bounds.Height()) / 2;
  1524. }
  1525. if (X < 0)
  1526. {
  1527. X = 0;
  1528. }
  1529. if (Y < 0)
  1530. {
  1531. Y = 0;
  1532. }
  1533. Form->SetBounds(X, Y, Bounds.Width(), Bounds.Height());
  1534. }
  1535. }
  1536. //---------------------------------------------------------------------------
  1537. void __fastcall ResizeForm(TCustomForm * Form, int Width, int Height)
  1538. {
  1539. // This has to be called only after DoFormWindowProc(CM_SHOWINGCHANGED),
  1540. // so that a correct monitor is considered.
  1541. // Note that we cannot use LastMonitor(), as ResizeForm is also called from
  1542. // TConsoleDialog::DoAdjustWindow, where we need to use the actual monitor
  1543. // (in case user moves the console window to a different monitor,
  1544. // than where a main window is [no matter how unlikely that is])
  1545. TRect WorkareaRect = Form->Monitor->WorkareaRect;
  1546. if (Height > WorkareaRect.Height())
  1547. {
  1548. Height = WorkareaRect.Height();
  1549. }
  1550. if (Width > WorkareaRect.Width())
  1551. {
  1552. Width = WorkareaRect.Width();
  1553. }
  1554. if (Height < Form->Constraints->MinHeight)
  1555. {
  1556. Height = Form->Constraints->MinHeight;
  1557. }
  1558. if (Width < Form->Constraints->MinWidth)
  1559. {
  1560. Width = Form->Constraints->MinWidth;
  1561. }
  1562. TRect Bounds = Form->BoundsRect;
  1563. int Top = Bounds.Top + ((Bounds.Height() - Height) / 2);
  1564. int Left = Bounds.Left + ((Bounds.Width() - Width) / 2);
  1565. if (Top + Height > WorkareaRect.Bottom)
  1566. {
  1567. Top = WorkareaRect.Bottom - Height;
  1568. }
  1569. if (Left + Width >= WorkareaRect.Right)
  1570. {
  1571. Left = WorkareaRect.Right - Width;
  1572. }
  1573. // WorkareaRect.Left is not 0, when secondary monitor is placed left of primary one.
  1574. // Similarly for WorkareaRect.Top.
  1575. if (Top < WorkareaRect.Top)
  1576. {
  1577. Top = WorkareaRect.Top;
  1578. }
  1579. if (Left < WorkareaRect.Left)
  1580. {
  1581. Left = WorkareaRect.Left;
  1582. }
  1583. Form->SetBounds(Left, Top, Width, Height);
  1584. Bounds = Form->BoundsRect;
  1585. // due to constraints, form can remain larger, make sure it is centered although
  1586. Left = Bounds.Left + ((Width - Bounds.Width()) / 2);
  1587. Top = Bounds.Top + ((Height - Bounds.Height()) / 2);
  1588. Form->SetBounds(Left, Top, Width, Height);
  1589. }
  1590. //---------------------------------------------------------------------------
  1591. TComponent * __fastcall GetFormOwner()
  1592. {
  1593. if (Screen->ActiveForm != NULL)
  1594. {
  1595. return Screen->ActiveForm;
  1596. }
  1597. else
  1598. {
  1599. return Application;
  1600. }
  1601. }
  1602. //---------------------------------------------------------------------------
  1603. void __fastcall SetCorrectFormParent(TForm * /*Form*/)
  1604. {
  1605. // noop
  1606. // remove
  1607. }
  1608. //---------------------------------------------------------------------------
  1609. void __fastcall InvokeHelp(TWinControl * Control)
  1610. {
  1611. DebugAssert(Control != NULL);
  1612. HELPINFO HelpInfo;
  1613. HelpInfo.cbSize = sizeof(HelpInfo);
  1614. HelpInfo.iContextType = HELPINFO_WINDOW;
  1615. HelpInfo.iCtrlId = 0;
  1616. HelpInfo.hItemHandle = Control->Handle;
  1617. HelpInfo.dwContextId = 0;
  1618. HelpInfo.MousePos.x = 0;
  1619. HelpInfo.MousePos.y = 0;
  1620. SendMessage(Control->Handle, WM_HELP, NULL, reinterpret_cast<long>(&HelpInfo));
  1621. }
  1622. //---------------------------------------------------------------------------
  1623. //---------------------------------------------------------------------------
  1624. static void __fastcall FocusableLabelCanvas(TStaticText * StaticText,
  1625. TControlCanvas ** ACanvas, TRect & R)
  1626. {
  1627. TControlCanvas * Canvas = new TControlCanvas();
  1628. try
  1629. {
  1630. Canvas->Control = StaticText;
  1631. Canvas->Font = StaticText->Font;
  1632. R = StaticText->ClientRect;
  1633. TSize TextSize;
  1634. if (StaticText->AutoSize)
  1635. {
  1636. // We possibly could use the same code as in !AutoSize branch,
  1637. // keeping this to avoid problems in existing code
  1638. UnicodeString Caption = StaticText->Caption;
  1639. bool AccelChar = false;
  1640. if (StaticText->ShowAccelChar)
  1641. {
  1642. Caption = StripHotkey(Caption);
  1643. AccelChar = (Caption != StaticText->Caption);
  1644. }
  1645. TextSize = Canvas->TextExtent(Caption);
  1646. DebugAssert(StaticText->BorderStyle == sbsNone); // not taken into account
  1647. if (AccelChar)
  1648. {
  1649. TextSize.cy += 2;
  1650. }
  1651. }
  1652. else
  1653. {
  1654. TRect TextRect;
  1655. SetRect(&TextRect, 0, 0, StaticText->Width, 0);
  1656. DrawText(Canvas->Handle, StaticText->Caption.c_str(), -1, &TextRect,
  1657. DT_CALCRECT | DT_WORDBREAK |
  1658. StaticText->DrawTextBiDiModeFlagsReadingOnly());
  1659. TextSize = TextRect.GetSize();
  1660. }
  1661. R.Bottom = R.Top + TextSize.cy;
  1662. // Should call ChangeBiDiModeAlignment when UseRightToLeftAlignment(),
  1663. // but the label seems to draw the text wrongly aligned, even though
  1664. // the alignment is correctly flipped in TCustomStaticText.CreateParams
  1665. switch (StaticText->Alignment)
  1666. {
  1667. case taLeftJustify:
  1668. R.Right = R.Left + TextSize.cx;
  1669. break;
  1670. case taRightJustify:
  1671. R.Left = Max(0, R.Right - TextSize.cx);
  1672. break;
  1673. case taCenter:
  1674. {
  1675. DebugFail(); // not used branch, possibly untested
  1676. int Diff = R.Width() - TextSize.cx;
  1677. R.Left += Diff / 2;
  1678. R.Right -= Diff - (Diff / 2);
  1679. }
  1680. break;
  1681. }
  1682. }
  1683. __finally
  1684. {
  1685. if (ACanvas == NULL)
  1686. {
  1687. delete Canvas;
  1688. }
  1689. }
  1690. if (ACanvas != NULL)
  1691. {
  1692. *ACanvas = Canvas;
  1693. }
  1694. }
  1695. //---------------------------------------------------------------------------
  1696. static void __fastcall FocusableLabelWindowProc(void * Data, TMessage & Message,
  1697. bool & Clicked)
  1698. {
  1699. Clicked = false;
  1700. TStaticText * StaticText = static_cast<TStaticText *>(Data);
  1701. if (Message.Msg == WM_LBUTTONDOWN)
  1702. {
  1703. StaticText->SetFocus();
  1704. // in case the action takes long, make sure focus is shown immediately
  1705. UpdateWindow(StaticText->Handle);
  1706. Clicked = true;
  1707. Message.Result = 1;
  1708. }
  1709. else if (Message.Msg == WM_RBUTTONDOWN)
  1710. {
  1711. StaticText->SetFocus();
  1712. Message.Result = 1;
  1713. }
  1714. else if (Message.Msg == WM_CHAR)
  1715. {
  1716. if (reinterpret_cast<TWMChar &>(Message).CharCode == L' ')
  1717. {
  1718. Clicked = true;
  1719. Message.Result = 1;
  1720. }
  1721. else
  1722. {
  1723. ControlWndProc(StaticText)(Message);
  1724. }
  1725. }
  1726. else if (Message.Msg == CM_DIALOGCHAR)
  1727. {
  1728. if (StaticText->CanFocus() && StaticText->ShowAccelChar &&
  1729. IsAccel(reinterpret_cast<TCMDialogChar &>(Message).CharCode, StaticText->Caption))
  1730. {
  1731. StaticText->SetFocus();
  1732. // in case the action takes long, make sure focus is shown immediately
  1733. UpdateWindow(StaticText->Handle);
  1734. Clicked = true;
  1735. Message.Result = 1;
  1736. }
  1737. else
  1738. {
  1739. ControlWndProc(StaticText)(Message);
  1740. }
  1741. }
  1742. else
  1743. {
  1744. ControlWndProc(StaticText)(Message);
  1745. }
  1746. if (Message.Msg == WM_PAINT)
  1747. {
  1748. TRect R;
  1749. TControlCanvas * Canvas;
  1750. FocusableLabelCanvas(StaticText, &Canvas, R);
  1751. try
  1752. {
  1753. if (StaticText->Focused())
  1754. {
  1755. Canvas->DrawFocusRect(R);
  1756. }
  1757. else if ((StaticText->Font->Color != LinkColor) && // LinkActionLabel and LinkLabel
  1758. !EndsStr(LinkAppLabelMark, StaticText->Caption)) // LinkAppLabel
  1759. {
  1760. Canvas->Pen->Style = psDot;
  1761. Canvas->Brush->Style = bsClear;
  1762. if (!StaticText->Enabled)
  1763. {
  1764. Canvas->Pen->Color = clBtnHighlight;
  1765. Canvas->MoveTo(R.Left + 1 + 1, R.Bottom);
  1766. Canvas->LineTo(R.Right + 1, R.Bottom);
  1767. Canvas->Pen->Color = clGrayText;
  1768. }
  1769. Canvas->MoveTo(R.Left, R.Bottom - 1);
  1770. Canvas->LineTo(R.Right, R.Bottom - 1);
  1771. }
  1772. }
  1773. __finally
  1774. {
  1775. delete Canvas;
  1776. }
  1777. }
  1778. else if ((Message.Msg == WM_SETFOCUS) || (Message.Msg == WM_KILLFOCUS) ||
  1779. (Message.Msg == CM_ENABLEDCHANGED))
  1780. {
  1781. StaticText->Invalidate();
  1782. }
  1783. }
  1784. //---------------------------------------------------------------------------
  1785. static THintWindow * PersistentHintWindow = NULL;
  1786. static TControl * PersistentHintControl = NULL;
  1787. //---------------------------------------------------------------------------
  1788. void __fastcall CancelPersistentHint()
  1789. {
  1790. if (PersistentHintWindow != NULL)
  1791. {
  1792. PersistentHintControl = NULL;
  1793. SAFE_DESTROY(PersistentHintWindow);
  1794. }
  1795. }
  1796. //---------------------------------------------------------------------------
  1797. void __fastcall ShowPersistentHint(TControl * Control, TPoint HintPos)
  1798. {
  1799. CancelPersistentHint();
  1800. THintInfo HintInfo;
  1801. HintInfo.HintControl = Control;
  1802. HintInfo.HintPos = HintPos;
  1803. HintInfo.HintMaxWidth = GetParentForm(Control)->Monitor->Width;
  1804. HintInfo.HintColor = Application->HintColor;
  1805. HintInfo.HintStr = GetShortHint(Control->Hint);
  1806. HintInfo.HintData = NULL;
  1807. bool CanShow = true;
  1808. if (Application->OnShowHint != NULL)
  1809. {
  1810. Application->OnShowHint(HintInfo.HintStr, CanShow, HintInfo);
  1811. }
  1812. if (CanShow)
  1813. {
  1814. PersistentHintControl = Control;
  1815. PersistentHintWindow = new TScreenTipHintWindow(Application);
  1816. PersistentHintWindow->BiDiMode = Control->BiDiMode;
  1817. PersistentHintWindow->Color = HintInfo.HintColor;
  1818. TRect HintWinRect;
  1819. if (HintInfo.HintMaxWidth < Control->Width)
  1820. {
  1821. HintInfo.HintMaxWidth = Control->Width;
  1822. }
  1823. HintWinRect = PersistentHintWindow->CalcHintRect(
  1824. HintInfo.HintMaxWidth, HintInfo.HintStr, HintInfo.HintData);
  1825. OffsetRect(HintWinRect, HintInfo.HintPos.x, HintInfo.HintPos.y);
  1826. // TODO: right align window placement for UseRightToLeftAlignment, see Forms.pas
  1827. PersistentHintWindow->ActivateHintData(HintWinRect, HintInfo.HintStr, HintInfo.HintData);
  1828. }
  1829. }
  1830. //---------------------------------------------------------------------------
  1831. static void __fastcall HintLabelWindowProc(void * Data, TMessage & Message)
  1832. {
  1833. bool Clicked = false;
  1834. bool Cancel = false;
  1835. TStaticText * StaticText = static_cast<TStaticText *>(Data);
  1836. if (Message.Msg == CM_HINTSHOW)
  1837. {
  1838. TCMHintShow & HintShow = reinterpret_cast<TCMHintShow &>(Message);
  1839. if (PersistentHintControl == StaticText)
  1840. {
  1841. // do not allow standard hint when persistent is already shown
  1842. HintShow.Result = 1;
  1843. }
  1844. else
  1845. {
  1846. HintShow.HintInfo->HideTimeout = 100000; // never
  1847. }
  1848. }
  1849. else if (Message.Msg == CN_KEYDOWN)
  1850. {
  1851. if ((reinterpret_cast<TWMKey &>(Message).CharCode == VK_ESCAPE) &&
  1852. (PersistentHintControl == StaticText))
  1853. {
  1854. CancelPersistentHint();
  1855. StaticText->Invalidate();
  1856. Message.Result = 1;
  1857. }
  1858. else
  1859. {
  1860. FocusableLabelWindowProc(Data, Message, Clicked);
  1861. }
  1862. }
  1863. else
  1864. {
  1865. FocusableLabelWindowProc(Data, Message, Clicked);
  1866. }
  1867. if (Message.Msg == CM_CANCELMODE)
  1868. {
  1869. TCMCancelMode & CancelMessage = (TCMCancelMode&)Message;
  1870. if ((CancelMessage.Sender != StaticText) &&
  1871. (CancelMessage.Sender != PersistentHintWindow))
  1872. {
  1873. Cancel = true;
  1874. }
  1875. }
  1876. if ((Message.Msg == WM_DESTROY) || (Message.Msg == WM_KILLFOCUS))
  1877. {
  1878. Cancel = true;
  1879. }
  1880. if (Cancel && (PersistentHintControl == StaticText))
  1881. {
  1882. CancelPersistentHint();
  1883. }
  1884. if (Clicked && (PersistentHintControl != StaticText))
  1885. {
  1886. TRect R;
  1887. TPoint HintPos;
  1888. FocusableLabelCanvas(StaticText, NULL, R);
  1889. HintPos.y = R.Bottom - R.Top;
  1890. HintPos.x = R.Left;
  1891. ShowPersistentHint(StaticText, StaticText->ClientToScreen(HintPos));
  1892. }
  1893. }
  1894. //---------------------------------------------------------------------------
  1895. void __fastcall HintLabel(TStaticText * StaticText, UnicodeString Hint)
  1896. {
  1897. // Currently all are right-justified, when other alignment is used,
  1898. // test respective branches in FocusableLabelCanvas.
  1899. DebugAssert(StaticText->Alignment == taRightJustify);
  1900. // With right-justify, it has to be off. We may not notice on original
  1901. // English version, results will differ with translations only
  1902. DebugAssert(!StaticText->AutoSize);
  1903. StaticText->ParentFont = true;
  1904. if (!Hint.IsEmpty())
  1905. {
  1906. StaticText->Hint = Hint;
  1907. }
  1908. StaticText->ShowHint = true;
  1909. StaticText->Cursor = crHandPoint;
  1910. TWndMethod WindowProc;
  1911. ((TMethod*)&WindowProc)->Data = StaticText;
  1912. ((TMethod*)&WindowProc)->Code = HintLabelWindowProc;
  1913. StaticText->WindowProc = WindowProc;
  1914. }
  1915. //---------------------------------------------------------------------------
  1916. static void __fastcall ComboBoxFixWindowProc(void * Data, TMessage & Message)
  1917. {
  1918. // it is TCustomComboxBox, but the properties are published only by TComboBox
  1919. TComboBox * ComboBox = static_cast<TComboBox *>(Data);
  1920. if (Message.Msg == WM_SIZE)
  1921. {
  1922. UnicodeString Text = ComboBox->Text;
  1923. try
  1924. {
  1925. ControlWndProc(ComboBox)(Message);
  1926. }
  1927. __finally
  1928. {
  1929. // workaround for bug in combo box, that causes it to change text to any
  1930. // item from drop down list which starts with current text,
  1931. // after control is resized (unless the text is in drop down list as well)
  1932. ComboBox->Text = Text;
  1933. // hide selection, which is wrongly shown when form is resized, even when the box has not focus
  1934. if (!ComboBox->Focused())
  1935. {
  1936. ComboBox->SelLength = 0;
  1937. }
  1938. }
  1939. }
  1940. else
  1941. {
  1942. ControlWndProc(ComboBox)(Message);
  1943. }
  1944. }
  1945. //---------------------------------------------------------------------------
  1946. void __fastcall FixComboBoxResizeBug(TCustomComboBox * ComboBox)
  1947. {
  1948. TWndMethod WindowProc;
  1949. ((TMethod*)&WindowProc)->Data = ComboBox;
  1950. ((TMethod*)&WindowProc)->Code = ComboBoxFixWindowProc;
  1951. ComboBox->WindowProc = WindowProc;
  1952. }
  1953. //---------------------------------------------------------------------------
  1954. static void __fastcall LinkLabelClick(TStaticText * StaticText)
  1955. {
  1956. if (StaticText->OnClick != NULL)
  1957. {
  1958. StaticText->OnClick(StaticText);
  1959. }
  1960. else
  1961. {
  1962. OpenBrowser(StaticText->Caption);
  1963. }
  1964. }
  1965. //---------------------------------------------------------------------------
  1966. static void __fastcall LinkLabelWindowProc(void * Data, TMessage & Message)
  1967. {
  1968. bool Clicked = false;
  1969. TStaticText * StaticText = static_cast<TStaticText *>(Data);
  1970. if (Message.Msg == WM_CONTEXTMENU)
  1971. {
  1972. TWMContextMenu & ContextMenu = reinterpret_cast<TWMContextMenu &>(Message);
  1973. if ((ContextMenu.Pos.x < 0) && (ContextMenu.Pos.y < 0))
  1974. {
  1975. TRect R;
  1976. FocusableLabelCanvas(StaticText, NULL, R);
  1977. TPoint P = StaticText->ClientToScreen(TPoint(R.Left, R.Bottom));
  1978. ContextMenu.Pos.x = static_cast<short>(P.x);
  1979. ContextMenu.Pos.y = static_cast<short>(P.y);
  1980. }
  1981. }
  1982. else if (Message.Msg == WM_KEYDOWN)
  1983. {
  1984. TWMKey & Key = reinterpret_cast<TWMKey &>(Message);
  1985. if ((GetKeyState(VK_CONTROL) < 0) && (Key.CharCode == L'C'))
  1986. {
  1987. TInstantOperationVisualizer Visualizer;
  1988. CopyToClipboard(StaticText->Caption);
  1989. Message.Result = 1;
  1990. }
  1991. else
  1992. {
  1993. FocusableLabelWindowProc(Data, Message, Clicked);
  1994. }
  1995. }
  1996. FocusableLabelWindowProc(Data, Message, Clicked);
  1997. if (Message.Msg == WM_DESTROY)
  1998. {
  1999. delete StaticText->PopupMenu;
  2000. DebugAssert(StaticText->PopupMenu == NULL);
  2001. }
  2002. if (Clicked)
  2003. {
  2004. LinkLabelClick(StaticText);
  2005. }
  2006. }
  2007. //---------------------------------------------------------------------------
  2008. static void __fastcall LinkLabelContextMenuClick(void * Data, TObject * Sender)
  2009. {
  2010. TStaticText * StaticText = static_cast<TStaticText *>(Data);
  2011. TMenuItem * MenuItem = dynamic_cast<TMenuItem *>(Sender);
  2012. DebugAssert(MenuItem != NULL);
  2013. if (MenuItem->Tag == 0)
  2014. {
  2015. LinkLabelClick(StaticText);
  2016. }
  2017. else
  2018. {
  2019. TInstantOperationVisualizer Visualizer;
  2020. CopyToClipboard(StaticText->Caption);
  2021. }
  2022. }
  2023. //---------------------------------------------------------------------------
  2024. static void __fastcall DoLinkLabel(TStaticText * StaticText)
  2025. {
  2026. StaticText->Transparent = false;
  2027. StaticText->ParentFont = true;
  2028. StaticText->Cursor = crHandPoint;
  2029. TWndMethod WindowProc;
  2030. ((TMethod*)&WindowProc)->Data = StaticText;
  2031. ((TMethod*)&WindowProc)->Code = LinkLabelWindowProc;
  2032. StaticText->WindowProc = WindowProc;
  2033. }
  2034. //---------------------------------------------------------------------------
  2035. void __fastcall LinkLabel(TStaticText * StaticText, UnicodeString Url,
  2036. TNotifyEvent OnEnter)
  2037. {
  2038. DoLinkLabel(StaticText);
  2039. StaticText->Font->Style = StaticText->Font->Style << fsUnderline;
  2040. reinterpret_cast<TButton*>(StaticText)->OnEnter = OnEnter;
  2041. if (!Url.IsEmpty())
  2042. {
  2043. StaticText->Caption = Url;
  2044. }
  2045. bool IsUrl = IsHttpOrHttpsUrl(StaticText->Caption);
  2046. if (IsUrl)
  2047. {
  2048. DebugAssert(StaticText->PopupMenu == NULL);
  2049. StaticText->PopupMenu = new TPopupMenu(StaticText);
  2050. try
  2051. {
  2052. TNotifyEvent ContextMenuOnClick;
  2053. ((TMethod*)&ContextMenuOnClick)->Data = StaticText;
  2054. ((TMethod*)&ContextMenuOnClick)->Code = LinkLabelContextMenuClick;
  2055. TMenuItem * Item;
  2056. Item = new TMenuItem(StaticText->PopupMenu);
  2057. Item->Caption = LoadStr(URL_LINK_OPEN);
  2058. Item->Tag = 0;
  2059. Item->ShortCut = ShortCut(L' ', TShiftState());
  2060. Item->OnClick = ContextMenuOnClick;
  2061. StaticText->PopupMenu->Items->Add(Item);
  2062. Item = new TMenuItem(StaticText->PopupMenu);
  2063. Item->Caption = LoadStr(EDIT_COPY);
  2064. Item->Tag = 1;
  2065. Item->ShortCut = ShortCut(L'C', TShiftState() << ssCtrl);
  2066. Item->OnClick = ContextMenuOnClick;
  2067. StaticText->PopupMenu->Items->Add(Item);
  2068. }
  2069. catch(...)
  2070. {
  2071. delete StaticText->PopupMenu;
  2072. DebugAssert(StaticText->PopupMenu == NULL);
  2073. throw;
  2074. }
  2075. }
  2076. StaticText->Font->Color = LinkColor;
  2077. }
  2078. //---------------------------------------------------------------------------
  2079. void __fastcall LinkActionLabel(TStaticText * StaticText)
  2080. {
  2081. DoLinkLabel(StaticText);
  2082. StaticText->Font->Color = LinkColor;
  2083. }
  2084. //---------------------------------------------------------------------------
  2085. void __fastcall LinkAppLabel(TStaticText * StaticText)
  2086. {
  2087. DoLinkLabel(StaticText);
  2088. StaticText->Caption = StaticText->Caption + LinkAppLabelMark;
  2089. }
  2090. //---------------------------------------------------------------------------
  2091. static void __fastcall HotTrackLabelMouseEnter(void * /*Data*/, TObject * Sender)
  2092. {
  2093. reinterpret_cast<TLabel *>(Sender)->Font->Color = clBlue;
  2094. }
  2095. //---------------------------------------------------------------------------
  2096. static void __fastcall HotTrackLabelMouseLeave(void * /*Data*/, TObject * Sender)
  2097. {
  2098. reinterpret_cast<TLabel *>(Sender)->ParentFont = true;
  2099. }
  2100. //---------------------------------------------------------------------------
  2101. void __fastcall HotTrackLabel(TLabel * Label)
  2102. {
  2103. DebugAssert(Label->OnMouseEnter == NULL);
  2104. DebugAssert(Label->OnMouseLeave == NULL);
  2105. Label->OnMouseEnter = MakeMethod<TNotifyEvent>(NULL, HotTrackLabelMouseEnter);
  2106. Label->OnMouseLeave = MakeMethod<TNotifyEvent>(NULL, HotTrackLabelMouseLeave);
  2107. }
  2108. //---------------------------------------------------------------------------
  2109. void __fastcall SetLabelHintPopup(TLabel * Label, const UnicodeString & Hint)
  2110. {
  2111. Label->Caption = Hint;
  2112. Label->Hint = Hint;
  2113. TRect Rect(0, 0, Label->Width, 0);
  2114. TScreenTipHintWindow::CalcHintTextRect(Label, Label->Canvas, Rect, Label->Caption);
  2115. Label->ShowHint = (Rect.Bottom > Label->Height);
  2116. }
  2117. //---------------------------------------------------------------------------
  2118. bool __fastcall HasLabelHintPopup(TLabel * Label, const UnicodeString & HintStr)
  2119. {
  2120. return (Label->Caption == HintStr);
  2121. }
  2122. //---------------------------------------------------------------------------
  2123. Forms::TMonitor * __fastcall FormMonitor(TCustomForm * Form)
  2124. {
  2125. Forms::TMonitor * Result;
  2126. if ((Application->MainForm != NULL) && (Application->MainForm != Form))
  2127. {
  2128. Result = Application->MainForm->Monitor;
  2129. }
  2130. else if (LastMonitor != NULL)
  2131. {
  2132. Result = LastMonitor;
  2133. }
  2134. else
  2135. {
  2136. int i = 0;
  2137. while ((i < Screen->MonitorCount) && !Screen->Monitors[i]->Primary)
  2138. {
  2139. i++;
  2140. }
  2141. DebugAssert(Screen->Monitors[i]->Primary);
  2142. Result = Screen->Monitors[i];
  2143. }
  2144. return Result;
  2145. }
  2146. //---------------------------------------------------------------------------
  2147. int __fastcall GetLastMonitor()
  2148. {
  2149. if (LastMonitor != NULL)
  2150. {
  2151. return LastMonitor->MonitorNum;
  2152. }
  2153. else
  2154. {
  2155. return -1;
  2156. }
  2157. }
  2158. //---------------------------------------------------------------------------
  2159. void __fastcall SetLastMonitor(int MonitorNum)
  2160. {
  2161. if ((MonitorNum >= 0) && (MonitorNum < Screen->MonitorCount))
  2162. {
  2163. LastMonitor = Screen->Monitors[MonitorNum];
  2164. }
  2165. else
  2166. {
  2167. LastMonitor = NULL;
  2168. }
  2169. }
  2170. //---------------------------------------------------------------------------
  2171. TForm * __fastcall _SafeFormCreate(TMetaClass * FormClass, TComponent * Owner)
  2172. {
  2173. TForm * Form;
  2174. if (Owner == NULL)
  2175. {
  2176. Owner = GetFormOwner();
  2177. }
  2178. // If there is no main form yet, make this one main.
  2179. // This:
  2180. // - Makes other forms (dialogs invoked from this one),
  2181. // be placed on the same monitor (otherwise all new forms get placed
  2182. // on primary monitor)
  2183. // - Triggers MainForm-specific code in DoFormWindowProc.
  2184. // - Shows button on taskbar
  2185. if (Application->MainForm == NULL)
  2186. {
  2187. Application->CreateForm(FormClass, &Form);
  2188. DebugAssert(Application->MainForm == Form);
  2189. }
  2190. else
  2191. {
  2192. Form = dynamic_cast<TForm *>(Construct(FormClass, Owner));
  2193. DebugAssert(Form != NULL);
  2194. }
  2195. return Form;
  2196. }
  2197. //---------------------------------------------------------------------------
  2198. bool __fastcall SupportsSplitButton()
  2199. {
  2200. return (Win32MajorVersion >= 6);
  2201. }
  2202. //---------------------------------------------------------------------------
  2203. static TButton * __fastcall FindDefaultButton(TWinControl * Control)
  2204. {
  2205. TButton * Result = NULL;
  2206. int Index = 0;
  2207. while ((Result == NULL) && (Index < Control->ControlCount))
  2208. {
  2209. TControl * ChildControl = Control->Controls[Index];
  2210. TButton * Button = dynamic_cast<TButton *>(ChildControl);
  2211. if ((Button != NULL) && Button->Default)
  2212. {
  2213. Result = Button;
  2214. }
  2215. else
  2216. {
  2217. TWinControl * WinControl = dynamic_cast<TWinControl *>(ChildControl);
  2218. if (WinControl != NULL)
  2219. {
  2220. Result = FindDefaultButton(WinControl);
  2221. }
  2222. }
  2223. Index++;
  2224. }
  2225. return Result;
  2226. }
  2227. //---------------------------------------------------------------------------
  2228. TModalResult __fastcall DefaultResult(TCustomForm * Form, TButton * DefaultButton)
  2229. {
  2230. // The point of this is to avoid hardcoding mrOk when checking dialog results.
  2231. // Previously we used != mrCancel instead, as mrCancel is more reliable,
  2232. // being automatically used for Esc/X buttons (and hence kind of forced to be used
  2233. // for Cancel buttons). But that failed to be reliable in the end, for
  2234. // ModalResult being mrNone, when Windows session is being logged off.
  2235. // We interpreted mrNone as OK, causing lots of troubles.
  2236. TModalResult Result = mrNone;
  2237. TButton * Button = FindDefaultButton(Form);
  2238. if (DebugAlwaysTrue(Button != NULL))
  2239. {
  2240. Result = Button->ModalResult;
  2241. }
  2242. if (Result == mrNone)
  2243. {
  2244. DebugAssert((DefaultButton != NULL) && (DefaultButton->ModalResult != mrNone));
  2245. Result = DefaultButton->ModalResult;
  2246. }
  2247. else
  2248. {
  2249. // If default button fallback was provided,
  2250. // make sure it is the default button we actually detected
  2251. DebugAssert((DefaultButton == NULL) || (Button == DefaultButton));
  2252. }
  2253. return Result;
  2254. }
  2255. //---------------------------------------------------------------------------
  2256. void __fastcall DefaultButton(TButton * Button, bool Default)
  2257. {
  2258. // default property setter does not have guard for "the same value"
  2259. if (Button->Default != Default)
  2260. {
  2261. Button->Default = Default;
  2262. }
  2263. }
  2264. //---------------------------------------------------------------------------
  2265. void __fastcall MemoKeyDown(TObject * Sender, WORD & Key, TShiftState Shift)
  2266. {
  2267. // Sender can be Form or Memo itself
  2268. TControl * Control = dynamic_cast<TControl *>(Sender);
  2269. if (DebugAlwaysTrue(Control != NULL))
  2270. {
  2271. TCustomForm * Form = GetParentForm(Control);
  2272. // Particularly when WantReturns is true,
  2273. // memo swallows also Esc, so we have to handle it ourselves.
  2274. // See also ReadOnlyControl.
  2275. if ((Key == VK_ESCAPE) && Shift.Empty())
  2276. {
  2277. Form->ModalResult = mrCancel;
  2278. Key = 0;
  2279. }
  2280. else if ((Key == VK_RETURN) && Shift.Contains(ssCtrl))
  2281. {
  2282. Form->ModalResult = DefaultResult(Form);
  2283. Key = 0;
  2284. }
  2285. }
  2286. }
  2287. //---------------------------------------------------------------------------
  2288. class TIconOwnerComponent : public TComponent
  2289. {
  2290. public:
  2291. __fastcall TIconOwnerComponent(TIcon * Icon) :
  2292. TComponent(NULL),
  2293. FIcon(Icon)
  2294. {
  2295. }
  2296. private:
  2297. std::unique_ptr<TIcon> FIcon;
  2298. };
  2299. //---------------------------------------------------------------------------
  2300. static void __fastcall FixFormIcon(TForm * Form, int Size, int WidthMetric, int HeightMetric)
  2301. {
  2302. // Whole this code is to call ReadIcon from Vcl.Graphics.pas with correct size
  2303. // Clone the icon data (whole .ico file content, that is originally loaded from .dfm)
  2304. // to a new TIcon that does not have a size fixed yet (size cannot be changed after handle is allocated)
  2305. std::unique_ptr<TMemoryStream> Stream(new TMemoryStream());
  2306. Form->Icon->SaveToStream(Stream.get());
  2307. std::unique_ptr<TIcon> Icon(new TIcon());
  2308. Stream->Position = 0;
  2309. Icon->LoadFromStream(Stream.get());
  2310. // Set desired size
  2311. int Width = GetSystemMetricsForControl(Form, WidthMetric);
  2312. int Height = GetSystemMetricsForControl(Form, HeightMetric);
  2313. Icon->SetSize(Width, Height);
  2314. // This calls TIcon::RequireHandle that retrieves the best icon for given size
  2315. LPARAM LParam = reinterpret_cast<LPARAM>(Icon->Handle);
  2316. SendMessage(Form->Handle, WM_SETICON, Size, LParam);
  2317. // Make sure the icon is released
  2318. TIconOwnerComponent * IconOwnerComponent = new TIconOwnerComponent(Icon.release());
  2319. IconOwnerComponent->Name = TIconOwnerComponent::QualifiedClassName() + IntToStr(Size);
  2320. Form->InsertComponent(IconOwnerComponent);
  2321. }
  2322. //---------------------------------------------------------------------------
  2323. void __fastcall FixFormIcons(TForm * Form)
  2324. {
  2325. // VCL sets only ICON_BIG (so small icon is scaled down by OS from big icon),
  2326. // and it uses a random (first?) size from the resource,
  2327. // not the best size.
  2328. FixFormIcon(Form, ICON_SMALL, SM_CXSMICON, SM_CYSMICON);
  2329. FixFormIcon(Form, ICON_BIG, SM_CXICON, SM_CYICON);
  2330. // We rely on VCL not calling WM_SETICON ever after
  2331. // (what it would do, if CreateWnd is called again).
  2332. // That would overwrite the ICON_BIG.
  2333. // We might be able to make sure it uses a correct size by calling
  2334. // TIcon.ReleaseHandle and setting a correct size.
  2335. }
  2336. //---------------------------------------------------------------------------
  2337. class TDesktopFontManager : public TComponent
  2338. {
  2339. public:
  2340. TDesktopFontManager();
  2341. virtual __fastcall ~TDesktopFontManager();
  2342. void AddControl(TControl * Control);
  2343. void Update();
  2344. protected:
  2345. virtual void __fastcall Notification(TComponent * AComponent, TOperation Operation);
  2346. private:
  2347. HWND FWindowHandle;
  2348. typedef std::set<TControl *> TControlSet;
  2349. TControlSet FControls;
  2350. void __fastcall WndProc(TMessage & Message);
  2351. void UpdateControl(TControl * Control);
  2352. };
  2353. //---------------------------------------------------------------------------
  2354. TDesktopFontManager::TDesktopFontManager() : TComponent(NULL)
  2355. {
  2356. // Alternative is using Application->HookMainWindow
  2357. FWindowHandle = AllocateHWnd(WndProc);
  2358. }
  2359. //---------------------------------------------------------------------------
  2360. __fastcall TDesktopFontManager::~TDesktopFontManager()
  2361. {
  2362. DeallocateHWnd(FWindowHandle);
  2363. }
  2364. //---------------------------------------------------------------------------
  2365. void __fastcall TDesktopFontManager::Notification(TComponent * AComponent, TOperation Operation)
  2366. {
  2367. if (DebugAlwaysTrue(Operation == opRemove))
  2368. {
  2369. TControl * Control = DebugNotNull(dynamic_cast<TControl *>(AComponent));
  2370. FControls.erase(Control);
  2371. }
  2372. TComponent::Notification(AComponent, Operation);
  2373. }
  2374. //---------------------------------------------------------------------------
  2375. void TDesktopFontManager::UpdateControl(TControl * Control)
  2376. {
  2377. class TPublicControl : public TControl
  2378. {
  2379. public:
  2380. __property Font;
  2381. };
  2382. TPublicControl * PublicControl = reinterpret_cast<TPublicControl *>(Control);
  2383. std::unique_ptr<TFont> DesktopFont(new TFont());
  2384. if (WinConfiguration->PanelFont.FontName.IsEmpty())
  2385. {
  2386. int PixelsPerInch = GetControlPixelsPerInch(Control);
  2387. TLogFont LogFont;
  2388. if (DebugAlwaysTrue(SystemParametersInfoForPixelsPerInch(SPI_GETICONTITLELOGFONT, sizeof(LogFont), &LogFont, 0, PixelsPerInch)))
  2389. {
  2390. DesktopFont->Handle = CreateFontIndirect(&LogFont);
  2391. }
  2392. }
  2393. else
  2394. {
  2395. TWinConfiguration::RestoreFont(WinConfiguration->PanelFont, DesktopFont.get());
  2396. DesktopFont->Height = ScaleByPixelsPerInchFromSystem(DesktopFont->Height, Control);
  2397. DesktopFont->PixelsPerInch = PublicControl->Font->PixelsPerInch;
  2398. }
  2399. PublicControl->Font->Assign(DesktopFont.get());
  2400. }
  2401. //---------------------------------------------------------------------------
  2402. void TDesktopFontManager::AddControl(TControl * Control)
  2403. {
  2404. FControls.insert(Control);
  2405. Control->FreeNotification(this);
  2406. UpdateControl(Control);
  2407. }
  2408. //---------------------------------------------------------------------------
  2409. void TDesktopFontManager::Update()
  2410. {
  2411. TControlSet::iterator I = FControls.begin();
  2412. while (I != FControls.end())
  2413. {
  2414. UpdateControl(*I);
  2415. I++;
  2416. }
  2417. }
  2418. //---------------------------------------------------------------------------
  2419. void __fastcall TDesktopFontManager::WndProc(TMessage & Message)
  2420. {
  2421. if (Message.Msg == WM_WININICHANGE)
  2422. {
  2423. Update();
  2424. }
  2425. Message.Result = DefWindowProc(FWindowHandle, Message.Msg, Message.WParam, Message.LParam);
  2426. }
  2427. //---------------------------------------------------------------------------
  2428. std::unique_ptr<TDesktopFontManager> DesktopFontManager(new TDesktopFontManager());
  2429. //---------------------------------------------------------------------------
  2430. void __fastcall UseDesktopFont(TControl * Control)
  2431. {
  2432. TCustomStatusBar * StatusBar = dynamic_cast<TCustomStatusBar *>(Control);
  2433. if (StatusBar != NULL)
  2434. {
  2435. // prevent syncing to system font
  2436. StatusBar->UseSystemFont = false;
  2437. }
  2438. DesktopFontManager->AddControl(Control);
  2439. }
  2440. //---------------------------------------------------------------------------
  2441. void __fastcall UpdateDesktopFont()
  2442. {
  2443. DesktopFontManager->Update();
  2444. }
  2445. //---------------------------------------------------------------------------
  2446. TShiftState __fastcall AllKeyShiftStates()
  2447. {
  2448. return TShiftState() << ssShift << ssAlt << ssCtrl;
  2449. }
  2450. //---------------------------------------------------------------------------
  2451. static bool __fastcall FormActivationHook(void * Data, TMessage & Message)
  2452. {
  2453. bool Result = false;
  2454. // Some dialogs, when application is restored from minimization,
  2455. // do not get activated. So we do it explicitly here.
  2456. // We cannot do this from TApplication::OnActivate because
  2457. // TApplication.WndProc resets focus to the last active window afterwards.
  2458. // So we override CM_ACTIVATE implementation here completelly.
  2459. if (Message.Msg == CM_ACTIVATE)
  2460. {
  2461. TCustomForm * Form = static_cast<TCustomForm *>(Data);
  2462. if (Screen->FocusedForm == Form)
  2463. {
  2464. ::SetFocus(Form->Handle);
  2465. // VCLCOPY
  2466. if (Application->OnActivate != NULL)
  2467. {
  2468. Application->OnActivate(Application);
  2469. }
  2470. Result = true;
  2471. }
  2472. }
  2473. return Result;
  2474. }
  2475. //---------------------------------------------------------------------------
  2476. void __fastcall HookFormActivation(TCustomForm * Form)
  2477. {
  2478. Application->HookMainWindow(MakeMethod<TWindowHook>(Form, FormActivationHook));
  2479. }
  2480. //---------------------------------------------------------------------------
  2481. void __fastcall UnhookFormActivation(TCustomForm * Form)
  2482. {
  2483. Application->UnhookMainWindow(MakeMethod<TWindowHook>(Form, FormActivationHook));
  2484. }
  2485. //---------------------------------------------------------------------------
  2486. void __fastcall ShowFormNoActivate(TForm * Form)
  2487. {
  2488. TPublicForm * PublicForm = static_cast<TPublicForm *>(Form);
  2489. // This is same as SendToBack, except for added SWP_NOACTIVATE (VCLCOPY)
  2490. SetWindowPos(PublicForm->WindowHandle, HWND_BOTTOM, 0, 0, 0, 0,
  2491. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
  2492. // This replaces TCustomForm::CMShowingChanged()
  2493. // which calls ShowWindow(Handle, SW_SHOWNORMAL).
  2494. ShowWindow(Form->Handle, SW_SHOWNOACTIVATE);
  2495. // - so we have to call DoShow explicitly.
  2496. PublicForm->DoShow();
  2497. // - also we skip applying TForm::Position (VCLCOPY)
  2498. if (DebugAlwaysTrue(Form->Position == poOwnerFormCenter))
  2499. {
  2500. TCustomForm * CenterForm = Application->MainForm;
  2501. TCustomForm * OwnerForm = dynamic_cast<TCustomForm *>(Form->Owner);
  2502. if (OwnerForm != NULL)
  2503. {
  2504. CenterForm = OwnerForm;
  2505. }
  2506. int X, Y;
  2507. if ((CenterForm != NULL) && (CenterForm != Form))
  2508. {
  2509. TRect Bounds = CenterForm->BoundsRect;
  2510. X = ((Bounds.Width() - Form->Width) / 2) + CenterForm->Left;
  2511. Y = ((Bounds.Height() - Form->Height) / 2) + CenterForm->Top;
  2512. }
  2513. else
  2514. {
  2515. X = (Screen->Width - Form->Width) / 2;
  2516. Y = (Screen->Height - Form->Height) / 2;
  2517. }
  2518. if (X < Screen->DesktopLeft)
  2519. {
  2520. X = Screen->DesktopLeft;
  2521. }
  2522. if (Y < Screen->DesktopTop)
  2523. {
  2524. Y = Screen->DesktopTop;
  2525. }
  2526. Form->SetBounds(X, Y, Form->Width, Form->Height);
  2527. // We cannot call SetWindowToMonitor().
  2528. // We cannot set FPosition = poDesigned, so workarea-checking code
  2529. // in DoFormWindowProc is not triggered
  2530. // If application is restored, dialog is not activated, do it manually.
  2531. // Wait for application to be activated to activate ourself.
  2532. HookFormActivation(Form);
  2533. }
  2534. }
  2535. //---------------------------------------------------------------------------
  2536. TPanel * __fastcall CreateBlankPanel(TComponent * Owner)
  2537. {
  2538. TPanel * Panel = new TPanel(Owner);
  2539. Panel->BevelOuter = bvNone;
  2540. Panel->BevelInner = bvNone; // default
  2541. Panel->BevelKind = bkNone;
  2542. return Panel;
  2543. }