GUITools.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524
  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 <PasTools.hpp>
  21. #include <VCLCommon.h>
  22. #include <Vcl.ScreenTips.hpp>
  23. #include "Animations96.h"
  24. #include "Animations120.h"
  25. #include "Animations144.h"
  26. #include "Animations192.h"
  27. //---------------------------------------------------------------------------
  28. #pragma package(smart_init)
  29. //---------------------------------------------------------------------------
  30. extern const UnicodeString PageantTool = L"pageant.exe";
  31. extern const UnicodeString PuttygenTool = L"puttygen.exe";
  32. //---------------------------------------------------------------------------
  33. bool __fastcall FindFile(UnicodeString & Path)
  34. {
  35. bool Result = FileExists(ApiPath(Path));
  36. if (!Result)
  37. {
  38. UnicodeString ProgramFiles32 = IncludeTrailingBackslash(GetEnvironmentVariable(L"ProgramFiles"));
  39. UnicodeString ProgramFiles64 = IncludeTrailingBackslash(GetEnvironmentVariable(L"ProgramW6432"));
  40. if (!ProgramFiles32.IsEmpty() &&
  41. SameText(Path.SubString(1, ProgramFiles32.Length()), ProgramFiles32) &&
  42. !ProgramFiles64.IsEmpty())
  43. {
  44. UnicodeString Path64 =
  45. ProgramFiles64 + Path.SubString(ProgramFiles32.Length() + 1, Path.Length() - ProgramFiles32.Length());
  46. if (FileExists(ApiPath(Path64)))
  47. {
  48. Path = Path64;
  49. Result = true;
  50. }
  51. }
  52. }
  53. if (!Result)
  54. {
  55. UnicodeString Paths = GetEnvironmentVariable(L"PATH");
  56. if (!Paths.IsEmpty())
  57. {
  58. UnicodeString NewPath = FileSearch(ExtractFileName(Path), Paths);
  59. Result = !NewPath.IsEmpty();
  60. if (Result)
  61. {
  62. Path = NewPath;
  63. }
  64. }
  65. }
  66. return Result;
  67. }
  68. //---------------------------------------------------------------------------
  69. void __fastcall OpenSessionInPutty(const UnicodeString PuttyPath,
  70. TSessionData * SessionData)
  71. {
  72. UnicodeString Program, AParams, Dir;
  73. SplitCommand(PuttyPath, Program, AParams, Dir);
  74. Program = ExpandEnvironmentVariables(Program);
  75. if (FindFile(Program))
  76. {
  77. AParams = ExpandEnvironmentVariables(AParams);
  78. UnicodeString Password = GUIConfiguration->PuttyPassword ? SessionData->Password : UnicodeString();
  79. TCustomCommandData Data(SessionData, SessionData->UserName, Password);
  80. TRemoteCustomCommand RemoteCustomCommand(Data, SessionData->RemoteDirectory);
  81. TWinInteractiveCustomCommand InteractiveCustomCommand(
  82. &RemoteCustomCommand, L"PuTTY", UnicodeString());
  83. UnicodeString Params =
  84. RemoteCustomCommand.Complete(InteractiveCustomCommand.Complete(AParams, false), true);
  85. UnicodeString PuttyParams;
  86. if (!RemoteCustomCommand.IsSiteCommand(AParams))
  87. {
  88. UnicodeString SessionName;
  89. TRegistryStorage * Storage = NULL;
  90. TSessionData * ExportData = NULL;
  91. TRegistryStorage * SourceStorage = NULL;
  92. try
  93. {
  94. Storage = new TRegistryStorage(Configuration->PuttySessionsKey);
  95. Storage->AccessMode = smReadWrite;
  96. // make it compatible with putty
  97. Storage->MungeStringValues = false;
  98. Storage->ForceAnsi = true;
  99. if (Storage->OpenRootKey(true))
  100. {
  101. if (Storage->KeyExists(SessionData->StorageKey))
  102. {
  103. SessionName = SessionData->SessionName;
  104. }
  105. else
  106. {
  107. SourceStorage = new TRegistryStorage(Configuration->PuttySessionsKey);
  108. SourceStorage->MungeStringValues = false;
  109. SourceStorage->ForceAnsi = true;
  110. if (SourceStorage->OpenSubKey(StoredSessions->DefaultSettings->Name, false) &&
  111. Storage->OpenSubKey(GUIConfiguration->PuttySession, true))
  112. {
  113. Storage->Copy(SourceStorage);
  114. Storage->CloseSubKey();
  115. }
  116. ExportData = new TSessionData(L"");
  117. ExportData->Assign(SessionData);
  118. ExportData->Modified = true;
  119. ExportData->Name = GUIConfiguration->PuttySession;
  120. ExportData->WinTitle = SessionData->SessionName;
  121. ExportData->Password = L"";
  122. if (SessionData->FSProtocol == fsFTP)
  123. {
  124. if (GUIConfiguration->TelnetForFtpInPutty)
  125. {
  126. ExportData->PuttyProtocol = PuttyTelnetProtocol;
  127. ExportData->PortNumber = TelnetPortNumber;
  128. // PuTTY does not allow -pw for telnet
  129. Password = L"";
  130. }
  131. else
  132. {
  133. ExportData->PuttyProtocol = PuttySshProtocol;
  134. ExportData->PortNumber = SshPortNumber;
  135. }
  136. }
  137. ExportData->Save(Storage, true);
  138. SessionName = GUIConfiguration->PuttySession;
  139. }
  140. }
  141. }
  142. __finally
  143. {
  144. delete Storage;
  145. delete ExportData;
  146. delete SourceStorage;
  147. }
  148. UnicodeString LoadSwitch = L"-load";
  149. int P = Params.LowerCase().Pos(LoadSwitch + L" ");
  150. if ((P == 0) || ((P > 1) && (Params[P - 1] != L' ')))
  151. {
  152. AddToList(PuttyParams, FORMAT(L"%s %s", (LoadSwitch, EscapePuttyCommandParam(SessionName))), L" ");
  153. }
  154. }
  155. if (!Password.IsEmpty() && !RemoteCustomCommand.IsPasswordCommand(AParams))
  156. {
  157. AddToList(PuttyParams, FORMAT(L"-pw %s", (EscapePuttyCommandParam(Password))), L" ");
  158. }
  159. AddToList(PuttyParams, Params, L" ");
  160. // PuTTY is started in its binary directory to allow relative paths in private key,
  161. // when opening PuTTY's own stored session.
  162. ExecuteShellChecked(Program, PuttyParams, true);
  163. }
  164. else
  165. {
  166. throw Exception(FMTLOAD(FILE_NOT_FOUND, (Program)));
  167. }
  168. }
  169. //---------------------------------------------------------------------------
  170. bool __fastcall FindTool(const UnicodeString & Name, UnicodeString & Path)
  171. {
  172. UnicodeString AppPath = IncludeTrailingBackslash(ExtractFilePath(Application->ExeName));
  173. Path = AppPath + Name;
  174. bool Result = true;
  175. if (!FileExists(ApiPath(Path)))
  176. {
  177. Path = AppPath + L"PuTTY\\" + Name;
  178. if (!FileExists(ApiPath(Path)))
  179. {
  180. Path = Name;
  181. if (!FindFile(Path))
  182. {
  183. Result = false;
  184. }
  185. }
  186. }
  187. return Result;
  188. }
  189. //---------------------------------------------------------------------------
  190. bool __fastcall CopyCommandToClipboard(const UnicodeString & Command)
  191. {
  192. bool Result = UseAlternativeFunction() && IsKeyPressed(VK_CONTROL);
  193. if (Result)
  194. {
  195. TInstantOperationVisualizer Visualizer;
  196. CopyToClipboard(Command);
  197. }
  198. return Result;
  199. }
  200. //---------------------------------------------------------------------------
  201. static bool __fastcall DoExecuteShell(const UnicodeString Path, const UnicodeString Params,
  202. bool ChangeWorkingDirectory, HANDLE * Handle)
  203. {
  204. bool Result = CopyCommandToClipboard(FormatCommand(Path, Params));
  205. if (!Result)
  206. {
  207. UnicodeString Directory = ExtractFilePath(Path);
  208. TShellExecuteInfoW ExecuteInfo;
  209. memset(&ExecuteInfo, 0, sizeof(ExecuteInfo));
  210. ExecuteInfo.cbSize = sizeof(ExecuteInfo);
  211. ExecuteInfo.fMask =
  212. SEE_MASK_FLAG_NO_UI |
  213. FLAGMASK((Handle != NULL), SEE_MASK_NOCLOSEPROCESS);
  214. ExecuteInfo.hwnd = Application->Handle;
  215. ExecuteInfo.lpFile = (wchar_t*)Path.data();
  216. ExecuteInfo.lpParameters = (wchar_t*)Params.data();
  217. ExecuteInfo.lpDirectory = (ChangeWorkingDirectory ? Directory.c_str() : NULL);
  218. ExecuteInfo.nShow = SW_SHOW;
  219. Result = (ShellExecuteEx(&ExecuteInfo) != 0);
  220. if (Result)
  221. {
  222. if (Handle != NULL)
  223. {
  224. *Handle = ExecuteInfo.hProcess;
  225. }
  226. }
  227. }
  228. return Result;
  229. }
  230. //---------------------------------------------------------------------------
  231. void __fastcall ExecuteShellChecked(const UnicodeString Path, const UnicodeString Params, bool ChangeWorkingDirectory)
  232. {
  233. if (!DoExecuteShell(Path, Params, ChangeWorkingDirectory, NULL))
  234. {
  235. throw EOSExtException(FMTLOAD(EXECUTE_APP_ERROR, (Path)));
  236. }
  237. }
  238. //---------------------------------------------------------------------------
  239. void __fastcall ExecuteShellChecked(const UnicodeString Command)
  240. {
  241. UnicodeString Program, Params, Dir;
  242. SplitCommand(Command, Program, Params, Dir);
  243. ExecuteShellChecked(Program, Params);
  244. }
  245. //---------------------------------------------------------------------------
  246. bool __fastcall ExecuteShell(const UnicodeString Path, const UnicodeString Params,
  247. HANDLE & Handle)
  248. {
  249. return DoExecuteShell(Path, Params, false, &Handle);
  250. }
  251. //---------------------------------------------------------------------------
  252. void __fastcall ExecuteShellCheckedAndWait(const UnicodeString Command,
  253. TProcessMessagesEvent ProcessMessages)
  254. {
  255. UnicodeString Program, Params, Dir;
  256. SplitCommand(Command, Program, Params, Dir);
  257. HANDLE ProcessHandle;
  258. bool Result = DoExecuteShell(Program, Params, false, &ProcessHandle);
  259. if (!Result)
  260. {
  261. throw EOSExtException(FMTLOAD(EXECUTE_APP_ERROR, (Program)));
  262. }
  263. else
  264. {
  265. if (ProcessMessages != NULL)
  266. {
  267. unsigned long WaitResult;
  268. do
  269. {
  270. // Same as in ExecuteProcessAndReadOutput
  271. WaitResult = WaitForSingleObject(ProcessHandle, 200);
  272. if (WaitResult == WAIT_FAILED)
  273. {
  274. throw Exception(LoadStr(DOCUMENT_WAIT_ERROR));
  275. }
  276. ProcessMessages();
  277. }
  278. while (WaitResult == WAIT_TIMEOUT);
  279. }
  280. else
  281. {
  282. WaitForSingleObject(ProcessHandle, INFINITE);
  283. }
  284. }
  285. }
  286. //---------------------------------------------------------------------------
  287. bool __fastcall SpecialFolderLocation(int PathID, UnicodeString & Path)
  288. {
  289. LPITEMIDLIST Pidl;
  290. wchar_t Buf[256];
  291. if (SHGetSpecialFolderLocation(NULL, PathID, &Pidl) == NO_ERROR &&
  292. SHGetPathFromIDList(Pidl, Buf))
  293. {
  294. Path = UnicodeString(Buf);
  295. return true;
  296. }
  297. return false;
  298. }
  299. //---------------------------------------------------------------------------
  300. UnicodeString __fastcall UniqTempDir(const UnicodeString BaseDir, const UnicodeString Identity,
  301. bool Mask)
  302. {
  303. DebugAssert(!BaseDir.IsEmpty());
  304. UnicodeString TempDir;
  305. do
  306. {
  307. TempDir = IncludeTrailingBackslash(BaseDir) + Identity;
  308. if (Mask)
  309. {
  310. TempDir += L"?????";
  311. }
  312. else
  313. {
  314. TempDir += IncludeTrailingBackslash(FormatDateTime(L"nnzzz", Now()));
  315. }
  316. }
  317. while (!Mask && DirectoryExists(ApiPath(TempDir)));
  318. return TempDir;
  319. }
  320. //---------------------------------------------------------------------------
  321. bool __fastcall DeleteDirectory(const UnicodeString DirName)
  322. {
  323. TSearchRecChecked sr;
  324. bool retval = true;
  325. if (FindFirstUnchecked(DirName + L"\\*", faAnyFile, sr) == 0) // VCL Function
  326. {
  327. if (FLAGSET(sr.Attr, faDirectory))
  328. {
  329. if (sr.Name != L"." && sr.Name != L"..")
  330. retval = DeleteDirectory(DirName + L"\\" + sr.Name);
  331. }
  332. else
  333. {
  334. retval = DeleteFile(ApiPath(DirName + L"\\" + sr.Name));
  335. }
  336. if (retval)
  337. {
  338. while (FindNextChecked(sr) == 0)
  339. { // VCL Function
  340. if (FLAGSET(sr.Attr, faDirectory))
  341. {
  342. if (sr.Name != L"." && sr.Name != L"..")
  343. retval = DeleteDirectory(DirName + L"\\" + sr.Name);
  344. }
  345. else
  346. {
  347. retval = DeleteFile(ApiPath(DirName + L"\\" + sr.Name));
  348. }
  349. if (!retval) break;
  350. }
  351. }
  352. }
  353. FindClose(sr);
  354. if (retval) retval = RemoveDir(ApiPath(DirName)); // VCL function
  355. return retval;
  356. }
  357. //---------------------------------------------------------------------------
  358. void __fastcall AddSessionColorImage(
  359. TCustomImageList * ImageList, TColor Color, int MaskIndex)
  360. {
  361. // This overly complex drawing is here to support color button on SiteAdvanced
  362. // dialog. There we use plain TImageList, instead of TPngImageList,
  363. // TButton does not work with transparent images
  364. // (not even TBitmap with Transparent = true)
  365. std::unique_ptr<TBitmap> MaskBitmap(new TBitmap());
  366. ImageList->GetBitmap(MaskIndex, MaskBitmap.get());
  367. std::unique_ptr<TPngImage> MaskImage(new TPngImage());
  368. MaskImage->Assign(MaskBitmap.get());
  369. std::unique_ptr<TPngImage> ColorImage(new TPngImage(COLOR_RGB, 16, ImageList->Width, ImageList->Height));
  370. TColor MaskTransparentColor = MaskImage->Pixels[0][0];
  371. TColor TransparentColor = MaskTransparentColor;
  372. // Expecting that the color to be replaced is in the centre of the image (HACK)
  373. TColor MaskColor = MaskImage->Pixels[ImageList->Width / 2][ImageList->Height / 2];
  374. for (int Y = 0; Y < ImageList->Height; Y++)
  375. {
  376. for (int X = 0; X < ImageList->Width; X++)
  377. {
  378. TColor SourceColor = MaskImage->Pixels[X][Y];
  379. TColor DestColor;
  380. // this branch is pointless as long as MaskTransparentColor and
  381. // TransparentColor are the same
  382. if (SourceColor == MaskTransparentColor)
  383. {
  384. DestColor = TransparentColor;
  385. }
  386. else if (SourceColor == MaskColor)
  387. {
  388. DestColor = Color;
  389. }
  390. else
  391. {
  392. DestColor = SourceColor;
  393. }
  394. ColorImage->Pixels[X][Y] = DestColor;
  395. }
  396. }
  397. std::unique_ptr<TBitmap> Bitmap(new TBitmap());
  398. Bitmap->SetSize(ImageList->Width, ImageList->Height);
  399. ColorImage->AssignTo(Bitmap.get());
  400. ImageList->AddMasked(Bitmap.get(), TransparentColor);
  401. }
  402. //---------------------------------------------------------------------------
  403. void __fastcall SetSubmenu(TTBXCustomItem * Item)
  404. {
  405. class TTBXPublicItem : public TTBXCustomItem
  406. {
  407. public:
  408. __property ItemStyle;
  409. };
  410. TTBXPublicItem * PublicItem = reinterpret_cast<TTBXPublicItem *>(Item);
  411. DebugAssert(PublicItem != NULL);
  412. // See TTBItemViewer.IsPtInButtonPart (called from TTBItemViewer.MouseDown)
  413. PublicItem->ItemStyle = PublicItem->ItemStyle << tbisSubmenu;
  414. }
  415. //---------------------------------------------------------------------------
  416. bool __fastcall IsEligibleForApplyingTabs(
  417. UnicodeString Line, int & TabPos, UnicodeString & Start, UnicodeString & Remaining)
  418. {
  419. bool Result = false;
  420. TabPos = Line.Pos(L"\t");
  421. if (TabPos > 0)
  422. {
  423. Remaining = Line.SubString(TabPos + 1, Line.Length() - TabPos);
  424. // WORKAROUND
  425. // Some translations still use obsolete hack of consecutive tabs to aling the contents.
  426. // Delete these, so that the following check does not fail on this
  427. while (Remaining.SubString(1, 1) == L"\t")
  428. {
  429. Remaining.Delete(1, 1);
  430. }
  431. // We do not have, not support, mutiple tabs on a single line
  432. if (DebugAlwaysTrue(Remaining.Pos(L"\t") == 0))
  433. {
  434. Start = Line.SubString(1, TabPos - 1);
  435. // WORKAROUND
  436. // Previously we padded the string before tab with spaces,
  437. // to aling the contents across multiple lines
  438. Start = Start.TrimRight();
  439. // at least two normal spaces for separation
  440. Start += L" ";
  441. Result = true;
  442. }
  443. }
  444. return Result;
  445. }
  446. //---------------------------------------------------------------------------
  447. static int __fastcall CalculateWidthByLength(UnicodeString Text, void * /*Arg*/)
  448. {
  449. return Text.Length();
  450. }
  451. //---------------------------------------------------------------------------
  452. void __fastcall ApplyTabs(
  453. UnicodeString & Text, wchar_t Padding,
  454. TCalculateWidth CalculateWidth, void * CalculateWidthArg)
  455. {
  456. if (CalculateWidth == NULL)
  457. {
  458. DebugAssert(CalculateWidthArg == NULL);
  459. CalculateWidth = CalculateWidthByLength;
  460. }
  461. std::unique_ptr<TStringList> Lines(TextToStringList(Text));
  462. int MaxWidth = -1;
  463. for (int Index = 0; Index < Lines->Count; Index++)
  464. {
  465. UnicodeString Line = Lines->Strings[Index];
  466. int TabPos;
  467. UnicodeString Start;
  468. UnicodeString Remaining;
  469. if (IsEligibleForApplyingTabs(Line, TabPos, Start, Remaining))
  470. {
  471. int Width = CalculateWidth(Start, CalculateWidthArg);
  472. MaxWidth = Max(MaxWidth, Width);
  473. }
  474. }
  475. // Optimization and also to prevent potential regression for texts without tabs
  476. if (MaxWidth >= 0)
  477. {
  478. for (int Index = 0; Index < Lines->Count; Index++)
  479. {
  480. UnicodeString Line = Lines->Strings[Index];
  481. int TabPos;
  482. UnicodeString Start;
  483. UnicodeString Remaining;
  484. if (IsEligibleForApplyingTabs(Line, TabPos, Start, Remaining))
  485. {
  486. int Width;
  487. int Iterations = 0;
  488. while ((Width = CalculateWidth(Start, CalculateWidthArg)) < MaxWidth)
  489. {
  490. int Wider = CalculateWidth(Start + Padding, CalculateWidthArg);
  491. // If padded string is wider than max width by more pixels
  492. // than non-padded string is shorter than max width
  493. if ((Wider > MaxWidth) && ((Wider - MaxWidth) > (MaxWidth - Width)))
  494. {
  495. break;
  496. }
  497. Start += Padding;
  498. Iterations++;
  499. // In rare case a tab is zero-width with some strange font (like HYLE)
  500. if (Iterations > 100)
  501. {
  502. break;
  503. }
  504. }
  505. Lines->Strings[Index] = Start + Remaining;
  506. }
  507. }
  508. Text = Lines->Text;
  509. // remove trailing newline
  510. Text = Text.TrimRight();
  511. }
  512. }
  513. //---------------------------------------------------------------------------
  514. static void __fastcall DoSelectScaledImageList(TImageList * ImageList)
  515. {
  516. TImageList * MatchingList = NULL;
  517. int MachingPixelsPerInch = 0;
  518. int PixelsPerInch = GetComponentPixelsPerInch(ImageList);
  519. for (int Index = 0; Index < ImageList->Owner->ComponentCount; Index++)
  520. {
  521. TImageList * OtherList = dynamic_cast<TImageList *>(ImageList->Owner->Components[Index]);
  522. if ((OtherList != NULL) &&
  523. (OtherList != ImageList) &&
  524. StartsStr(ImageList->Name, OtherList->Name))
  525. {
  526. UnicodeString OtherListPixelsPerInchStr =
  527. OtherList->Name.SubString(
  528. ImageList->Name.Length() + 1, OtherList->Name.Length() - ImageList->Name.Length());
  529. int OtherListPixelsPerInch = StrToInt(OtherListPixelsPerInchStr);
  530. if ((OtherListPixelsPerInch <= PixelsPerInch) &&
  531. ((MatchingList == NULL) ||
  532. (MachingPixelsPerInch < OtherListPixelsPerInch)))
  533. {
  534. MatchingList = OtherList;
  535. MachingPixelsPerInch = OtherListPixelsPerInch;
  536. }
  537. }
  538. }
  539. if (MatchingList != NULL)
  540. {
  541. UnicodeString ImageListBackupName = ImageList->Name + IntToStr(USER_DEFAULT_SCREEN_DPI);
  542. if (ImageList->Owner->FindComponent(ImageListBackupName) == NULL)
  543. {
  544. TImageList * ImageListBackup;
  545. TPngImageList * PngImageList = dynamic_cast<TPngImageList *>(ImageList);
  546. if (PngImageList != NULL)
  547. {
  548. ImageListBackup = new TPngImageList(ImageList->Owner);
  549. }
  550. else
  551. {
  552. ImageListBackup = new TImageList(ImageList->Owner);
  553. }
  554. ImageListBackup->Name = ImageListBackupName;
  555. ImageList->Owner->InsertComponent(ImageListBackup);
  556. CopyImageList(ImageListBackup, ImageList);
  557. }
  558. CopyImageList(ImageList, MatchingList);
  559. }
  560. }
  561. //---------------------------------------------------------------------------
  562. static void __fastcall ImageListRescale(TComponent * Sender, TObject * /*Token*/)
  563. {
  564. TImageList * ImageList = DebugNotNull(dynamic_cast<TImageList *>(Sender));
  565. DoSelectScaledImageList(ImageList);
  566. }
  567. //---------------------------------------------------------------------------
  568. void __fastcall SelectScaledImageList(TImageList * ImageList)
  569. {
  570. DoSelectScaledImageList(ImageList);
  571. SetRescaleFunction(ImageList, ImageListRescale);
  572. }
  573. //---------------------------------------------------------------------------
  574. void __fastcall CopyImageList(TImageList * TargetList, TImageList * SourceList)
  575. {
  576. // Maybe this is not necessary, once the TPngImageList::Assign was fixed
  577. TPngImageList * PngTargetList = dynamic_cast<TPngImageList *>(TargetList);
  578. TPngImageList * PngSourceList = dynamic_cast<TPngImageList *>(SourceList);
  579. TargetList->Clear();
  580. TargetList->Height = SourceList->Height;
  581. TargetList->Width = SourceList->Width;
  582. if ((PngTargetList != NULL) && (PngSourceList != NULL))
  583. {
  584. // AddImages won't copy the names and we need them for
  585. // LoadDialogImage and TFrameAnimation
  586. PngTargetList->PngImages->Assign(PngSourceList->PngImages);
  587. }
  588. else
  589. {
  590. TargetList->AddImages(SourceList);
  591. }
  592. }
  593. //---------------------------------------------------------------------------
  594. static bool __fastcall DoLoadDialogImage(TImage * Image, const UnicodeString & ImageName)
  595. {
  596. bool Result = false;
  597. if (GlyphsModule != NULL)
  598. {
  599. TPngImageList * DialogImages = GetDialogImages(Image);
  600. int Index;
  601. for (Index = 0; Index < DialogImages->PngImages->Count; Index++)
  602. {
  603. TPngImageCollectionItem * PngItem = DialogImages->PngImages->Items[Index];
  604. if (SameText(PngItem->Name, ImageName))
  605. {
  606. Image->Picture->Assign(PngItem->PngImage);
  607. break;
  608. }
  609. }
  610. DebugAssert(Index < DialogImages->PngImages->Count);
  611. Result = true;
  612. }
  613. // When showing an exception from wWinMain, the images are released already.
  614. // Non-existence of the glyphs module is just a good indication of that.
  615. // We expect errors only.
  616. else if (ImageName == L"Error")
  617. {
  618. Image->Picture->Icon->Handle = LoadIcon(0, IDI_HAND);
  619. }
  620. // For showing an information about trace files
  621. else if (DebugAlwaysTrue(ImageName == L"Information"))
  622. {
  623. Image->Picture->Icon->Handle = LoadIcon(0, IDI_APPLICATION);
  624. }
  625. return Result;
  626. }
  627. //---------------------------------------------------------------------------
  628. class TDialogImageName : public TObject
  629. {
  630. public:
  631. UnicodeString ImageName;
  632. };
  633. //---------------------------------------------------------------------------
  634. static void __fastcall DialogImageRescale(TComponent * Sender, TObject * Token)
  635. {
  636. TImage * Image = DebugNotNull(dynamic_cast<TImage *>(Sender));
  637. TDialogImageName * DialogImageName = DebugNotNull(dynamic_cast<TDialogImageName *>(Token));
  638. DoLoadDialogImage(Image, DialogImageName->ImageName);
  639. }
  640. //---------------------------------------------------------------------------
  641. void __fastcall LoadDialogImage(TImage * Image, const UnicodeString & ImageName)
  642. {
  643. if (DoLoadDialogImage(Image, ImageName))
  644. {
  645. TDialogImageName * DialogImageName = new TDialogImageName();
  646. DialogImageName->ImageName = ImageName;
  647. SetRescaleFunction(Image, DialogImageRescale, DialogImageName, true);
  648. }
  649. }
  650. //---------------------------------------------------------------------------
  651. int __fastcall DialogImageSize(TForm * Form)
  652. {
  653. return ScaleByPixelsPerInch(32, Form);
  654. }
  655. //---------------------------------------------------------------------------
  656. void __fastcall HideComponentsPanel(TForm * Form)
  657. {
  658. TComponent * Component = DebugNotNull(Form->FindComponent(L"ComponentsPanel"));
  659. TPanel * Panel = DebugNotNull(dynamic_cast<TPanel *>(Component));
  660. DebugAssert(Panel->Align == alBottom);
  661. int Offset = Panel->Height;
  662. Panel->Visible = false;
  663. Panel->Height = 0;
  664. Form->Height -= Offset;
  665. for (int Index = 0; Index < Form->ControlCount; Index++)
  666. {
  667. TControl * Control = Form->Controls[Index];
  668. // Shift back bottom-anchored controls
  669. // (needed for toolbar panel on Progress window and buttons on Preferences dialog),
  670. if ((Control->Align == alNone) &&
  671. Control->Anchors.Contains(akBottom) &&
  672. !Control->Anchors.Contains(akTop))
  673. {
  674. Control->Top += Offset;
  675. }
  676. // Resize back all-anchored controls
  677. // (needed for main panel on Preferences dialog),
  678. if (Control->Anchors.Contains(akBottom) &&
  679. Control->Anchors.Contains(akTop))
  680. {
  681. Control->Height += Offset;
  682. }
  683. }
  684. }
  685. //---------------------------------------------------------------------------
  686. class TBrowserViewer : public TWebBrowserEx
  687. {
  688. public:
  689. __fastcall virtual TBrowserViewer(TComponent* AOwner);
  690. void __fastcall AddLinkHandler(
  691. const UnicodeString & Url, TNotifyEvent Handler);
  692. void __fastcall NavigateToUrl(const UnicodeString & Url);
  693. TControl * LoadingPanel;
  694. protected:
  695. DYNAMIC void __fastcall DoContextPopup(const TPoint & MousePos, bool & Handled);
  696. void __fastcall DocumentComplete(
  697. TObject * Sender, const _di_IDispatch Disp, const OleVariant & URL);
  698. void __fastcall BeforeNavigate2(
  699. TObject * Sender, const _di_IDispatch Disp, const OleVariant & URL,
  700. const OleVariant & Flags, const OleVariant & TargetFrameName,
  701. const OleVariant & PostData, const OleVariant & Headers, WordBool & Cancel);
  702. bool FComplete;
  703. std::map<UnicodeString, TNotifyEvent> FHandlers;
  704. };
  705. //---------------------------------------------------------------------------
  706. __fastcall TBrowserViewer::TBrowserViewer(TComponent* AOwner) :
  707. TWebBrowserEx(AOwner)
  708. {
  709. FComplete = false;
  710. OnDocumentComplete = DocumentComplete;
  711. OnBeforeNavigate2 = BeforeNavigate2;
  712. LoadingPanel = NULL;
  713. }
  714. //---------------------------------------------------------------------------
  715. void __fastcall TBrowserViewer::AddLinkHandler(
  716. const UnicodeString & Url, TNotifyEvent Handler)
  717. {
  718. FHandlers.insert(std::make_pair(Url, Handler));
  719. }
  720. //---------------------------------------------------------------------------
  721. void __fastcall TBrowserViewer::DoContextPopup(const TPoint & MousePos, bool & Handled)
  722. {
  723. // suppress built-in context menu
  724. Handled = true;
  725. TWebBrowserEx::DoContextPopup(MousePos, Handled);
  726. }
  727. //---------------------------------------------------------------------------
  728. void __fastcall TBrowserViewer::DocumentComplete(
  729. TObject * /*Sender*/, const _di_IDispatch /*Disp*/, const OleVariant & /*URL*/)
  730. {
  731. SetBrowserDesignModeOff(this);
  732. FComplete = true;
  733. if (LoadingPanel != NULL)
  734. {
  735. LoadingPanel->Visible = false;
  736. }
  737. }
  738. //---------------------------------------------------------------------------
  739. void __fastcall TBrowserViewer::BeforeNavigate2(
  740. TObject * /*Sender*/, const _di_IDispatch /*Disp*/, const OleVariant & AURL,
  741. const OleVariant & /*Flags*/, const OleVariant & /*TargetFrameName*/,
  742. const OleVariant & /*PostData*/, const OleVariant & /*Headers*/, WordBool & Cancel)
  743. {
  744. // If OnDocumentComplete was not called yet, is has to be our initial message URL,
  745. // opened using TWebBrowserEx::Navigate(), allow it.
  746. // Otherwise it's user navigating, block that and open link
  747. // in an external browser, possibly adding campaign parameters on the way.
  748. if (FComplete)
  749. {
  750. Cancel = 1;
  751. UnicodeString URL = AURL;
  752. if (FHandlers.count(URL) > 0)
  753. {
  754. FHandlers[URL](this);
  755. }
  756. else
  757. {
  758. OpenBrowser(URL);
  759. }
  760. }
  761. }
  762. //---------------------------------------------------------------------------
  763. void __fastcall TBrowserViewer::NavigateToUrl(const UnicodeString & Url)
  764. {
  765. FComplete = false;
  766. Navigate(Url.c_str());
  767. }
  768. //---------------------------------------------------------------------------
  769. TPanel * __fastcall CreateLabelPanel(TPanel * Parent, const UnicodeString & Label)
  770. {
  771. TPanel * Result = CreateBlankPanel(Parent);
  772. Result->Parent = Parent;
  773. Result->Align = alClient;
  774. Result->Caption = Label;
  775. return Result;
  776. }
  777. //---------------------------------------------------------------------------
  778. TWebBrowserEx * __fastcall CreateBrowserViewer(TPanel * Parent, const UnicodeString & LoadingLabel)
  779. {
  780. TBrowserViewer * Result = new TBrowserViewer(Parent);
  781. // TWebBrowserEx has its own unrelated Name and Parent properties.
  782. // The name is used in DownloadUpdate().
  783. static_cast<TWinControl *>(Result)->Name = L"BrowserViewer";
  784. static_cast<TWinControl *>(Result)->Parent = Parent;
  785. Result->Align = alClient;
  786. Result->ControlBorder = cbNone;
  787. Result->LoadingPanel = CreateLabelPanel(Parent, LoadingLabel);
  788. return Result;
  789. }
  790. //---------------------------------------------------------------------------
  791. void __fastcall SetBrowserDesignModeOff(TWebBrowserEx * WebBrowser)
  792. {
  793. if (DebugAlwaysTrue(WebBrowser->Document2 != NULL))
  794. {
  795. WebBrowser->Document2->designMode = L"Off";
  796. }
  797. }
  798. //---------------------------------------------------------------------------
  799. void __fastcall AddBrowserLinkHandler(TWebBrowserEx * WebBrowser,
  800. const UnicodeString & Url, TNotifyEvent Handler)
  801. {
  802. TBrowserViewer * BrowserViewer = dynamic_cast<TBrowserViewer *>(WebBrowser);
  803. if (DebugAlwaysTrue(BrowserViewer != NULL))
  804. {
  805. BrowserViewer->AddLinkHandler(Url, Handler);
  806. }
  807. }
  808. //---------------------------------------------------------------------------
  809. void __fastcall NavigateBrowserToUrl(TWebBrowserEx * WebBrowser, const UnicodeString & Url)
  810. {
  811. TBrowserViewer * BrowserViewer = dynamic_cast<TBrowserViewer *>(WebBrowser);
  812. if (DebugAlwaysTrue(BrowserViewer != NULL))
  813. {
  814. BrowserViewer->NavigateToUrl(Url);
  815. }
  816. }
  817. //---------------------------------------------------------------------------
  818. TComponent * __fastcall FindComponentRecursively(TComponent * Root, const UnicodeString & Name)
  819. {
  820. for (int Index = 0; Index < Root->ComponentCount; Index++)
  821. {
  822. TComponent * Component = Root->Components[Index];
  823. if (CompareText(Component->Name, Name) == 0)
  824. {
  825. return Component;
  826. }
  827. Component = FindComponentRecursively(Component, Name);
  828. if (Component != NULL)
  829. {
  830. return Component;
  831. }
  832. }
  833. return NULL;
  834. }
  835. //---------------------------------------------------------------------------
  836. TLocalCustomCommand::TLocalCustomCommand()
  837. {
  838. }
  839. //---------------------------------------------------------------------------
  840. TLocalCustomCommand::TLocalCustomCommand(
  841. const TCustomCommandData & Data, const UnicodeString & RemotePath, const UnicodeString & LocalPath) :
  842. TFileCustomCommand(Data, RemotePath)
  843. {
  844. FLocalPath = LocalPath;
  845. }
  846. //---------------------------------------------------------------------------
  847. TLocalCustomCommand::TLocalCustomCommand(const TCustomCommandData & Data,
  848. const UnicodeString & RemotePath, const UnicodeString & LocalPath, const UnicodeString & FileName,
  849. const UnicodeString & LocalFileName, const UnicodeString & FileList) :
  850. TFileCustomCommand(Data, RemotePath, FileName, FileList)
  851. {
  852. FLocalPath = LocalPath;
  853. FLocalFileName = LocalFileName;
  854. }
  855. //---------------------------------------------------------------------------
  856. int __fastcall TLocalCustomCommand::PatternLen(const UnicodeString & Command, int Index)
  857. {
  858. int Len;
  859. if ((Index < Command.Length()) && (Command[Index + 1] == L'\\'))
  860. {
  861. Len = 2;
  862. }
  863. else if ((Index < Command.Length()) && (Command[Index + 1] == L'^'))
  864. {
  865. Len = 3;
  866. }
  867. else
  868. {
  869. Len = TFileCustomCommand::PatternLen(Command, Index);
  870. }
  871. return Len;
  872. }
  873. //---------------------------------------------------------------------------
  874. bool __fastcall TLocalCustomCommand::PatternReplacement(
  875. int Index, const UnicodeString & Pattern, UnicodeString & Replacement, bool & Delimit)
  876. {
  877. bool Result;
  878. if (Pattern == L"!\\")
  879. {
  880. // When used as "!\" in an argument to PowerShell, the trailing \ would escpae the ",
  881. // so we exclude it
  882. Replacement = ExcludeTrailingBackslash(FLocalPath);
  883. Result = true;
  884. }
  885. else if (Pattern == L"!^!")
  886. {
  887. Replacement = FLocalFileName;
  888. Result = true;
  889. }
  890. else
  891. {
  892. Result = TFileCustomCommand::PatternReplacement(Index, Pattern, Replacement, Delimit);
  893. }
  894. return Result;
  895. }
  896. //---------------------------------------------------------------------------
  897. void __fastcall TLocalCustomCommand::DelimitReplacement(
  898. UnicodeString & /*Replacement*/, wchar_t /*Quote*/)
  899. {
  900. // never delimit local commands
  901. }
  902. //---------------------------------------------------------------------------
  903. bool __fastcall TLocalCustomCommand::HasLocalFileName(const UnicodeString & Command)
  904. {
  905. return FindPattern(Command, L'^');
  906. }
  907. //---------------------------------------------------------------------------
  908. bool __fastcall TLocalCustomCommand::IsFileCommand(const UnicodeString & Command)
  909. {
  910. return TFileCustomCommand::IsFileCommand(Command) || HasLocalFileName(Command);
  911. }
  912. //---------------------------------------------------------------------------
  913. //---------------------------------------------------------------------------
  914. typedef std::set<TDataModule *> TImagesModules;
  915. static TImagesModules ImagesModules;
  916. static std::map<int, TPngImageList *> AnimationsImages;
  917. static std::map<int, TImageList *> ButtonImages;
  918. static std::map<int, TPngImageList *> DialogImages;
  919. //---------------------------------------------------------------------------
  920. int __fastcall NormalizePixelsPerInch(int PixelsPerInch)
  921. {
  922. if (PixelsPerInch >= 192)
  923. {
  924. PixelsPerInch = 192;
  925. }
  926. else if (PixelsPerInch >= 144)
  927. {
  928. PixelsPerInch = 144;
  929. }
  930. else if (PixelsPerInch >= 120)
  931. {
  932. PixelsPerInch = 120;
  933. }
  934. else
  935. {
  936. PixelsPerInch = 96;
  937. }
  938. return PixelsPerInch;
  939. }
  940. //---------------------------------------------------------------------------
  941. static int __fastcall NeedImagesModule(TControl * Control)
  942. {
  943. int PixelsPerInch = NormalizePixelsPerInch(GetControlPixelsPerInch(Control));
  944. if (AnimationsImages.find(PixelsPerInch) == AnimationsImages.end())
  945. {
  946. TDataModule * ImagesModule;
  947. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  948. try
  949. {
  950. if (PixelsPerInch == 192)
  951. {
  952. ImagesModule = new TAnimations192Module(Application);
  953. }
  954. else if (PixelsPerInch == 144)
  955. {
  956. ImagesModule = new TAnimations144Module(Application);
  957. }
  958. else if (PixelsPerInch == 120)
  959. {
  960. ImagesModule = new TAnimations120Module(Application);
  961. }
  962. else
  963. {
  964. DebugAssert(PixelsPerInch == 96);
  965. ImagesModule = new TAnimations96Module(Application);
  966. }
  967. ImagesModules.insert(ImagesModule);
  968. TPngImageList * AAnimationImages =
  969. DebugNotNull(dynamic_cast<TPngImageList *>(ImagesModule->FindComponent(L"AnimationImages")));
  970. AnimationsImages.insert(std::make_pair(PixelsPerInch, AAnimationImages));
  971. TImageList * AButtonImages =
  972. DebugNotNull(dynamic_cast<TImageList *>(ImagesModule->FindComponent(L"ButtonImages")));
  973. ButtonImages.insert(std::make_pair(PixelsPerInch, AButtonImages));
  974. TPngImageList * ADialogImages =
  975. DebugNotNull(dynamic_cast<TPngImageList *>(ImagesModule->FindComponent(L"DialogImages")));
  976. DialogImages.insert(std::make_pair(PixelsPerInch, ADialogImages));
  977. }
  978. __finally
  979. {
  980. GUIConfiguration->ChangeResourceModule(ResourceModule);
  981. }
  982. }
  983. return PixelsPerInch;
  984. }
  985. //---------------------------------------------------------------------------
  986. TPngImageList * __fastcall GetAnimationsImages(TControl * Control)
  987. {
  988. int PixelsPerInch = NeedImagesModule(Control);
  989. return DebugNotNull(AnimationsImages[PixelsPerInch]);
  990. }
  991. //---------------------------------------------------------------------------
  992. TImageList * __fastcall GetButtonImages(TControl * Control)
  993. {
  994. int PixelsPerInch = NeedImagesModule(Control);
  995. return DebugNotNull(ButtonImages[PixelsPerInch]);
  996. }
  997. //---------------------------------------------------------------------------
  998. TPngImageList * __fastcall GetDialogImages(TControl * Control)
  999. {
  1000. int PixelsPerInch = NeedImagesModule(Control);
  1001. return DebugNotNull(DialogImages[PixelsPerInch]);
  1002. }
  1003. //---------------------------------------------------------------------------
  1004. void __fastcall ReleaseImagesModules()
  1005. {
  1006. TImagesModules::iterator i = ImagesModules.begin();
  1007. while (i != ImagesModules.end())
  1008. {
  1009. delete (*i);
  1010. i++;
  1011. }
  1012. ImagesModules.clear();
  1013. }
  1014. //---------------------------------------------------------------------------
  1015. __fastcall TFrameAnimation::TFrameAnimation()
  1016. {
  1017. FFirstFrame = -1;
  1018. }
  1019. //---------------------------------------------------------------------------
  1020. void __fastcall TFrameAnimation::Init(TPaintBox * PaintBox, const UnicodeString & Name)
  1021. {
  1022. FName = Name;
  1023. FPaintBox = PaintBox;
  1024. FPaintBox->ControlStyle = FPaintBox->ControlStyle << csOpaque;
  1025. DebugAssert((FPaintBox->OnPaint == NULL) || (FPaintBox->OnPaint == PaintBoxPaint));
  1026. FPaintBox->OnPaint = PaintBoxPaint;
  1027. SetRescaleFunction(FPaintBox, PaintBoxRescale, reinterpret_cast<TObject *>(this));
  1028. DoInit();
  1029. }
  1030. //---------------------------------------------------------------------------
  1031. void __fastcall TFrameAnimation::DoInit()
  1032. {
  1033. FImageList = GetAnimationsImages(FPaintBox);
  1034. FFirstFrame = -1;
  1035. FFirstLoopFrame = -1;
  1036. FPaintBox->Width = FImageList->Width;
  1037. FPaintBox->Height = FImageList->Height;
  1038. if (!FName.IsEmpty())
  1039. {
  1040. int Frame = 0;
  1041. while (Frame < FImageList->PngImages->Count)
  1042. {
  1043. UnicodeString FrameData = FImageList->PngImages->Items[Frame]->Name;
  1044. UnicodeString FrameName;
  1045. FrameName = CutToChar(FrameData, L'_', false);
  1046. if (SameText(FName, FrameName))
  1047. {
  1048. int FrameIndex = StrToInt(CutToChar(FrameData, L'_', false));
  1049. if (FFirstFrame < 0)
  1050. {
  1051. FFirstFrame = Frame;
  1052. }
  1053. if ((FFirstLoopFrame < 0) && (FrameIndex > 0))
  1054. {
  1055. FFirstLoopFrame = Frame;
  1056. }
  1057. FLastFrame = Frame;
  1058. }
  1059. else
  1060. {
  1061. if (FFirstFrame >= 0)
  1062. {
  1063. // optimization
  1064. break;
  1065. }
  1066. }
  1067. Frame++;
  1068. }
  1069. DebugAssert(FFirstFrame >= 0);
  1070. DebugAssert(FFirstLoopFrame >= 0);
  1071. }
  1072. Stop();
  1073. }
  1074. //---------------------------------------------------------------------------
  1075. void __fastcall TFrameAnimation::PaintBoxRescale(TComponent * /*Sender*/, TObject * Token)
  1076. {
  1077. TFrameAnimation * FrameAnimation = reinterpret_cast<TFrameAnimation *>(Token);
  1078. FrameAnimation->Rescale();
  1079. }
  1080. //---------------------------------------------------------------------------
  1081. void __fastcall TFrameAnimation::Rescale()
  1082. {
  1083. bool Started = (FTimer != NULL) && FTimer->Enabled;
  1084. DoInit();
  1085. if (Started)
  1086. {
  1087. Start();
  1088. }
  1089. }
  1090. //---------------------------------------------------------------------------
  1091. void __fastcall TFrameAnimation::Start()
  1092. {
  1093. if (FFirstFrame >= 0)
  1094. {
  1095. FNextFrameTick = GetTickCount();
  1096. CalculateNextFrameTick();
  1097. if (FTimer == NULL)
  1098. {
  1099. FTimer = new TTimer(GetParentForm(FPaintBox));
  1100. FTimer->Interval = static_cast<int>(GUIUpdateInterval);
  1101. FTimer->OnTimer = Timer;
  1102. }
  1103. else
  1104. {
  1105. // reset timer
  1106. FTimer->Enabled = false;
  1107. FTimer->Enabled = true;
  1108. }
  1109. }
  1110. }
  1111. //---------------------------------------------------------------------------
  1112. void __fastcall TFrameAnimation::Timer(TObject * /*Sender*/)
  1113. {
  1114. Animate();
  1115. }
  1116. //---------------------------------------------------------------------------
  1117. void __fastcall TFrameAnimation::PaintBoxPaint(TObject * Sender)
  1118. {
  1119. if (FFirstFrame >= 0)
  1120. {
  1121. // Double-buffered drawing to prevent flicker (as the images are transparent)
  1122. DebugUsedParam(Sender);
  1123. DebugAssert(FPaintBox == Sender);
  1124. DebugAssert(FPaintBox->ControlStyle.Contains(csOpaque));
  1125. std::unique_ptr<TBitmap> Bitmap(new TBitmap());
  1126. Bitmap->SetSize(FPaintBox->Width, FPaintBox->Height);
  1127. Bitmap->Canvas->Brush->Color = FPaintBox->Color;
  1128. TRect Rect(0, 0, Bitmap->Width, Bitmap->Height);
  1129. Bitmap->Canvas->FillRect(Rect);
  1130. TGraphic * Graphic = GetCurrentImage()->PngImage;
  1131. DebugAssert(Graphic->Width == FPaintBox->Width);
  1132. DebugAssert(Graphic->Height == FPaintBox->Height);
  1133. Bitmap->Canvas->Draw(0, 0, Graphic);
  1134. FPaintBox->Canvas->Draw(0, 0, Bitmap.get());
  1135. }
  1136. FPainted = true;
  1137. }
  1138. //---------------------------------------------------------------------------
  1139. void __fastcall TFrameAnimation::Repaint()
  1140. {
  1141. FPainted = false;
  1142. // If the form is not showing yet, the Paint() is not even called
  1143. FPaintBox->Repaint();
  1144. if (!FPainted)
  1145. {
  1146. // Paint later, alternativelly we may keep trying Repaint() in Animate().
  1147. // See also a hack in TAuthenticateForm::Log.
  1148. FPaintBox->Invalidate();
  1149. }
  1150. }
  1151. //---------------------------------------------------------------------------
  1152. void __fastcall TFrameAnimation::Stop()
  1153. {
  1154. FNextFrameTick = std::numeric_limits<DWORD>::max();
  1155. FCurrentFrame = FFirstFrame;
  1156. Repaint();
  1157. if (FTimer != NULL)
  1158. {
  1159. FTimer->Enabled = false;
  1160. }
  1161. }
  1162. //---------------------------------------------------------------------------
  1163. void __fastcall TFrameAnimation::Animate()
  1164. {
  1165. if (FFirstFrame >= 0)
  1166. {
  1167. // UPGRADE: Use GetTickCount64() when we stop supporting Windows XP.
  1168. DWORD TickCount = GetTickCount();
  1169. // Keep in sync with an opposite condition at the end of the loop.
  1170. // We may skip some frames if we got stalled for a while
  1171. while (TickCount >= FNextFrameTick)
  1172. {
  1173. if (FCurrentFrame >= FLastFrame)
  1174. {
  1175. FCurrentFrame = FFirstLoopFrame;
  1176. }
  1177. else
  1178. {
  1179. FCurrentFrame++;
  1180. }
  1181. CalculateNextFrameTick();
  1182. Repaint();
  1183. }
  1184. }
  1185. }
  1186. //---------------------------------------------------------------------------
  1187. TPngImageCollectionItem * __fastcall TFrameAnimation::GetCurrentImage()
  1188. {
  1189. return FImageList->PngImages->Items[FCurrentFrame];
  1190. }
  1191. //---------------------------------------------------------------------------
  1192. void __fastcall TFrameAnimation::CalculateNextFrameTick()
  1193. {
  1194. TPngImageCollectionItem * ImageItem = GetCurrentImage();
  1195. UnicodeString Duration = ImageItem->Name;
  1196. CutToChar(Duration, L'_', false);
  1197. // skip index (is not really used)
  1198. CutToChar(Duration, L'_', false);
  1199. // This should overflow, when tick count wraps.
  1200. FNextFrameTick += StrToInt(Duration) * 10;
  1201. }
  1202. //---------------------------------------------------------------------------
  1203. //---------------------------------------------------------------------------
  1204. // Hints use:
  1205. // - Cleanup list tooltip (multi line)
  1206. // - Combo edit button
  1207. // - Transfer settings label (multi line, follows label size and font)
  1208. // - HintLabel (hint and persistent hint, multipline)
  1209. // - status bar hints
  1210. //---------------------------------------------------------------------------
  1211. __fastcall TScreenTipHintWindow::TScreenTipHintWindow(TComponent * Owner) :
  1212. THintWindow(Owner)
  1213. {
  1214. FParentPainting = false;
  1215. }
  1216. //---------------------------------------------------------------------------
  1217. int __fastcall TScreenTipHintWindow::GetTextFlags(TControl * Control)
  1218. {
  1219. return DT_LEFT | DT_WORDBREAK | DT_NOPREFIX | Control->DrawTextBiDiModeFlagsReadingOnly();
  1220. }
  1221. //---------------------------------------------------------------------------
  1222. bool __fastcall TScreenTipHintWindow::UseBoldShortHint(TControl * HintControl)
  1223. {
  1224. return
  1225. (dynamic_cast<TTBCustomDockableWindow *>(HintControl) != NULL) ||
  1226. (dynamic_cast<TTBPopupWindow *>(HintControl) != NULL);
  1227. }
  1228. //---------------------------------------------------------------------------
  1229. bool __fastcall TScreenTipHintWindow::IsPathLabel(TControl * HintControl)
  1230. {
  1231. return (dynamic_cast<TPathLabel *>(HintControl) != NULL);
  1232. }
  1233. //---------------------------------------------------------------------------
  1234. bool __fastcall TScreenTipHintWindow::IsHintPopup(TControl * HintControl, const UnicodeString & Hint)
  1235. {
  1236. TLabel * HintLabel = dynamic_cast<TLabel *>(HintControl);
  1237. return (HintLabel != NULL) && HasLabelHintPopup(HintLabel, Hint);
  1238. }
  1239. //---------------------------------------------------------------------------
  1240. int __fastcall TScreenTipHintWindow::GetMargin(TControl * HintControl, const UnicodeString & Hint)
  1241. {
  1242. int Result;
  1243. if (IsHintPopup(HintControl, Hint) || IsPathLabel(HintControl))
  1244. {
  1245. Result = 3;
  1246. }
  1247. else
  1248. {
  1249. Result = 6;
  1250. }
  1251. Result = ScaleByTextHeight(HintControl, Result);
  1252. return Result;
  1253. }
  1254. //---------------------------------------------------------------------------
  1255. TFont * __fastcall TScreenTipHintWindow::GetFont(TControl * HintControl, const UnicodeString & Hint)
  1256. {
  1257. TFont * Result;
  1258. if (IsHintPopup(HintControl, Hint) || IsPathLabel(HintControl))
  1259. {
  1260. Result = reinterpret_cast<TLabel *>(dynamic_cast<TCustomLabel *>(HintControl))->Font;
  1261. }
  1262. else
  1263. {
  1264. FScaledHintFont.reset(new TFont());
  1265. FScaledHintFont->Assign(Screen->HintFont);
  1266. FScaledHintFont->Size = ScaleByPixelsPerInchFromSystem(FScaledHintFont->Size, HintControl);
  1267. Result = FScaledHintFont.get();
  1268. }
  1269. return Result;
  1270. }
  1271. //---------------------------------------------------------------------------
  1272. void __fastcall TScreenTipHintWindow::CalcHintTextRect(TControl * Control, TCanvas * Canvas, TRect & Rect, const UnicodeString & Hint)
  1273. {
  1274. const int Flags = DT_CALCRECT | GetTextFlags(Control);
  1275. DrawText(Canvas->Handle, Hint.c_str(), -1, &Rect, Flags);
  1276. }
  1277. //---------------------------------------------------------------------------
  1278. TRect __fastcall TScreenTipHintWindow::CalcHintRect(int MaxWidth, const UnicodeString AHint, void * AData)
  1279. {
  1280. TControl * HintControl = GetHintControl(AData);
  1281. int Margin = GetMargin(HintControl, AHint);
  1282. const UnicodeString ShortHint = GetShortHint(AHint);
  1283. const UnicodeString LongHint = GetLongHintIfAny(AHint);
  1284. Canvas->Font->Assign(GetFont(HintControl, AHint));
  1285. const int ScreenTipTextOnlyWidth = ScaleByTextHeight(HintControl, cScreenTipTextOnlyWidth);
  1286. if (!LongHint.IsEmpty())
  1287. {
  1288. // double-margin on the right
  1289. MaxWidth = ScreenTipTextOnlyWidth - (3 * Margin);
  1290. }
  1291. // Multi line short hints can be twice as wide, to not break the individual lines unless really necessary.
  1292. // (login site tree, clean up dialog list, preferences custom command list, persistent hint, etc).
  1293. // And they also can be twice as wide, to not break the individual lines unless really necessary.
  1294. if (ShortHint.Pos(L"\n") > 0)
  1295. {
  1296. MaxWidth *= 2;
  1297. }
  1298. bool HintPopup = IsHintPopup(HintControl, AHint);
  1299. if (HintPopup)
  1300. {
  1301. MaxWidth = HintControl->Width;
  1302. }
  1303. if (UseBoldShortHint(HintControl))
  1304. {
  1305. Canvas->Font->Style = TFontStyles() << fsBold;
  1306. }
  1307. TRect ShortRect(0, 0, MaxWidth, 0);
  1308. CalcHintTextRect(this, Canvas, ShortRect, ShortHint);
  1309. Canvas->Font->Style = TFontStyles();
  1310. TRect Result;
  1311. if (LongHint.IsEmpty())
  1312. {
  1313. Result = ShortRect;
  1314. if (HintPopup)
  1315. {
  1316. Result.Right = MaxWidth + 2 * Margin;
  1317. }
  1318. else
  1319. {
  1320. Result.Right += 3 * Margin;
  1321. }
  1322. Result.Bottom += 2 * Margin;
  1323. }
  1324. else
  1325. {
  1326. const int LongIndentation = Margin * 3 / 2;
  1327. TRect LongRect(0, 0, MaxWidth - LongIndentation, 0);
  1328. CalcHintTextRect(this, Canvas, LongRect, LongHint);
  1329. Result.Right = ScreenTipTextOnlyWidth;
  1330. Result.Bottom = Margin + ShortRect.Height() + (Margin / 3 * 5) + LongRect.Height() + Margin;
  1331. }
  1332. // VCLCOPY: To counter the increase in THintWindow::ActivateHintData
  1333. Result.Bottom -= 4;
  1334. return Result;
  1335. }
  1336. //---------------------------------------------------------------------------
  1337. void __fastcall TScreenTipHintWindow::ActivateHintData(const TRect & ARect, const UnicodeString AHint, void * AData)
  1338. {
  1339. FShortHint = GetShortHint(AHint);
  1340. FLongHint = GetLongHintIfAny(AHint);
  1341. FHintControl = GetHintControl(AData);
  1342. FMargin = GetMargin(FHintControl, AHint);
  1343. FHintPopup = IsHintPopup(FHintControl, AHint);
  1344. Canvas->Font->Assign(GetFont(FHintControl, AHint));
  1345. TRect Rect = ARect;
  1346. if (FHintPopup)
  1347. {
  1348. Rect.SetLocation(FHintControl->ClientToScreen(TPoint(-FMargin, -FMargin)));
  1349. }
  1350. if (IsPathLabel(FHintControl))
  1351. {
  1352. Rect.Offset(-FMargin, -FMargin);
  1353. }
  1354. THintWindow::ActivateHintData(Rect, FShortHint, AData);
  1355. }
  1356. //---------------------------------------------------------------------------
  1357. TControl * __fastcall TScreenTipHintWindow::GetHintControl(void * Data)
  1358. {
  1359. return reinterpret_cast<TControl *>(DebugNotNull(Data));
  1360. }
  1361. //---------------------------------------------------------------------------
  1362. UnicodeString __fastcall TScreenTipHintWindow::GetLongHintIfAny(const UnicodeString & AHint)
  1363. {
  1364. UnicodeString Result;
  1365. int P = Pos(L"|", AHint);
  1366. if (P > 0)
  1367. {
  1368. Result = GetLongHint(AHint);
  1369. }
  1370. return Result;
  1371. }
  1372. //---------------------------------------------------------------------------
  1373. void __fastcall TScreenTipHintWindow::Dispatch(void * AMessage)
  1374. {
  1375. TMessage * Message = static_cast<TMessage*>(AMessage);
  1376. switch (Message->Msg)
  1377. {
  1378. case WM_GETTEXTLENGTH:
  1379. if (FParentPainting)
  1380. {
  1381. // make THintWindow::Paint() not paint the Caption
  1382. Message->Result = 0;
  1383. }
  1384. else
  1385. {
  1386. THintWindow::Dispatch(AMessage);
  1387. }
  1388. break;
  1389. default:
  1390. THintWindow::Dispatch(AMessage);
  1391. break;
  1392. }
  1393. }
  1394. //---------------------------------------------------------------------------
  1395. void __fastcall TScreenTipHintWindow::Paint()
  1396. {
  1397. // paint frame/background
  1398. {
  1399. TAutoFlag ParentPaintingFlag(FParentPainting);
  1400. THintWindow::Paint();
  1401. }
  1402. const int Flags = GetTextFlags(this);
  1403. const int Margin = FMargin - 1; // 1 = border
  1404. TRect Rect = ClientRect;
  1405. Rect.Inflate(-Margin, -Margin);
  1406. if (!FHintPopup)
  1407. {
  1408. Rect.Right -= FMargin;
  1409. }
  1410. if (UseBoldShortHint(FHintControl))
  1411. {
  1412. Canvas->Font->Style = TFontStyles() << fsBold;
  1413. }
  1414. DrawText(Canvas->Handle, FShortHint.c_str(), -1, &Rect, Flags);
  1415. TRect ShortRect = Rect;
  1416. DrawText(Canvas->Handle, FShortHint.c_str(), -1, &ShortRect, DT_CALCRECT | Flags);
  1417. Canvas->Font->Style = TFontStyles();
  1418. if (!FLongHint.IsEmpty())
  1419. {
  1420. Rect.Left += FMargin * 3 / 2;
  1421. Rect.Top += ShortRect.Height() + (FMargin / 3 * 5);
  1422. DrawText(Canvas->Handle, FLongHint.c_str(), -1, &Rect, Flags);
  1423. }
  1424. }