VCLCommon.cpp 91 KB

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