1
0

Tools.cpp 46 KB

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