VCLCommon.cpp 87 KB

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