VCLCommon.cpp 99 KB

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