GUITools.cpp 68 KB

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