GUITools.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517
  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. while ((Width = CalculateWidth(Start, CalculateWidthArg)) < MaxWidth)
  488. {
  489. int Wider = CalculateWidth(Start + Padding, CalculateWidthArg);
  490. // If padded string is wider than max width by more pixels
  491. // than non-padded string is shorter than max width
  492. if ((Wider > MaxWidth) && ((Wider - MaxWidth) > (MaxWidth - Width)))
  493. {
  494. break;
  495. }
  496. Start += Padding;
  497. }
  498. Lines->Strings[Index] = Start + Remaining;
  499. }
  500. }
  501. Text = Lines->Text;
  502. // remove trailing newline
  503. Text = Text.TrimRight();
  504. }
  505. }
  506. //---------------------------------------------------------------------------
  507. static void __fastcall DoSelectScaledImageList(TImageList * ImageList)
  508. {
  509. TImageList * MatchingList = NULL;
  510. int MachingPixelsPerInch = 0;
  511. int PixelsPerInch = GetComponentPixelsPerInch(ImageList);
  512. for (int Index = 0; Index < ImageList->Owner->ComponentCount; Index++)
  513. {
  514. TImageList * OtherList = dynamic_cast<TImageList *>(ImageList->Owner->Components[Index]);
  515. if ((OtherList != NULL) &&
  516. (OtherList != ImageList) &&
  517. StartsStr(ImageList->Name, OtherList->Name))
  518. {
  519. UnicodeString OtherListPixelsPerInchStr =
  520. OtherList->Name.SubString(
  521. ImageList->Name.Length() + 1, OtherList->Name.Length() - ImageList->Name.Length());
  522. int OtherListPixelsPerInch = StrToInt(OtherListPixelsPerInchStr);
  523. if ((OtherListPixelsPerInch <= PixelsPerInch) &&
  524. ((MatchingList == NULL) ||
  525. (MachingPixelsPerInch < OtherListPixelsPerInch)))
  526. {
  527. MatchingList = OtherList;
  528. MachingPixelsPerInch = OtherListPixelsPerInch;
  529. }
  530. }
  531. }
  532. if (MatchingList != NULL)
  533. {
  534. UnicodeString ImageListBackupName = ImageList->Name + IntToStr(USER_DEFAULT_SCREEN_DPI);
  535. if (ImageList->Owner->FindComponent(ImageListBackupName) == NULL)
  536. {
  537. TImageList * ImageListBackup;
  538. TPngImageList * PngImageList = dynamic_cast<TPngImageList *>(ImageList);
  539. if (PngImageList != NULL)
  540. {
  541. ImageListBackup = new TPngImageList(ImageList->Owner);
  542. }
  543. else
  544. {
  545. ImageListBackup = new TImageList(ImageList->Owner);
  546. }
  547. ImageListBackup->Name = ImageListBackupName;
  548. ImageList->Owner->InsertComponent(ImageListBackup);
  549. CopyImageList(ImageListBackup, ImageList);
  550. }
  551. CopyImageList(ImageList, MatchingList);
  552. }
  553. }
  554. //---------------------------------------------------------------------------
  555. static void __fastcall ImageListRescale(TComponent * Sender, TObject * /*Token*/)
  556. {
  557. TImageList * ImageList = DebugNotNull(dynamic_cast<TImageList *>(Sender));
  558. DoSelectScaledImageList(ImageList);
  559. }
  560. //---------------------------------------------------------------------------
  561. void __fastcall SelectScaledImageList(TImageList * ImageList)
  562. {
  563. DoSelectScaledImageList(ImageList);
  564. SetRescaleFunction(ImageList, ImageListRescale);
  565. }
  566. //---------------------------------------------------------------------------
  567. void __fastcall CopyImageList(TImageList * TargetList, TImageList * SourceList)
  568. {
  569. // Maybe this is not necessary, once the TPngImageList::Assign was fixed
  570. TPngImageList * PngTargetList = dynamic_cast<TPngImageList *>(TargetList);
  571. TPngImageList * PngSourceList = dynamic_cast<TPngImageList *>(SourceList);
  572. TargetList->Clear();
  573. TargetList->Height = SourceList->Height;
  574. TargetList->Width = SourceList->Width;
  575. if ((PngTargetList != NULL) && (PngSourceList != NULL))
  576. {
  577. // AddImages won't copy the names and we need them for
  578. // LoadDialogImage and TFrameAnimation
  579. PngTargetList->PngImages->Assign(PngSourceList->PngImages);
  580. }
  581. else
  582. {
  583. TargetList->AddImages(SourceList);
  584. }
  585. }
  586. //---------------------------------------------------------------------------
  587. static bool __fastcall DoLoadDialogImage(TImage * Image, const UnicodeString & ImageName)
  588. {
  589. bool Result = false;
  590. if (GlyphsModule != NULL)
  591. {
  592. TPngImageList * DialogImages = GetDialogImages(Image);
  593. int Index;
  594. for (Index = 0; Index < DialogImages->PngImages->Count; Index++)
  595. {
  596. TPngImageCollectionItem * PngItem = DialogImages->PngImages->Items[Index];
  597. if (SameText(PngItem->Name, ImageName))
  598. {
  599. Image->Picture->Assign(PngItem->PngImage);
  600. break;
  601. }
  602. }
  603. DebugAssert(Index < DialogImages->PngImages->Count);
  604. Result = true;
  605. }
  606. // When showing an exception from wWinMain, the images are released already.
  607. // Non-existence of the glyphs module is just a good indication of that.
  608. // We expect errors only.
  609. else if (ImageName == L"Error")
  610. {
  611. Image->Picture->Icon->Handle = LoadIcon(0, IDI_HAND);
  612. }
  613. // For showing an information about trace files
  614. else if (DebugAlwaysTrue(ImageName == L"Information"))
  615. {
  616. Image->Picture->Icon->Handle = LoadIcon(0, IDI_APPLICATION);
  617. }
  618. return Result;
  619. }
  620. //---------------------------------------------------------------------------
  621. class TDialogImageName : public TObject
  622. {
  623. public:
  624. UnicodeString ImageName;
  625. };
  626. //---------------------------------------------------------------------------
  627. static void __fastcall DialogImageRescale(TComponent * Sender, TObject * Token)
  628. {
  629. TImage * Image = DebugNotNull(dynamic_cast<TImage *>(Sender));
  630. TDialogImageName * DialogImageName = DebugNotNull(dynamic_cast<TDialogImageName *>(Token));
  631. DoLoadDialogImage(Image, DialogImageName->ImageName);
  632. }
  633. //---------------------------------------------------------------------------
  634. void __fastcall LoadDialogImage(TImage * Image, const UnicodeString & ImageName)
  635. {
  636. if (DoLoadDialogImage(Image, ImageName))
  637. {
  638. TDialogImageName * DialogImageName = new TDialogImageName();
  639. DialogImageName->ImageName = ImageName;
  640. SetRescaleFunction(Image, DialogImageRescale, DialogImageName, true);
  641. }
  642. }
  643. //---------------------------------------------------------------------------
  644. int __fastcall DialogImageSize(TForm * Form)
  645. {
  646. return ScaleByPixelsPerInch(32, Form);
  647. }
  648. //---------------------------------------------------------------------------
  649. void __fastcall HideComponentsPanel(TForm * Form)
  650. {
  651. TComponent * Component = DebugNotNull(Form->FindComponent(L"ComponentsPanel"));
  652. TPanel * Panel = DebugNotNull(dynamic_cast<TPanel *>(Component));
  653. DebugAssert(Panel->Align == alBottom);
  654. int Offset = Panel->Height;
  655. Panel->Visible = false;
  656. Panel->Height = 0;
  657. Form->Height -= Offset;
  658. for (int Index = 0; Index < Form->ControlCount; Index++)
  659. {
  660. TControl * Control = Form->Controls[Index];
  661. // Shift back bottom-anchored controls
  662. // (needed for toolbar panel on Progress window and buttons on Preferences dialog),
  663. if ((Control->Align == alNone) &&
  664. Control->Anchors.Contains(akBottom) &&
  665. !Control->Anchors.Contains(akTop))
  666. {
  667. Control->Top += Offset;
  668. }
  669. // Resize back all-anchored controls
  670. // (needed for main panel on Preferences dialog),
  671. if (Control->Anchors.Contains(akBottom) &&
  672. Control->Anchors.Contains(akTop))
  673. {
  674. Control->Height += Offset;
  675. }
  676. }
  677. }
  678. //---------------------------------------------------------------------------
  679. class TBrowserViewer : public TWebBrowserEx
  680. {
  681. public:
  682. __fastcall virtual TBrowserViewer(TComponent* AOwner);
  683. void __fastcall AddLinkHandler(
  684. const UnicodeString & Url, TNotifyEvent Handler);
  685. void __fastcall NavigateToUrl(const UnicodeString & Url);
  686. TControl * LoadingPanel;
  687. protected:
  688. DYNAMIC void __fastcall DoContextPopup(const TPoint & MousePos, bool & Handled);
  689. void __fastcall DocumentComplete(
  690. TObject * Sender, const _di_IDispatch Disp, const OleVariant & URL);
  691. void __fastcall BeforeNavigate2(
  692. TObject * Sender, const _di_IDispatch Disp, const OleVariant & URL,
  693. const OleVariant & Flags, const OleVariant & TargetFrameName,
  694. const OleVariant & PostData, const OleVariant & Headers, WordBool & Cancel);
  695. bool FComplete;
  696. std::map<UnicodeString, TNotifyEvent> FHandlers;
  697. };
  698. //---------------------------------------------------------------------------
  699. __fastcall TBrowserViewer::TBrowserViewer(TComponent* AOwner) :
  700. TWebBrowserEx(AOwner)
  701. {
  702. FComplete = false;
  703. OnDocumentComplete = DocumentComplete;
  704. OnBeforeNavigate2 = BeforeNavigate2;
  705. LoadingPanel = NULL;
  706. }
  707. //---------------------------------------------------------------------------
  708. void __fastcall TBrowserViewer::AddLinkHandler(
  709. const UnicodeString & Url, TNotifyEvent Handler)
  710. {
  711. FHandlers.insert(std::make_pair(Url, Handler));
  712. }
  713. //---------------------------------------------------------------------------
  714. void __fastcall TBrowserViewer::DoContextPopup(const TPoint & MousePos, bool & Handled)
  715. {
  716. // suppress built-in context menu
  717. Handled = true;
  718. TWebBrowserEx::DoContextPopup(MousePos, Handled);
  719. }
  720. //---------------------------------------------------------------------------
  721. void __fastcall TBrowserViewer::DocumentComplete(
  722. TObject * /*Sender*/, const _di_IDispatch /*Disp*/, const OleVariant & /*URL*/)
  723. {
  724. SetBrowserDesignModeOff(this);
  725. FComplete = true;
  726. if (LoadingPanel != NULL)
  727. {
  728. LoadingPanel->Visible = false;
  729. }
  730. }
  731. //---------------------------------------------------------------------------
  732. void __fastcall TBrowserViewer::BeforeNavigate2(
  733. TObject * /*Sender*/, const _di_IDispatch /*Disp*/, const OleVariant & AURL,
  734. const OleVariant & /*Flags*/, const OleVariant & /*TargetFrameName*/,
  735. const OleVariant & /*PostData*/, const OleVariant & /*Headers*/, WordBool & Cancel)
  736. {
  737. // If OnDocumentComplete was not called yet, is has to be our initial message URL,
  738. // opened using TWebBrowserEx::Navigate(), allow it.
  739. // Otherwise it's user navigating, block that and open link
  740. // in an external browser, possibly adding campaign parameters on the way.
  741. if (FComplete)
  742. {
  743. Cancel = 1;
  744. UnicodeString URL = AURL;
  745. if (FHandlers.count(URL) > 0)
  746. {
  747. FHandlers[URL](this);
  748. }
  749. else
  750. {
  751. OpenBrowser(URL);
  752. }
  753. }
  754. }
  755. //---------------------------------------------------------------------------
  756. void __fastcall TBrowserViewer::NavigateToUrl(const UnicodeString & Url)
  757. {
  758. FComplete = false;
  759. Navigate(Url.c_str());
  760. }
  761. //---------------------------------------------------------------------------
  762. TPanel * __fastcall CreateLabelPanel(TPanel * Parent, const UnicodeString & Label)
  763. {
  764. TPanel * Result = CreateBlankPanel(Parent);
  765. Result->Parent = Parent;
  766. Result->Align = alClient;
  767. Result->Caption = Label;
  768. return Result;
  769. }
  770. //---------------------------------------------------------------------------
  771. TWebBrowserEx * __fastcall CreateBrowserViewer(TPanel * Parent, const UnicodeString & LoadingLabel)
  772. {
  773. TBrowserViewer * Result = new TBrowserViewer(Parent);
  774. // TWebBrowserEx has its own unrelated Name and Parent properties.
  775. // The name is used in DownloadUpdate().
  776. static_cast<TWinControl *>(Result)->Name = L"BrowserViewer";
  777. static_cast<TWinControl *>(Result)->Parent = Parent;
  778. Result->Align = alClient;
  779. Result->ControlBorder = cbNone;
  780. Result->LoadingPanel = CreateLabelPanel(Parent, LoadingLabel);
  781. return Result;
  782. }
  783. //---------------------------------------------------------------------------
  784. void __fastcall SetBrowserDesignModeOff(TWebBrowserEx * WebBrowser)
  785. {
  786. if (DebugAlwaysTrue(WebBrowser->Document2 != NULL))
  787. {
  788. WebBrowser->Document2->designMode = L"Off";
  789. }
  790. }
  791. //---------------------------------------------------------------------------
  792. void __fastcall AddBrowserLinkHandler(TWebBrowserEx * WebBrowser,
  793. const UnicodeString & Url, TNotifyEvent Handler)
  794. {
  795. TBrowserViewer * BrowserViewer = dynamic_cast<TBrowserViewer *>(WebBrowser);
  796. if (DebugAlwaysTrue(BrowserViewer != NULL))
  797. {
  798. BrowserViewer->AddLinkHandler(Url, Handler);
  799. }
  800. }
  801. //---------------------------------------------------------------------------
  802. void __fastcall NavigateBrowserToUrl(TWebBrowserEx * WebBrowser, const UnicodeString & Url)
  803. {
  804. TBrowserViewer * BrowserViewer = dynamic_cast<TBrowserViewer *>(WebBrowser);
  805. if (DebugAlwaysTrue(BrowserViewer != NULL))
  806. {
  807. BrowserViewer->NavigateToUrl(Url);
  808. }
  809. }
  810. //---------------------------------------------------------------------------
  811. TComponent * __fastcall FindComponentRecursively(TComponent * Root, const UnicodeString & Name)
  812. {
  813. for (int Index = 0; Index < Root->ComponentCount; Index++)
  814. {
  815. TComponent * Component = Root->Components[Index];
  816. if (CompareText(Component->Name, Name) == 0)
  817. {
  818. return Component;
  819. }
  820. Component = FindComponentRecursively(Component, Name);
  821. if (Component != NULL)
  822. {
  823. return Component;
  824. }
  825. }
  826. return NULL;
  827. }
  828. //---------------------------------------------------------------------------
  829. TLocalCustomCommand::TLocalCustomCommand()
  830. {
  831. }
  832. //---------------------------------------------------------------------------
  833. TLocalCustomCommand::TLocalCustomCommand(
  834. const TCustomCommandData & Data, const UnicodeString & RemotePath, const UnicodeString & LocalPath) :
  835. TFileCustomCommand(Data, RemotePath)
  836. {
  837. FLocalPath = LocalPath;
  838. }
  839. //---------------------------------------------------------------------------
  840. TLocalCustomCommand::TLocalCustomCommand(const TCustomCommandData & Data,
  841. const UnicodeString & RemotePath, const UnicodeString & LocalPath, const UnicodeString & FileName,
  842. const UnicodeString & LocalFileName, const UnicodeString & FileList) :
  843. TFileCustomCommand(Data, RemotePath, FileName, FileList)
  844. {
  845. FLocalPath = LocalPath;
  846. FLocalFileName = LocalFileName;
  847. }
  848. //---------------------------------------------------------------------------
  849. int __fastcall TLocalCustomCommand::PatternLen(const UnicodeString & Command, int Index)
  850. {
  851. int Len;
  852. if ((Index < Command.Length()) && (Command[Index + 1] == L'\\'))
  853. {
  854. Len = 2;
  855. }
  856. else if ((Index < Command.Length()) && (Command[Index + 1] == L'^'))
  857. {
  858. Len = 3;
  859. }
  860. else
  861. {
  862. Len = TFileCustomCommand::PatternLen(Command, Index);
  863. }
  864. return Len;
  865. }
  866. //---------------------------------------------------------------------------
  867. bool __fastcall TLocalCustomCommand::PatternReplacement(
  868. int Index, const UnicodeString & Pattern, UnicodeString & Replacement, bool & Delimit)
  869. {
  870. bool Result;
  871. if (Pattern == L"!\\")
  872. {
  873. // When used as "!\" in an argument to PowerShell, the trailing \ would escpae the ",
  874. // so we exclude it
  875. Replacement = ExcludeTrailingBackslash(FLocalPath);
  876. Result = true;
  877. }
  878. else if (Pattern == L"!^!")
  879. {
  880. Replacement = FLocalFileName;
  881. Result = true;
  882. }
  883. else
  884. {
  885. Result = TFileCustomCommand::PatternReplacement(Index, Pattern, Replacement, Delimit);
  886. }
  887. return Result;
  888. }
  889. //---------------------------------------------------------------------------
  890. void __fastcall TLocalCustomCommand::DelimitReplacement(
  891. UnicodeString & /*Replacement*/, wchar_t /*Quote*/)
  892. {
  893. // never delimit local commands
  894. }
  895. //---------------------------------------------------------------------------
  896. bool __fastcall TLocalCustomCommand::HasLocalFileName(const UnicodeString & Command)
  897. {
  898. return FindPattern(Command, L'^');
  899. }
  900. //---------------------------------------------------------------------------
  901. bool __fastcall TLocalCustomCommand::IsFileCommand(const UnicodeString & Command)
  902. {
  903. return TFileCustomCommand::IsFileCommand(Command) || HasLocalFileName(Command);
  904. }
  905. //---------------------------------------------------------------------------
  906. //---------------------------------------------------------------------------
  907. typedef std::set<TDataModule *> TImagesModules;
  908. static TImagesModules ImagesModules;
  909. static std::map<int, TPngImageList *> AnimationsImages;
  910. static std::map<int, TImageList *> ButtonImages;
  911. static std::map<int, TPngImageList *> DialogImages;
  912. //---------------------------------------------------------------------------
  913. int __fastcall NormalizePixelsPerInch(int PixelsPerInch)
  914. {
  915. if (PixelsPerInch >= 192)
  916. {
  917. PixelsPerInch = 192;
  918. }
  919. else if (PixelsPerInch >= 144)
  920. {
  921. PixelsPerInch = 144;
  922. }
  923. else if (PixelsPerInch >= 120)
  924. {
  925. PixelsPerInch = 120;
  926. }
  927. else
  928. {
  929. PixelsPerInch = 96;
  930. }
  931. return PixelsPerInch;
  932. }
  933. //---------------------------------------------------------------------------
  934. static int __fastcall NeedImagesModule(TControl * Control)
  935. {
  936. int PixelsPerInch = NormalizePixelsPerInch(GetControlPixelsPerInch(Control));
  937. if (AnimationsImages.find(PixelsPerInch) == AnimationsImages.end())
  938. {
  939. TDataModule * ImagesModule;
  940. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  941. try
  942. {
  943. if (PixelsPerInch == 192)
  944. {
  945. ImagesModule = new TAnimations192Module(Application);
  946. }
  947. else if (PixelsPerInch == 144)
  948. {
  949. ImagesModule = new TAnimations144Module(Application);
  950. }
  951. else if (PixelsPerInch == 120)
  952. {
  953. ImagesModule = new TAnimations120Module(Application);
  954. }
  955. else
  956. {
  957. DebugAssert(PixelsPerInch == 96);
  958. ImagesModule = new TAnimations96Module(Application);
  959. }
  960. ImagesModules.insert(ImagesModule);
  961. TPngImageList * AAnimationImages =
  962. DebugNotNull(dynamic_cast<TPngImageList *>(ImagesModule->FindComponent(L"AnimationImages")));
  963. AnimationsImages.insert(std::make_pair(PixelsPerInch, AAnimationImages));
  964. TImageList * AButtonImages =
  965. DebugNotNull(dynamic_cast<TImageList *>(ImagesModule->FindComponent(L"ButtonImages")));
  966. ButtonImages.insert(std::make_pair(PixelsPerInch, AButtonImages));
  967. TPngImageList * ADialogImages =
  968. DebugNotNull(dynamic_cast<TPngImageList *>(ImagesModule->FindComponent(L"DialogImages")));
  969. DialogImages.insert(std::make_pair(PixelsPerInch, ADialogImages));
  970. }
  971. __finally
  972. {
  973. GUIConfiguration->ChangeResourceModule(ResourceModule);
  974. }
  975. }
  976. return PixelsPerInch;
  977. }
  978. //---------------------------------------------------------------------------
  979. TPngImageList * __fastcall GetAnimationsImages(TControl * Control)
  980. {
  981. int PixelsPerInch = NeedImagesModule(Control);
  982. return DebugNotNull(AnimationsImages[PixelsPerInch]);
  983. }
  984. //---------------------------------------------------------------------------
  985. TImageList * __fastcall GetButtonImages(TControl * Control)
  986. {
  987. int PixelsPerInch = NeedImagesModule(Control);
  988. return DebugNotNull(ButtonImages[PixelsPerInch]);
  989. }
  990. //---------------------------------------------------------------------------
  991. TPngImageList * __fastcall GetDialogImages(TControl * Control)
  992. {
  993. int PixelsPerInch = NeedImagesModule(Control);
  994. return DebugNotNull(DialogImages[PixelsPerInch]);
  995. }
  996. //---------------------------------------------------------------------------
  997. void __fastcall ReleaseImagesModules()
  998. {
  999. TImagesModules::iterator i = ImagesModules.begin();
  1000. while (i != ImagesModules.end())
  1001. {
  1002. delete (*i);
  1003. i++;
  1004. }
  1005. ImagesModules.clear();
  1006. }
  1007. //---------------------------------------------------------------------------
  1008. __fastcall TFrameAnimation::TFrameAnimation()
  1009. {
  1010. FFirstFrame = -1;
  1011. }
  1012. //---------------------------------------------------------------------------
  1013. void __fastcall TFrameAnimation::Init(TPaintBox * PaintBox, const UnicodeString & Name)
  1014. {
  1015. FName = Name;
  1016. FPaintBox = PaintBox;
  1017. FPaintBox->ControlStyle = FPaintBox->ControlStyle << csOpaque;
  1018. DebugAssert((FPaintBox->OnPaint == NULL) || (FPaintBox->OnPaint == PaintBoxPaint));
  1019. FPaintBox->OnPaint = PaintBoxPaint;
  1020. SetRescaleFunction(FPaintBox, PaintBoxRescale, reinterpret_cast<TObject *>(this));
  1021. DoInit();
  1022. }
  1023. //---------------------------------------------------------------------------
  1024. void __fastcall TFrameAnimation::DoInit()
  1025. {
  1026. FImageList = GetAnimationsImages(FPaintBox);
  1027. FFirstFrame = -1;
  1028. FFirstLoopFrame = -1;
  1029. FPaintBox->Width = FImageList->Width;
  1030. FPaintBox->Height = FImageList->Height;
  1031. if (!FName.IsEmpty())
  1032. {
  1033. int Frame = 0;
  1034. while (Frame < FImageList->PngImages->Count)
  1035. {
  1036. UnicodeString FrameData = FImageList->PngImages->Items[Frame]->Name;
  1037. UnicodeString FrameName;
  1038. FrameName = CutToChar(FrameData, L'_', false);
  1039. if (SameText(FName, FrameName))
  1040. {
  1041. int FrameIndex = StrToInt(CutToChar(FrameData, L'_', false));
  1042. if (FFirstFrame < 0)
  1043. {
  1044. FFirstFrame = Frame;
  1045. }
  1046. if ((FFirstLoopFrame < 0) && (FrameIndex > 0))
  1047. {
  1048. FFirstLoopFrame = Frame;
  1049. }
  1050. FLastFrame = Frame;
  1051. }
  1052. else
  1053. {
  1054. if (FFirstFrame >= 0)
  1055. {
  1056. // optimization
  1057. break;
  1058. }
  1059. }
  1060. Frame++;
  1061. }
  1062. DebugAssert(FFirstFrame >= 0);
  1063. DebugAssert(FFirstLoopFrame >= 0);
  1064. }
  1065. Stop();
  1066. }
  1067. //---------------------------------------------------------------------------
  1068. void __fastcall TFrameAnimation::PaintBoxRescale(TComponent * /*Sender*/, TObject * Token)
  1069. {
  1070. TFrameAnimation * FrameAnimation = reinterpret_cast<TFrameAnimation *>(Token);
  1071. FrameAnimation->Rescale();
  1072. }
  1073. //---------------------------------------------------------------------------
  1074. void __fastcall TFrameAnimation::Rescale()
  1075. {
  1076. bool Started = (FTimer != NULL) && FTimer->Enabled;
  1077. DoInit();
  1078. if (Started)
  1079. {
  1080. Start();
  1081. }
  1082. }
  1083. //---------------------------------------------------------------------------
  1084. void __fastcall TFrameAnimation::Start()
  1085. {
  1086. if (FFirstFrame >= 0)
  1087. {
  1088. FNextFrameTick = GetTickCount();
  1089. CalculateNextFrameTick();
  1090. if (FTimer == NULL)
  1091. {
  1092. FTimer = new TTimer(GetParentForm(FPaintBox));
  1093. FTimer->Interval = static_cast<int>(GUIUpdateInterval);
  1094. FTimer->OnTimer = Timer;
  1095. }
  1096. else
  1097. {
  1098. // reset timer
  1099. FTimer->Enabled = false;
  1100. FTimer->Enabled = true;
  1101. }
  1102. }
  1103. }
  1104. //---------------------------------------------------------------------------
  1105. void __fastcall TFrameAnimation::Timer(TObject * /*Sender*/)
  1106. {
  1107. Animate();
  1108. }
  1109. //---------------------------------------------------------------------------
  1110. void __fastcall TFrameAnimation::PaintBoxPaint(TObject * Sender)
  1111. {
  1112. if (FFirstFrame >= 0)
  1113. {
  1114. // Double-buffered drawing to prevent flicker (as the images are transparent)
  1115. DebugUsedParam(Sender);
  1116. DebugAssert(FPaintBox == Sender);
  1117. DebugAssert(FPaintBox->ControlStyle.Contains(csOpaque));
  1118. std::unique_ptr<TBitmap> Bitmap(new TBitmap());
  1119. Bitmap->SetSize(FPaintBox->Width, FPaintBox->Height);
  1120. Bitmap->Canvas->Brush->Color = FPaintBox->Color;
  1121. TRect Rect(0, 0, Bitmap->Width, Bitmap->Height);
  1122. Bitmap->Canvas->FillRect(Rect);
  1123. TGraphic * Graphic = GetCurrentImage()->PngImage;
  1124. DebugAssert(Graphic->Width == FPaintBox->Width);
  1125. DebugAssert(Graphic->Height == FPaintBox->Height);
  1126. Bitmap->Canvas->Draw(0, 0, Graphic);
  1127. FPaintBox->Canvas->Draw(0, 0, Bitmap.get());
  1128. }
  1129. FPainted = true;
  1130. }
  1131. //---------------------------------------------------------------------------
  1132. void __fastcall TFrameAnimation::Repaint()
  1133. {
  1134. FPainted = false;
  1135. // If the form is not showing yet, the Paint() is not even called
  1136. FPaintBox->Repaint();
  1137. if (!FPainted)
  1138. {
  1139. // Paint later, alternativelly we may keep trying Repaint() in Animate().
  1140. // See also a hack in TAuthenticateForm::Log.
  1141. FPaintBox->Invalidate();
  1142. }
  1143. }
  1144. //---------------------------------------------------------------------------
  1145. void __fastcall TFrameAnimation::Stop()
  1146. {
  1147. FNextFrameTick = std::numeric_limits<DWORD>::max();
  1148. FCurrentFrame = FFirstFrame;
  1149. Repaint();
  1150. if (FTimer != NULL)
  1151. {
  1152. FTimer->Enabled = false;
  1153. }
  1154. }
  1155. //---------------------------------------------------------------------------
  1156. void __fastcall TFrameAnimation::Animate()
  1157. {
  1158. if (FFirstFrame >= 0)
  1159. {
  1160. // UPGRADE: Use GetTickCount64() when we stop supporting Windows XP.
  1161. DWORD TickCount = GetTickCount();
  1162. // Keep in sync with an opposite condition at the end of the loop.
  1163. // We may skip some frames if we got stalled for a while
  1164. while (TickCount >= FNextFrameTick)
  1165. {
  1166. if (FCurrentFrame >= FLastFrame)
  1167. {
  1168. FCurrentFrame = FFirstLoopFrame;
  1169. }
  1170. else
  1171. {
  1172. FCurrentFrame++;
  1173. }
  1174. CalculateNextFrameTick();
  1175. Repaint();
  1176. }
  1177. }
  1178. }
  1179. //---------------------------------------------------------------------------
  1180. TPngImageCollectionItem * __fastcall TFrameAnimation::GetCurrentImage()
  1181. {
  1182. return FImageList->PngImages->Items[FCurrentFrame];
  1183. }
  1184. //---------------------------------------------------------------------------
  1185. void __fastcall TFrameAnimation::CalculateNextFrameTick()
  1186. {
  1187. TPngImageCollectionItem * ImageItem = GetCurrentImage();
  1188. UnicodeString Duration = ImageItem->Name;
  1189. CutToChar(Duration, L'_', false);
  1190. // skip index (is not really used)
  1191. CutToChar(Duration, L'_', false);
  1192. // This should overflow, when tick count wraps.
  1193. FNextFrameTick += StrToInt(Duration) * 10;
  1194. }
  1195. //---------------------------------------------------------------------------
  1196. //---------------------------------------------------------------------------
  1197. // Hints use:
  1198. // - Cleanup list tooltip (multi line)
  1199. // - Combo edit button
  1200. // - Transfer settings label (multi line, follows label size and font)
  1201. // - HintLabel (hint and persistent hint, multipline)
  1202. // - status bar hints
  1203. //---------------------------------------------------------------------------
  1204. __fastcall TScreenTipHintWindow::TScreenTipHintWindow(TComponent * Owner) :
  1205. THintWindow(Owner)
  1206. {
  1207. FParentPainting = false;
  1208. }
  1209. //---------------------------------------------------------------------------
  1210. int __fastcall TScreenTipHintWindow::GetTextFlags(TControl * Control)
  1211. {
  1212. return DT_LEFT | DT_WORDBREAK | DT_NOPREFIX | Control->DrawTextBiDiModeFlagsReadingOnly();
  1213. }
  1214. //---------------------------------------------------------------------------
  1215. bool __fastcall TScreenTipHintWindow::UseBoldShortHint(TControl * HintControl)
  1216. {
  1217. return
  1218. (dynamic_cast<TTBCustomDockableWindow *>(HintControl) != NULL) ||
  1219. (dynamic_cast<TTBPopupWindow *>(HintControl) != NULL);
  1220. }
  1221. //---------------------------------------------------------------------------
  1222. bool __fastcall TScreenTipHintWindow::IsPathLabel(TControl * HintControl)
  1223. {
  1224. return (dynamic_cast<TPathLabel *>(HintControl) != NULL);
  1225. }
  1226. //---------------------------------------------------------------------------
  1227. bool __fastcall TScreenTipHintWindow::IsHintPopup(TControl * HintControl, const UnicodeString & Hint)
  1228. {
  1229. TLabel * HintLabel = dynamic_cast<TLabel *>(HintControl);
  1230. return (HintLabel != NULL) && HasLabelHintPopup(HintLabel, Hint);
  1231. }
  1232. //---------------------------------------------------------------------------
  1233. int __fastcall TScreenTipHintWindow::GetMargin(TControl * HintControl, const UnicodeString & Hint)
  1234. {
  1235. int Result;
  1236. if (IsHintPopup(HintControl, Hint) || IsPathLabel(HintControl))
  1237. {
  1238. Result = 3;
  1239. }
  1240. else
  1241. {
  1242. Result = 6;
  1243. }
  1244. Result = ScaleByTextHeight(HintControl, Result);
  1245. return Result;
  1246. }
  1247. //---------------------------------------------------------------------------
  1248. TFont * __fastcall TScreenTipHintWindow::GetFont(TControl * HintControl, const UnicodeString & Hint)
  1249. {
  1250. TFont * Result;
  1251. if (IsHintPopup(HintControl, Hint) || IsPathLabel(HintControl))
  1252. {
  1253. Result = reinterpret_cast<TLabel *>(dynamic_cast<TCustomLabel *>(HintControl))->Font;
  1254. }
  1255. else
  1256. {
  1257. FScaledHintFont.reset(new TFont());
  1258. FScaledHintFont->Assign(Screen->HintFont);
  1259. FScaledHintFont->Size = ScaleByPixelsPerInchFromSystem(FScaledHintFont->Size, HintControl);
  1260. Result = FScaledHintFont.get();
  1261. }
  1262. return Result;
  1263. }
  1264. //---------------------------------------------------------------------------
  1265. void __fastcall TScreenTipHintWindow::CalcHintTextRect(TControl * Control, TCanvas * Canvas, TRect & Rect, const UnicodeString & Hint)
  1266. {
  1267. const int Flags = DT_CALCRECT | GetTextFlags(Control);
  1268. DrawText(Canvas->Handle, Hint.c_str(), -1, &Rect, Flags);
  1269. }
  1270. //---------------------------------------------------------------------------
  1271. TRect __fastcall TScreenTipHintWindow::CalcHintRect(int MaxWidth, const UnicodeString AHint, void * AData)
  1272. {
  1273. TControl * HintControl = GetHintControl(AData);
  1274. int Margin = GetMargin(HintControl, AHint);
  1275. const UnicodeString ShortHint = GetShortHint(AHint);
  1276. const UnicodeString LongHint = GetLongHintIfAny(AHint);
  1277. Canvas->Font->Assign(GetFont(HintControl, AHint));
  1278. const int ScreenTipTextOnlyWidth = ScaleByTextHeight(HintControl, cScreenTipTextOnlyWidth);
  1279. if (!LongHint.IsEmpty())
  1280. {
  1281. // double-margin on the right
  1282. MaxWidth = ScreenTipTextOnlyWidth - (3 * Margin);
  1283. }
  1284. // Multi line short hints can be twice as wide, to not break the individual lines unless really necessary.
  1285. // (login site tree, clean up dialog list, preferences custom command list, persistent hint, etc).
  1286. // And they also can be twice as wide, to not break the individual lines unless really necessary.
  1287. if (ShortHint.Pos(L"\n") > 0)
  1288. {
  1289. MaxWidth *= 2;
  1290. }
  1291. bool HintPopup = IsHintPopup(HintControl, AHint);
  1292. if (HintPopup)
  1293. {
  1294. MaxWidth = HintControl->Width;
  1295. }
  1296. if (UseBoldShortHint(HintControl))
  1297. {
  1298. Canvas->Font->Style = TFontStyles() << fsBold;
  1299. }
  1300. TRect ShortRect(0, 0, MaxWidth, 0);
  1301. CalcHintTextRect(this, Canvas, ShortRect, ShortHint);
  1302. Canvas->Font->Style = TFontStyles();
  1303. TRect Result;
  1304. if (LongHint.IsEmpty())
  1305. {
  1306. Result = ShortRect;
  1307. if (HintPopup)
  1308. {
  1309. Result.Right = MaxWidth + 2 * Margin;
  1310. }
  1311. else
  1312. {
  1313. Result.Right += 3 * Margin;
  1314. }
  1315. Result.Bottom += 2 * Margin;
  1316. }
  1317. else
  1318. {
  1319. const int LongIndentation = Margin * 3 / 2;
  1320. TRect LongRect(0, 0, MaxWidth - LongIndentation, 0);
  1321. CalcHintTextRect(this, Canvas, LongRect, LongHint);
  1322. Result.Right = ScreenTipTextOnlyWidth;
  1323. Result.Bottom = Margin + ShortRect.Height() + (Margin / 3 * 5) + LongRect.Height() + Margin;
  1324. }
  1325. // VCLCOPY: To counter the increase in THintWindow::ActivateHintData
  1326. Result.Bottom -= 4;
  1327. return Result;
  1328. }
  1329. //---------------------------------------------------------------------------
  1330. void __fastcall TScreenTipHintWindow::ActivateHintData(const TRect & ARect, const UnicodeString AHint, void * AData)
  1331. {
  1332. FShortHint = GetShortHint(AHint);
  1333. FLongHint = GetLongHintIfAny(AHint);
  1334. FHintControl = GetHintControl(AData);
  1335. FMargin = GetMargin(FHintControl, AHint);
  1336. FHintPopup = IsHintPopup(FHintControl, AHint);
  1337. Canvas->Font->Assign(GetFont(FHintControl, AHint));
  1338. TRect Rect = ARect;
  1339. if (FHintPopup)
  1340. {
  1341. Rect.SetLocation(FHintControl->ClientToScreen(TPoint(-FMargin, -FMargin)));
  1342. }
  1343. if (IsPathLabel(FHintControl))
  1344. {
  1345. Rect.Offset(-FMargin, -FMargin);
  1346. }
  1347. THintWindow::ActivateHintData(Rect, FShortHint, AData);
  1348. }
  1349. //---------------------------------------------------------------------------
  1350. TControl * __fastcall TScreenTipHintWindow::GetHintControl(void * Data)
  1351. {
  1352. return reinterpret_cast<TControl *>(DebugNotNull(Data));
  1353. }
  1354. //---------------------------------------------------------------------------
  1355. UnicodeString __fastcall TScreenTipHintWindow::GetLongHintIfAny(const UnicodeString & AHint)
  1356. {
  1357. UnicodeString Result;
  1358. int P = Pos(L"|", AHint);
  1359. if (P > 0)
  1360. {
  1361. Result = GetLongHint(AHint);
  1362. }
  1363. return Result;
  1364. }
  1365. //---------------------------------------------------------------------------
  1366. void __fastcall TScreenTipHintWindow::Dispatch(void * AMessage)
  1367. {
  1368. TMessage * Message = static_cast<TMessage*>(AMessage);
  1369. switch (Message->Msg)
  1370. {
  1371. case WM_GETTEXTLENGTH:
  1372. if (FParentPainting)
  1373. {
  1374. // make THintWindow::Paint() not paint the Caption
  1375. Message->Result = 0;
  1376. }
  1377. else
  1378. {
  1379. THintWindow::Dispatch(AMessage);
  1380. }
  1381. break;
  1382. default:
  1383. THintWindow::Dispatch(AMessage);
  1384. break;
  1385. }
  1386. }
  1387. //---------------------------------------------------------------------------
  1388. void __fastcall TScreenTipHintWindow::Paint()
  1389. {
  1390. // paint frame/background
  1391. {
  1392. TAutoFlag ParentPaintingFlag(FParentPainting);
  1393. THintWindow::Paint();
  1394. }
  1395. const int Flags = GetTextFlags(this);
  1396. const int Margin = FMargin - 1; // 1 = border
  1397. TRect Rect = ClientRect;
  1398. Rect.Inflate(-Margin, -Margin);
  1399. if (!FHintPopup)
  1400. {
  1401. Rect.Right -= FMargin;
  1402. }
  1403. if (UseBoldShortHint(FHintControl))
  1404. {
  1405. Canvas->Font->Style = TFontStyles() << fsBold;
  1406. }
  1407. DrawText(Canvas->Handle, FShortHint.c_str(), -1, &Rect, Flags);
  1408. TRect ShortRect = Rect;
  1409. DrawText(Canvas->Handle, FShortHint.c_str(), -1, &ShortRect, DT_CALCRECT | Flags);
  1410. Canvas->Font->Style = TFontStyles();
  1411. if (!FLongHint.IsEmpty())
  1412. {
  1413. Rect.Left += FMargin * 3 / 2;
  1414. Rect.Top += ShortRect.Height() + (FMargin / 3 * 5);
  1415. DrawText(Canvas->Handle, FLongHint.c_str(), -1, &Rect, Flags);
  1416. }
  1417. }