GUITools.cpp 60 KB

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