VCLCommon.cpp 87 KB

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