GUITools.cpp 55 KB

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