VCLCommon.cpp 83 KB

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