GUITools.cpp 68 KB

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