VCLCommon.cpp 85 KB

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