VCLCommon.cpp 87 KB

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