Tools.cpp 56 KB

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