VCLCommon.cpp 84 KB

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