Tools.cpp 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <Consts.hpp>
  5. #include <shlobj.h>
  6. #include <stdio.h>
  7. #define INITGUID
  8. #include <propkey.h>
  9. #include <powrprof.h>
  10. #include <Common.h>
  11. #include <TextsWin.h>
  12. #include <TextsCore.h>
  13. #include <HelpWin.h>
  14. #include <Exceptions.h>
  15. #include <CoreMain.h>
  16. #include <RemoteFiles.h>
  17. #include <PuttyTools.h>
  18. #include "GUITools.h"
  19. #include "VCLCommon.h"
  20. #include "Setup.h"
  21. #include "Tools.h"
  22. #include <WinHelpViewer.hpp>
  23. #include <PasTools.hpp>
  24. #include <System.Win.ComObj.hpp>
  25. #include <StrUtils.hpp>
  26. #include <WinConfiguration.h>
  27. #include <ProgParams.h>
  28. //---------------------------------------------------------------------------
  29. // WORKAROUND
  30. // VCL includes wininet.h (even with NO_WIN32_LEAN_AND_MEAN)
  31. // and it cannot be combined with winhttp.h as of current Windows SDK.
  32. // This is hack to allow that.
  33. // https://web.archive.org/web/20140612011622/https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/8f468d9f-3f15-452c-803d-fc63ab3f684e/cannot-use-both-winineth-and-winhttph
  34. #undef BOOLAPI
  35. #undef SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
  36. #undef SECURITY_FLAG_IGNORE_CERT_CN_INVALID
  37. #define URL_COMPONENTS URL_COMPONENTS_ANOTHER
  38. #define URL_COMPONENTSA URL_COMPONENTSA_ANOTHER
  39. #define URL_COMPONENTSW URL_COMPONENTSW_ANOTHER
  40. #define LPURL_COMPONENTS LPURL_COMPONENTS_ANOTHER
  41. #define LPURL_COMPONENTSA LPURL_COMPONENTS_ANOTHER
  42. #define LPURL_COMPONENTSW LPURL_COMPONENTS_ANOTHER
  43. #define INTERNET_SCHEME INTERNET_SCHEME_ANOTHER
  44. #define LPINTERNET_SCHEME LPINTERNET_SCHEME_ANOTHER
  45. #define HTTP_VERSION_INFO HTTP_VERSION_INFO_ANOTHER
  46. #define LPHTTP_VERSION_INFO LPHTTP_VERSION_INFO_ANOTHER
  47. #include <winhttp.h>
  48. #undef URL_COMPONENTS
  49. #undef URL_COMPONENTSA
  50. #undef URL_COMPONENTSW
  51. #undef LPURL_COMPONENTS
  52. #undef LPURL_COMPONENTSA
  53. #undef LPURL_COMPONENTSW
  54. #undef INTERNET_SCHEME
  55. #undef LPINTERNET_SCHEME
  56. #undef HTTP_VERSION_INFO
  57. #undef LPHTTP_VERSION_INFO
  58. //---------------------------------------------------------------------------
  59. #pragma package(smart_init)
  60. //---------------------------------------------------------------------------
  61. TFontStyles __fastcall IntToFontStyles(int value)
  62. {
  63. TFontStyles Result;
  64. for (int i = fsBold; i <= fsStrikeOut; i++)
  65. {
  66. if (value & 1)
  67. {
  68. Result << (TFontStyle)i;
  69. }
  70. value >>= 1;
  71. }
  72. return Result;
  73. }
  74. //---------------------------------------------------------------------------
  75. int __fastcall FontStylesToInt(const TFontStyles value)
  76. {
  77. int Result = 0;
  78. for (int i = fsStrikeOut; i >= fsBold; i--)
  79. {
  80. Result <<= 1;
  81. if (value.Contains((TFontStyle)i))
  82. {
  83. Result |= 1;
  84. }
  85. }
  86. return Result;
  87. }
  88. //---------------------------------------------------------------------------
  89. bool __fastcall SameFont(TFont * Font1, TFont * Font2)
  90. {
  91. // keep in sync with TFontConfiguration::operator !=
  92. return
  93. SameText(Font1->Name, Font2->Name) && (Font1->Height == Font2->Height) &&
  94. (Font1->Charset == Font2->Charset) && (Font1->Style == Font2->Style);
  95. }
  96. //---------------------------------------------------------------------------
  97. TColor __fastcall GetWindowTextColor(TColor BackgroundColor, TColor Color)
  98. {
  99. if (Color == TColor(0))
  100. {
  101. // Could use current theme TMT_TEXTCOLOR - see https://github.com/ysc3839/win32-darkmode
  102. Color = (IsDarkColor(BackgroundColor) ? clWhite : clWindowText);
  103. SetContrast(Color, BackgroundColor, 180);
  104. }
  105. return Color;
  106. }
  107. //---------------------------------------------------------------------------
  108. TColor __fastcall GetWindowColor(TColor Color)
  109. {
  110. if (Color == TColor(0))
  111. {
  112. // Could use current theme TMT_FILLCOLOR - see https://github.com/ysc3839/win32-darkmode
  113. Color = (WinConfiguration->UseDarkTheme() ? static_cast<TColor>(RGB(0x20, 0x20, 0x20)) : clWindow);
  114. }
  115. return Color;
  116. }
  117. //---------------------------------------------------------------------------
  118. TColor __fastcall GetBtnFaceColor()
  119. {
  120. return WinConfiguration->UseDarkTheme() ? TColor(RGB(43, 43, 43)) : clBtnFace;
  121. }
  122. //---------------------------------------------------------------------------
  123. TColor GetLightLinkColor()
  124. {
  125. return clBlue;
  126. }
  127. //---------------------------------------------------------------------------
  128. TColor GetLinkColor(TControl * Control)
  129. {
  130. // dark theme Windows 11 Settings app On/Off toggle color
  131. return UseDarkModeForControl(Control) ? TColor(RGB(0x4C, 0xC2, 0xFF)) : GetLightLinkColor();
  132. }
  133. //---------------------------------------------------------------------------
  134. TColor __fastcall GetNonZeroColor(TColor Color)
  135. {
  136. // 0,0,0 is "default color"
  137. if (Color == TColor(0))
  138. {
  139. // use near-black instead
  140. Color = TColor(RGB(1, 1, 1));
  141. }
  142. return Color;
  143. }
  144. //---------------------------------------------------------------------------
  145. void __fastcall CenterFormOn(TForm * Form, TControl * CenterOn)
  146. {
  147. TPoint ScreenPoint = CenterOn->ClientToScreen(TPoint(0, 0));
  148. Form->Left = ScreenPoint.x + (CenterOn->Width / 2) - (Form->Width / 2);
  149. Form->Top = ScreenPoint.y + (CenterOn->Height / 2) - (Form->Height / 2);
  150. }
  151. //---------------------------------------------------------------------------
  152. UnicodeString __fastcall GetListViewStr(TCustomListView * ListView)
  153. {
  154. UnicodeString Result;
  155. TListView * AListView = static_cast<TListView *>(ListView);
  156. for (int Index = 0; Index < AListView->Columns->Count; Index++)
  157. {
  158. AddToList(Result, IntToStr(AListView->Column[Index]->Width), L",");
  159. }
  160. // WORKAROUND
  161. // Adding an additional comma after the list,
  162. // to ensure that old versions that did not expect the pixels-per-inch part,
  163. // stop at the comma, otherwise they try to parse the
  164. // "last-column-width;pixels-per-inch" as integer and throw.
  165. // For the other instance of this hack, see TCustomListViewColProperties.GetParamsStr
  166. Result += L",;" + SavePixelsPerInch(ListView);
  167. return Result;
  168. }
  169. //---------------------------------------------------------------------------
  170. void __fastcall LoadListViewStr(TCustomListView * ListView, UnicodeString ALayoutStr)
  171. {
  172. UnicodeString LayoutStr = CutToChar(ALayoutStr, L';', true);
  173. int PixelsPerInch = LoadPixelsPerInch(CutToChar(ALayoutStr, L';', true), ListView);
  174. int Index = 0;
  175. TListView * AListView = static_cast<TListView *>(ListView);
  176. while (!LayoutStr.IsEmpty() && (Index < AListView->Columns->Count))
  177. {
  178. int Width;
  179. if (TryStrToInt(CutToChar(LayoutStr, L',', true), Width))
  180. {
  181. AListView->Column[Index]->Width = LoadDimension(Width, PixelsPerInch, ListView);
  182. }
  183. Index++;
  184. }
  185. }
  186. //---------------------------------------------------------------------------
  187. wchar_t FormDataSep = L';';
  188. //---------------------------------------------------------------------------
  189. void LoadFormDimensions(
  190. const UnicodeString & AData, int PixelsPerInch, Forms::TMonitor * Monitor, TForm * Form, TRect & Bounds, bool & DefaultPos)
  191. {
  192. UnicodeString Data = AData;
  193. UnicodeString LeftStr = CutToChar(Data, FormDataSep, true);
  194. UnicodeString TopStr = CutToChar(Data, FormDataSep, true);
  195. UnicodeString RightStr = CutToChar(Data, FormDataSep, true);
  196. UnicodeString BottomStr = CutToChar(Data, FormDataSep, true);
  197. DefaultPos = (StrToIntDef(LeftStr, 0) == -1) && (StrToIntDef(TopStr, 0) == -1);
  198. if (!DefaultPos)
  199. {
  200. Bounds.Left = StrToDimensionDef(LeftStr, PixelsPerInch, Form, Bounds.Left);
  201. Bounds.Top = StrToDimensionDef(TopStr, PixelsPerInch, Form, Bounds.Top);
  202. }
  203. else
  204. {
  205. Bounds.Left = 0;
  206. Bounds.Top = 0;
  207. }
  208. Bounds.Right = StrToDimensionDef(RightStr, PixelsPerInch, Form, Bounds.Right);
  209. Bounds.Bottom = StrToDimensionDef(BottomStr, PixelsPerInch, Form, Bounds.Bottom);
  210. // move to the target monitor
  211. OffsetRect(Bounds, Monitor->Left, Monitor->Top);
  212. // reduce window size to that of monitor size
  213. // (this does not cut window into monitor!)
  214. if (Bounds.Width() > Monitor->WorkareaRect.Width())
  215. {
  216. Bounds.Right -= (Bounds.Width() - Monitor->WorkareaRect.Width());
  217. }
  218. if (Bounds.Height() > Monitor->WorkareaRect.Height())
  219. {
  220. Bounds.Bottom -= (Bounds.Height() - Monitor->WorkareaRect.Height());
  221. }
  222. }
  223. //---------------------------------------------------------------------------
  224. static void CenterOnMonitor(TForm * Form, Forms::TMonitor * Monitor, const TRect & Bounds)
  225. {
  226. Form->BoundsRect = Monitor->BoundsRect.CenteredRect(Bounds);
  227. }
  228. //---------------------------------------------------------------------------
  229. void RestoreForm(const UnicodeString & AData, TForm * Form, bool PositionOnly, const UnicodeString & DefaultData)
  230. {
  231. DebugAssert(Form);
  232. UnicodeString Data = AData;
  233. if (!Data.IsEmpty())
  234. {
  235. Forms::TMonitor * Monitor = FormMonitor(Form);
  236. UnicodeString BoundsStr;
  237. for (int Index = 0; Index < 4; Index++)
  238. {
  239. CutToChar(Data, FormDataSep, true);
  240. }
  241. TWindowState State = (TWindowState)StrToIntDef(CutToChar(Data, FormDataSep, true), (int)wsNormal);
  242. int PixelsPerInch = LoadPixelsPerInch(CutToChar(Data, FormDataSep, true), Form);
  243. TRect OriginalBounds = Form->BoundsRect;
  244. int OriginalPixelsPerInch = Form->PixelsPerInch;
  245. Form->WindowState = State;
  246. if (State == wsNormal)
  247. {
  248. bool DefaultPos;
  249. TRect Bounds = OriginalBounds;
  250. LoadFormDimensions(AData, PixelsPerInch, Monitor, Form, Bounds, DefaultPos);
  251. int Padding = ScaleByPixelsPerInch(20, Monitor);
  252. if (DefaultPos ||
  253. ((Bounds.Left < Monitor->Left - Padding) ||
  254. (Bounds.Left > Monitor->Left + Monitor->WorkareaRect.Width() - Padding) ||
  255. (Bounds.Top < Monitor->Top - Padding) ||
  256. (Bounds.Top > Monitor->Top + Monitor->WorkareaRect.Height() - Padding)))
  257. {
  258. bool ExplicitPlacing = !Monitor->Primary;
  259. if (!ExplicitPlacing)
  260. {
  261. TPosition Position;
  262. if ((Application->MainForm == NULL) || (Application->MainForm == Form))
  263. {
  264. Position = poDefaultPosOnly;
  265. }
  266. else
  267. {
  268. Position = poOwnerFormCenter;
  269. }
  270. // If handle is allocated already, changing Position reallocates it, what brings lot of nasty side effects.
  271. if (Form->HandleAllocated() && (Form->Position != Position))
  272. {
  273. ExplicitPlacing = true;
  274. }
  275. else
  276. {
  277. Form->Width = Bounds.Width();
  278. Form->Height = Bounds.Height();
  279. }
  280. }
  281. if (ExplicitPlacing)
  282. {
  283. // when positioning on non-primary monitor, we need
  284. // to handle that ourselves, so place window to center
  285. if (!PositionOnly)
  286. {
  287. CenterOnMonitor(Form, Monitor, Bounds);
  288. }
  289. if (!Form->HandleAllocated())
  290. {
  291. Form->Position = poDesigned;
  292. }
  293. }
  294. }
  295. else
  296. {
  297. Form->Position = poDesigned;
  298. if (!PositionOnly)
  299. {
  300. Form->BoundsRect = Bounds;
  301. // If setting bounds moved the form to another monitor with non-default DPI,
  302. // recalculate the size to avoid rounding issues
  303. // (as the form was very likely moved to the monitor, where the sizes were saved)
  304. // See also TCustomScpExplorerForm::DoShow()
  305. if (OriginalPixelsPerInch != Form->PixelsPerInch)
  306. {
  307. TRect Bounds2 = OriginalBounds;
  308. LoadFormDimensions(AData, PixelsPerInch, Monitor, Form, Bounds2, DefaultPos);
  309. DebugAssert(!DefaultPos);
  310. Form->BoundsRect = Bounds2;
  311. }
  312. }
  313. }
  314. }
  315. else if (State == wsMaximized)
  316. {
  317. Form->Position = poDesigned;
  318. if (!PositionOnly)
  319. {
  320. TRect Bounds2 = OriginalBounds;
  321. bool DefaultPos;
  322. // This gives the form after unmaximization somewhat reasonable size,
  323. // but it does not really set exact dimensions, let only with scaling
  324. LoadFormDimensions(DefaultData, USER_DEFAULT_SCREEN_DPI, Monitor, Form, Bounds2, DefaultPos);
  325. DebugAssert(DefaultPos);
  326. CenterOnMonitor(Form, Monitor, Bounds2);
  327. }
  328. }
  329. }
  330. else if (Form->Position == poDesigned)
  331. {
  332. Form->Position = poDefaultPosOnly;
  333. }
  334. }
  335. //---------------------------------------------------------------------------
  336. UnicodeString __fastcall StoreForm(TForm * Form)
  337. {
  338. DebugAssert(Form);
  339. TRect Bounds = Form->BoundsRect;
  340. OffsetRect(Bounds, -Form->Monitor->Left, -Form->Monitor->Top);
  341. UnicodeString Result =
  342. FORMAT(L"%d;%d;%d;%d;%d;%s", (SaveDimension(Bounds.Left), SaveDimension(Bounds.Top),
  343. SaveDimension(Bounds.Right), SaveDimension(Bounds.Bottom),
  344. // we do not want WinSCP to start minimized next time (we cannot handle that anyway).
  345. (int)(Form->WindowState == wsMinimized ? GetWindowStateBeforeMimimize(Form) : Form->WindowState),
  346. SavePixelsPerInch(Form)));
  347. return Result;
  348. }
  349. //---------------------------------------------------------------------------
  350. void __fastcall RestoreFormSize(UnicodeString Data, TForm * Form)
  351. {
  352. // This has to be called only after DoFormWindowProc(CM_SHOWINGCHANGED).
  353. // See comment in ResizeForm.
  354. UnicodeString WidthStr = CutToChar(Data, L',', true);
  355. UnicodeString HeightStr = CutToChar(Data, L',', true);
  356. int PixelsPerInch = LoadPixelsPerInch(CutToChar(Data, L',', true), Form);
  357. int Width = StrToDimensionDef(WidthStr, PixelsPerInch, Form, Form->Width);
  358. int Height = StrToDimensionDef(HeightStr, PixelsPerInch, Form, Form->Height);
  359. ResizeForm(Form, Width, Height);
  360. }
  361. //---------------------------------------------------------------------------
  362. UnicodeString __fastcall StoreFormSize(TForm * Form)
  363. {
  364. return FORMAT(L"%d,%d,%s", (Form->Width, Form->Height, SavePixelsPerInch(Form)));
  365. }
  366. //---------------------------------------------------------------------------
  367. void ExecuteProcessAndReadOutput(const UnicodeString & Command, UnicodeString & Output, DWORD & ExitCode, bool ReadStdErr)
  368. {
  369. SECURITY_ATTRIBUTES SecurityAttributes;
  370. ZeroMemory(&SecurityAttributes, sizeof(SecurityAttributes));
  371. SecurityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
  372. SecurityAttributes.bInheritHandle = TRUE;
  373. SecurityAttributes.lpSecurityDescriptor = NULL;
  374. HANDLE PipeRead = INVALID_HANDLE_VALUE;
  375. HANDLE PipeWrite = INVALID_HANDLE_VALUE;
  376. if (!CreatePipe(&PipeRead, &PipeWrite, &SecurityAttributes, 0) ||
  377. !SetHandleInformation(PipeRead, HANDLE_FLAG_INHERIT, 0))
  378. {
  379. throw EOSExtException(FMTLOAD(EXECUTE_APP_ERROR, (Command)));
  380. }
  381. PROCESS_INFORMATION ProcessInformation;
  382. ZeroMemory(&ProcessInformation, sizeof(ProcessInformation));
  383. try
  384. {
  385. try
  386. {
  387. STARTUPINFO StartupInfo;
  388. ZeroMemory(&StartupInfo, sizeof(StartupInfo));
  389. StartupInfo.cb = sizeof(STARTUPINFO);
  390. if (ReadStdErr)
  391. {
  392. StartupInfo.hStdError = PipeWrite;
  393. }
  394. StartupInfo.hStdOutput = PipeWrite;
  395. StartupInfo.wShowWindow = SW_HIDE;
  396. StartupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  397. if (!CreateProcess(NULL, Command.c_str(), NULL, NULL, TRUE, 0, NULL, NULL, &StartupInfo, &ProcessInformation))
  398. {
  399. throw EOSExtException(FMTLOAD(EXECUTE_APP_ERROR, (Command)));
  400. }
  401. }
  402. __finally
  403. {
  404. // If we do not close the handle here, the ReadFile below would get stuck once the app finishes writting,
  405. // as it still sees that someone "can" write to the pipe.
  406. CloseHandle(PipeWrite);
  407. }
  408. DWORD BytesAvail;
  409. while (PeekNamedPipe(PipeRead, NULL, 0, NULL, &BytesAvail, NULL))
  410. {
  411. if (BytesAvail > 0)
  412. {
  413. char Buffer[4096];
  414. DWORD BytesToRead = std::min(BytesAvail, static_cast<unsigned long>(sizeof(Buffer)));
  415. DWORD BytesRead;
  416. if (ReadFile(PipeRead, Buffer, BytesToRead, &BytesRead, NULL))
  417. {
  418. Output += UnicodeString(UTF8String(Buffer, BytesRead));
  419. }
  420. }
  421. // Same as in ExecuteShellCheckedAndWait
  422. Sleep(50);
  423. Application->ProcessMessages();
  424. }
  425. DebugCheck(GetExitCodeProcess(ProcessInformation.hProcess, &ExitCode));
  426. }
  427. __finally
  428. {
  429. CloseHandle(ProcessInformation.hProcess);
  430. CloseHandle(ProcessInformation.hThread);
  431. CloseHandle(PipeRead);
  432. }
  433. }
  434. //---------------------------------------------------------------------------
  435. static void __fastcall DoExecuteProcessAndReadOutput(
  436. const UnicodeString & Command, const UnicodeString & HelpKeyword, UnicodeString & Output)
  437. {
  438. if (!CopyCommandToClipboard(Command))
  439. {
  440. DWORD ExitCode;
  441. ExecuteProcessAndReadOutput(Command, Output, ExitCode, true);
  442. if (ExitCode != 0)
  443. {
  444. UnicodeString Buf = Output;
  445. UnicodeString Buf2;
  446. if (ExtractMainInstructions(Buf, Buf2))
  447. {
  448. throw ExtException(Output, EmptyStr, HelpKeyword);
  449. }
  450. else
  451. {
  452. UnicodeString Message = MainInstructions(FMTLOAD(COMMAND_FAILED_CODEONLY, (static_cast<int>(ExitCode))));
  453. throw ExtException(Message, Output, HelpKeyword);
  454. }
  455. }
  456. }
  457. }
  458. //---------------------------------------------------------------------------
  459. void __fastcall ExecuteProcessChecked(
  460. const UnicodeString & Command, const UnicodeString & HelpKeyword, UnicodeString * Output)
  461. {
  462. if (Output == NULL)
  463. {
  464. ExecuteShellChecked(Command);
  465. }
  466. else
  467. {
  468. DoExecuteProcessAndReadOutput(Command, HelpKeyword, *Output);
  469. }
  470. }
  471. //---------------------------------------------------------------------------
  472. void __fastcall ExecuteProcessCheckedAndWait(
  473. const UnicodeString & Command, const UnicodeString & HelpKeyword, UnicodeString * Output)
  474. {
  475. if (Output == NULL)
  476. {
  477. ExecuteShellCheckedAndWait(Command, &Application->ProcessMessages);
  478. }
  479. else
  480. {
  481. DoExecuteProcessAndReadOutput(Command, HelpKeyword, *Output);
  482. }
  483. }
  484. //---------------------------------------------------------------------------
  485. bool __fastcall IsKeyPressed(int VirtualKey)
  486. {
  487. return FLAGSET(GetAsyncKeyState(VirtualKey), 0x8000);
  488. }
  489. //---------------------------------------------------------------------------
  490. bool __fastcall UseAlternativeFunction()
  491. {
  492. return IsKeyPressed(VK_SHIFT);
  493. }
  494. //---------------------------------------------------------------------------
  495. bool __fastcall OpenInNewWindow()
  496. {
  497. return UseAlternativeFunction();
  498. }
  499. //---------------------------------------------------------------------------
  500. void ExecuteSelf(const UnicodeString & Params)
  501. {
  502. ExecuteShellChecked(Application->ExeName, Params);
  503. }
  504. //---------------------------------------------------------------------------
  505. void __fastcall ExecuteNewInstance(const UnicodeString & Param, const UnicodeString & AdditionalParams)
  506. {
  507. UnicodeString Arg;
  508. if (!Param.IsEmpty())
  509. {
  510. Arg = FORMAT(L"\"%s\"", (Param));
  511. }
  512. UnicodeString Space(L" ");
  513. AddToList(Arg, TProgramParams::FormatSwitch(NEWINSTANCE_SWICH), Space);
  514. AddToList(Arg, AdditionalParams, Space);
  515. ExecuteSelf(Arg);
  516. }
  517. //---------------------------------------------------------------------------
  518. IShellLink * __fastcall CreateDesktopShortCut(const UnicodeString & Name,
  519. const UnicodeString &File, const UnicodeString & Params, const UnicodeString & Description,
  520. int SpecialFolder, int IconIndex, bool Return)
  521. {
  522. IShellLink* pLink = NULL;
  523. if (SpecialFolder < 0)
  524. {
  525. SpecialFolder = CSIDL_DESKTOPDIRECTORY;
  526. }
  527. try
  528. {
  529. OleCheck(CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void **) &pLink));
  530. try
  531. {
  532. pLink->SetPath(File.c_str());
  533. pLink->SetDescription(Description.c_str());
  534. pLink->SetArguments(Params.c_str());
  535. pLink->SetShowCmd(SW_SHOW);
  536. // Explicitly setting icon file,
  537. // without this icons are not shown at least in Windows 7 jumplist
  538. pLink->SetIconLocation(File.c_str(), IconIndex);
  539. IPersistFile* pPersistFile;
  540. if (!Return &&
  541. SUCCEEDED(pLink->QueryInterface(IID_IPersistFile, (void **)&pPersistFile)))
  542. {
  543. try
  544. {
  545. LPMALLOC ShellMalloc;
  546. LPITEMIDLIST DesktopPidl;
  547. wchar_t DesktopDir[MAX_PATH];
  548. OleCheck(SHGetMalloc(&ShellMalloc));
  549. try
  550. {
  551. OleCheck(SHGetSpecialFolderLocation(NULL, SpecialFolder, &DesktopPidl));
  552. OleCheck(SHGetPathFromIDList(DesktopPidl, DesktopDir));
  553. }
  554. __finally
  555. {
  556. ShellMalloc->Free(DesktopPidl);
  557. ShellMalloc->Release();
  558. }
  559. WideString strShortCutLocation(DesktopDir);
  560. // Name can contain even path (e.g. to create quick launch icon)
  561. strShortCutLocation += UnicodeString(L"\\") + Name + L".lnk";
  562. OleCheck(pPersistFile->Save(strShortCutLocation.c_bstr(), TRUE));
  563. }
  564. __finally
  565. {
  566. pPersistFile->Release();
  567. }
  568. }
  569. // this is necessary for Windows 7 taskbar jump list links
  570. IPropertyStore * PropertyStore;
  571. if (SUCCEEDED(pLink->QueryInterface(IID_IPropertyStore, (void**)&PropertyStore)))
  572. {
  573. PROPVARIANT Prop;
  574. Prop.vt = VT_LPWSTR;
  575. Prop.pwszVal = Name.c_str();
  576. PropertyStore->SetValue(PKEY_Title, Prop);
  577. PropertyStore->Commit();
  578. PropertyStore->Release();
  579. }
  580. }
  581. catch(...)
  582. {
  583. pLink->Release();
  584. throw;
  585. }
  586. if (!Return)
  587. {
  588. pLink->Release();
  589. pLink = NULL;
  590. }
  591. }
  592. catch(Exception & E)
  593. {
  594. throw ExtException(&E, LoadStr(CREATE_SHORTCUT_ERROR));
  595. }
  596. return pLink;
  597. }
  598. //---------------------------------------------------------------------------
  599. IShellLink * __fastcall CreateAppDesktopShortCut(
  600. const UnicodeString & Name, const UnicodeString & AParams, const UnicodeString & Description,
  601. int SpecialFolder, int IconIndex, bool Return)
  602. {
  603. UnicodeString ParamValue = Configuration->GetIniFileParamValue();
  604. UnicodeString Params;
  605. if (!ParamValue.IsEmpty())
  606. {
  607. Params = TProgramParams::FormatSwitch(INI_SWITCH) + L"=" + AddQuotes(ParamValue);
  608. }
  609. AddToList(Params, AParams, L" ");
  610. return CreateDesktopShortCut(Name, Application->ExeName, Params, Description, SpecialFolder, IconIndex, Return);
  611. }
  612. //---------------------------------------------------------------------------
  613. IShellLink * __fastcall CreateDesktopSessionShortCut(
  614. const UnicodeString & SessionName, UnicodeString Name,
  615. const UnicodeString & AdditionalParams, int SpecialFolder, int IconIndex,
  616. bool Return)
  617. {
  618. bool DefaultsOnly;
  619. UnicodeString InfoTip;
  620. bool IsFolder = StoredSessions->IsFolder(SessionName);
  621. bool IsWorkspace = StoredSessions->IsWorkspace(SessionName);
  622. if (IsFolder || IsWorkspace)
  623. {
  624. InfoTip = FMTLOAD(
  625. (IsFolder ? SHORTCUT_INFO_TIP_FOLDER : SHORTCUT_INFO_TIP_WORKSPACE),
  626. (SessionName));
  627. if (Name.IsEmpty())
  628. {
  629. // no slashes in filename
  630. Name = UnixExtractFileName(SessionName);
  631. }
  632. }
  633. else
  634. {
  635. // this should not be done for workspaces and folders
  636. TSessionData * SessionData =
  637. StoredSessions->ParseUrl(EncodeUrlString(SessionName), NULL, DefaultsOnly);
  638. InfoTip =
  639. FMTLOAD(SHORTCUT_INFO_TIP, (SessionName, SessionData->InfoTip));
  640. if (Name.IsEmpty())
  641. {
  642. // no slashes in filename
  643. Name = SessionData->LocalName;
  644. }
  645. delete SessionData;
  646. }
  647. return
  648. CreateAppDesktopShortCut(ValidLocalFileName(Name),
  649. FORMAT(L"\"%s\"%s%s", (EncodeUrlString(SessionName), (AdditionalParams.IsEmpty() ? L"" : L" "), AdditionalParams)),
  650. InfoTip, SpecialFolder, IconIndex, Return);
  651. }
  652. //---------------------------------------------------------------------------
  653. void ValidateMask(const UnicodeString & Mask, int ForceDirectoryMasks)
  654. {
  655. TFileMasks Masks(ForceDirectoryMasks);
  656. Masks = Mask;
  657. }
  658. //---------------------------------------------------------------------------
  659. template<class TEditControl>
  660. void __fastcall ValidateMaskEditT(const UnicodeString & Mask, TEditControl * Edit, int ForceDirectoryMasks)
  661. {
  662. DebugAssert(Edit != NULL);
  663. if (!IsCancelButtonBeingClicked(Edit))
  664. {
  665. try
  666. {
  667. ValidateMask(Mask, ForceDirectoryMasks);
  668. }
  669. catch(EFileMasksException & E)
  670. {
  671. ShowExtendedException(&E);
  672. Edit->SetFocus();
  673. // This does not work for TEdit and TMemo (descendants of TCustomEdit) anymore,
  674. // as it re-selects whole text on exception in TCustomEdit.CMExit
  675. Edit->SelStart = E.ErrorStart - 1;
  676. Edit->SelLength = E.ErrorLen;
  677. Abort();
  678. }
  679. }
  680. }
  681. //---------------------------------------------------------------------------
  682. void __fastcall ValidateMaskEdit(TComboBox * Edit)
  683. {
  684. ValidateMaskEditT(Edit->Text, Edit, -1);
  685. }
  686. //---------------------------------------------------------------------------
  687. void __fastcall ValidateMaskEdit(TEdit * Edit)
  688. {
  689. ValidateMaskEditT(Edit->Text, Edit, -1);
  690. }
  691. //---------------------------------------------------------------------------
  692. void __fastcall ValidateMaskEdit(TMemo * Edit, bool Directory)
  693. {
  694. if (!IsCancelButtonBeingClicked(Edit))
  695. {
  696. UnicodeString Mask = TFileMasks::ComposeMaskStr(GetUnwrappedMemoLines(Edit), Directory);
  697. ValidateMaskEditT(Mask, Edit, Directory ? 1 : 0);
  698. }
  699. }
  700. //---------------------------------------------------------------------------
  701. TStrings * __fastcall GetUnwrappedMemoLines(TMemo * Memo)
  702. {
  703. // This removes soft linebreaks when text in memo wraps
  704. // (Memo->Lines includes soft linebreaks, while Memo->Text does not)
  705. return TextToStringList(Memo->Text);
  706. }
  707. //---------------------------------------------------------------------------
  708. void __fastcall ExitActiveControl(TForm * Form)
  709. {
  710. if (Form->ActiveControl != NULL)
  711. {
  712. TNotifyEvent OnExit = ((TEdit*)Form->ActiveControl)->OnExit;
  713. if (OnExit != NULL)
  714. {
  715. OnExit(Form->ActiveControl);
  716. }
  717. }
  718. }
  719. //---------------------------------------------------------------------------
  720. bool __fastcall IsWinSCPUrl(const UnicodeString & Url)
  721. {
  722. UnicodeString HomePageUrl = LoadStr(HOMEPAGE_URL);
  723. UnicodeString HttpHomePageUrl = ChangeUrlProtocol(HomePageUrl, HttpProtocol);
  724. DebugAssert(HomePageUrl != HttpHomePageUrl);
  725. return
  726. StartsText(HomePageUrl, Url) ||
  727. StartsText(HttpHomePageUrl, Url);
  728. }
  729. //---------------------------------------------------------------------------
  730. UnicodeString __fastcall SecureUrl(const UnicodeString & Url)
  731. {
  732. UnicodeString Result = Url;
  733. if (IsWinSCPUrl(Url) && IsHttpUrl(Url))
  734. {
  735. Result = ChangeUrlProtocol(Result, HttpsProtocol);
  736. }
  737. return Result;
  738. }
  739. //---------------------------------------------------------------------------
  740. void __fastcall OpenBrowser(UnicodeString URL)
  741. {
  742. if (IsWinSCPUrl(URL))
  743. {
  744. DebugAssert(!IsHttpUrl(URL));
  745. URL = CampaignUrl(URL);
  746. }
  747. if (!CopyCommandToClipboard(URL))
  748. {
  749. // Rather arbitrary limit. Opening a URL over approx. 5 KB fails in Chrome, Firefox and Edge.
  750. const int URLLimit = 4*1024;
  751. if (URL.Length() > URLLimit)
  752. {
  753. URL.SetLength(URLLimit);
  754. }
  755. ShellExecute(Application->Handle, L"open", URL.c_str(), NULL, NULL, SW_SHOWNORMAL);
  756. }
  757. }
  758. //---------------------------------------------------------------------------
  759. void __fastcall OpenFolderInExplorer(const UnicodeString & Path)
  760. {
  761. if ((int)ShellExecute(Application->Handle, L"explore",
  762. (wchar_t*)Path.data(), NULL, NULL, SW_SHOWNORMAL) <= 32)
  763. {
  764. throw Exception(FMTLOAD(EXPLORE_LOCAL_DIR_ERROR, (Path)));
  765. }
  766. }
  767. //---------------------------------------------------------------------------
  768. void __fastcall OpenFileInExplorer(const UnicodeString & Path)
  769. {
  770. PCIDLIST_ABSOLUTE Folder = ILCreateFromPathW(ApiPath(Path).c_str());
  771. SHOpenFolderAndSelectItems(Folder, 0, NULL, 0);
  772. }
  773. //---------------------------------------------------------------------------
  774. void __fastcall ShowHelp(const UnicodeString & AHelpKeyword)
  775. {
  776. // see also AppendUrlParams
  777. UnicodeString HelpKeyword = AHelpKeyword;
  778. const wchar_t FragmentSeparator = L'#';
  779. UnicodeString HelpPath = CutToChar(HelpKeyword, FragmentSeparator, false);
  780. UnicodeString HelpUrl = FMTLOAD(DOCUMENTATION_KEYWORD_URL2, (HelpPath, Configuration->ProductVersion, GUIConfiguration->AppliedLocaleHex));
  781. AddToList(HelpUrl, HelpKeyword, FragmentSeparator);
  782. OpenBrowser(HelpUrl);
  783. }
  784. //---------------------------------------------------------------------------
  785. bool __fastcall IsFormatInClipboard(unsigned int Format)
  786. {
  787. bool Result = OpenClipboard(0);
  788. if (Result)
  789. {
  790. Result = IsClipboardFormatAvailable(Format);
  791. CloseClipboard();
  792. }
  793. return Result;
  794. }
  795. //---------------------------------------------------------------------------
  796. HANDLE __fastcall OpenTextFromClipboard(const wchar_t *& Text)
  797. {
  798. UnicodeString ErrorContext;
  799. try
  800. {
  801. HANDLE Result = NULL;
  802. ErrorContext = L"open";
  803. if (OpenClipboard(0))
  804. {
  805. // Check also for CF_TEXT?
  806. ErrorContext = L"getdata";
  807. Result = GetClipboardData(CF_UNICODETEXT);
  808. if (Result != NULL)
  809. {
  810. ErrorContext = L"lock";
  811. Text = static_cast<const wchar_t*>(GlobalLock(Result));
  812. }
  813. else
  814. {
  815. ErrorContext = L"close";
  816. CloseClipboard();
  817. }
  818. }
  819. return Result;
  820. }
  821. catch (EAccessViolation & E)
  822. {
  823. throw EAccessViolation(AddContextToExceptionMessage(E, ErrorContext));
  824. }
  825. }
  826. //---------------------------------------------------------------------------
  827. void __fastcall CloseTextFromClipboard(HANDLE Handle)
  828. {
  829. UnicodeString ErrorContext;
  830. try
  831. {
  832. if (Handle != NULL)
  833. {
  834. ErrorContext = "unlock";
  835. GlobalUnlock(Handle);
  836. }
  837. ErrorContext = "close";
  838. CloseClipboard();
  839. }
  840. catch (EAccessViolation & E)
  841. {
  842. throw EAccessViolation(AddContextToExceptionMessage(E, ErrorContext));
  843. }
  844. }
  845. //---------------------------------------------------------------------------
  846. bool __fastcall TextFromClipboard(UnicodeString & Text, bool Trim)
  847. {
  848. UnicodeString ErrorContext;
  849. try
  850. {
  851. const wchar_t * AText = NULL;
  852. ErrorContext = L"open";
  853. HANDLE Handle = OpenTextFromClipboard(AText);
  854. bool Result = (Handle != NULL);
  855. if (Result)
  856. {
  857. // For all current uses (URL pasting, key/fingerprint pasting, known_hosts pasting, "more messages" copying,
  858. // permissions pasting), 64KB is large enough.
  859. const int Limit = 64*1024;
  860. ErrorContext = L"size";
  861. size_t Size = GlobalSize(Handle);
  862. int Len = (Size / sizeof(*AText)) - 1;
  863. if (Len > Limit)
  864. {
  865. ErrorContext = FORMAT(L"substring(%d,%d)", (int(Size), Len));
  866. Text = UnicodeString(AText, Limit);
  867. }
  868. else
  869. {
  870. ErrorContext = FORMAT(L"string(%d,%d)", (int(Size), Len));
  871. Text = AText;
  872. }
  873. if (Trim)
  874. {
  875. ErrorContext = L"trim";
  876. Text = Text.Trim();
  877. }
  878. ErrorContext = L"close";
  879. CloseTextFromClipboard(Handle);
  880. }
  881. return Result;
  882. }
  883. catch (EAccessViolation & E)
  884. {
  885. throw EAccessViolation(AddContextToExceptionMessage(E, ErrorContext));
  886. }
  887. }
  888. //---------------------------------------------------------------------------
  889. bool __fastcall NonEmptyTextFromClipboard(UnicodeString & Text)
  890. {
  891. return
  892. TextFromClipboard(Text, true) &&
  893. !Text.IsEmpty();
  894. }
  895. //---------------------------------------------------------------------------
  896. static bool __fastcall GetResource(
  897. const UnicodeString ResName, void *& Content, unsigned long & Size)
  898. {
  899. HRSRC Resource = FindResourceEx(HInstance, RT_RCDATA, ResName.c_str(),
  900. MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL));
  901. bool Result = (Resource != NULL);
  902. if (Result)
  903. {
  904. Size = SizeofResource(HInstance, Resource);
  905. if (!Size)
  906. {
  907. throw Exception(FORMAT(L"Cannot get size of resource %s", (ResName)));
  908. }
  909. Content = LoadResource(HInstance, Resource);
  910. if (!Content)
  911. {
  912. throw Exception(FORMAT(L"Cannot read resource %s", (ResName)));
  913. }
  914. Content = LockResource(Content);
  915. if (!Content)
  916. {
  917. throw Exception(FORMAT(L"Cannot lock resource %s", (ResName)));
  918. }
  919. }
  920. return Result;
  921. }
  922. //---------------------------------------------------------------------------
  923. bool __fastcall DumpResourceToFile(const UnicodeString ResName,
  924. const UnicodeString FileName)
  925. {
  926. void * Content;
  927. unsigned long Size;
  928. bool Result = GetResource(ResName, Content, Size);
  929. if (Result)
  930. {
  931. FILE * f = _wfopen(ApiPath(FileName).c_str(), L"wb");
  932. if (!f)
  933. {
  934. throw Exception(FORMAT(L"Cannot create file %s", (FileName)));
  935. }
  936. if (fwrite(Content, 1, Size, f) != Size)
  937. {
  938. throw Exception(FORMAT(L"Cannot write to file %s", (FileName)));
  939. }
  940. fclose(f);
  941. }
  942. return Result;
  943. }
  944. //---------------------------------------------------------------------------
  945. UnicodeString __fastcall ReadResource(const UnicodeString ResName)
  946. {
  947. void * Content;
  948. unsigned long Size;
  949. UnicodeString Result;
  950. if (GetResource(ResName, Content, Size))
  951. {
  952. Result = UnicodeString(UTF8String(static_cast<char*>(Content), Size));
  953. }
  954. return Result;
  955. }
  956. //---------------------------------------------------------------------------
  957. template <class T>
  958. void __fastcall BrowseForExecutableT(T * Control, UnicodeString Title,
  959. UnicodeString Filter, bool FileNameCommand, bool Escape)
  960. {
  961. UnicodeString Executable, Program, Params, Dir;
  962. Executable = Control->Text;
  963. if (FileNameCommand)
  964. {
  965. ReformatFileNameCommand(Executable);
  966. }
  967. SplitCommand(Executable, Program, Params, Dir);
  968. TOpenDialog * FileDialog = new TOpenDialog(Application);
  969. try
  970. {
  971. if (Escape)
  972. {
  973. Program = ReplaceStr(Program, L"\\\\", L"\\");
  974. }
  975. UnicodeString ExpandedProgram = ExpandEnvironmentVariables(Program);
  976. FileDialog->FileName = ExpandedProgram;
  977. UnicodeString InitialDir = ExtractFilePath(ExpandedProgram);
  978. if (!InitialDir.IsEmpty())
  979. {
  980. FileDialog->InitialDir = InitialDir;
  981. }
  982. FileDialog->Filter = Filter;
  983. FileDialog->Title = Title;
  984. if (FileDialog->Execute())
  985. {
  986. TNotifyEvent PrevOnChange = Control->OnChange;
  987. Control->OnChange = NULL;
  988. try
  989. {
  990. // preserve unexpanded file, if the destination has not changed actually
  991. if (!IsPathToSameFile(ExpandedProgram, FileDialog->FileName))
  992. {
  993. Program = FileDialog->FileName;
  994. if (Escape)
  995. {
  996. Program = ReplaceStr(Program, L"\\", L"\\\\");
  997. }
  998. }
  999. Control->Text = FormatCommand(Program, Params);
  1000. }
  1001. __finally
  1002. {
  1003. Control->OnChange = PrevOnChange;
  1004. }
  1005. if (Control->OnExit != NULL)
  1006. {
  1007. Control->OnExit(Control);
  1008. }
  1009. }
  1010. }
  1011. __finally
  1012. {
  1013. delete FileDialog;
  1014. }
  1015. }
  1016. //---------------------------------------------------------------------------
  1017. void __fastcall BrowseForExecutable(TEdit * Control, UnicodeString Title,
  1018. UnicodeString Filter, bool FileNameCommand, bool Escape)
  1019. {
  1020. BrowseForExecutableT(Control, Title, Filter, FileNameCommand, Escape);
  1021. }
  1022. //---------------------------------------------------------------------------
  1023. void __fastcall BrowseForExecutable(TComboBox * Control, UnicodeString Title,
  1024. UnicodeString Filter, bool FileNameCommand, bool Escape)
  1025. {
  1026. BrowseForExecutableT(Control, Title, Filter, FileNameCommand, Escape);
  1027. }
  1028. //---------------------------------------------------------------------------
  1029. bool __fastcall FontDialog(TFont * Font)
  1030. {
  1031. bool Result;
  1032. TFontDialog * Dialog = new TFontDialog(Application);
  1033. try
  1034. {
  1035. Dialog->Device = fdScreen;
  1036. Dialog->Options = TFontDialogOptions() << fdForceFontExist;
  1037. Dialog->Font = Font;
  1038. Result = Dialog->Execute();
  1039. if (Result)
  1040. {
  1041. Font->Assign(Dialog->Font);
  1042. }
  1043. }
  1044. __finally
  1045. {
  1046. delete Dialog;
  1047. }
  1048. return Result;
  1049. }
  1050. //---------------------------------------------------------------------------
  1051. bool __fastcall SaveDialog(UnicodeString Title, UnicodeString Filter,
  1052. UnicodeString DefaultExt, UnicodeString & FileName)
  1053. {
  1054. bool Result;
  1055. #if 0
  1056. TFileSaveDialog * Dialog = new TFileSaveDialog(Application);
  1057. try
  1058. {
  1059. Dialog->Title = Title;
  1060. FilterToFileTypes(Filter, Dialog->FileTypes);
  1061. Dialog->DefaultExtension = DefaultExt;
  1062. Dialog->FileName = FileName;
  1063. UnicodeString DefaultFolder = ExtractFilePath(FileName);
  1064. if (!DefaultFolder.IsEmpty())
  1065. {
  1066. Dialog->DefaultFolder = DefaultFolder;
  1067. }
  1068. Dialog->Options = Dialog->Options << fdoOverWritePrompt << fdoForceFileSystem <<
  1069. fdoPathMustExist << fdoNoReadOnlyReturn;
  1070. Result = Dialog->Execute();
  1071. if (Result)
  1072. {
  1073. FileName = Dialog->FileName;
  1074. }
  1075. }
  1076. __finally
  1077. {
  1078. delete Dialog;
  1079. }
  1080. #else
  1081. TSaveDialog * Dialog = new TSaveDialog(Application);
  1082. try
  1083. {
  1084. Dialog->Title = Title;
  1085. Dialog->Filter = Filter;
  1086. Dialog->DefaultExt = DefaultExt;
  1087. Dialog->FileName = FileName;
  1088. UnicodeString InitialDir = ExtractFilePath(FileName);
  1089. if (!InitialDir.IsEmpty())
  1090. {
  1091. Dialog->InitialDir = InitialDir;
  1092. }
  1093. Dialog->Options = Dialog->Options << ofOverwritePrompt << ofPathMustExist <<
  1094. ofNoReadOnlyReturn;
  1095. Result = Dialog->Execute();
  1096. if (Result)
  1097. {
  1098. FileName = Dialog->FileName;
  1099. }
  1100. }
  1101. __finally
  1102. {
  1103. delete Dialog;
  1104. }
  1105. #endif
  1106. return Result;
  1107. }
  1108. //---------------------------------------------------------------------------
  1109. void __fastcall CopyToClipboard(UnicodeString Text)
  1110. {
  1111. HANDLE Data;
  1112. void * DataPtr;
  1113. AppLogFmt(L"Copying text to clipboard [%d]", (Text.Length()));
  1114. if (OpenClipboard(0))
  1115. {
  1116. try
  1117. {
  1118. size_t Size = (Text.Length() + 1) * sizeof(wchar_t);
  1119. Data = GlobalAlloc(GMEM_MOVEABLE + GMEM_DDESHARE, Size);
  1120. try
  1121. {
  1122. DataPtr = GlobalLock(Data);
  1123. try
  1124. {
  1125. memcpy(DataPtr, Text.c_str(), Size);
  1126. EmptyClipboard();
  1127. SetClipboardData(CF_UNICODETEXT, Data);
  1128. }
  1129. __finally
  1130. {
  1131. GlobalUnlock(Data);
  1132. }
  1133. }
  1134. catch(...)
  1135. {
  1136. GlobalFree(Data);
  1137. throw;
  1138. }
  1139. }
  1140. __finally
  1141. {
  1142. CloseClipboard();
  1143. }
  1144. AppLogFmt(L"Copied text to clipboard [%d]", (Text.Length()));
  1145. }
  1146. else
  1147. {
  1148. throw Exception(Vcl_Consts_SCannotOpenClipboard);
  1149. }
  1150. }
  1151. //---------------------------------------------------------------------------
  1152. void __fastcall CopyToClipboard(TStrings * Strings)
  1153. {
  1154. if (Strings->Count > 0)
  1155. {
  1156. CopyToClipboard(StringsToText(Strings));
  1157. }
  1158. }
  1159. //---------------------------------------------------------------------------
  1160. static void __fastcall AcquireShutDownPrivileges()
  1161. {
  1162. HANDLE Token;
  1163. // Get a token for this process.
  1164. Win32Check(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &Token));
  1165. TOKEN_PRIVILEGES Priv;
  1166. ZeroMemory(&Priv, sizeof(Priv));
  1167. // Get the LUID for the shutdown privilege.
  1168. // For hibernate/suspend, you need the same:
  1169. // https://stackoverflow.com/q/959589/850848
  1170. Win32Check(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &Priv.Privileges[0].Luid));
  1171. Priv.PrivilegeCount = 1; // one privilege to set
  1172. Priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1173. // Get the shutdown privilege for this process.
  1174. Win32Check(AdjustTokenPrivileges(Token, FALSE, &Priv, 0, (PTOKEN_PRIVILEGES)NULL, 0));
  1175. }
  1176. //---------------------------------------------------------------------------
  1177. void __fastcall ShutDownWindows()
  1178. {
  1179. AcquireShutDownPrivileges();
  1180. // Shut down the system and force all applications to close.
  1181. Win32Check(ExitWindowsEx(EWX_SHUTDOWN | EWX_POWEROFF,
  1182. SHTDN_REASON_MAJOR_OTHER | SHTDN_REASON_MINOR_OTHER | SHTDN_REASON_FLAG_PLANNED));
  1183. }
  1184. //---------------------------------------------------------------------------
  1185. void __fastcall SuspendWindows()
  1186. {
  1187. AcquireShutDownPrivileges();
  1188. // https://learn.microsoft.com/en-us/windows/win32/api/powrprof/nf-powrprof-setsuspendstate
  1189. Win32Check(SetSuspendState(false, false, false));
  1190. }
  1191. //---------------------------------------------------------------------------
  1192. void __fastcall EditSelectBaseName(HWND Edit)
  1193. {
  1194. UnicodeString Text;
  1195. Text.SetLength(GetWindowTextLength(Edit) + 1);
  1196. GetWindowText(Edit, Text.c_str(), Text.Length());
  1197. int P = Text.LastDelimiter(L".");
  1198. if (P > 0)
  1199. {
  1200. // SendMessage does not work, if edit control is not fully
  1201. // initialized yet
  1202. PostMessage(Edit, EM_SETSEL, 0, P - 1);
  1203. }
  1204. }
  1205. //---------------------------------------------------------------------------
  1206. UnicodeString GetConvertedKeyFileName(const UnicodeString & FileName)
  1207. {
  1208. return ChangeFileExt(FileName, FORMAT(L".%s", (PuttyKeyExt)));
  1209. }
  1210. //---------------------------------------------------------------------------
  1211. static bool TryAddMatchingKeyCertificate(
  1212. TPrivateKey * PrivateKey, const UnicodeString & CertificateFileName, UnicodeString & Result)
  1213. {
  1214. if (FileExists(CertificateFileName))
  1215. {
  1216. try
  1217. {
  1218. AddCertificateToKey(PrivateKey, CertificateFileName);
  1219. Result = CertificateFileName;
  1220. }
  1221. catch (Exception & E)
  1222. {
  1223. AppLogFmt(L"Cannot add certificate from auto-detected \"%s\": %s", (CertificateFileName, E.Message));
  1224. }
  1225. }
  1226. return !Result.IsEmpty();
  1227. }
  1228. //---------------------------------------------------------------------------
  1229. UnicodeString AddMatchingKeyCertificate(TPrivateKey * PrivateKey, const UnicodeString & FileName)
  1230. {
  1231. UnicodeString CertificateFileName = FileName;
  1232. UnicodeString S = FORMAT(L".%s", (PuttyKeyExt));
  1233. if (EndsText(S, CertificateFileName))
  1234. {
  1235. CertificateFileName.SetLength(CertificateFileName.Length() - S.Length());
  1236. }
  1237. UnicodeString Result;
  1238. TryAddMatchingKeyCertificate(PrivateKey, CertificateFileName + L"-cert.pub", Result) ||
  1239. TryAddMatchingKeyCertificate(PrivateKey, CertificateFileName + L".pub-aadcert.pub", Result);
  1240. return Result;
  1241. }
  1242. //---------------------------------------------------------------------------
  1243. static void __fastcall ConvertKey(UnicodeString & FileName, TKeyType Type)
  1244. {
  1245. UnicodeString Passphrase;
  1246. UnicodeString Comment;
  1247. if (IsKeyEncrypted(Type, FileName, Comment))
  1248. {
  1249. if (!InputDialog(
  1250. LoadStr(PASSPHRASE_TITLE),
  1251. FORMAT(LoadStr(PROMPT_KEY_PASSPHRASE), (Comment)),
  1252. Passphrase, HELP_NONE, NULL, false, NULL, false))
  1253. {
  1254. Abort();
  1255. }
  1256. }
  1257. TPrivateKey * PrivateKey = LoadKey(Type, FileName, Passphrase);
  1258. try
  1259. {
  1260. AppLogFmt(L"Loaded key from \"%s\".", (FileName));
  1261. UnicodeString CertificateMessage;
  1262. UnicodeString CertificateFileName = AddMatchingKeyCertificate(PrivateKey, FileName);
  1263. if (!CertificateFileName.IsEmpty())
  1264. {
  1265. AppLogFmt(L"Added certificate from auto-detected \"%s\".", (CertificateFileName));
  1266. CertificateMessage = L"\n" + FMTLOAD(CERTIFICATE_ADDED, (CertificateFileName));
  1267. }
  1268. FileName = GetConvertedKeyFileName(FileName);
  1269. if (!SaveDialog(LoadStr(CONVERTKEY_SAVE_TITLE), LoadStr(CONVERTKEY_SAVE_FILTER), PuttyKeyExt, FileName))
  1270. {
  1271. Abort();
  1272. }
  1273. SaveKey(ktSSH2, FileName, Passphrase, PrivateKey);
  1274. AppLogFmt(L"Saved converted key to \"%s\".", (FileName));
  1275. UnicodeString Message =
  1276. MainInstructions(FMTLOAD(CONVERTKEY_SAVED, (FileName))) +
  1277. CertificateMessage;
  1278. MessageDialog(Message, qtInformation, qaOK);
  1279. }
  1280. __finally
  1281. {
  1282. FreeKey(PrivateKey);
  1283. }
  1284. }
  1285. //---------------------------------------------------------------------------
  1286. void DoVerifyKey(UnicodeString & FileName, bool Convert, UnicodeString & Message, TStrings *& MoreMessages, UnicodeString & HelpKeyword)
  1287. {
  1288. std::unique_ptr<TStrings> AMoreMessages;
  1289. if (!FileName.Trim().IsEmpty())
  1290. {
  1291. FileName = ExpandEnvironmentVariables(FileName);
  1292. TKeyType Type = KeyType(FileName);
  1293. // reason _wfopen failed
  1294. int Error = errno;
  1295. HelpKeyword = HELP_LOGIN_KEY_TYPE;
  1296. UnicodeString PuttygenPath;
  1297. switch (Type)
  1298. {
  1299. case ktOpenSSHPEM:
  1300. case ktOpenSSHNew:
  1301. case ktSSHCom:
  1302. {
  1303. UnicodeString TypeName = ((Type == ktOpenSSHPEM) || (Type == ktOpenSSHNew)) ? L"OpenSSH" : L"ssh.com";
  1304. Message = FMTLOAD(KEY_TYPE_UNSUPPORTED2, (FileName, TypeName));
  1305. if (Convert)
  1306. {
  1307. Configuration->Usage->Inc(L"PrivateKeyConvertSuggestionsNative");
  1308. UnicodeString ConvertMessage = FMTLOAD(KEY_TYPE_CONVERT4, (TypeName, RemoveMainInstructionsTag(Message)));
  1309. Message = EmptyStr;
  1310. if (MoreMessageDialog(ConvertMessage, NULL, qtConfirmation, qaOK | qaCancel, HelpKeyword) == qaOK)
  1311. {
  1312. ConvertKey(FileName, Type);
  1313. Configuration->Usage->Inc(L"PrivateKeyConverted");
  1314. }
  1315. else
  1316. {
  1317. Abort();
  1318. }
  1319. }
  1320. else
  1321. {
  1322. HelpKeyword = HELP_KEY_TYPE_UNSUPPORTED;
  1323. }
  1324. }
  1325. break;
  1326. case ktSSH1:
  1327. Message = MainInstructions(FMTLOAD(KEY_TYPE_SSH1, (FileName)));
  1328. break;
  1329. case ktSSH2:
  1330. Message = TestKey(Type, FileName);
  1331. break;
  1332. case ktSSH1Public:
  1333. case ktSSH2PublicRFC4716:
  1334. case ktSSH2PublicOpenSSH:
  1335. // noop
  1336. break;
  1337. case ktUnopenable:
  1338. Message = MainInstructions(FMTLOAD(KEY_TYPE_UNOPENABLE, (FileName)));
  1339. if (Error != ERROR_SUCCESS)
  1340. {
  1341. AMoreMessages.reset(TextToStringList(SysErrorMessageForError(Error)));
  1342. }
  1343. break;
  1344. default:
  1345. DebugFail();
  1346. // fallthru
  1347. case ktUnknown:
  1348. Message = MainInstructions(FMTLOAD(KEY_TYPE_UNKNOWN2, (FileName)));
  1349. break;
  1350. }
  1351. }
  1352. MoreMessages = AMoreMessages.release();
  1353. }
  1354. //---------------------------------------------------------------------------
  1355. static void __fastcall DoVerifyKey(UnicodeString & FileName, bool Convert, bool CanIgnore)
  1356. {
  1357. TStrings * AMoreMessages;
  1358. UnicodeString Message;
  1359. UnicodeString HelpKeyword;
  1360. DoVerifyKey(FileName, Convert, Message, AMoreMessages, HelpKeyword);
  1361. std::unique_ptr<TStrings> MoreMessages(AMoreMessages);
  1362. if (!Message.IsEmpty())
  1363. {
  1364. Configuration->Usage->Inc(L"PrivateKeySelectErrors");
  1365. unsigned int Answers = (CanIgnore ? (qaIgnore | qaAbort) : qaOK);
  1366. if (MoreMessageDialog(Message, MoreMessages.get(), qtWarning, Answers, HelpKeyword) != qaIgnore)
  1367. {
  1368. Abort();
  1369. }
  1370. }
  1371. }
  1372. //---------------------------------------------------------------------------
  1373. void __fastcall VerifyAndConvertKey(UnicodeString & FileName, bool CanIgnore)
  1374. {
  1375. DoVerifyKey(FileName, true, CanIgnore);
  1376. }
  1377. //---------------------------------------------------------------------------
  1378. void __fastcall VerifyKey(const UnicodeString & FileName)
  1379. {
  1380. UnicodeString AFileName(FileName);
  1381. DoVerifyKey(AFileName, false, true);
  1382. }
  1383. //---------------------------------------------------------------------------
  1384. void __fastcall VerifyCertificate(const UnicodeString & FileName)
  1385. {
  1386. if (!FileName.Trim().IsEmpty())
  1387. {
  1388. try
  1389. {
  1390. CheckCertificate(FileName);
  1391. }
  1392. catch (Exception & E)
  1393. {
  1394. if (ExceptionMessageDialog(&E, qtWarning, L"", qaIgnore | qaAbort) == qaAbort)
  1395. {
  1396. Abort();
  1397. }
  1398. }
  1399. }
  1400. }
  1401. //---------------------------------------------------------------------------
  1402. bool __fastcall DetectSystemExternalEditor(
  1403. bool AllowDefaultEditor,
  1404. UnicodeString & Executable, UnicodeString & ExecutableDescription,
  1405. UnicodeString & UsageState, bool & TryNextTime)
  1406. {
  1407. bool Result = false;
  1408. UnicodeString TempName = ExcludeTrailingBackslash(WinConfiguration->TemporaryDir()) + L".txt";
  1409. if (FileExists(ApiPath(TempName)))
  1410. {
  1411. TryNextTime = true;
  1412. UsageState = "F";
  1413. }
  1414. else
  1415. {
  1416. unsigned int File = FileCreate(ApiPath(TempName));
  1417. if (File == (unsigned int)INVALID_HANDLE_VALUE)
  1418. {
  1419. TryNextTime = true;
  1420. UsageState = "F";
  1421. }
  1422. else
  1423. {
  1424. FileClose(File);
  1425. try
  1426. {
  1427. wchar_t ExecutableBuf[MAX_PATH];
  1428. if (!SUCCEEDED(FindExecutable(TempName.c_str(), NULL, ExecutableBuf)))
  1429. {
  1430. UsageState = "N";
  1431. }
  1432. else
  1433. {
  1434. Executable = ExecutableBuf;
  1435. if (Executable.IsEmpty() ||
  1436. !FileExists(ApiPath(Executable)))
  1437. {
  1438. UsageState = "N";
  1439. }
  1440. else
  1441. {
  1442. UnicodeString ExecutableName = ExtractFileName(Executable);
  1443. if (!AllowDefaultEditor &&
  1444. SameText(ExecutableName, TEditorPreferences::GetDefaultExternalEditor()))
  1445. {
  1446. UsageState = "P";
  1447. Executable = L"";
  1448. }
  1449. else if (SameText(ExecutableName, "openwith.exe"))
  1450. {
  1451. UsageState = "W";
  1452. Executable = L"";
  1453. }
  1454. else
  1455. {
  1456. try
  1457. {
  1458. ExecutableDescription = Configuration->GetFileDescription(Executable);
  1459. }
  1460. catch(...)
  1461. {
  1462. }
  1463. if (ExecutableDescription.IsEmpty())
  1464. {
  1465. ExecutableDescription = ExecutableName;
  1466. }
  1467. Result = true;
  1468. }
  1469. }
  1470. }
  1471. }
  1472. __finally
  1473. {
  1474. DeleteFile(ApiPath(TempName));
  1475. }
  1476. }
  1477. }
  1478. return Result;
  1479. }
  1480. //---------------------------------------------------------------------------
  1481. // this was moved to global scope in past in some attempt to fix crashes,
  1482. // not sure it really helped
  1483. WINHTTP_CURRENT_USER_IE_PROXY_CONFIG IEProxyInfo;
  1484. //---------------------------------------------------------------------------
  1485. static bool __fastcall GetProxyUrlFromIE(UnicodeString & Proxy)
  1486. {
  1487. bool Result = false;
  1488. memset(&IEProxyInfo, 0, sizeof(IEProxyInfo));
  1489. if (WinHttpGetIEProxyConfigForCurrentUser(&IEProxyInfo))
  1490. {
  1491. if (IEProxyInfo.lpszProxy != NULL)
  1492. {
  1493. UnicodeString IEProxy = IEProxyInfo.lpszProxy;
  1494. Proxy = L"";
  1495. while (Proxy.IsEmpty() && !IEProxy.IsEmpty())
  1496. {
  1497. UnicodeString Str = CutToChar(IEProxy, L';', true);
  1498. if (Str.Pos(L"=") == 0)
  1499. {
  1500. Proxy = Str;
  1501. }
  1502. else
  1503. {
  1504. UnicodeString Protocol = CutToChar(Str, L'=', true);
  1505. if (SameText(Protocol, L"http"))
  1506. {
  1507. Proxy = Str;
  1508. }
  1509. }
  1510. }
  1511. GlobalFree(IEProxyInfo.lpszProxy);
  1512. Result = true;
  1513. }
  1514. if (IEProxyInfo.lpszAutoConfigUrl != NULL)
  1515. {
  1516. GlobalFree(IEProxyInfo.lpszAutoConfigUrl);
  1517. }
  1518. if (IEProxyInfo.lpszProxyBypass != NULL)
  1519. {
  1520. GlobalFree(IEProxyInfo.lpszProxyBypass);
  1521. }
  1522. }
  1523. return Result;
  1524. }
  1525. //---------------------------------------------------------------------------
  1526. bool __fastcall AutodetectProxy(UnicodeString & HostName, int & PortNumber)
  1527. {
  1528. bool Result = false;
  1529. /* First we try for proxy info direct from the registry if
  1530. it's available. */
  1531. UnicodeString Proxy;
  1532. WINHTTP_PROXY_INFO ProxyInfo;
  1533. memset(&ProxyInfo, 0, sizeof(ProxyInfo));
  1534. if (WinHttpGetDefaultProxyConfiguration(&ProxyInfo))
  1535. {
  1536. if (ProxyInfo.lpszProxy != NULL)
  1537. {
  1538. Proxy = ProxyInfo.lpszProxy;
  1539. GlobalFree(ProxyInfo.lpszProxy);
  1540. Result = true;
  1541. }
  1542. if (ProxyInfo.lpszProxyBypass != NULL)
  1543. {
  1544. GlobalFree(ProxyInfo.lpszProxyBypass);
  1545. }
  1546. }
  1547. /* The next fallback is to get the proxy info from MSIE. This is also
  1548. usually much quicker than WinHttpGetProxyForUrl(), although sometimes
  1549. it seems to fall back to that, based on the longish delay involved.
  1550. Another issue with this is that it won't work in a service process
  1551. that isn't impersonating an interactive user (since there isn't a
  1552. current user), but in that case we just fall back to
  1553. WinHttpGetProxyForUrl() */
  1554. if (!Result)
  1555. {
  1556. Result = GetProxyUrlFromIE(Proxy);
  1557. }
  1558. if (Result)
  1559. {
  1560. if (Proxy.Trim().IsEmpty())
  1561. {
  1562. Result = false;
  1563. }
  1564. else
  1565. {
  1566. HostName = CutToChar(Proxy, L':', true);
  1567. PortNumber = StrToIntDef(Proxy, ProxyPortNumber);
  1568. AppLogFmt("Proxy autodetected: %s:%d", (HostName, PortNumber));
  1569. }
  1570. }
  1571. // We can also use WinHttpGetProxyForUrl, but it is lengthy
  1572. // See the source address of the code for example
  1573. return Result;
  1574. }
  1575. //---------------------------------------------------------------------------
  1576. //---------------------------------------------------------------------------
  1577. class TWinHelpTester : public TInterfacedObject, public IWinHelpTester
  1578. {
  1579. public:
  1580. virtual bool __fastcall CanShowALink(const UnicodeString ALink, const UnicodeString FileName);
  1581. virtual bool __fastcall CanShowTopic(const UnicodeString Topic, const UnicodeString FileName);
  1582. virtual bool __fastcall CanShowContext(const int Context, const UnicodeString FileName);
  1583. virtual TStringList * __fastcall GetHelpStrings(const UnicodeString ALink);
  1584. virtual UnicodeString __fastcall GetHelpPath();
  1585. virtual UnicodeString __fastcall GetDefaultHelpFile();
  1586. IUNKNOWN
  1587. };
  1588. //---------------------------------------------------------------------------
  1589. class TCustomHelpSelector : public TInterfacedObject, public IHelpSelector
  1590. {
  1591. public:
  1592. __fastcall TCustomHelpSelector(const UnicodeString & Name);
  1593. virtual int __fastcall SelectKeyword(TStrings * Keywords);
  1594. virtual int __fastcall TableOfContents(TStrings * Contents);
  1595. IUNKNOWN
  1596. private:
  1597. UnicodeString FName;
  1598. };
  1599. //---------------------------------------------------------------------------
  1600. void __fastcall AssignHelpSelector(IHelpSelector * HelpSelector)
  1601. {
  1602. _di_IHelpSystem HelpSystem;
  1603. if (GetHelpSystem(HelpSystem))
  1604. {
  1605. HelpSystem->AssignHelpSelector(HelpSelector);
  1606. }
  1607. }
  1608. //---------------------------------------------------------------------------
  1609. void __fastcall InitializeCustomHelp(ICustomHelpViewer * HelpViewer)
  1610. {
  1611. _di_IHelpManager HelpManager;
  1612. RegisterViewer(HelpViewer, HelpManager);
  1613. // Register dummy tester that disables win help
  1614. WinHelpTester = new TWinHelpTester();
  1615. AssignHelpSelector(new TCustomHelpSelector(HelpViewer->GetViewerName()));
  1616. }
  1617. //---------------------------------------------------------------------------
  1618. void __fastcall FinalizeCustomHelp()
  1619. {
  1620. AssignHelpSelector(NULL);
  1621. }
  1622. //---------------------------------------------------------------------------
  1623. //---------------------------------------------------------------------------
  1624. bool __fastcall TWinHelpTester::CanShowALink(const UnicodeString ALink,
  1625. const UnicodeString FileName)
  1626. {
  1627. return !Application->HelpFile.IsEmpty();
  1628. }
  1629. //---------------------------------------------------------------------------
  1630. bool __fastcall TWinHelpTester::CanShowTopic(const UnicodeString Topic,
  1631. const UnicodeString FileName)
  1632. {
  1633. DebugFail();
  1634. return !Application->HelpFile.IsEmpty();
  1635. }
  1636. //---------------------------------------------------------------------------
  1637. bool __fastcall TWinHelpTester::CanShowContext(const int /*Context*/,
  1638. const UnicodeString FileName)
  1639. {
  1640. DebugFail();
  1641. return !Application->HelpFile.IsEmpty();
  1642. }
  1643. //---------------------------------------------------------------------------
  1644. TStringList * __fastcall TWinHelpTester::GetHelpStrings(const UnicodeString ALink)
  1645. {
  1646. DebugFail();
  1647. TStringList * Result = new TStringList();
  1648. Result->Add(ViewerName + L": " + ALink);
  1649. return Result;
  1650. }
  1651. //---------------------------------------------------------------------------
  1652. UnicodeString __fastcall TWinHelpTester::GetHelpPath()
  1653. {
  1654. // never called on windows anyway
  1655. return ExtractFilePath(Application->HelpFile);
  1656. }
  1657. //---------------------------------------------------------------------------
  1658. UnicodeString __fastcall TWinHelpTester::GetDefaultHelpFile()
  1659. {
  1660. return Application->HelpFile;
  1661. }
  1662. //---------------------------------------------------------------------------
  1663. //---------------------------------------------------------------------------
  1664. __fastcall TCustomHelpSelector::TCustomHelpSelector(const UnicodeString & Name) :
  1665. FName(Name)
  1666. {
  1667. }
  1668. //---------------------------------------------------------------------------
  1669. int __fastcall TCustomHelpSelector::SelectKeyword(TStrings * /*Keywords*/)
  1670. {
  1671. DebugFail();
  1672. return 0;
  1673. }
  1674. //---------------------------------------------------------------------------
  1675. int __fastcall TCustomHelpSelector::TableOfContents(TStrings * Contents)
  1676. {
  1677. return Contents->IndexOf(FName);
  1678. }