Tools.cpp 47 KB

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