VCLCommon.cpp 95 KB

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