GUITools.cpp 53 KB

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