VCLCommon.cpp 90 KB

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