Tools.cpp 53 KB

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