VCLCommon.cpp 96 KB

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