1
0

Tools.cpp 56 KB

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