Tools.cpp 49 KB

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