Tools.cpp 53 KB

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