VCLCommon.cpp 89 KB

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