VCLCommon.cpp 98 KB

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