GUITools.cpp 37 KB

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