Tools.cpp 56 KB

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