GUITools.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <shlobj.h>
  5. #include <Common.h>
  6. #include "GUITools.h"
  7. #include "GUIConfiguration.h"
  8. #include <TextsCore.h>
  9. #include <CoreMain.h>
  10. #include <SessionData.h>
  11. #include <WinInterface.h>
  12. #include <TbxUtils.hpp>
  13. #include <Math.hpp>
  14. #include <WebBrowserEx.hpp>
  15. #include <Tools.h>
  16. #include "PngImageList.hpp"
  17. #include <StrUtils.hpp>
  18. #include <limits>
  19. #include <Glyphs.h>
  20. #include <Animations.h>
  21. #include <PasTools.hpp>
  22. #include <VCLCommon.h>
  23. //---------------------------------------------------------------------------
  24. #pragma package(smart_init)
  25. //---------------------------------------------------------------------------
  26. extern const UnicodeString PageantTool = L"pageant.exe";
  27. extern const UnicodeString PuttygenTool = L"puttygen.exe";
  28. //---------------------------------------------------------------------------
  29. bool __fastcall FindFile(UnicodeString & Path)
  30. {
  31. bool Result = FileExists(ApiPath(Path));
  32. if (!Result)
  33. {
  34. UnicodeString Paths = GetEnvironmentVariable(L"PATH");
  35. if (!Paths.IsEmpty())
  36. {
  37. UnicodeString NewPath = FileSearch(ExtractFileName(Path), Paths);
  38. Result = !NewPath.IsEmpty();
  39. if (Result)
  40. {
  41. Path = NewPath;
  42. }
  43. }
  44. }
  45. return Result;
  46. }
  47. //---------------------------------------------------------------------------
  48. void __fastcall OpenSessionInPutty(const UnicodeString PuttyPath,
  49. TSessionData * SessionData)
  50. {
  51. UnicodeString Program, AParams, Dir;
  52. SplitCommand(PuttyPath, Program, AParams, Dir);
  53. Program = ExpandEnvironmentVariables(Program);
  54. if (FindFile(Program))
  55. {
  56. AParams = ExpandEnvironmentVariables(AParams);
  57. UnicodeString Password = GUIConfiguration->PuttyPassword ? SessionData->Password : UnicodeString();
  58. TCustomCommandData Data(SessionData, 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. UnicodeString PuttyParams;
  65. if (!RemoteCustomCommand.IsSiteCommand(AParams))
  66. {
  67. UnicodeString SessionName;
  68. TRegistryStorage * Storage = NULL;
  69. TSessionData * ExportData = NULL;
  70. TRegistryStorage * SourceStorage = NULL;
  71. try
  72. {
  73. Storage = new TRegistryStorage(Configuration->PuttySessionsKey);
  74. Storage->AccessMode = smReadWrite;
  75. // make it compatible with putty
  76. Storage->MungeStringValues = false;
  77. Storage->ForceAnsi = true;
  78. if (Storage->OpenRootKey(true))
  79. {
  80. if (Storage->KeyExists(SessionData->StorageKey))
  81. {
  82. SessionName = SessionData->SessionName;
  83. }
  84. else
  85. {
  86. SourceStorage = new TRegistryStorage(Configuration->PuttySessionsKey);
  87. SourceStorage->MungeStringValues = false;
  88. SourceStorage->ForceAnsi = true;
  89. if (SourceStorage->OpenSubKey(StoredSessions->DefaultSettings->Name, false) &&
  90. Storage->OpenSubKey(GUIConfiguration->PuttySession, true))
  91. {
  92. Storage->Copy(SourceStorage);
  93. Storage->CloseSubKey();
  94. }
  95. ExportData = new TSessionData(L"");
  96. ExportData->Assign(SessionData);
  97. ExportData->Modified = true;
  98. ExportData->Name = GUIConfiguration->PuttySession;
  99. ExportData->Password = L"";
  100. if (SessionData->FSProtocol == fsFTP)
  101. {
  102. if (GUIConfiguration->TelnetForFtpInPutty)
  103. {
  104. ExportData->PuttyProtocol = PuttyTelnetProtocol;
  105. ExportData->PortNumber = TelnetPortNumber;
  106. // PuTTY does not allow -pw for telnet
  107. Password = L"";
  108. }
  109. else
  110. {
  111. ExportData->PuttyProtocol = PuttySshProtocol;
  112. ExportData->PortNumber = SshPortNumber;
  113. }
  114. }
  115. ExportData->Save(Storage, true);
  116. SessionName = GUIConfiguration->PuttySession;
  117. }
  118. }
  119. }
  120. __finally
  121. {
  122. delete Storage;
  123. delete ExportData;
  124. delete SourceStorage;
  125. }
  126. AddToList(PuttyParams, FORMAT(L"-load %s", (EscapePuttyCommandParam(SessionName))), L" ");
  127. }
  128. if (!Password.IsEmpty() && !RemoteCustomCommand.IsPasswordCommand(AParams))
  129. {
  130. AddToList(PuttyParams, FORMAT(L"-pw %s", (EscapePuttyCommandParam(Password))), L" ");
  131. }
  132. AddToList(PuttyParams, Params, L" ");
  133. if (!ExecuteShell(Program, PuttyParams))
  134. {
  135. throw Exception(FMTLOAD(EXECUTE_APP_ERROR, (Program)));
  136. }
  137. }
  138. else
  139. {
  140. throw Exception(FMTLOAD(FILE_NOT_FOUND, (Program)));
  141. }
  142. }
  143. //---------------------------------------------------------------------------
  144. bool __fastcall FindTool(const UnicodeString & Name, UnicodeString & Path)
  145. {
  146. UnicodeString AppPath = IncludeTrailingBackslash(ExtractFilePath(Application->ExeName));
  147. Path = AppPath + Name;
  148. bool Result = true;
  149. if (!FileExists(ApiPath(Path)))
  150. {
  151. Path = AppPath + L"PuTTY\\" + Name;
  152. if (!FileExists(ApiPath(Path)))
  153. {
  154. Path = Name;
  155. if (!FindFile(Path))
  156. {
  157. Result = false;
  158. }
  159. }
  160. }
  161. return Result;
  162. }
  163. //---------------------------------------------------------------------------
  164. bool __fastcall ExecuteShell(const UnicodeString Path, const UnicodeString Params)
  165. {
  166. return ((int)ShellExecute(NULL, L"open", (wchar_t*)Path.data(),
  167. (wchar_t*)Params.data(), NULL, SW_SHOWNORMAL) > 32);
  168. }
  169. //---------------------------------------------------------------------------
  170. bool __fastcall ExecuteShell(const UnicodeString Path, const UnicodeString Params,
  171. HANDLE & Handle)
  172. {
  173. bool Result;
  174. TShellExecuteInfoW ExecuteInfo;
  175. memset(&ExecuteInfo, 0, sizeof(ExecuteInfo));
  176. ExecuteInfo.cbSize = sizeof(ExecuteInfo);
  177. ExecuteInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
  178. ExecuteInfo.hwnd = Application->Handle;
  179. ExecuteInfo.lpFile = (wchar_t*)Path.data();
  180. ExecuteInfo.lpParameters = (wchar_t*)Params.data();
  181. ExecuteInfo.nShow = SW_SHOW;
  182. Result = (ShellExecuteEx(&ExecuteInfo) != 0);
  183. if (Result)
  184. {
  185. Handle = ExecuteInfo.hProcess;
  186. }
  187. return Result;
  188. }
  189. //---------------------------------------------------------------------------
  190. bool __fastcall ExecuteShellAndWait(HWND Handle, const UnicodeString Path,
  191. const UnicodeString Params, TProcessMessagesEvent ProcessMessages)
  192. {
  193. bool Result;
  194. TShellExecuteInfoW ExecuteInfo;
  195. memset(&ExecuteInfo, 0, sizeof(ExecuteInfo));
  196. ExecuteInfo.cbSize = sizeof(ExecuteInfo);
  197. ExecuteInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
  198. ExecuteInfo.hwnd = Handle;
  199. ExecuteInfo.lpFile = (wchar_t*)Path.data();
  200. ExecuteInfo.lpParameters = (wchar_t*)Params.data();
  201. ExecuteInfo.nShow = SW_SHOW;
  202. Result = (ShellExecuteEx(&ExecuteInfo) != 0);
  203. if (Result)
  204. {
  205. if (ProcessMessages != NULL)
  206. {
  207. unsigned long WaitResult;
  208. do
  209. {
  210. WaitResult = WaitForSingleObject(ExecuteInfo.hProcess, 200);
  211. if (WaitResult == WAIT_FAILED)
  212. {
  213. throw Exception(LoadStr(DOCUMENT_WAIT_ERROR));
  214. }
  215. ProcessMessages();
  216. }
  217. while (WaitResult == WAIT_TIMEOUT);
  218. }
  219. else
  220. {
  221. WaitForSingleObject(ExecuteInfo.hProcess, INFINITE);
  222. }
  223. }
  224. return Result;
  225. }
  226. //---------------------------------------------------------------------------
  227. bool __fastcall ExecuteShellAndWait(HWND Handle, const UnicodeString Command,
  228. TProcessMessagesEvent ProcessMessages)
  229. {
  230. UnicodeString Program, Params, Dir;
  231. SplitCommand(Command, Program, Params, Dir);
  232. return ExecuteShellAndWait(Handle, Program, Params, ProcessMessages);
  233. }
  234. //---------------------------------------------------------------------------
  235. bool __fastcall SpecialFolderLocation(int PathID, UnicodeString & Path)
  236. {
  237. LPITEMIDLIST Pidl;
  238. wchar_t Buf[256];
  239. if (SHGetSpecialFolderLocation(NULL, PathID, &Pidl) == NO_ERROR &&
  240. SHGetPathFromIDList(Pidl, Buf))
  241. {
  242. Path = UnicodeString(Buf);
  243. return true;
  244. }
  245. return false;
  246. }
  247. //---------------------------------------------------------------------------
  248. static UnicodeString __fastcall GetWineHomeFolder()
  249. {
  250. UnicodeString Result;
  251. UnicodeString WineHostHome = GetEnvironmentVariable(L"WINE_HOST_HOME");
  252. if (!WineHostHome.IsEmpty())
  253. {
  254. Result = L"Z:" + FromUnixPath(WineHostHome);
  255. }
  256. else
  257. {
  258. // Should we use WinAPI GetUserName() instead?
  259. UnicodeString UserName = GetEnvironmentVariable(L"USERNAME");
  260. if (!UserName.IsEmpty())
  261. {
  262. Result = L"Z:\\home\\" + UserName;
  263. }
  264. }
  265. if (!DirectoryExists(Result))
  266. {
  267. Result = L"";
  268. }
  269. return Result;
  270. }
  271. //---------------------------------------------------------------------------
  272. UnicodeString __fastcall GetPersonalFolder()
  273. {
  274. UnicodeString Result;
  275. ::SpecialFolderLocation(CSIDL_PERSONAL, Result);
  276. if (IsWine())
  277. {
  278. UnicodeString WineHome = GetWineHomeFolder();
  279. if (!WineHome.IsEmpty())
  280. {
  281. // if at least home exists, use it
  282. Result = WineHome;
  283. // but try to go deeper to "Documents"
  284. UnicodeString WineDocuments =
  285. IncludeTrailingBackslash(WineHome) + L"Documents";
  286. if (DirectoryExists(WineDocuments))
  287. {
  288. Result = WineDocuments;
  289. }
  290. }
  291. }
  292. return Result;
  293. }
  294. //---------------------------------------------------------------------------
  295. UnicodeString __fastcall GetDesktopFolder()
  296. {
  297. UnicodeString Result;
  298. ::SpecialFolderLocation(CSIDL_DESKTOPDIRECTORY, Result);
  299. if (IsWine())
  300. {
  301. UnicodeString WineHome = GetWineHomeFolder();
  302. if (!WineHome.IsEmpty())
  303. {
  304. UnicodeString WineDesktop =
  305. IncludeTrailingBackslash(WineHome) + L"Desktop";
  306. if (DirectoryExists(WineHome))
  307. {
  308. Result = WineDesktop;
  309. }
  310. }
  311. }
  312. return Result;
  313. }
  314. //---------------------------------------------------------------------------
  315. UnicodeString __fastcall UniqTempDir(const UnicodeString BaseDir, const UnicodeString Identity,
  316. bool Mask)
  317. {
  318. assert(!BaseDir.IsEmpty());
  319. UnicodeString TempDir;
  320. do
  321. {
  322. TempDir = IncludeTrailingBackslash(BaseDir) + Identity;
  323. if (Mask)
  324. {
  325. TempDir += L"?????";
  326. }
  327. else
  328. {
  329. TempDir += IncludeTrailingBackslash(FormatDateTime(L"nnzzz", Now()));
  330. }
  331. }
  332. while (!Mask && DirectoryExists(ApiPath(TempDir)));
  333. return TempDir;
  334. }
  335. //---------------------------------------------------------------------------
  336. bool __fastcall DeleteDirectory(const UnicodeString DirName)
  337. {
  338. TSearchRecChecked sr;
  339. bool retval = true;
  340. if (FindFirstUnchecked(DirName + L"\\*", faAnyFile, sr) == 0) // VCL Function
  341. {
  342. if (FLAGSET(sr.Attr, faDirectory))
  343. {
  344. if (sr.Name != L"." && sr.Name != L"..")
  345. retval = DeleteDirectory(DirName + L"\\" + sr.Name);
  346. }
  347. else
  348. {
  349. retval = DeleteFile(ApiPath(DirName + L"\\" + sr.Name));
  350. }
  351. if (retval)
  352. {
  353. while (FindNextChecked(sr) == 0)
  354. { // VCL Function
  355. if (FLAGSET(sr.Attr, faDirectory))
  356. {
  357. if (sr.Name != L"." && sr.Name != L"..")
  358. retval = DeleteDirectory(DirName + L"\\" + sr.Name);
  359. }
  360. else
  361. {
  362. retval = DeleteFile(ApiPath(DirName + L"\\" + sr.Name));
  363. }
  364. if (!retval) break;
  365. }
  366. }
  367. }
  368. FindClose(sr);
  369. if (retval) retval = RemoveDir(ApiPath(DirName)); // VCL function
  370. return retval;
  371. }
  372. //---------------------------------------------------------------------------
  373. UnicodeString __fastcall FormatDateTimeSpan(const UnicodeString TimeFormat, TDateTime DateTime)
  374. {
  375. UnicodeString Result;
  376. if (int(DateTime) > 0)
  377. {
  378. Result = IntToStr(int(DateTime)) + L", ";
  379. }
  380. // days are decremented, because when there are to many of them,
  381. // "integer overflow" error occurs
  382. Result += FormatDateTime(TimeFormat, DateTime - int(DateTime));
  383. return Result;
  384. }
  385. //---------------------------------------------------------------------------
  386. void __fastcall AddSessionColorImage(
  387. TCustomImageList * ImageList, TColor Color, int MaskIndex)
  388. {
  389. // This overly complex drawing is here to support color button on SiteAdvanced
  390. // dialog. There we use plain TImageList, instead of TPngImageList,
  391. // TButton does not work with transparent images
  392. // (not even TBitmap with Transparent = true)
  393. std::unique_ptr<TBitmap> MaskBitmap(new TBitmap());
  394. ImageList->GetBitmap(MaskIndex, MaskBitmap.get());
  395. std::unique_ptr<TPngImage> MaskImage(new TPngImage());
  396. MaskImage->Assign(MaskBitmap.get());
  397. std::unique_ptr<TPngImage> ColorImage(new TPngImage(COLOR_RGB, 16, ImageList->Width, ImageList->Height));
  398. TColor MaskTransparentColor = MaskImage->Pixels[0][0];
  399. TColor TransparentColor = MaskTransparentColor;
  400. // Expecting that the color to be replaced is in the centre of the image (HACK)
  401. TColor MaskColor = MaskImage->Pixels[ImageList->Width / 2][ImageList->Height / 2];
  402. for (int Y = 0; Y < ImageList->Height; Y++)
  403. {
  404. for (int X = 0; X < ImageList->Width; X++)
  405. {
  406. TColor SourceColor = MaskImage->Pixels[X][Y];
  407. TColor DestColor;
  408. // this branch is pointless as long as MaskTransparentColor and
  409. // TransparentColor are the same
  410. if (SourceColor == MaskTransparentColor)
  411. {
  412. DestColor = TransparentColor;
  413. }
  414. else if (SourceColor == MaskColor)
  415. {
  416. DestColor = Color;
  417. }
  418. else
  419. {
  420. DestColor = SourceColor;
  421. }
  422. ColorImage->Pixels[X][Y] = DestColor;
  423. }
  424. }
  425. std::unique_ptr<TBitmap> Bitmap(new TBitmap());
  426. Bitmap->SetSize(ImageList->Width, ImageList->Height);
  427. ColorImage->AssignTo(Bitmap.get());
  428. ImageList->AddMasked(Bitmap.get(), TransparentColor);
  429. }
  430. //---------------------------------------------------------------------------
  431. void __fastcall SetSubmenu(TTBXCustomItem * Item)
  432. {
  433. class TTBXPublicItem : public TTBXCustomItem
  434. {
  435. public:
  436. __property ItemStyle;
  437. };
  438. TTBXPublicItem * PublicItem = reinterpret_cast<TTBXPublicItem *>(Item);
  439. DebugAssert(PublicItem != NULL);
  440. // See TTBItemViewer.IsPtInButtonPart (called from TTBItemViewer.MouseDown)
  441. PublicItem->ItemStyle = PublicItem->ItemStyle << tbisSubmenu;
  442. }
  443. //---------------------------------------------------------------------------
  444. bool __fastcall IsEligibleForApplyingTabs(
  445. UnicodeString Line, int & TabPos, UnicodeString & Start, UnicodeString & Remaining)
  446. {
  447. bool Result = false;
  448. TabPos = Line.Pos(L"\t");
  449. if (TabPos > 0)
  450. {
  451. Remaining = Line.SubString(TabPos + 1, Line.Length() - TabPos);
  452. // WORKAROUND
  453. // Some translations still use obsolete hack of consecutive tabs to aling the contents.
  454. // Delete these, so that the following check does not fail on this
  455. while (Remaining.SubString(1, 1) == L"\t")
  456. {
  457. Remaining.Delete(1, 1);
  458. }
  459. // We do not have, not support, mutiple tabs on a single line
  460. if (ALWAYS_TRUE(Remaining.Pos(L"\t") == 0))
  461. {
  462. Start = Line.SubString(1, TabPos - 1);
  463. // WORKAROUND
  464. // Previously we padded the string before tab with spaces,
  465. // to aling the contents across multiple lines
  466. Start = Start.TrimRight();
  467. // at least two normal spaces for separation
  468. Start += L" ";
  469. Result = true;
  470. }
  471. }
  472. return Result;
  473. }
  474. //---------------------------------------------------------------------------
  475. static int __fastcall CalculateWidthByLength(UnicodeString Text, void * /*Arg*/)
  476. {
  477. return Text.Length();
  478. }
  479. //---------------------------------------------------------------------------
  480. void __fastcall ApplyTabs(
  481. UnicodeString & Text, wchar_t Padding,
  482. TCalculateWidth CalculateWidth, void * CalculateWidthArg)
  483. {
  484. if (CalculateWidth == NULL)
  485. {
  486. DebugAssert(CalculateWidthArg == NULL);
  487. CalculateWidth = CalculateWidthByLength;
  488. }
  489. std::unique_ptr<TStringList> Lines(TextToStringList(Text));
  490. int MaxWidth = -1;
  491. for (int Index = 0; Index < Lines->Count; Index++)
  492. {
  493. UnicodeString Line = Lines->Strings[Index];
  494. int TabPos;
  495. UnicodeString Start;
  496. UnicodeString Remaining;
  497. if (IsEligibleForApplyingTabs(Line, TabPos, Start, Remaining))
  498. {
  499. int Width = CalculateWidth(Start, CalculateWidthArg);
  500. MaxWidth = Max(MaxWidth, Width);
  501. }
  502. }
  503. // Optimization and also to prevent potential regression for texts without tabs
  504. if (MaxWidth >= 0)
  505. {
  506. for (int Index = 0; Index < Lines->Count; Index++)
  507. {
  508. UnicodeString Line = Lines->Strings[Index];
  509. int TabPos;
  510. UnicodeString Start;
  511. UnicodeString Remaining;
  512. if (IsEligibleForApplyingTabs(Line, TabPos, Start, Remaining))
  513. {
  514. int Width;
  515. while ((Width = CalculateWidth(Start, CalculateWidthArg)) < MaxWidth)
  516. {
  517. int Wider = CalculateWidth(Start + Padding, CalculateWidthArg);
  518. // If padded string is wider than max width by more pixels
  519. // than non-padded string is shorter than max width
  520. if ((Wider > MaxWidth) && ((Wider - MaxWidth) > (MaxWidth - Width)))
  521. {
  522. break;
  523. }
  524. Start += Padding;
  525. }
  526. Lines->Strings[Index] = Start + Remaining;
  527. }
  528. }
  529. Text = Lines->Text;
  530. // remove trailing newline
  531. Text = Text.TrimRight();
  532. }
  533. }
  534. //---------------------------------------------------------------------------
  535. void __fastcall SelectScaledImageList(TImageList * ImageList)
  536. {
  537. TImageList * MatchingList = NULL;
  538. int MachingPixelsPerInch = 0;
  539. int PixelsPerInch = Screen->PixelsPerInch;
  540. for (int Index = 0; Index < ImageList->Owner->ComponentCount; Index++)
  541. {
  542. TImageList * OtherList = dynamic_cast<TImageList *>(ImageList->Owner->Components[Index]);
  543. if ((OtherList != NULL) &&
  544. (OtherList != ImageList) &&
  545. StartsStr(ImageList->Name, OtherList->Name))
  546. {
  547. UnicodeString OtherListPixelsPerInchStr =
  548. OtherList->Name.SubString(
  549. ImageList->Name.Length() + 1, OtherList->Name.Length() - ImageList->Name.Length());
  550. int OtherListPixelsPerInch = StrToInt(OtherListPixelsPerInchStr);
  551. if ((OtherListPixelsPerInch <= PixelsPerInch) &&
  552. ((MatchingList == NULL) ||
  553. (MachingPixelsPerInch < OtherListPixelsPerInch)))
  554. {
  555. MatchingList = OtherList;
  556. MachingPixelsPerInch = OtherListPixelsPerInch;
  557. }
  558. }
  559. }
  560. if (MatchingList != NULL)
  561. {
  562. CopyImageList(ImageList, MatchingList);
  563. }
  564. }
  565. //---------------------------------------------------------------------------
  566. void __fastcall CopyImageList(TImageList * TargetList, TImageList * SourceList)
  567. {
  568. TPngImageList * PngTargetList = dynamic_cast<TPngImageList *>(TargetList);
  569. TPngImageList * PngSourceList = dynamic_cast<TPngImageList *>(SourceList);
  570. TargetList->Clear();
  571. TargetList->Height = SourceList->Height;
  572. TargetList->Width = SourceList->Width;
  573. if ((PngTargetList != NULL) && (PngSourceList != NULL))
  574. {
  575. // AddImages won't copy the names and we need them for
  576. // LoadDialogImage and TFrameAnimation
  577. PngTargetList->PngImages->Assign(PngSourceList->PngImages);
  578. }
  579. else
  580. {
  581. TargetList->AddImages(SourceList);
  582. }
  583. }
  584. //---------------------------------------------------------------------------
  585. void __fastcall CopyDataModule(TDataModule * TargetModule, TDataModule * SourceModule)
  586. {
  587. DebugAssert(TargetModule->ComponentCount == SourceModule->ComponentCount);
  588. typedef std::vector<std::pair<TComponent *, TComponent *> > TComponentPairs;
  589. TComponentPairs ComponentPairs;
  590. for (int Index = 0; Index < TargetModule->ComponentCount; Index++)
  591. {
  592. TComponent * TargetComponent = TargetModule->Components[Index];
  593. TComponent * SourceComponent = SourceModule->FindComponent(TargetComponent->Name);
  594. if (ALWAYS_TRUE(SourceComponent != NULL))
  595. {
  596. ComponentPairs.push_back(std::make_pair(TargetComponent, SourceComponent));
  597. }
  598. }
  599. TComponentPairs::const_iterator Iterator = ComponentPairs.begin();
  600. while (Iterator != ComponentPairs.end())
  601. {
  602. TComponent * TargetComponent = Iterator->first;
  603. TComponent * SourceComponent = Iterator->second;
  604. TargetModule->RemoveComponent(TargetComponent);
  605. SourceModule->RemoveComponent(SourceComponent);
  606. TargetModule->InsertComponent(SourceComponent);
  607. SourceModule->InsertComponent(TargetComponent);
  608. Iterator++;
  609. }
  610. }
  611. //---------------------------------------------------------------------------
  612. void __fastcall LoadDialogImage(TImage * Image, const UnicodeString & ImageName)
  613. {
  614. if (GlyphsModule != NULL)
  615. {
  616. TPngImageList * DialogImages = GlyphsModule->DialogImages;
  617. int Index;
  618. for (Index = 0; Index < DialogImages->PngImages->Count; Index++)
  619. {
  620. TPngImageCollectionItem * PngItem = DialogImages->PngImages->Items[Index];
  621. if (SameText(PngItem->Name, ImageName))
  622. {
  623. Image->Picture->Assign(PngItem->PngImage);
  624. break;
  625. }
  626. }
  627. DebugAssert(Index < DialogImages->PngImages->Count);
  628. }
  629. // When showing an exception from wWinMain, the glyphs module does not exist anymore.
  630. // We expect errors only.
  631. else if (ALWAYS_TRUE(ImageName == L"Error"))
  632. {
  633. Image->Picture->Icon->Handle = LoadIcon(0, IDI_HAND);
  634. }
  635. }
  636. //---------------------------------------------------------------------------
  637. int __fastcall DialogImageSize()
  638. {
  639. return ScaleByPixelsPerInch(32);
  640. }
  641. //---------------------------------------------------------------------------
  642. void __fastcall HideComponentsPanel(TForm * Form)
  643. {
  644. TComponent * Component = NOT_NULL(Form->FindComponent(L"ComponentsPanel"));
  645. TPanel * Panel = NOT_NULL(dynamic_cast<TPanel *>(Component));
  646. DebugAssert(Panel->Align == alBottom);
  647. int Offset = Panel->Height;
  648. Panel->Visible = false;
  649. Form->Height -= Offset;
  650. // Shift back bottom-anchored controls
  651. // (needed for toolbar panel on Progress window)
  652. for (int Index = 0; Index < Form->ControlCount; Index++)
  653. {
  654. TControl * Control = Form->Controls[Index];
  655. if ((Control->Align == alNone) &&
  656. Control->Anchors.Contains(akBottom) &&
  657. !Control->Anchors.Contains(akTop))
  658. {
  659. Control->Top += Offset;
  660. }
  661. }
  662. }
  663. //---------------------------------------------------------------------------
  664. class TBrowserViewer : public TWebBrowserEx
  665. {
  666. public:
  667. __fastcall virtual TBrowserViewer(TComponent* AOwner);
  668. void __fastcall AddLinkHandler(
  669. const UnicodeString & Url, TNotifyEvent Handler);
  670. void __fastcall NavigateToUrl(const UnicodeString & Url);
  671. TControl * LoadingPanel;
  672. protected:
  673. DYNAMIC void __fastcall DoContextPopup(const TPoint & MousePos, bool & Handled);
  674. void __fastcall DocumentComplete(
  675. TObject * Sender, const _di_IDispatch Disp, const OleVariant & URL);
  676. void __fastcall BeforeNavigate2(
  677. TObject * Sender, const _di_IDispatch Disp, const OleVariant & URL,
  678. const OleVariant & Flags, const OleVariant & TargetFrameName,
  679. const OleVariant & PostData, const OleVariant & Headers, WordBool & Cancel);
  680. bool FComplete;
  681. std::map<UnicodeString, TNotifyEvent> FHandlers;
  682. };
  683. //---------------------------------------------------------------------------
  684. __fastcall TBrowserViewer::TBrowserViewer(TComponent* AOwner) :
  685. TWebBrowserEx(AOwner)
  686. {
  687. FComplete = false;
  688. OnDocumentComplete = DocumentComplete;
  689. OnBeforeNavigate2 = BeforeNavigate2;
  690. LoadingPanel = NULL;
  691. }
  692. //---------------------------------------------------------------------------
  693. void __fastcall TBrowserViewer::AddLinkHandler(
  694. const UnicodeString & Url, TNotifyEvent Handler)
  695. {
  696. FHandlers.insert(std::make_pair(Url, Handler));
  697. }
  698. //---------------------------------------------------------------------------
  699. void __fastcall TBrowserViewer::DoContextPopup(const TPoint & MousePos, bool & Handled)
  700. {
  701. // suppress built-in context menu
  702. Handled = true;
  703. TWebBrowserEx::DoContextPopup(MousePos, Handled);
  704. }
  705. //---------------------------------------------------------------------------
  706. void __fastcall TBrowserViewer::DocumentComplete(
  707. TObject * /*Sender*/, const _di_IDispatch /*Disp*/, const OleVariant & /*URL*/)
  708. {
  709. SetBrowserDesignModeOff(this);
  710. FComplete = true;
  711. if (LoadingPanel != NULL)
  712. {
  713. LoadingPanel->Visible = false;
  714. }
  715. }
  716. //---------------------------------------------------------------------------
  717. void __fastcall TBrowserViewer::BeforeNavigate2(
  718. TObject * /*Sender*/, const _di_IDispatch /*Disp*/, const OleVariant & AURL,
  719. const OleVariant & /*Flags*/, const OleVariant & /*TargetFrameName*/,
  720. const OleVariant & /*PostData*/, const OleVariant & /*Headers*/, WordBool & Cancel)
  721. {
  722. // If OnDocumentComplete was not called yet, is has to be our initial message URL,
  723. // opened using TWebBrowserEx::Navigate(), allow it.
  724. // Otherwise it's user navigating, block that and open link
  725. // in an external browser, possibly adding campaign parameters on the way.
  726. if (FComplete)
  727. {
  728. Cancel = 1;
  729. UnicodeString URL = AURL;
  730. if (FHandlers.count(URL) > 0)
  731. {
  732. FHandlers[URL](this);
  733. }
  734. else
  735. {
  736. OpenBrowser(URL);
  737. }
  738. }
  739. }
  740. //---------------------------------------------------------------------------
  741. void __fastcall TBrowserViewer::NavigateToUrl(const UnicodeString & Url)
  742. {
  743. FComplete = false;
  744. Navigate(Url.c_str());
  745. }
  746. //---------------------------------------------------------------------------
  747. TPanel * __fastcall CreateLabelPanel(TPanel * Parent, const UnicodeString & Label)
  748. {
  749. TPanel * Result = CreateBlankPanel(Parent);
  750. Result->Parent = Parent;
  751. Result->Align = alClient;
  752. Result->Caption = Label;
  753. return Result;
  754. }
  755. //---------------------------------------------------------------------------
  756. TWebBrowserEx * __fastcall CreateBrowserViewer(TPanel * Parent, const UnicodeString & LoadingLabel)
  757. {
  758. TBrowserViewer * Result = new TBrowserViewer(Parent);
  759. // TWebBrowserEx has its own unrelated Name and Parent properties.
  760. // The name is used in DownloadUpdate().
  761. static_cast<TWinControl *>(Result)->Name = L"BrowserViewer";
  762. static_cast<TWinControl *>(Result)->Parent = Parent;
  763. Result->Align = alClient;
  764. Result->ControlBorder = cbNone;
  765. Result->LoadingPanel = CreateLabelPanel(Parent, LoadingLabel);
  766. return Result;
  767. }
  768. //---------------------------------------------------------------------------
  769. void __fastcall SetBrowserDesignModeOff(TWebBrowserEx * WebBrowser)
  770. {
  771. if (ALWAYS_TRUE(WebBrowser->Document2 != NULL))
  772. {
  773. WebBrowser->Document2->designMode = L"Off";
  774. }
  775. }
  776. //---------------------------------------------------------------------------
  777. void __fastcall AddBrowserLinkHandler(TWebBrowserEx * WebBrowser,
  778. const UnicodeString & Url, TNotifyEvent Handler)
  779. {
  780. TBrowserViewer * BrowserViewer = dynamic_cast<TBrowserViewer *>(WebBrowser);
  781. if (ALWAYS_TRUE(BrowserViewer != NULL))
  782. {
  783. BrowserViewer->AddLinkHandler(Url, Handler);
  784. }
  785. }
  786. //---------------------------------------------------------------------------
  787. void __fastcall NavigateBrowserToUrl(TWebBrowserEx * WebBrowser, const UnicodeString & Url)
  788. {
  789. TBrowserViewer * BrowserViewer = dynamic_cast<TBrowserViewer *>(WebBrowser);
  790. if (ALWAYS_TRUE(BrowserViewer != NULL))
  791. {
  792. BrowserViewer->NavigateToUrl(Url);
  793. }
  794. }
  795. //---------------------------------------------------------------------------
  796. TLocalCustomCommand::TLocalCustomCommand()
  797. {
  798. }
  799. //---------------------------------------------------------------------------
  800. TLocalCustomCommand::TLocalCustomCommand(const TCustomCommandData & Data,
  801. const UnicodeString & Path) :
  802. TFileCustomCommand(Data, Path)
  803. {
  804. }
  805. //---------------------------------------------------------------------------
  806. TLocalCustomCommand::TLocalCustomCommand(const TCustomCommandData & Data,
  807. const UnicodeString & Path, const UnicodeString & FileName,
  808. const UnicodeString & LocalFileName, const UnicodeString & FileList) :
  809. TFileCustomCommand(Data, Path, FileName, FileList)
  810. {
  811. FLocalFileName = LocalFileName;
  812. }
  813. //---------------------------------------------------------------------------
  814. int __fastcall TLocalCustomCommand::PatternLen(const UnicodeString & Command, int Index)
  815. {
  816. int Len;
  817. if ((Index < Command.Length()) && (Command[Index + 1] == L'^'))
  818. {
  819. Len = 3;
  820. }
  821. else
  822. {
  823. Len = TFileCustomCommand::PatternLen(Command, Index);
  824. }
  825. return Len;
  826. }
  827. //---------------------------------------------------------------------------
  828. bool __fastcall TLocalCustomCommand::PatternReplacement(
  829. const UnicodeString & Pattern, UnicodeString & Replacement, bool & Delimit)
  830. {
  831. bool Result;
  832. if (Pattern == L"!^!")
  833. {
  834. Replacement = FLocalFileName;
  835. Result = true;
  836. }
  837. else
  838. {
  839. Result = TFileCustomCommand::PatternReplacement(Pattern, Replacement, Delimit);
  840. }
  841. return Result;
  842. }
  843. //---------------------------------------------------------------------------
  844. void __fastcall TLocalCustomCommand::DelimitReplacement(
  845. UnicodeString & /*Replacement*/, wchar_t /*Quote*/)
  846. {
  847. // never delimit local commands
  848. }
  849. //---------------------------------------------------------------------------
  850. bool __fastcall TLocalCustomCommand::HasLocalFileName(const UnicodeString & Command)
  851. {
  852. return FindPattern(Command, L'^');
  853. }
  854. //---------------------------------------------------------------------------
  855. bool __fastcall TLocalCustomCommand::IsFileCommand(const UnicodeString & Command)
  856. {
  857. return TFileCustomCommand::IsFileCommand(Command) || HasLocalFileName(Command);
  858. }
  859. //---------------------------------------------------------------------------
  860. //---------------------------------------------------------------------------
  861. __fastcall TFrameAnimation::TFrameAnimation()
  862. {
  863. FFirstFrame = -1;
  864. }
  865. //---------------------------------------------------------------------------
  866. void __fastcall TFrameAnimation::Init(TPaintBox * PaintBox, const UnicodeString & Name)
  867. {
  868. DoInit(PaintBox, NULL, Name, Name.IsEmpty());
  869. }
  870. //---------------------------------------------------------------------------
  871. void __fastcall TFrameAnimation::DoInit(TPaintBox * PaintBox, TPngImageList * ImageList, const UnicodeString & Name, bool Null)
  872. {
  873. FImageList = (ImageList != NULL) ? ImageList : GetAnimationsModule()->AnimationImages;
  874. FFirstFrame = -1;
  875. FFirstLoopFrame = -1;
  876. DebugAssert((PaintBox->OnPaint == NULL) || (PaintBox->OnPaint == PaintBoxPaint));
  877. PaintBox->ControlStyle = PaintBox->ControlStyle << csOpaque;
  878. PaintBox->OnPaint = PaintBoxPaint;
  879. PaintBox->Width = FImageList->Width;
  880. PaintBox->Height = FImageList->Height;
  881. FPaintBox = PaintBox;
  882. if (!Null)
  883. {
  884. int Frame = 0;
  885. while (Frame < FImageList->PngImages->Count)
  886. {
  887. UnicodeString FrameData = FImageList->PngImages->Items[Frame]->Name;
  888. UnicodeString FrameName;
  889. FrameName = CutToChar(FrameData, L'_', false);
  890. if (SameText(Name, FrameName))
  891. {
  892. int FrameIndex = StrToInt(CutToChar(FrameData, L'_', false));
  893. if (FFirstFrame < 0)
  894. {
  895. FFirstFrame = Frame;
  896. }
  897. if ((FFirstLoopFrame < 0) && (FrameIndex > 0))
  898. {
  899. FFirstLoopFrame = Frame;
  900. }
  901. FLastFrame = Frame;
  902. }
  903. else
  904. {
  905. if (FFirstFrame >= 0)
  906. {
  907. // optimization
  908. break;
  909. }
  910. }
  911. Frame++;
  912. }
  913. DebugAssert(FFirstFrame >= 0);
  914. DebugAssert(FFirstLoopFrame >= 0);
  915. }
  916. Stop();
  917. }
  918. //---------------------------------------------------------------------------
  919. void __fastcall TFrameAnimation::Start()
  920. {
  921. if (FFirstFrame >= 0)
  922. {
  923. FNextFrameTick = GetTickCount();
  924. CalculateNextFrameTick();
  925. if (FTimer == NULL)
  926. {
  927. FTimer = new TTimer(GetParentForm(FPaintBox));
  928. FTimer->Interval = static_cast<int>(GUIUpdateInterval);
  929. FTimer->OnTimer = Timer;
  930. }
  931. else
  932. {
  933. // reset timer
  934. FTimer->Enabled = false;
  935. FTimer->Enabled = true;
  936. }
  937. }
  938. }
  939. //---------------------------------------------------------------------------
  940. void __fastcall TFrameAnimation::Timer(TObject * /*Sender*/)
  941. {
  942. Animate();
  943. }
  944. //---------------------------------------------------------------------------
  945. void __fastcall TFrameAnimation::PaintBoxPaint(TObject * Sender)
  946. {
  947. if (FFirstFrame >= 0)
  948. {
  949. // Double-buffered drawing to prevent flicker (as the images are transparent)
  950. USEDPARAM(Sender);
  951. DebugAssert(FPaintBox == Sender);
  952. DebugAssert(FPaintBox->ControlStyle.Contains(csOpaque));
  953. std::unique_ptr<TBitmap> Bitmap(new TBitmap());
  954. Bitmap->SetSize(FPaintBox->Width, FPaintBox->Height);
  955. Bitmap->Canvas->Brush->Color = FPaintBox->Color;
  956. TRect Rect(0, 0, Bitmap->Width, Bitmap->Height);
  957. Bitmap->Canvas->FillRect(Rect);
  958. TGraphic * Graphic = GetCurrentImage()->PngImage;
  959. // Do not trigger assertion when animation size does not match scaled
  960. // paint box as we do not have scaled animations available yet
  961. DebugAssert((Graphic->Width == FPaintBox->Width) || (Screen->PixelsPerInch != USER_DEFAULT_SCREEN_DPI));
  962. DebugAssert((Graphic->Height == FPaintBox->Height) || (Screen->PixelsPerInch != USER_DEFAULT_SCREEN_DPI));
  963. Bitmap->Canvas->Draw(0, 0, Graphic);
  964. FPaintBox->Canvas->Draw(0, 0, Bitmap.get());
  965. }
  966. FPainted = true;
  967. }
  968. //---------------------------------------------------------------------------
  969. void __fastcall TFrameAnimation::Repaint()
  970. {
  971. FPainted = false;
  972. // Ff the form is not showing yet, the Paint() is not even called
  973. FPaintBox->Repaint();
  974. if (!FPainted)
  975. {
  976. // Paint later, alternativelly we may keep trying Repaint() in Animate().
  977. // See also a hack in TAuthenticateForm::Log.
  978. FPaintBox->Invalidate();
  979. }
  980. }
  981. //---------------------------------------------------------------------------
  982. void __fastcall TFrameAnimation::Stop()
  983. {
  984. FNextFrameTick = std::numeric_limits<DWORD>::max();
  985. FCurrentFrame = FFirstFrame;
  986. Repaint();
  987. if (FTimer != NULL)
  988. {
  989. FTimer->Enabled = false;
  990. }
  991. }
  992. //---------------------------------------------------------------------------
  993. void __fastcall TFrameAnimation::Animate()
  994. {
  995. if (FFirstFrame >= 0)
  996. {
  997. // UPGRADE: Use GetTickCount64() when we stop supporting Windows XP.
  998. DWORD TickCount = GetTickCount();
  999. // Keep in sync with an opposite condition at the end of the loop.
  1000. // We may skip some frames if we got stalled for a while
  1001. while (TickCount >= FNextFrameTick)
  1002. {
  1003. if (FCurrentFrame >= FLastFrame)
  1004. {
  1005. FCurrentFrame = FFirstLoopFrame;
  1006. }
  1007. else
  1008. {
  1009. FCurrentFrame++;
  1010. }
  1011. CalculateNextFrameTick();
  1012. Repaint();
  1013. }
  1014. }
  1015. }
  1016. //---------------------------------------------------------------------------
  1017. TPngImageCollectionItem * __fastcall TFrameAnimation::GetCurrentImage()
  1018. {
  1019. return FImageList->PngImages->Items[FCurrentFrame];
  1020. }
  1021. //---------------------------------------------------------------------------
  1022. void __fastcall TFrameAnimation::CalculateNextFrameTick()
  1023. {
  1024. TPngImageCollectionItem * ImageItem = GetCurrentImage();
  1025. UnicodeString Duration = ImageItem->Name;
  1026. CutToChar(Duration, L'_', false);
  1027. // skip index (is not really used)
  1028. CutToChar(Duration, L'_', false);
  1029. // This should overflow, when tick count wraps.
  1030. FNextFrameTick += StrToInt(Duration) * 10;
  1031. }
  1032. //---------------------------------------------------------------------------