1
0

GUITools.cpp 46 KB

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