VCLCommon.cpp 87 KB

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