VCLCommon.cpp 83 KB

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