1
0

GUITools.cpp 67 KB

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