VCLCommon.cpp 86 KB

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