Tools.cpp 48 KB

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