GUITools.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. //---------------------------------------------------------------------------
  2. #define NO_WIN32_LEAN_AND_MEAN
  3. #include <vcl.h>
  4. #pragma hdrstop
  5. #include <shlobj.h>
  6. #include <Common.h>
  7. #include "GUITools.h"
  8. #include "GUIConfiguration.h"
  9. #include <TextsCore.h>
  10. #include <CoreMain.h>
  11. #include <SessionData.h>
  12. #include <WinInterface.h>
  13. #include <TbxUtils.hpp>
  14. #include <Math.hpp>
  15. #include "PngImageList.hpp"
  16. //---------------------------------------------------------------------------
  17. #pragma package(smart_init)
  18. //---------------------------------------------------------------------------
  19. extern const UnicodeString PageantTool = L"pageant.exe";
  20. extern const UnicodeString PuttygenTool = L"puttygen.exe";
  21. //---------------------------------------------------------------------------
  22. bool __fastcall FindFile(UnicodeString & Path)
  23. {
  24. bool Result = FileExists(Path);
  25. if (!Result)
  26. {
  27. int Len = GetEnvironmentVariable(L"PATH", NULL, 0);
  28. if (Len > 0)
  29. {
  30. UnicodeString Paths;
  31. Paths.SetLength(Len - 1);
  32. GetEnvironmentVariable(L"PATH", Paths.c_str(), Len);
  33. UnicodeString NewPath = FileSearch(ExtractFileName(Path), Paths);
  34. Result = !NewPath.IsEmpty();
  35. if (Result)
  36. {
  37. Path = NewPath;
  38. }
  39. }
  40. }
  41. return Result;
  42. }
  43. //---------------------------------------------------------------------------
  44. bool __fastcall FileExistsEx(UnicodeString Path)
  45. {
  46. return FindFile(Path);
  47. }
  48. //---------------------------------------------------------------------------
  49. void __fastcall OpenSessionInPutty(const UnicodeString PuttyPath,
  50. TSessionData * SessionData, UnicodeString UserName, UnicodeString Password)
  51. {
  52. UnicodeString Program, AParams, Dir;
  53. SplitCommand(PuttyPath, Program, AParams, Dir);
  54. Program = ExpandEnvironmentVariables(Program);
  55. if (FindFile(Program))
  56. {
  57. AParams = ExpandEnvironmentVariables(AParams);
  58. TCustomCommandData Data(SessionData, UserName, Password);
  59. TRemoteCustomCommand RemoteCustomCommand(Data, SessionData->RemoteDirectory);
  60. TWinInteractiveCustomCommand InteractiveCustomCommand(
  61. &RemoteCustomCommand, L"PuTTY");
  62. UnicodeString Params =
  63. RemoteCustomCommand.Complete(InteractiveCustomCommand.Complete(AParams, false), true);
  64. if (!RemoteCustomCommand.IsSiteCommand(AParams))
  65. {
  66. UnicodeString SessionName;
  67. TRegistryStorage * Storage = NULL;
  68. TSessionData * ExportData = NULL;
  69. TRegistryStorage * SourceStorage = NULL;
  70. try
  71. {
  72. Storage = new TRegistryStorage(Configuration->PuttySessionsKey);
  73. Storage->AccessMode = smReadWrite;
  74. // make it compatible with putty
  75. Storage->MungeStringValues = false;
  76. Storage->ForceAnsi = true;
  77. if (Storage->OpenRootKey(true))
  78. {
  79. if (Storage->KeyExists(SessionData->StorageKey))
  80. {
  81. SessionName = SessionData->SessionName;
  82. }
  83. else
  84. {
  85. SourceStorage = new TRegistryStorage(Configuration->PuttySessionsKey);
  86. SourceStorage->MungeStringValues = false;
  87. SourceStorage->ForceAnsi = true;
  88. if (SourceStorage->OpenSubKey(StoredSessions->DefaultSettings->Name, false) &&
  89. Storage->OpenSubKey(GUIConfiguration->PuttySession, true))
  90. {
  91. Storage->Copy(SourceStorage);
  92. Storage->CloseSubKey();
  93. }
  94. ExportData = new TSessionData(L"");
  95. ExportData->Assign(SessionData);
  96. ExportData->Modified = true;
  97. ExportData->Name = GUIConfiguration->PuttySession;
  98. ExportData->Password = L"";
  99. if (SessionData->FSProtocol == fsFTP)
  100. {
  101. if (GUIConfiguration->TelnetForFtpInPutty)
  102. {
  103. ExportData->PuttyProtocol = PuttyTelnetProtocol;
  104. ExportData->PortNumber = TelnetPortNumber;
  105. // PuTTY does not allow -pw for telnet
  106. Password = L"";
  107. }
  108. else
  109. {
  110. ExportData->PuttyProtocol = PuttySshProtocol;
  111. ExportData->PortNumber = SshPortNumber;
  112. }
  113. }
  114. ExportData->Save(Storage, true);
  115. SessionName = GUIConfiguration->PuttySession;
  116. }
  117. }
  118. }
  119. __finally
  120. {
  121. delete Storage;
  122. delete ExportData;
  123. delete SourceStorage;
  124. }
  125. AddToList(Params, FORMAT(L"-load %s", (EscapePuttyCommandParam(SessionName))), L" ");
  126. }
  127. if (!Password.IsEmpty() && !RemoteCustomCommand.IsPasswordCommand(AParams))
  128. {
  129. AddToList(Params, FORMAT(L"-pw %s", (EscapePuttyCommandParam(Password))), L" ");
  130. }
  131. if (!ExecuteShell(Program, Params))
  132. {
  133. throw Exception(FMTLOAD(EXECUTE_APP_ERROR, (Program)));
  134. }
  135. }
  136. else
  137. {
  138. throw Exception(FMTLOAD(FILE_NOT_FOUND, (Program)));
  139. }
  140. }
  141. //---------------------------------------------------------------------------
  142. bool __fastcall FindTool(const UnicodeString & Name, UnicodeString & Path)
  143. {
  144. UnicodeString AppPath = IncludeTrailingBackslash(ExtractFilePath(Application->ExeName));
  145. Path = AppPath + Name;
  146. bool Result = true;
  147. if (!FileExists(Path))
  148. {
  149. Path = AppPath + L"PuTTY\\" + Name;
  150. if (!FileExists(Path))
  151. {
  152. Path = Name;
  153. if (!FindFile(Path))
  154. {
  155. Result = false;
  156. }
  157. }
  158. }
  159. return Result;
  160. }
  161. //---------------------------------------------------------------------------
  162. bool __fastcall ExecuteShell(const UnicodeString Path, const UnicodeString Params)
  163. {
  164. return ((int)ShellExecute(NULL, L"open", (wchar_t*)Path.data(),
  165. (wchar_t*)Params.data(), NULL, SW_SHOWNORMAL) > 32);
  166. }
  167. //---------------------------------------------------------------------------
  168. bool __fastcall ExecuteShell(const UnicodeString Path, const UnicodeString Params,
  169. HANDLE & Handle)
  170. {
  171. bool Result;
  172. TShellExecuteInfoW ExecuteInfo;
  173. memset(&ExecuteInfo, 0, sizeof(ExecuteInfo));
  174. ExecuteInfo.cbSize = sizeof(ExecuteInfo);
  175. ExecuteInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
  176. ExecuteInfo.hwnd = Application->Handle;
  177. ExecuteInfo.lpFile = (wchar_t*)Path.data();
  178. ExecuteInfo.lpParameters = (wchar_t*)Params.data();
  179. ExecuteInfo.nShow = SW_SHOW;
  180. Result = (ShellExecuteEx(&ExecuteInfo) != 0);
  181. if (Result)
  182. {
  183. Handle = ExecuteInfo.hProcess;
  184. }
  185. return Result;
  186. }
  187. //---------------------------------------------------------------------------
  188. bool __fastcall ExecuteShellAndWait(HWND Handle, const UnicodeString Path,
  189. const UnicodeString Params, TProcessMessagesEvent ProcessMessages)
  190. {
  191. bool Result;
  192. TShellExecuteInfoW ExecuteInfo;
  193. memset(&ExecuteInfo, 0, sizeof(ExecuteInfo));
  194. ExecuteInfo.cbSize = sizeof(ExecuteInfo);
  195. ExecuteInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
  196. ExecuteInfo.hwnd = Handle;
  197. ExecuteInfo.lpFile = (wchar_t*)Path.data();
  198. ExecuteInfo.lpParameters = (wchar_t*)Params.data();
  199. ExecuteInfo.nShow = SW_SHOW;
  200. Result = (ShellExecuteEx(&ExecuteInfo) != 0);
  201. if (Result)
  202. {
  203. if (ProcessMessages != NULL)
  204. {
  205. unsigned long WaitResult;
  206. do
  207. {
  208. WaitResult = WaitForSingleObject(ExecuteInfo.hProcess, 200);
  209. if (WaitResult == WAIT_FAILED)
  210. {
  211. throw Exception(LoadStr(DOCUMENT_WAIT_ERROR));
  212. }
  213. ProcessMessages();
  214. }
  215. while (WaitResult == WAIT_TIMEOUT);
  216. }
  217. else
  218. {
  219. WaitForSingleObject(ExecuteInfo.hProcess, INFINITE);
  220. }
  221. }
  222. return Result;
  223. }
  224. //---------------------------------------------------------------------------
  225. bool __fastcall ExecuteShellAndWait(HWND Handle, const UnicodeString Command,
  226. TProcessMessagesEvent ProcessMessages)
  227. {
  228. UnicodeString Program, Params, Dir;
  229. SplitCommand(Command, Program, Params, Dir);
  230. return ExecuteShellAndWait(Handle, Program, Params, ProcessMessages);
  231. }
  232. //---------------------------------------------------------------------------
  233. bool __fastcall SpecialFolderLocation(int PathID, UnicodeString & Path)
  234. {
  235. LPITEMIDLIST Pidl;
  236. wchar_t Buf[256];
  237. if (SHGetSpecialFolderLocation(NULL, PathID, &Pidl) == NO_ERROR &&
  238. SHGetPathFromIDList(Pidl, Buf))
  239. {
  240. Path = UnicodeString(Buf);
  241. return true;
  242. }
  243. return false;
  244. }
  245. //---------------------------------------------------------------------------
  246. UnicodeString __fastcall ItemsFormatString(const UnicodeString SingleItemFormat,
  247. const UnicodeString MultiItemsFormat, int Count, const UnicodeString FirstItem)
  248. {
  249. UnicodeString Result;
  250. if (Count == 1)
  251. {
  252. Result = FORMAT(SingleItemFormat, (FirstItem));
  253. }
  254. else
  255. {
  256. Result = FORMAT(MultiItemsFormat, (Count));
  257. }
  258. return Result;
  259. }
  260. //---------------------------------------------------------------------------
  261. UnicodeString __fastcall ItemsFormatString(const UnicodeString SingleItemFormat,
  262. const UnicodeString MultiItemsFormat, TStrings * Items)
  263. {
  264. return ItemsFormatString(SingleItemFormat, MultiItemsFormat,
  265. Items->Count, (Items->Count > 0 ? Items->Strings[0] : UnicodeString()));
  266. }
  267. //---------------------------------------------------------------------------
  268. UnicodeString __fastcall FileNameFormatString(const UnicodeString SingleFileFormat,
  269. const UnicodeString MultiFilesFormat, TStrings * Files, bool Remote)
  270. {
  271. assert(Files != NULL);
  272. UnicodeString Item;
  273. if (Files->Count > 0)
  274. {
  275. Item = Remote ? UnixExtractFileName(Files->Strings[0]) :
  276. ExtractFileName(Files->Strings[0]);
  277. }
  278. return ItemsFormatString(SingleFileFormat, MultiFilesFormat,
  279. Files->Count, Item);
  280. }
  281. //---------------------------------------------------------------------------
  282. UnicodeString __fastcall UniqTempDir(const UnicodeString BaseDir, const UnicodeString Identity,
  283. bool Mask)
  284. {
  285. UnicodeString TempDir;
  286. do
  287. {
  288. TempDir = BaseDir.IsEmpty() ? SystemTemporaryDirectory() : BaseDir;
  289. TempDir = IncludeTrailingBackslash(TempDir) + Identity;
  290. if (Mask)
  291. {
  292. TempDir += L"?????";
  293. }
  294. else
  295. {
  296. TempDir += IncludeTrailingBackslash(FormatDateTime(L"nnzzz", Now()));
  297. };
  298. }
  299. while (!Mask && DirectoryExists(TempDir));
  300. return TempDir;
  301. }
  302. //---------------------------------------------------------------------------
  303. bool __fastcall DeleteDirectory(const UnicodeString DirName)
  304. {
  305. TSearchRecChecked sr;
  306. bool retval = true;
  307. if (FindFirstUnchecked(DirName + L"\\*", faAnyFile, sr) == 0) // VCL Function
  308. {
  309. if (FLAGSET(sr.Attr, faDirectory))
  310. {
  311. if (sr.Name != L"." && sr.Name != L"..")
  312. retval = DeleteDirectory(DirName + L"\\" + sr.Name);
  313. }
  314. else
  315. {
  316. retval = DeleteFile(DirName + L"\\" + sr.Name);
  317. }
  318. if (retval)
  319. {
  320. while (FindNextChecked(sr) == 0)
  321. { // VCL Function
  322. if (FLAGSET(sr.Attr, faDirectory))
  323. {
  324. if (sr.Name != L"." && sr.Name != L"..")
  325. retval = DeleteDirectory(DirName + L"\\" + sr.Name);
  326. }
  327. else
  328. {
  329. retval = DeleteFile(DirName + L"\\" + sr.Name);
  330. }
  331. if (!retval) break;
  332. }
  333. }
  334. }
  335. FindClose(sr);
  336. if (retval) retval = RemoveDir(DirName); // VCL function
  337. return retval;
  338. }
  339. //---------------------------------------------------------------------------
  340. UnicodeString __fastcall FormatDateTimeSpan(const UnicodeString TimeFormat, TDateTime DateTime)
  341. {
  342. UnicodeString Result;
  343. if (int(DateTime) > 0)
  344. {
  345. Result = IntToStr(int(DateTime)) + L", ";
  346. }
  347. // days are decremented, because when there are to many of them,
  348. // "integer overflow" error occurs
  349. Result += FormatDateTime(TimeFormat, DateTime - int(DateTime));
  350. return Result;
  351. }
  352. //---------------------------------------------------------------------------
  353. void __fastcall AddSessionColorImage(
  354. TCustomImageList * ImageList, TColor Color, int MaskIndex)
  355. {
  356. // This overly complex drawing is here to support color button on SiteAdvanced
  357. // dialog. There we use plain TImageList, instead of TPngImageList,
  358. // TButton does not work with transparent images
  359. // (not even TBitmap with Transparent = true)
  360. std::unique_ptr<TBitmap> MaskBitmap(new TBitmap());
  361. ImageList->GetBitmap(MaskIndex, MaskBitmap.get());
  362. std::unique_ptr<TPngImage> MaskImage(new TPngImage());
  363. MaskImage->Assign(MaskBitmap.get());
  364. std::unique_ptr<TPngImage> ColorImage(new TPngImage(COLOR_RGB, 16, ImageList->Width, ImageList->Height));
  365. TColor MaskTransparentColor = MaskImage->Pixels[0][0];
  366. TColor TransparentColor = MaskTransparentColor;
  367. // Expecting that the color to be replaced is in the centre of the image (HACK)
  368. TColor MaskColor = MaskImage->Pixels[ImageList->Width / 2][ImageList->Height / 2];
  369. for (int Y = 0; Y < ImageList->Height; Y++)
  370. {
  371. for (int X = 0; X < ImageList->Width; X++)
  372. {
  373. TColor SourceColor = MaskImage->Pixels[X][Y];
  374. TColor DestColor;
  375. // this branch is pointless as long as MaskTransparentColor and
  376. // TransparentColor are the same
  377. if (SourceColor == MaskTransparentColor)
  378. {
  379. DestColor = TransparentColor;
  380. }
  381. else if (SourceColor == MaskColor)
  382. {
  383. DestColor = Color;
  384. }
  385. else
  386. {
  387. DestColor = SourceColor;
  388. }
  389. ColorImage->Pixels[X][Y] = DestColor;
  390. }
  391. }
  392. std::unique_ptr<TBitmap> Bitmap(new TBitmap());
  393. Bitmap->SetSize(ImageList->Width, ImageList->Height);
  394. ColorImage->AssignTo(Bitmap.get());
  395. ImageList->AddMasked(Bitmap.get(), TransparentColor);
  396. }
  397. //---------------------------------------------------------------------------
  398. bool __fastcall IsEligibleForApplyingTabs(
  399. UnicodeString Line, int & TabPos, UnicodeString & Start, UnicodeString & Remaining)
  400. {
  401. bool Result = false;
  402. TabPos = Line.Pos(L"\t");
  403. if (TabPos > 0)
  404. {
  405. Remaining = Line.SubString(TabPos + 1, Line.Length() - TabPos);
  406. // WORKAROUND
  407. // Some translations still use obsolete hack of consecutive tabs to aling the contents.
  408. // Delete these, so that the following check does not fail on this
  409. while (Remaining.SubString(1, 1) == L"\t")
  410. {
  411. Remaining.Delete(1, 1);
  412. }
  413. // We do not have, not support, mutiple tabs on a single line
  414. if (ALWAYS_TRUE(Remaining.Pos(L"\t") == 0))
  415. {
  416. Start = Line.SubString(1, TabPos - 1);
  417. // WORKAROUND
  418. // Previously we padded the string before tab with spaces,
  419. // to aling the contents across multiple lines
  420. Start = Start.TrimRight();
  421. // at least two normal spaces for separation
  422. Start += L" ";
  423. Result = true;
  424. }
  425. }
  426. return Result;
  427. }
  428. //---------------------------------------------------------------------------
  429. static int __fastcall CalculateWidthByLength(UnicodeString Text, void * /*Arg*/)
  430. {
  431. return Text.Length();
  432. }
  433. //---------------------------------------------------------------------------
  434. void __fastcall ApplyTabs(
  435. UnicodeString & Text, wchar_t Padding,
  436. TCalculateWidth CalculateWidth, void * CalculateWidthArg)
  437. {
  438. if (CalculateWidth == NULL)
  439. {
  440. assert(CalculateWidthArg == NULL);
  441. CalculateWidth = CalculateWidthByLength;
  442. }
  443. std::unique_ptr<TStringList> Lines(new TStringList());
  444. Lines->Text = Text;
  445. int MaxWidth = -1;
  446. for (int Index = 0; Index < Lines->Count; Index++)
  447. {
  448. UnicodeString Line = Lines->Strings[Index];
  449. int TabPos;
  450. UnicodeString Start;
  451. UnicodeString Remaining;
  452. if (IsEligibleForApplyingTabs(Line, TabPos, Start, Remaining))
  453. {
  454. int Width = CalculateWidth(Start, CalculateWidthArg);
  455. MaxWidth = Max(MaxWidth, Width);
  456. }
  457. }
  458. // Optimization and also to prevent potential regression for texts without tabs
  459. if (MaxWidth >= 0)
  460. {
  461. for (int Index = 0; Index < Lines->Count; Index++)
  462. {
  463. UnicodeString Line = Lines->Strings[Index];
  464. int TabPos;
  465. UnicodeString Start;
  466. UnicodeString Remaining;
  467. if (IsEligibleForApplyingTabs(Line, TabPos, Start, Remaining))
  468. {
  469. int Width;
  470. while ((Width = CalculateWidth(Start, CalculateWidthArg)) < MaxWidth)
  471. {
  472. int Wider = CalculateWidth(Start + Padding, CalculateWidthArg);
  473. // If padded string is wider than max width by more pixels
  474. // than non-padded string is shorter than max width
  475. if ((Wider > MaxWidth) && ((Wider - MaxWidth) > (MaxWidth - Width)))
  476. {
  477. break;
  478. }
  479. Start += Padding;
  480. }
  481. Lines->Strings[Index] = Start + Remaining;
  482. }
  483. }
  484. Text = Lines->Text;
  485. // remove trailing newline
  486. Text = Text.TrimRight();
  487. }
  488. }
  489. //---------------------------------------------------------------------------
  490. TLocalCustomCommand::TLocalCustomCommand()
  491. {
  492. }
  493. //---------------------------------------------------------------------------
  494. TLocalCustomCommand::TLocalCustomCommand(const TCustomCommandData & Data,
  495. const UnicodeString & Path) :
  496. TFileCustomCommand(Data, Path)
  497. {
  498. }
  499. //---------------------------------------------------------------------------
  500. TLocalCustomCommand::TLocalCustomCommand(const TCustomCommandData & Data,
  501. const UnicodeString & Path, const UnicodeString & FileName,
  502. const UnicodeString & LocalFileName, const UnicodeString & FileList) :
  503. TFileCustomCommand(Data, Path, FileName, FileList)
  504. {
  505. FLocalFileName = LocalFileName;
  506. }
  507. //---------------------------------------------------------------------------
  508. int __fastcall TLocalCustomCommand::PatternLen(const UnicodeString & Command, int Index)
  509. {
  510. int Len;
  511. if ((Index < Command.Length()) && (Command[Index + 1] == L'^'))
  512. {
  513. Len = 3;
  514. }
  515. else
  516. {
  517. Len = TFileCustomCommand::PatternLen(Command, Index);
  518. }
  519. return Len;
  520. }
  521. //---------------------------------------------------------------------------
  522. bool __fastcall TLocalCustomCommand::PatternReplacement(
  523. const UnicodeString & Pattern, UnicodeString & Replacement, bool & Delimit)
  524. {
  525. bool Result;
  526. if (Pattern == L"!^!")
  527. {
  528. Replacement = FLocalFileName;
  529. Result = true;
  530. }
  531. else
  532. {
  533. Result = TFileCustomCommand::PatternReplacement(Pattern, Replacement, Delimit);
  534. }
  535. return Result;
  536. }
  537. //---------------------------------------------------------------------------
  538. void __fastcall TLocalCustomCommand::DelimitReplacement(
  539. UnicodeString & /*Replacement*/, wchar_t /*Quote*/)
  540. {
  541. // never delimit local commands
  542. }
  543. //---------------------------------------------------------------------------
  544. bool __fastcall TLocalCustomCommand::HasLocalFileName(const UnicodeString & Command)
  545. {
  546. return FindPattern(Command, L'^');
  547. }
  548. //---------------------------------------------------------------------------
  549. bool __fastcall TLocalCustomCommand::IsFileCommand(const UnicodeString & Command)
  550. {
  551. return TFileCustomCommand::IsFileCommand(Command) || HasLocalFileName(Command);
  552. }