Tools.cpp 49 KB

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