GUITools.cpp 60 KB

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