GUITools.cpp 69 KB

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