Tools.cpp 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708
  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 ExecuteSelf(const UnicodeString & Params)
  465. {
  466. ExecuteShellChecked(Application->ExeName, Params);
  467. }
  468. //---------------------------------------------------------------------------
  469. void __fastcall ExecuteNewInstance(const UnicodeString & Param, const UnicodeString & AdditionalParams)
  470. {
  471. UnicodeString Arg;
  472. if (!Param.IsEmpty())
  473. {
  474. Arg = FORMAT(L"\"%s\"", (Param));
  475. }
  476. UnicodeString Space(L" ");
  477. AddToList(Arg, TProgramParams::FormatSwitch(NEWINSTANCE_SWICH), Space);
  478. AddToList(Arg, AdditionalParams, Space);
  479. ExecuteSelf(Arg);
  480. }
  481. //---------------------------------------------------------------------------
  482. IShellLink * __fastcall CreateDesktopShortCut(const UnicodeString & Name,
  483. const UnicodeString &File, const UnicodeString & Params, const UnicodeString & Description,
  484. int SpecialFolder, int IconIndex, bool Return)
  485. {
  486. IShellLink* pLink = NULL;
  487. if (SpecialFolder < 0)
  488. {
  489. SpecialFolder = CSIDL_DESKTOPDIRECTORY;
  490. }
  491. try
  492. {
  493. OleCheck(CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void **) &pLink));
  494. try
  495. {
  496. pLink->SetPath(File.c_str());
  497. pLink->SetDescription(Description.c_str());
  498. pLink->SetArguments(Params.c_str());
  499. pLink->SetShowCmd(SW_SHOW);
  500. // Explicitly setting icon file,
  501. // without this icons are not shown at least in Windows 7 jumplist
  502. pLink->SetIconLocation(File.c_str(), IconIndex);
  503. IPersistFile* pPersistFile;
  504. if (!Return &&
  505. SUCCEEDED(pLink->QueryInterface(IID_IPersistFile, (void **)&pPersistFile)))
  506. {
  507. try
  508. {
  509. LPMALLOC ShellMalloc;
  510. LPITEMIDLIST DesktopPidl;
  511. wchar_t DesktopDir[MAX_PATH];
  512. OleCheck(SHGetMalloc(&ShellMalloc));
  513. try
  514. {
  515. OleCheck(SHGetSpecialFolderLocation(NULL, SpecialFolder, &DesktopPidl));
  516. OleCheck(SHGetPathFromIDList(DesktopPidl, DesktopDir));
  517. }
  518. __finally
  519. {
  520. ShellMalloc->Free(DesktopPidl);
  521. ShellMalloc->Release();
  522. }
  523. WideString strShortCutLocation(DesktopDir);
  524. // Name can contain even path (e.g. to create quick launch icon)
  525. strShortCutLocation += UnicodeString(L"\\") + Name + L".lnk";
  526. OleCheck(pPersistFile->Save(strShortCutLocation.c_bstr(), TRUE));
  527. }
  528. __finally
  529. {
  530. pPersistFile->Release();
  531. }
  532. }
  533. // this is necessary for Windows 7 taskbar jump list links
  534. IPropertyStore * PropertyStore;
  535. if (SUCCEEDED(pLink->QueryInterface(IID_IPropertyStore, (void**)&PropertyStore)))
  536. {
  537. PROPVARIANT Prop;
  538. Prop.vt = VT_LPWSTR;
  539. Prop.pwszVal = Name.c_str();
  540. PropertyStore->SetValue(PKEY_Title, Prop);
  541. PropertyStore->Commit();
  542. PropertyStore->Release();
  543. }
  544. }
  545. catch(...)
  546. {
  547. pLink->Release();
  548. throw;
  549. }
  550. if (!Return)
  551. {
  552. pLink->Release();
  553. pLink = NULL;
  554. }
  555. }
  556. catch(Exception & E)
  557. {
  558. throw ExtException(&E, LoadStr(CREATE_SHORTCUT_ERROR));
  559. }
  560. return pLink;
  561. }
  562. //---------------------------------------------------------------------------
  563. IShellLink * __fastcall CreateAppDesktopShortCut(
  564. const UnicodeString & Name, const UnicodeString & AParams, const UnicodeString & Description,
  565. int SpecialFolder, int IconIndex, bool Return)
  566. {
  567. UnicodeString ParamValue = Configuration->GetIniFileParamValue();
  568. UnicodeString Params;
  569. if (!ParamValue.IsEmpty())
  570. {
  571. Params = TProgramParams::FormatSwitch(INI_SWITCH) + L"=" + AddQuotes(ParamValue);
  572. }
  573. AddToList(Params, AParams, L" ");
  574. return CreateDesktopShortCut(Name, Application->ExeName, Params, Description, SpecialFolder, IconIndex, Return);
  575. }
  576. //---------------------------------------------------------------------------
  577. IShellLink * __fastcall CreateDesktopSessionShortCut(
  578. const UnicodeString & SessionName, UnicodeString Name,
  579. const UnicodeString & AdditionalParams, int SpecialFolder, int IconIndex,
  580. bool Return)
  581. {
  582. bool DefaultsOnly;
  583. UnicodeString InfoTip;
  584. bool IsFolder = StoredSessions->IsFolder(SessionName);
  585. bool IsWorkspace = StoredSessions->IsWorkspace(SessionName);
  586. if (IsFolder || IsWorkspace)
  587. {
  588. InfoTip = FMTLOAD(
  589. (IsFolder ? SHORTCUT_INFO_TIP_FOLDER : SHORTCUT_INFO_TIP_WORKSPACE),
  590. (SessionName));
  591. if (Name.IsEmpty())
  592. {
  593. // no slashes in filename
  594. Name = UnixExtractFileName(SessionName);
  595. }
  596. }
  597. else
  598. {
  599. // this should not be done for workspaces and folders
  600. TSessionData * SessionData =
  601. StoredSessions->ParseUrl(EncodeUrlString(SessionName), NULL, DefaultsOnly);
  602. InfoTip =
  603. FMTLOAD(SHORTCUT_INFO_TIP, (SessionName, SessionData->InfoTip));
  604. if (Name.IsEmpty())
  605. {
  606. // no slashes in filename
  607. Name = SessionData->LocalName;
  608. }
  609. delete SessionData;
  610. }
  611. return
  612. CreateAppDesktopShortCut(ValidLocalFileName(Name),
  613. FORMAT(L"\"%s\"%s%s", (EncodeUrlString(SessionName), (AdditionalParams.IsEmpty() ? L"" : L" "), AdditionalParams)),
  614. InfoTip, SpecialFolder, IconIndex, Return);
  615. }
  616. //---------------------------------------------------------------------------
  617. void ValidateMask(const UnicodeString & Mask, int ForceDirectoryMasks)
  618. {
  619. TFileMasks Masks(ForceDirectoryMasks);
  620. Masks = Mask;
  621. }
  622. //---------------------------------------------------------------------------
  623. template<class TEditControl>
  624. void __fastcall ValidateMaskEditT(const UnicodeString & Mask, TEditControl * Edit, int ForceDirectoryMasks)
  625. {
  626. DebugAssert(Edit != NULL);
  627. if (!IsCancelButtonBeingClicked(Edit))
  628. {
  629. try
  630. {
  631. ValidateMask(Mask, ForceDirectoryMasks);
  632. }
  633. catch(EFileMasksException & E)
  634. {
  635. ShowExtendedException(&E);
  636. Edit->SetFocus();
  637. // This does not work for TEdit and TMemo (descendants of TCustomEdit) anymore,
  638. // as it re-selects whole text on exception in TCustomEdit.CMExit
  639. Edit->SelStart = E.ErrorStart - 1;
  640. Edit->SelLength = E.ErrorLen;
  641. Abort();
  642. }
  643. }
  644. }
  645. //---------------------------------------------------------------------------
  646. void __fastcall ValidateMaskEdit(TComboBox * Edit)
  647. {
  648. ValidateMaskEditT(Edit->Text, Edit, -1);
  649. }
  650. //---------------------------------------------------------------------------
  651. void __fastcall ValidateMaskEdit(TEdit * Edit)
  652. {
  653. ValidateMaskEditT(Edit->Text, Edit, -1);
  654. }
  655. //---------------------------------------------------------------------------
  656. void __fastcall ValidateMaskEdit(TMemo * Edit, bool Directory)
  657. {
  658. if (!IsCancelButtonBeingClicked(Edit))
  659. {
  660. UnicodeString Mask = TFileMasks::ComposeMaskStr(GetUnwrappedMemoLines(Edit), Directory);
  661. ValidateMaskEditT(Mask, Edit, Directory ? 1 : 0);
  662. }
  663. }
  664. //---------------------------------------------------------------------------
  665. TStrings * __fastcall GetUnwrappedMemoLines(TMemo * Memo)
  666. {
  667. // This removes soft linebreaks when text in memo wraps
  668. // (Memo->Lines includes soft linebreaks, while Memo->Text does not)
  669. return TextToStringList(Memo->Text);
  670. }
  671. //---------------------------------------------------------------------------
  672. void __fastcall ExitActiveControl(TForm * Form)
  673. {
  674. if (Form->ActiveControl != NULL)
  675. {
  676. TNotifyEvent OnExit = ((TEdit*)Form->ActiveControl)->OnExit;
  677. if (OnExit != NULL)
  678. {
  679. OnExit(Form->ActiveControl);
  680. }
  681. }
  682. }
  683. //---------------------------------------------------------------------------
  684. bool __fastcall IsWinSCPUrl(const UnicodeString & Url)
  685. {
  686. UnicodeString HomePageUrl = LoadStr(HOMEPAGE_URL);
  687. UnicodeString HttpHomePageUrl = ChangeUrlProtocol(HomePageUrl, HttpProtocol);
  688. DebugAssert(HomePageUrl != HttpHomePageUrl);
  689. return
  690. StartsText(HomePageUrl, Url) ||
  691. StartsText(HttpHomePageUrl, Url);
  692. }
  693. //---------------------------------------------------------------------------
  694. UnicodeString __fastcall SecureUrl(const UnicodeString & Url)
  695. {
  696. UnicodeString Result = Url;
  697. if (IsWinSCPUrl(Url) && IsHttpUrl(Url))
  698. {
  699. Result = ChangeUrlProtocol(Result, HttpsProtocol);
  700. }
  701. return Result;
  702. }
  703. //---------------------------------------------------------------------------
  704. void __fastcall OpenBrowser(UnicodeString URL)
  705. {
  706. if (IsWinSCPUrl(URL))
  707. {
  708. DebugAssert(!IsHttpUrl(URL));
  709. URL = CampaignUrl(URL);
  710. }
  711. if (!CopyCommandToClipboard(URL))
  712. {
  713. // Rather arbitrary limit. Opening a URL over approx. 5 KB fails in Chrome, Firefox and Edge.
  714. const int URLLimit = 4*1024;
  715. if (URL.Length() > URLLimit)
  716. {
  717. URL.SetLength(URLLimit);
  718. }
  719. ShellExecute(Application->Handle, L"open", URL.c_str(), NULL, NULL, SW_SHOWNORMAL);
  720. }
  721. }
  722. //---------------------------------------------------------------------------
  723. void __fastcall OpenFolderInExplorer(const UnicodeString & Path)
  724. {
  725. if ((int)ShellExecute(Application->Handle, L"explore",
  726. (wchar_t*)Path.data(), NULL, NULL, SW_SHOWNORMAL) <= 32)
  727. {
  728. throw Exception(FMTLOAD(EXPLORE_LOCAL_DIR_ERROR, (Path)));
  729. }
  730. }
  731. //---------------------------------------------------------------------------
  732. void __fastcall OpenFileInExplorer(const UnicodeString & Path)
  733. {
  734. PCIDLIST_ABSOLUTE Folder = ILCreateFromPathW(ApiPath(Path).c_str());
  735. SHOpenFolderAndSelectItems(Folder, 0, NULL, 0);
  736. }
  737. //---------------------------------------------------------------------------
  738. void __fastcall ShowHelp(const UnicodeString & AHelpKeyword)
  739. {
  740. // see also AppendUrlParams
  741. UnicodeString HelpKeyword = AHelpKeyword;
  742. const wchar_t FragmentSeparator = L'#';
  743. UnicodeString HelpPath = CutToChar(HelpKeyword, FragmentSeparator, false);
  744. UnicodeString HelpUrl = FMTLOAD(DOCUMENTATION_KEYWORD_URL2, (HelpPath, Configuration->ProductVersion, GUIConfiguration->AppliedLocaleHex));
  745. AddToList(HelpUrl, HelpKeyword, FragmentSeparator);
  746. OpenBrowser(HelpUrl);
  747. }
  748. //---------------------------------------------------------------------------
  749. bool __fastcall IsFormatInClipboard(unsigned int Format)
  750. {
  751. bool Result = OpenClipboard(0);
  752. if (Result)
  753. {
  754. Result = IsClipboardFormatAvailable(Format);
  755. CloseClipboard();
  756. }
  757. return Result;
  758. }
  759. //---------------------------------------------------------------------------
  760. HANDLE __fastcall OpenTextFromClipboard(const wchar_t *& Text)
  761. {
  762. UnicodeString ErrorContext;
  763. try
  764. {
  765. HANDLE Result = NULL;
  766. ErrorContext = L"open";
  767. if (OpenClipboard(0))
  768. {
  769. // Check also for CF_TEXT?
  770. ErrorContext = L"getdata";
  771. Result = GetClipboardData(CF_UNICODETEXT);
  772. if (Result != NULL)
  773. {
  774. ErrorContext = L"lock";
  775. Text = static_cast<const wchar_t*>(GlobalLock(Result));
  776. }
  777. else
  778. {
  779. ErrorContext = L"close";
  780. CloseClipboard();
  781. }
  782. }
  783. return Result;
  784. }
  785. catch (EAccessViolation & E)
  786. {
  787. throw EAccessViolation(AddContextToExceptionMessage(E, ErrorContext));
  788. }
  789. }
  790. //---------------------------------------------------------------------------
  791. void __fastcall CloseTextFromClipboard(HANDLE Handle)
  792. {
  793. UnicodeString ErrorContext;
  794. try
  795. {
  796. if (Handle != NULL)
  797. {
  798. ErrorContext = "unlock";
  799. GlobalUnlock(Handle);
  800. }
  801. ErrorContext = "close";
  802. CloseClipboard();
  803. }
  804. catch (EAccessViolation & E)
  805. {
  806. throw EAccessViolation(AddContextToExceptionMessage(E, ErrorContext));
  807. }
  808. }
  809. //---------------------------------------------------------------------------
  810. bool __fastcall TextFromClipboard(UnicodeString & Text, bool Trim)
  811. {
  812. UnicodeString ErrorContext;
  813. try
  814. {
  815. const wchar_t * AText = NULL;
  816. ErrorContext = L"open";
  817. HANDLE Handle = OpenTextFromClipboard(AText);
  818. bool Result = (Handle != NULL);
  819. if (Result)
  820. {
  821. // For all current uses (URL pasting, key/fingerprint pasting, known_hosts pasting, "more messages" copying,
  822. // permissions pasting), 64KB is large enough.
  823. const int Limit = 64*1024;
  824. ErrorContext = L"size";
  825. size_t Size = GlobalSize(Handle);
  826. int Len = (Size / sizeof(*AText)) - 1;
  827. if (Len > Limit)
  828. {
  829. ErrorContext = FORMAT(L"substring(%d,%d)", (int(Size), Len));
  830. Text = UnicodeString(AText, Limit);
  831. }
  832. else
  833. {
  834. ErrorContext = FORMAT(L"string(%d,%d)", (int(Size), Len));
  835. Text = AText;
  836. }
  837. if (Trim)
  838. {
  839. ErrorContext = L"trim";
  840. Text = Text.Trim();
  841. }
  842. ErrorContext = L"close";
  843. CloseTextFromClipboard(Handle);
  844. }
  845. return Result;
  846. }
  847. catch (EAccessViolation & E)
  848. {
  849. throw EAccessViolation(AddContextToExceptionMessage(E, ErrorContext));
  850. }
  851. }
  852. //---------------------------------------------------------------------------
  853. bool __fastcall NonEmptyTextFromClipboard(UnicodeString & Text)
  854. {
  855. return
  856. TextFromClipboard(Text, true) &&
  857. !Text.IsEmpty();
  858. }
  859. //---------------------------------------------------------------------------
  860. static bool __fastcall GetResource(
  861. const UnicodeString ResName, void *& Content, unsigned long & Size)
  862. {
  863. HRSRC Resource = FindResourceEx(HInstance, RT_RCDATA, ResName.c_str(),
  864. MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL));
  865. bool Result = (Resource != NULL);
  866. if (Result)
  867. {
  868. Size = SizeofResource(HInstance, Resource);
  869. if (!Size)
  870. {
  871. throw Exception(FORMAT(L"Cannot get size of resource %s", (ResName)));
  872. }
  873. Content = LoadResource(HInstance, Resource);
  874. if (!Content)
  875. {
  876. throw Exception(FORMAT(L"Cannot read resource %s", (ResName)));
  877. }
  878. Content = LockResource(Content);
  879. if (!Content)
  880. {
  881. throw Exception(FORMAT(L"Cannot lock resource %s", (ResName)));
  882. }
  883. }
  884. return Result;
  885. }
  886. //---------------------------------------------------------------------------
  887. bool __fastcall DumpResourceToFile(const UnicodeString ResName,
  888. const UnicodeString FileName)
  889. {
  890. void * Content;
  891. unsigned long Size;
  892. bool Result = GetResource(ResName, Content, Size);
  893. if (Result)
  894. {
  895. FILE * f = _wfopen(ApiPath(FileName).c_str(), L"wb");
  896. if (!f)
  897. {
  898. throw Exception(FORMAT(L"Cannot create file %s", (FileName)));
  899. }
  900. if (fwrite(Content, 1, Size, f) != Size)
  901. {
  902. throw Exception(FORMAT(L"Cannot write to file %s", (FileName)));
  903. }
  904. fclose(f);
  905. }
  906. return Result;
  907. }
  908. //---------------------------------------------------------------------------
  909. UnicodeString __fastcall ReadResource(const UnicodeString ResName)
  910. {
  911. void * Content;
  912. unsigned long Size;
  913. UnicodeString Result;
  914. if (GetResource(ResName, Content, Size))
  915. {
  916. Result = UnicodeString(UTF8String(static_cast<char*>(Content), Size));
  917. }
  918. return Result;
  919. }
  920. //---------------------------------------------------------------------------
  921. template <class T>
  922. void __fastcall BrowseForExecutableT(T * Control, UnicodeString Title,
  923. UnicodeString Filter, bool FileNameCommand, bool Escape)
  924. {
  925. UnicodeString Executable, Program, Params, Dir;
  926. Executable = Control->Text;
  927. if (FileNameCommand)
  928. {
  929. ReformatFileNameCommand(Executable);
  930. }
  931. SplitCommand(Executable, Program, Params, Dir);
  932. TOpenDialog * FileDialog = new TOpenDialog(Application);
  933. try
  934. {
  935. if (Escape)
  936. {
  937. Program = ReplaceStr(Program, L"\\\\", L"\\");
  938. }
  939. UnicodeString ExpandedProgram = ExpandEnvironmentVariables(Program);
  940. FileDialog->FileName = ExpandedProgram;
  941. UnicodeString InitialDir = ExtractFilePath(ExpandedProgram);
  942. if (!InitialDir.IsEmpty())
  943. {
  944. FileDialog->InitialDir = InitialDir;
  945. }
  946. FileDialog->Filter = Filter;
  947. FileDialog->Title = Title;
  948. if (FileDialog->Execute())
  949. {
  950. TNotifyEvent PrevOnChange = Control->OnChange;
  951. Control->OnChange = NULL;
  952. try
  953. {
  954. // preserve unexpanded file, if the destination has not changed actually
  955. if (!IsPathToSameFile(ExpandedProgram, FileDialog->FileName))
  956. {
  957. Program = FileDialog->FileName;
  958. if (Escape)
  959. {
  960. Program = ReplaceStr(Program, L"\\", L"\\\\");
  961. }
  962. }
  963. Control->Text = FormatCommand(Program, Params);
  964. }
  965. __finally
  966. {
  967. Control->OnChange = PrevOnChange;
  968. }
  969. if (Control->OnExit != NULL)
  970. {
  971. Control->OnExit(Control);
  972. }
  973. }
  974. }
  975. __finally
  976. {
  977. delete FileDialog;
  978. }
  979. }
  980. //---------------------------------------------------------------------------
  981. void __fastcall BrowseForExecutable(TEdit * Control, UnicodeString Title,
  982. UnicodeString Filter, bool FileNameCommand, bool Escape)
  983. {
  984. BrowseForExecutableT(Control, Title, Filter, FileNameCommand, Escape);
  985. }
  986. //---------------------------------------------------------------------------
  987. void __fastcall BrowseForExecutable(TComboBox * Control, UnicodeString Title,
  988. UnicodeString Filter, bool FileNameCommand, bool Escape)
  989. {
  990. BrowseForExecutableT(Control, Title, Filter, FileNameCommand, Escape);
  991. }
  992. //---------------------------------------------------------------------------
  993. bool __fastcall FontDialog(TFont * Font)
  994. {
  995. bool Result;
  996. TFontDialog * Dialog = new TFontDialog(Application);
  997. try
  998. {
  999. Dialog->Device = fdScreen;
  1000. Dialog->Options = TFontDialogOptions() << fdForceFontExist;
  1001. Dialog->Font = Font;
  1002. Result = Dialog->Execute();
  1003. if (Result)
  1004. {
  1005. Font->Assign(Dialog->Font);
  1006. }
  1007. }
  1008. __finally
  1009. {
  1010. delete Dialog;
  1011. }
  1012. return Result;
  1013. }
  1014. //---------------------------------------------------------------------------
  1015. bool __fastcall SaveDialog(UnicodeString Title, UnicodeString Filter,
  1016. UnicodeString DefaultExt, UnicodeString & FileName)
  1017. {
  1018. bool Result;
  1019. #if 0
  1020. TFileSaveDialog * Dialog = new TFileSaveDialog(Application);
  1021. try
  1022. {
  1023. Dialog->Title = Title;
  1024. FilterToFileTypes(Filter, Dialog->FileTypes);
  1025. Dialog->DefaultExtension = DefaultExt;
  1026. Dialog->FileName = FileName;
  1027. UnicodeString DefaultFolder = ExtractFilePath(FileName);
  1028. if (!DefaultFolder.IsEmpty())
  1029. {
  1030. Dialog->DefaultFolder = DefaultFolder;
  1031. }
  1032. Dialog->Options = Dialog->Options << fdoOverWritePrompt << fdoForceFileSystem <<
  1033. fdoPathMustExist << fdoNoReadOnlyReturn;
  1034. Result = Dialog->Execute();
  1035. if (Result)
  1036. {
  1037. FileName = Dialog->FileName;
  1038. }
  1039. }
  1040. __finally
  1041. {
  1042. delete Dialog;
  1043. }
  1044. #else
  1045. TSaveDialog * Dialog = new TSaveDialog(Application);
  1046. try
  1047. {
  1048. Dialog->Title = Title;
  1049. Dialog->Filter = Filter;
  1050. Dialog->DefaultExt = DefaultExt;
  1051. Dialog->FileName = FileName;
  1052. UnicodeString InitialDir = ExtractFilePath(FileName);
  1053. if (!InitialDir.IsEmpty())
  1054. {
  1055. Dialog->InitialDir = InitialDir;
  1056. }
  1057. Dialog->Options = Dialog->Options << ofOverwritePrompt << ofPathMustExist <<
  1058. ofNoReadOnlyReturn;
  1059. Result = Dialog->Execute();
  1060. if (Result)
  1061. {
  1062. FileName = Dialog->FileName;
  1063. }
  1064. }
  1065. __finally
  1066. {
  1067. delete Dialog;
  1068. }
  1069. #endif
  1070. return Result;
  1071. }
  1072. //---------------------------------------------------------------------------
  1073. void __fastcall CopyToClipboard(UnicodeString Text)
  1074. {
  1075. HANDLE Data;
  1076. void * DataPtr;
  1077. AppLogFmt("Copying text to clipboard [%d]", (Text.Length()));
  1078. if (OpenClipboard(0))
  1079. {
  1080. try
  1081. {
  1082. size_t Size = (Text.Length() + 1) * sizeof(wchar_t);
  1083. Data = GlobalAlloc(GMEM_MOVEABLE + GMEM_DDESHARE, Size);
  1084. try
  1085. {
  1086. DataPtr = GlobalLock(Data);
  1087. try
  1088. {
  1089. memcpy(DataPtr, Text.c_str(), Size);
  1090. EmptyClipboard();
  1091. SetClipboardData(CF_UNICODETEXT, Data);
  1092. }
  1093. __finally
  1094. {
  1095. GlobalUnlock(Data);
  1096. }
  1097. }
  1098. catch(...)
  1099. {
  1100. GlobalFree(Data);
  1101. throw;
  1102. }
  1103. }
  1104. __finally
  1105. {
  1106. CloseClipboard();
  1107. }
  1108. AppLogFmt("Copied text to clipboard [%d]", (Text.Length()));
  1109. }
  1110. else
  1111. {
  1112. throw Exception(Vcl_Consts_SCannotOpenClipboard);
  1113. }
  1114. }
  1115. //---------------------------------------------------------------------------
  1116. void __fastcall CopyToClipboard(TStrings * Strings)
  1117. {
  1118. if (Strings->Count > 0)
  1119. {
  1120. CopyToClipboard(StringsToText(Strings));
  1121. }
  1122. }
  1123. //---------------------------------------------------------------------------
  1124. bool __fastcall IsWin64()
  1125. {
  1126. static int Result = -1;
  1127. if (Result < 0)
  1128. {
  1129. Result = 0;
  1130. BOOL Wow64Process = FALSE;
  1131. if (IsWow64Process(GetCurrentProcess(), &Wow64Process))
  1132. {
  1133. if (Wow64Process)
  1134. {
  1135. Result = 1;
  1136. }
  1137. }
  1138. }
  1139. return (Result > 0);
  1140. }
  1141. //---------------------------------------------------------------------------
  1142. static void __fastcall AcquireShutDownPrivileges()
  1143. {
  1144. HANDLE Token;
  1145. // Get a token for this process.
  1146. Win32Check(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &Token));
  1147. TOKEN_PRIVILEGES Priv;
  1148. ZeroMemory(&Priv, sizeof(Priv));
  1149. // Get the LUID for the shutdown privilege.
  1150. // For hibernate/suspend, you need the same:
  1151. // https://stackoverflow.com/q/959589/850848
  1152. Win32Check(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &Priv.Privileges[0].Luid));
  1153. Priv.PrivilegeCount = 1; // one privilege to set
  1154. Priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1155. // Get the shutdown privilege for this process.
  1156. Win32Check(AdjustTokenPrivileges(Token, FALSE, &Priv, 0, (PTOKEN_PRIVILEGES)NULL, 0));
  1157. }
  1158. //---------------------------------------------------------------------------
  1159. void __fastcall ShutDownWindows()
  1160. {
  1161. AcquireShutDownPrivileges();
  1162. // Shut down the system and force all applications to close.
  1163. Win32Check(ExitWindowsEx(EWX_SHUTDOWN | EWX_POWEROFF,
  1164. SHTDN_REASON_MAJOR_OTHER | SHTDN_REASON_MINOR_OTHER | SHTDN_REASON_FLAG_PLANNED));
  1165. }
  1166. //---------------------------------------------------------------------------
  1167. void __fastcall SuspendWindows()
  1168. {
  1169. AcquireShutDownPrivileges();
  1170. // https://learn.microsoft.com/en-us/windows/win32/api/powrprof/nf-powrprof-setsuspendstate
  1171. Win32Check(SetSuspendState(false, false, false));
  1172. }
  1173. //---------------------------------------------------------------------------
  1174. void __fastcall EditSelectBaseName(HWND Edit)
  1175. {
  1176. UnicodeString Text;
  1177. Text.SetLength(GetWindowTextLength(Edit) + 1);
  1178. GetWindowText(Edit, Text.c_str(), Text.Length());
  1179. int P = Text.LastDelimiter(L".");
  1180. if (P > 0)
  1181. {
  1182. // SendMessage does not work, if edit control is not fully
  1183. // initialized yet
  1184. PostMessage(Edit, EM_SETSEL, 0, P - 1);
  1185. }
  1186. }
  1187. //---------------------------------------------------------------------------
  1188. UnicodeString GetConvertedKeyFileName(const UnicodeString & FileName)
  1189. {
  1190. return ChangeFileExt(FileName, FORMAT(L".%s", (PuttyKeyExt)));
  1191. }
  1192. //---------------------------------------------------------------------------
  1193. static void __fastcall ConvertKey(UnicodeString & FileName, TKeyType Type)
  1194. {
  1195. UnicodeString Passphrase;
  1196. UnicodeString Comment;
  1197. if (IsKeyEncrypted(Type, FileName, Comment))
  1198. {
  1199. if (!InputDialog(
  1200. LoadStr(PASSPHRASE_TITLE),
  1201. FORMAT(LoadStr(PROMPT_KEY_PASSPHRASE), (Comment)),
  1202. Passphrase, HELP_NONE, NULL, false, NULL, false))
  1203. {
  1204. Abort();
  1205. }
  1206. }
  1207. TPrivateKey * PrivateKey = LoadKey(Type, FileName, Passphrase);
  1208. try
  1209. {
  1210. FileName = GetConvertedKeyFileName(FileName);
  1211. if (!SaveDialog(LoadStr(CONVERTKEY_SAVE_TITLE), LoadStr(CONVERTKEY_SAVE_FILTER), PuttyKeyExt, FileName))
  1212. {
  1213. Abort();
  1214. }
  1215. SaveKey(ktSSH2, FileName, Passphrase, PrivateKey);
  1216. MessageDialog(MainInstructions(FMTLOAD(CONVERTKEY_SAVED, (FileName))), qtInformation, qaOK);
  1217. }
  1218. __finally
  1219. {
  1220. FreeKey(PrivateKey);
  1221. }
  1222. }
  1223. //---------------------------------------------------------------------------
  1224. void DoVerifyKey(UnicodeString & FileName, bool Convert, UnicodeString & Message, TStrings *& MoreMessages, UnicodeString & HelpKeyword)
  1225. {
  1226. std::unique_ptr<TStrings> AMoreMessages;
  1227. if (!FileName.Trim().IsEmpty())
  1228. {
  1229. FileName = ExpandEnvironmentVariables(FileName);
  1230. TKeyType Type = KeyType(FileName);
  1231. // reason _wfopen failed
  1232. int Error = errno;
  1233. HelpKeyword = HELP_LOGIN_KEY_TYPE;
  1234. UnicodeString PuttygenPath;
  1235. switch (Type)
  1236. {
  1237. case ktOpenSSHPEM:
  1238. case ktOpenSSHNew:
  1239. case ktSSHCom:
  1240. {
  1241. UnicodeString TypeName = ((Type == ktOpenSSHPEM) || (Type == ktOpenSSHNew)) ? L"OpenSSH" : L"ssh.com";
  1242. Message = FMTLOAD(KEY_TYPE_UNSUPPORTED2, (FileName, TypeName));
  1243. if (Convert)
  1244. {
  1245. Configuration->Usage->Inc(L"PrivateKeyConvertSuggestionsNative");
  1246. UnicodeString ConvertMessage = FMTLOAD(KEY_TYPE_CONVERT4, (TypeName, RemoveMainInstructionsTag(Message)));
  1247. Message = EmptyStr;
  1248. if (MoreMessageDialog(ConvertMessage, NULL, qtConfirmation, qaOK | qaCancel, HelpKeyword) == qaOK)
  1249. {
  1250. ConvertKey(FileName, Type);
  1251. Configuration->Usage->Inc(L"PrivateKeyConverted");
  1252. }
  1253. else
  1254. {
  1255. Abort();
  1256. }
  1257. }
  1258. else
  1259. {
  1260. HelpKeyword = HELP_KEY_TYPE_UNSUPPORTED;
  1261. }
  1262. }
  1263. break;
  1264. case ktSSH1:
  1265. Message = MainInstructions(FMTLOAD(KEY_TYPE_SSH1, (FileName)));
  1266. break;
  1267. case ktSSH2:
  1268. Message = TestKey(Type, FileName);
  1269. break;
  1270. case ktSSH1Public:
  1271. case ktSSH2PublicRFC4716:
  1272. case ktSSH2PublicOpenSSH:
  1273. // noop
  1274. break;
  1275. case ktUnopenable:
  1276. Message = MainInstructions(FMTLOAD(KEY_TYPE_UNOPENABLE, (FileName)));
  1277. if (Error != ERROR_SUCCESS)
  1278. {
  1279. AMoreMessages.reset(TextToStringList(SysErrorMessageForError(Error)));
  1280. }
  1281. break;
  1282. default:
  1283. DebugFail();
  1284. // fallthru
  1285. case ktUnknown:
  1286. Message = MainInstructions(FMTLOAD(KEY_TYPE_UNKNOWN2, (FileName)));
  1287. break;
  1288. }
  1289. }
  1290. MoreMessages = AMoreMessages.release();
  1291. }
  1292. //---------------------------------------------------------------------------
  1293. static void __fastcall DoVerifyKey(UnicodeString & FileName, bool Convert, bool CanIgnore)
  1294. {
  1295. TStrings * AMoreMessages;
  1296. UnicodeString Message;
  1297. UnicodeString HelpKeyword;
  1298. DoVerifyKey(FileName, Convert, Message, AMoreMessages, HelpKeyword);
  1299. std::unique_ptr<TStrings> MoreMessages(AMoreMessages);
  1300. if (!Message.IsEmpty())
  1301. {
  1302. Configuration->Usage->Inc(L"PrivateKeySelectErrors");
  1303. unsigned int Answers = (CanIgnore ? (qaIgnore | qaAbort) : qaOK);
  1304. if (MoreMessageDialog(Message, MoreMessages.get(), qtWarning, Answers, HelpKeyword) != qaIgnore)
  1305. {
  1306. Abort();
  1307. }
  1308. }
  1309. }
  1310. //---------------------------------------------------------------------------
  1311. void __fastcall VerifyAndConvertKey(UnicodeString & FileName, bool CanIgnore)
  1312. {
  1313. DoVerifyKey(FileName, true, CanIgnore);
  1314. }
  1315. //---------------------------------------------------------------------------
  1316. void __fastcall VerifyKey(const UnicodeString & FileName)
  1317. {
  1318. UnicodeString AFileName(FileName);
  1319. DoVerifyKey(AFileName, false, true);
  1320. }
  1321. //---------------------------------------------------------------------------
  1322. void __fastcall VerifyCertificate(const UnicodeString & FileName)
  1323. {
  1324. if (!FileName.Trim().IsEmpty())
  1325. {
  1326. try
  1327. {
  1328. CheckCertificate(FileName);
  1329. }
  1330. catch (Exception & E)
  1331. {
  1332. if (ExceptionMessageDialog(&E, qtWarning, L"", qaIgnore | qaAbort) == qaAbort)
  1333. {
  1334. Abort();
  1335. }
  1336. }
  1337. }
  1338. }
  1339. //---------------------------------------------------------------------------
  1340. bool __fastcall DetectSystemExternalEditor(
  1341. bool AllowDefaultEditor,
  1342. UnicodeString & Executable, UnicodeString & ExecutableDescription,
  1343. UnicodeString & UsageState, bool & TryNextTime)
  1344. {
  1345. bool Result = false;
  1346. UnicodeString TempName = ExcludeTrailingBackslash(WinConfiguration->TemporaryDir()) + L".txt";
  1347. if (FileExists(ApiPath(TempName)))
  1348. {
  1349. TryNextTime = true;
  1350. UsageState = "F";
  1351. }
  1352. else
  1353. {
  1354. unsigned int File = FileCreate(ApiPath(TempName));
  1355. if (File == (unsigned int)INVALID_HANDLE_VALUE)
  1356. {
  1357. TryNextTime = true;
  1358. UsageState = "F";
  1359. }
  1360. else
  1361. {
  1362. FileClose(File);
  1363. try
  1364. {
  1365. wchar_t ExecutableBuf[MAX_PATH];
  1366. if (!SUCCEEDED(FindExecutable(TempName.c_str(), NULL, ExecutableBuf)))
  1367. {
  1368. UsageState = "N";
  1369. }
  1370. else
  1371. {
  1372. Executable = ExecutableBuf;
  1373. if (Executable.IsEmpty() ||
  1374. !FileExists(ApiPath(Executable)))
  1375. {
  1376. UsageState = "N";
  1377. }
  1378. else
  1379. {
  1380. UnicodeString ExecutableName = ExtractFileName(Executable);
  1381. if (!AllowDefaultEditor &&
  1382. SameText(ExecutableName, TEditorPreferences::GetDefaultExternalEditor()))
  1383. {
  1384. UsageState = "P";
  1385. Executable = L"";
  1386. }
  1387. else if (SameText(ExecutableName, "openwith.exe"))
  1388. {
  1389. UsageState = "W";
  1390. Executable = L"";
  1391. }
  1392. else
  1393. {
  1394. try
  1395. {
  1396. ExecutableDescription = Configuration->GetFileDescription(Executable);
  1397. }
  1398. catch(...)
  1399. {
  1400. }
  1401. if (ExecutableDescription.IsEmpty())
  1402. {
  1403. ExecutableDescription = ExecutableName;
  1404. }
  1405. Result = true;
  1406. }
  1407. }
  1408. }
  1409. }
  1410. __finally
  1411. {
  1412. DeleteFile(ApiPath(TempName));
  1413. }
  1414. }
  1415. }
  1416. return Result;
  1417. }
  1418. //---------------------------------------------------------------------------
  1419. // this was moved to global scope in past in some attempt to fix crashes,
  1420. // not sure it really helped
  1421. WINHTTP_CURRENT_USER_IE_PROXY_CONFIG IEProxyInfo;
  1422. //---------------------------------------------------------------------------
  1423. static bool __fastcall GetProxyUrlFromIE(UnicodeString & Proxy)
  1424. {
  1425. bool Result = false;
  1426. memset(&IEProxyInfo, 0, sizeof(IEProxyInfo));
  1427. if (WinHttpGetIEProxyConfigForCurrentUser(&IEProxyInfo))
  1428. {
  1429. if (IEProxyInfo.lpszProxy != NULL)
  1430. {
  1431. UnicodeString IEProxy = IEProxyInfo.lpszProxy;
  1432. Proxy = L"";
  1433. while (Proxy.IsEmpty() && !IEProxy.IsEmpty())
  1434. {
  1435. UnicodeString Str = CutToChar(IEProxy, L';', true);
  1436. if (Str.Pos(L"=") == 0)
  1437. {
  1438. Proxy = Str;
  1439. }
  1440. else
  1441. {
  1442. UnicodeString Protocol = CutToChar(Str, L'=', true);
  1443. if (SameText(Protocol, L"http"))
  1444. {
  1445. Proxy = Str;
  1446. }
  1447. }
  1448. }
  1449. GlobalFree(IEProxyInfo.lpszProxy);
  1450. Result = true;
  1451. }
  1452. if (IEProxyInfo.lpszAutoConfigUrl != NULL)
  1453. {
  1454. GlobalFree(IEProxyInfo.lpszAutoConfigUrl);
  1455. }
  1456. if (IEProxyInfo.lpszProxyBypass != NULL)
  1457. {
  1458. GlobalFree(IEProxyInfo.lpszProxyBypass);
  1459. }
  1460. }
  1461. return Result;
  1462. }
  1463. //---------------------------------------------------------------------------
  1464. bool __fastcall AutodetectProxy(UnicodeString & HostName, int & PortNumber)
  1465. {
  1466. bool Result = false;
  1467. /* First we try for proxy info direct from the registry if
  1468. it's available. */
  1469. UnicodeString Proxy;
  1470. WINHTTP_PROXY_INFO ProxyInfo;
  1471. memset(&ProxyInfo, 0, sizeof(ProxyInfo));
  1472. if (WinHttpGetDefaultProxyConfiguration(&ProxyInfo))
  1473. {
  1474. if (ProxyInfo.lpszProxy != NULL)
  1475. {
  1476. Proxy = ProxyInfo.lpszProxy;
  1477. GlobalFree(ProxyInfo.lpszProxy);
  1478. Result = true;
  1479. }
  1480. if (ProxyInfo.lpszProxyBypass != NULL)
  1481. {
  1482. GlobalFree(ProxyInfo.lpszProxyBypass);
  1483. }
  1484. }
  1485. /* The next fallback is to get the proxy info from MSIE. This is also
  1486. usually much quicker than WinHttpGetProxyForUrl(), although sometimes
  1487. it seems to fall back to that, based on the longish delay involved.
  1488. Another issue with this is that it won't work in a service process
  1489. that isn't impersonating an interactive user (since there isn't a
  1490. current user), but in that case we just fall back to
  1491. WinHttpGetProxyForUrl() */
  1492. if (!Result)
  1493. {
  1494. Result = GetProxyUrlFromIE(Proxy);
  1495. }
  1496. if (Result)
  1497. {
  1498. if (Proxy.Trim().IsEmpty())
  1499. {
  1500. Result = false;
  1501. }
  1502. else
  1503. {
  1504. HostName = CutToChar(Proxy, L':', true);
  1505. PortNumber = StrToIntDef(Proxy, ProxyPortNumber);
  1506. }
  1507. }
  1508. // We can also use WinHttpGetProxyForUrl, but it is lengthy
  1509. // See the source address of the code for example
  1510. return Result;
  1511. }
  1512. //---------------------------------------------------------------------------
  1513. //---------------------------------------------------------------------------
  1514. class TWinHelpTester : public TInterfacedObject, public IWinHelpTester
  1515. {
  1516. public:
  1517. virtual bool __fastcall CanShowALink(const UnicodeString ALink, const UnicodeString FileName);
  1518. virtual bool __fastcall CanShowTopic(const UnicodeString Topic, const UnicodeString FileName);
  1519. virtual bool __fastcall CanShowContext(const int Context, const UnicodeString FileName);
  1520. virtual TStringList * __fastcall GetHelpStrings(const UnicodeString ALink);
  1521. virtual UnicodeString __fastcall GetHelpPath();
  1522. virtual UnicodeString __fastcall GetDefaultHelpFile();
  1523. IUNKNOWN
  1524. };
  1525. //---------------------------------------------------------------------------
  1526. class TCustomHelpSelector : public TInterfacedObject, public IHelpSelector
  1527. {
  1528. public:
  1529. __fastcall TCustomHelpSelector(const UnicodeString & Name);
  1530. virtual int __fastcall SelectKeyword(TStrings * Keywords);
  1531. virtual int __fastcall TableOfContents(TStrings * Contents);
  1532. IUNKNOWN
  1533. private:
  1534. UnicodeString FName;
  1535. };
  1536. //---------------------------------------------------------------------------
  1537. void __fastcall AssignHelpSelector(IHelpSelector * HelpSelector)
  1538. {
  1539. _di_IHelpSystem HelpSystem;
  1540. if (GetHelpSystem(HelpSystem))
  1541. {
  1542. HelpSystem->AssignHelpSelector(HelpSelector);
  1543. }
  1544. }
  1545. //---------------------------------------------------------------------------
  1546. void __fastcall InitializeCustomHelp(ICustomHelpViewer * HelpViewer)
  1547. {
  1548. _di_IHelpManager HelpManager;
  1549. RegisterViewer(HelpViewer, HelpManager);
  1550. // Register dummy tester that disables win help
  1551. WinHelpTester = new TWinHelpTester();
  1552. AssignHelpSelector(new TCustomHelpSelector(HelpViewer->GetViewerName()));
  1553. }
  1554. //---------------------------------------------------------------------------
  1555. void __fastcall FinalizeCustomHelp()
  1556. {
  1557. AssignHelpSelector(NULL);
  1558. }
  1559. //---------------------------------------------------------------------------
  1560. //---------------------------------------------------------------------------
  1561. bool __fastcall TWinHelpTester::CanShowALink(const UnicodeString ALink,
  1562. const UnicodeString FileName)
  1563. {
  1564. return !Application->HelpFile.IsEmpty();
  1565. }
  1566. //---------------------------------------------------------------------------
  1567. bool __fastcall TWinHelpTester::CanShowTopic(const UnicodeString Topic,
  1568. const UnicodeString FileName)
  1569. {
  1570. DebugFail();
  1571. return !Application->HelpFile.IsEmpty();
  1572. }
  1573. //---------------------------------------------------------------------------
  1574. bool __fastcall TWinHelpTester::CanShowContext(const int /*Context*/,
  1575. const UnicodeString FileName)
  1576. {
  1577. DebugFail();
  1578. return !Application->HelpFile.IsEmpty();
  1579. }
  1580. //---------------------------------------------------------------------------
  1581. TStringList * __fastcall TWinHelpTester::GetHelpStrings(const UnicodeString ALink)
  1582. {
  1583. DebugFail();
  1584. TStringList * Result = new TStringList();
  1585. Result->Add(ViewerName + L": " + ALink);
  1586. return Result;
  1587. }
  1588. //---------------------------------------------------------------------------
  1589. UnicodeString __fastcall TWinHelpTester::GetHelpPath()
  1590. {
  1591. // never called on windows anyway
  1592. return ExtractFilePath(Application->HelpFile);
  1593. }
  1594. //---------------------------------------------------------------------------
  1595. UnicodeString __fastcall TWinHelpTester::GetDefaultHelpFile()
  1596. {
  1597. return Application->HelpFile;
  1598. }
  1599. //---------------------------------------------------------------------------
  1600. //---------------------------------------------------------------------------
  1601. __fastcall TCustomHelpSelector::TCustomHelpSelector(const UnicodeString & Name) :
  1602. FName(Name)
  1603. {
  1604. }
  1605. //---------------------------------------------------------------------------
  1606. int __fastcall TCustomHelpSelector::SelectKeyword(TStrings * /*Keywords*/)
  1607. {
  1608. DebugFail();
  1609. return 0;
  1610. }
  1611. //---------------------------------------------------------------------------
  1612. int __fastcall TCustomHelpSelector::TableOfContents(TStrings * Contents)
  1613. {
  1614. return Contents->IndexOf(FName);
  1615. }