GUITools.cpp 70 KB

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