GUITools.cpp 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152
  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 __fastcall OpenSessionInPutty(const UnicodeString PuttyPath,
  144. TSessionData * SessionData)
  145. {
  146. // See also TSiteAdvancedDialog::PuttySettingsButtonClick
  147. UnicodeString Program, AParams, Dir;
  148. SplitCommand(PuttyPath, Program, AParams, Dir);
  149. Program = ExpandEnvironmentVariables(Program);
  150. if (FindFile(Program))
  151. {
  152. AParams = ExpandEnvironmentVariables(AParams);
  153. UnicodeString Password;
  154. if (GUIConfiguration->PuttyPassword)
  155. {
  156. // Passphrase has precendence, as it's more likely entered by user during authentication, hence more likely really needed.
  157. if (!SessionData->Passphrase.IsEmpty())
  158. {
  159. Password = SessionData->Passphrase;
  160. }
  161. else if (!SessionData->Password.IsEmpty())
  162. {
  163. Password = SessionData->Password;
  164. }
  165. }
  166. TCustomCommandData Data(SessionData, SessionData->UserName, Password);
  167. TLocalCustomCommand LocalCustomCommand(Data, SessionData->RemoteDirectory, SessionData->LocalDirectory);
  168. TWinInteractiveCustomCommand InteractiveCustomCommand(
  169. &LocalCustomCommand, L"PuTTY", UnicodeString());
  170. UnicodeString Params =
  171. LocalCustomCommand.Complete(InteractiveCustomCommand.Complete(AParams, false), true);
  172. UnicodeString PuttyParams;
  173. if (!LocalCustomCommand.IsSiteCommand(AParams))
  174. {
  175. {
  176. bool SessionList = false;
  177. std::unique_ptr<THierarchicalStorage> SourceHostKeyStorage(Configuration->CreateScpStorage(SessionList));
  178. std::unique_ptr<THierarchicalStorage> TargetHostKeyStorage(new TRegistryStorage(Configuration->PuttyRegistryStorageKey));
  179. TargetHostKeyStorage->Explicit = true;
  180. TargetHostKeyStorage->AccessMode = smReadWrite;
  181. std::unique_ptr<TStoredSessionList> HostKeySessionList(new TStoredSessionList());
  182. HostKeySessionList->OwnsObjects = false;
  183. HostKeySessionList->Add(SessionData);
  184. TStoredSessionList::ImportHostKeys(SourceHostKeyStorage.get(), TargetHostKeyStorage.get(), HostKeySessionList.get(), false);
  185. }
  186. if (IsUWP())
  187. {
  188. bool Telnet = (SessionData->FSProtocol == fsFTP) && GUIConfiguration->TelnetForFtpInPutty;
  189. if (Telnet)
  190. {
  191. AddToList(PuttyParams, L"-telnet", L" ");
  192. // PuTTY does not allow -pw for telnet
  193. Password = L"";
  194. }
  195. AddToList(PuttyParams, EscapePuttyCommandParam(SessionData->HostName), L" ");
  196. if (!SessionData->UserName.IsEmpty())
  197. {
  198. AddToList(PuttyParams, FORMAT(L"-l %s", (EscapePuttyCommandParam(SessionData->UserName))), L" ");
  199. }
  200. if ((SessionData->FSProtocol != fsFTP) && (SessionData->PortNumber != SshPortNumber))
  201. {
  202. AddToList(PuttyParams, FORMAT(L"-P %d", (SessionData->PortNumber)), L" ");
  203. }
  204. if (!Telnet)
  205. {
  206. if (!SessionData->PublicKeyFile.IsEmpty())
  207. {
  208. AddToList(PuttyParams, FORMAT(L"-i \"%s\"", (SessionData->PublicKeyFile)), L" ");
  209. }
  210. AddToList(PuttyParams, (SessionData->TryAgent ? L"-agent" : L"-noagent"), L" ");
  211. if (SessionData->TryAgent)
  212. {
  213. AddToList(PuttyParams, (SessionData->AgentFwd ? L"-A" : L"-a"), L" ");
  214. }
  215. if (SessionData->Compression)
  216. {
  217. AddToList(PuttyParams, L"-C", L" ");
  218. }
  219. AddToList(PuttyParams, 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, bool Enable)
  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. if (Enable)
  658. {
  659. PublicItem->ItemStyle = PublicItem->ItemStyle << tbisSubmenu;
  660. }
  661. else
  662. {
  663. PublicItem->ItemStyle = PublicItem->ItemStyle >> tbisSubmenu;
  664. }
  665. }
  666. //---------------------------------------------------------------------------
  667. bool __fastcall IsEligibleForApplyingTabs(
  668. UnicodeString Line, int & TabPos, UnicodeString & Start, UnicodeString & Remaining)
  669. {
  670. bool Result = false;
  671. TabPos = Line.Pos(L"\t");
  672. if (TabPos > 0)
  673. {
  674. Remaining = Line.SubString(TabPos + 1, Line.Length() - TabPos);
  675. // WORKAROUND
  676. // Some translations still use obsolete hack of consecutive tabs to aling the contents.
  677. // Delete these, so that the following check does not fail on this
  678. while (Remaining.SubString(1, 1) == L"\t")
  679. {
  680. Remaining.Delete(1, 1);
  681. }
  682. // We do not have, not support, mutiple tabs on a single line
  683. if (DebugAlwaysTrue(Remaining.Pos(L"\t") == 0))
  684. {
  685. Start = Line.SubString(1, TabPos - 1);
  686. // WORKAROUND
  687. // Previously we padded the string before tab with spaces,
  688. // to aling the contents across multiple lines
  689. Start = Start.TrimRight();
  690. // at least two normal spaces for separation
  691. Start += L" ";
  692. Result = true;
  693. }
  694. }
  695. return Result;
  696. }
  697. //---------------------------------------------------------------------------
  698. static int __fastcall CalculateWidthByLength(UnicodeString Text, void * /*Arg*/)
  699. {
  700. return Text.Length();
  701. }
  702. //---------------------------------------------------------------------------
  703. void __fastcall ApplyTabs(
  704. UnicodeString & Text, wchar_t Padding,
  705. TCalculateWidth CalculateWidth, void * CalculateWidthArg)
  706. {
  707. if (CalculateWidth == NULL)
  708. {
  709. DebugAssert(CalculateWidthArg == NULL);
  710. CalculateWidth = CalculateWidthByLength;
  711. }
  712. std::unique_ptr<TStringList> Lines(TextToStringList(Text));
  713. int MaxWidth = -1;
  714. for (int Index = 0; Index < Lines->Count; Index++)
  715. {
  716. UnicodeString Line = Lines->Strings[Index];
  717. int TabPos;
  718. UnicodeString Start;
  719. UnicodeString Remaining;
  720. if (IsEligibleForApplyingTabs(Line, TabPos, Start, Remaining))
  721. {
  722. int Width = CalculateWidth(Start, CalculateWidthArg);
  723. MaxWidth = Max(MaxWidth, Width);
  724. }
  725. }
  726. // Optimization and also to prevent potential regression for texts without tabs
  727. if (MaxWidth >= 0)
  728. {
  729. for (int Index = 0; Index < Lines->Count; Index++)
  730. {
  731. UnicodeString Line = Lines->Strings[Index];
  732. int TabPos;
  733. UnicodeString Start;
  734. UnicodeString Remaining;
  735. if (IsEligibleForApplyingTabs(Line, TabPos, Start, Remaining))
  736. {
  737. int Width;
  738. int Iterations = 0;
  739. while ((Width = CalculateWidth(Start, CalculateWidthArg)) < MaxWidth)
  740. {
  741. int Wider = CalculateWidth(Start + Padding, CalculateWidthArg);
  742. // If padded string is wider than max width by more pixels
  743. // than non-padded string is shorter than max width
  744. if ((Wider > MaxWidth) && ((Wider - MaxWidth) > (MaxWidth - Width)))
  745. {
  746. break;
  747. }
  748. Start += Padding;
  749. Iterations++;
  750. // In rare case a tab is zero-width with some strange font (like HYLE)
  751. if (Iterations > 100)
  752. {
  753. break;
  754. }
  755. }
  756. Lines->Strings[Index] = Start + Remaining;
  757. }
  758. }
  759. Text = Lines->Text;
  760. // remove trailing newline
  761. Text = Text.TrimRight();
  762. }
  763. }
  764. //---------------------------------------------------------------------------
  765. static void __fastcall DoSelectScaledImageList(TImageList * ImageList)
  766. {
  767. TImageList * MatchingList = NULL;
  768. int MachingPixelsPerInch = 0;
  769. int PixelsPerInch = GetComponentPixelsPerInch(ImageList);
  770. for (int Index = 0; Index < ImageList->Owner->ComponentCount; Index++)
  771. {
  772. TImageList * OtherList = dynamic_cast<TImageList *>(ImageList->Owner->Components[Index]);
  773. if ((OtherList != NULL) &&
  774. (OtherList != ImageList) &&
  775. StartsStr(ImageList->Name, OtherList->Name))
  776. {
  777. UnicodeString OtherListPixelsPerInchStr =
  778. OtherList->Name.SubString(
  779. ImageList->Name.Length() + 1, OtherList->Name.Length() - ImageList->Name.Length());
  780. int OtherListPixelsPerInch = StrToInt(OtherListPixelsPerInchStr);
  781. if ((OtherListPixelsPerInch <= PixelsPerInch) &&
  782. ((MatchingList == NULL) ||
  783. (MachingPixelsPerInch < OtherListPixelsPerInch)))
  784. {
  785. MatchingList = OtherList;
  786. MachingPixelsPerInch = OtherListPixelsPerInch;
  787. }
  788. }
  789. }
  790. if (MatchingList != NULL)
  791. {
  792. UnicodeString ImageListBackupName = ImageList->Name + IntToStr(USER_DEFAULT_SCREEN_DPI);
  793. if (ImageList->Owner->FindComponent(ImageListBackupName) == NULL)
  794. {
  795. TImageList * ImageListBackup;
  796. TPngImageList * PngImageList = dynamic_cast<TPngImageList *>(ImageList);
  797. if (PngImageList != NULL)
  798. {
  799. ImageListBackup = new TPngImageList(ImageList->Owner);
  800. }
  801. else
  802. {
  803. ImageListBackup = new TImageList(ImageList->Owner);
  804. }
  805. ImageListBackup->Name = ImageListBackupName;
  806. ImageList->Owner->InsertComponent(ImageListBackup);
  807. CopyImageList(ImageListBackup, ImageList);
  808. }
  809. CopyImageList(ImageList, MatchingList);
  810. }
  811. }
  812. //---------------------------------------------------------------------------
  813. static void __fastcall ImageListRescale(TComponent * Sender, TObject * /*Token*/)
  814. {
  815. TImageList * ImageList = DebugNotNull(dynamic_cast<TImageList *>(Sender));
  816. DoSelectScaledImageList(ImageList);
  817. }
  818. //---------------------------------------------------------------------------
  819. void __fastcall SelectScaledImageList(TImageList * ImageList)
  820. {
  821. DoSelectScaledImageList(ImageList);
  822. SetRescaleFunction(ImageList, ImageListRescale);
  823. }
  824. //---------------------------------------------------------------------------
  825. void __fastcall CopyImageList(TImageList * TargetList, TImageList * SourceList)
  826. {
  827. // Maybe this is not necessary, once the TPngImageList::Assign was fixed
  828. TPngImageList * PngTargetList = dynamic_cast<TPngImageList *>(TargetList);
  829. TPngImageList * PngSourceList = dynamic_cast<TPngImageList *>(SourceList);
  830. TargetList->Clear();
  831. TargetList->Height = SourceList->Height;
  832. TargetList->Width = SourceList->Width;
  833. if ((PngTargetList != NULL) && (PngSourceList != NULL))
  834. {
  835. // AddImages won't copy the names and we need them for
  836. // LoadDialogImage and TFrameAnimation
  837. PngTargetList->PngImages->Assign(PngSourceList->PngImages);
  838. }
  839. else
  840. {
  841. TargetList->AddImages(SourceList);
  842. }
  843. }
  844. //---------------------------------------------------------------------------
  845. static bool __fastcall DoLoadDialogImage(TImage * Image, const UnicodeString & ImageName)
  846. {
  847. bool Result = false;
  848. if (GlyphsModule != NULL)
  849. {
  850. TPngImageList * DialogImages = GetDialogImages(Image);
  851. int Index;
  852. for (Index = 0; Index < DialogImages->PngImages->Count; Index++)
  853. {
  854. TPngImageCollectionItem * PngItem = DialogImages->PngImages->Items[Index];
  855. if (SameText(PngItem->Name, ImageName))
  856. {
  857. Image->Picture->Assign(PngItem->PngImage);
  858. break;
  859. }
  860. }
  861. DebugAssert(Index < DialogImages->PngImages->Count);
  862. Result = true;
  863. }
  864. // When showing an exception from wWinMain, the images are released already.
  865. // Non-existence of the glyphs module is just a good indication of that.
  866. // We expect errors only.
  867. else if (ImageName == L"Error")
  868. {
  869. Image->Picture->Icon->Handle = LoadIcon(0, IDI_HAND);
  870. }
  871. // For showing an information about trace files
  872. else if (DebugAlwaysTrue(ImageName == L"Information"))
  873. {
  874. Image->Picture->Icon->Handle = LoadIcon(0, IDI_APPLICATION);
  875. }
  876. return Result;
  877. }
  878. //---------------------------------------------------------------------------
  879. class TDialogImageName : public TObject
  880. {
  881. public:
  882. UnicodeString ImageName;
  883. };
  884. //---------------------------------------------------------------------------
  885. static void __fastcall DialogImageRescale(TComponent * Sender, TObject * Token)
  886. {
  887. TImage * Image = DebugNotNull(dynamic_cast<TImage *>(Sender));
  888. TDialogImageName * DialogImageName = DebugNotNull(dynamic_cast<TDialogImageName *>(Token));
  889. DoLoadDialogImage(Image, DialogImageName->ImageName);
  890. }
  891. //---------------------------------------------------------------------------
  892. void __fastcall LoadDialogImage(TImage * Image, const UnicodeString & ImageName)
  893. {
  894. if (DoLoadDialogImage(Image, ImageName))
  895. {
  896. TDialogImageName * DialogImageName = new TDialogImageName();
  897. DialogImageName->ImageName = ImageName;
  898. SetRescaleFunction(Image, DialogImageRescale, DialogImageName, true);
  899. }
  900. }
  901. //---------------------------------------------------------------------------
  902. int __fastcall DialogImageSize(TForm * Form)
  903. {
  904. return ScaleByPixelsPerInch(32, Form);
  905. }
  906. //---------------------------------------------------------------------------
  907. void __fastcall HideComponentsPanel(TForm * Form)
  908. {
  909. TComponent * Component = DebugNotNull(Form->FindComponent(L"ComponentsPanel"));
  910. TPanel * Panel = DebugNotNull(dynamic_cast<TPanel *>(Component));
  911. DebugAssert(Panel->Align == alBottom);
  912. int Offset = Panel->Height;
  913. Panel->Visible = false;
  914. Panel->Height = 0;
  915. Form->Height -= Offset;
  916. for (int Index = 0; Index < Form->ControlCount; Index++)
  917. {
  918. TControl * Control = Form->Controls[Index];
  919. // Shift back bottom-anchored controls
  920. // (needed for toolbar panel on Progress window and buttons on Preferences dialog),
  921. if ((Control->Align == alNone) &&
  922. Control->Anchors.Contains(akBottom) &&
  923. !Control->Anchors.Contains(akTop))
  924. {
  925. Control->Top += Offset;
  926. }
  927. // Resize back all-anchored controls
  928. // (needed for main panel on Preferences dialog),
  929. if (Control->Anchors.Contains(akBottom) &&
  930. Control->Anchors.Contains(akTop))
  931. {
  932. Control->Height += Offset;
  933. }
  934. }
  935. }
  936. //---------------------------------------------------------------------------
  937. UnicodeString FormatIncrementalSearchStatus(const UnicodeString & Text, bool HaveNext)
  938. {
  939. UnicodeString Result =
  940. L" " + FMTLOAD(INC_SEARCH, (Text)) +
  941. (HaveNext ? L" " + LoadStr(INC_NEXT_SEARCH) : UnicodeString());
  942. return Result;
  943. }
  944. //---------------------------------------------------------------------------
  945. class TCustomDocHandler : public TComponent, public ::IDocHostUIHandler
  946. {
  947. public:
  948. __fastcall TCustomDocHandler(TComponent * Owner) : TComponent(Owner)
  949. {
  950. }
  951. protected:
  952. #pragma warn -hid
  953. virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID ClassId, void ** Intf)
  954. {
  955. HRESULT Result = S_OK;
  956. if (ClassId == IID_IUnknown)
  957. {
  958. *Intf = (IUnknown *)this;
  959. }
  960. else if (ClassId == ::IID_IDocHostUIHandler)
  961. {
  962. *Intf = (::IDocHostUIHandler *)this;
  963. }
  964. else
  965. {
  966. Result = E_NOINTERFACE;
  967. }
  968. return Result;
  969. }
  970. #pragma warn .hid
  971. virtual ULONG STDMETHODCALLTYPE AddRef()
  972. {
  973. return -1;
  974. }
  975. virtual ULONG STDMETHODCALLTYPE Release()
  976. {
  977. return -1;
  978. }
  979. virtual HRESULT STDMETHODCALLTYPE ShowContextMenu(
  980. DWORD dwID, POINT * ppt, IUnknown * pcmdtReserved, IDispatch * pdispReserved)
  981. {
  982. // No context menu
  983. // (implementing IDocHostUIHandler reenabled context menu disabled by TBrowserViewer::DoContextPopup)
  984. return S_OK;
  985. }
  986. virtual HRESULT STDMETHODCALLTYPE GetHostInfo(::_DOCHOSTUIINFO * Info)
  987. {
  988. // Setting ControlBorder is ignored with IDocHostUIHandler.
  989. // DOCHOSTUIFLAG_DPI_AWARE does not seem to have any effect
  990. Info->dwFlags |= DOCHOSTUIFLAG_SCROLL_NO | DOCHOSTUIFLAG_NO3DBORDER | DOCHOSTUIFLAG_DPI_AWARE;
  991. return S_OK;
  992. }
  993. virtual HRESULT STDMETHODCALLTYPE ShowUI(
  994. DWORD dwID, IOleInPlaceActiveObject * pActiveObject, IOleCommandTarget * pCommandTarget, IOleInPlaceFrame * pFrame,
  995. IOleInPlaceUIWindow * pDoc)
  996. {
  997. return E_NOTIMPL;
  998. }
  999. virtual HRESULT STDMETHODCALLTYPE HideUI()
  1000. {
  1001. return E_NOTIMPL;
  1002. }
  1003. virtual HRESULT STDMETHODCALLTYPE UpdateUI()
  1004. {
  1005. return E_NOTIMPL;
  1006. }
  1007. virtual HRESULT STDMETHODCALLTYPE EnableModeless(BOOL fEnable)
  1008. {
  1009. return E_NOTIMPL;
  1010. }
  1011. virtual HRESULT STDMETHODCALLTYPE OnDocWindowActivate(BOOL fActivate)
  1012. {
  1013. return E_NOTIMPL;
  1014. }
  1015. virtual HRESULT STDMETHODCALLTYPE OnFrameWindowActivate(BOOL fActivate)
  1016. {
  1017. return E_NOTIMPL;
  1018. }
  1019. virtual HRESULT STDMETHODCALLTYPE ResizeBorder(LPCRECT prcBorder, IOleInPlaceUIWindow * pUIWindow, BOOL fRameWindow)
  1020. {
  1021. return E_NOTIMPL;
  1022. }
  1023. virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator(LPMSG lpMsg, const GUID * pguidCmdGroup, DWORD nCmdID)
  1024. {
  1025. return E_NOTIMPL;
  1026. }
  1027. virtual HRESULT STDMETHODCALLTYPE GetOptionKeyPath(LPOLESTR * pchKey, DWORD dw)
  1028. {
  1029. return E_NOTIMPL;
  1030. }
  1031. virtual HRESULT STDMETHODCALLTYPE GetDropTarget(IDropTarget * pDropTarget, IDropTarget ** ppDropTarget)
  1032. {
  1033. return E_NOTIMPL;
  1034. }
  1035. virtual HRESULT STDMETHODCALLTYPE GetExternal(IDispatch ** ppDispatch)
  1036. {
  1037. return E_NOTIMPL;
  1038. }
  1039. virtual HRESULT STDMETHODCALLTYPE TranslateUrl(DWORD dwTranslate, OLECHAR * pchURLIn, OLECHAR ** ppchURLOut)
  1040. {
  1041. return E_NOTIMPL;
  1042. }
  1043. virtual HRESULT STDMETHODCALLTYPE FilterDataObject(IDataObject * pDO, IDataObject ** ppDORet)
  1044. {
  1045. return E_NOTIMPL;
  1046. }
  1047. };
  1048. //---------------------------------------------------------------------------
  1049. class TBrowserViewer : public TWebBrowserEx
  1050. {
  1051. public:
  1052. __fastcall virtual TBrowserViewer(TComponent* AOwner);
  1053. void __fastcall AddLinkHandler(
  1054. const UnicodeString & Url, TNotifyEvent Handler);
  1055. void __fastcall NavigateToUrl(const UnicodeString & Url);
  1056. TControl * LoadingPanel;
  1057. protected:
  1058. DYNAMIC void __fastcall DoContextPopup(const TPoint & MousePos, bool & Handled);
  1059. void __fastcall DocumentComplete(
  1060. TObject * Sender, const _di_IDispatch Disp, const OleVariant & URL);
  1061. void __fastcall BeforeNavigate2(
  1062. TObject * Sender, const _di_IDispatch Disp, const OleVariant & URL,
  1063. const OleVariant & Flags, const OleVariant & TargetFrameName,
  1064. const OleVariant & PostData, const OleVariant & Headers, WordBool & Cancel);
  1065. bool FComplete;
  1066. std::map<UnicodeString, TNotifyEvent> FHandlers;
  1067. };
  1068. //---------------------------------------------------------------------------
  1069. __fastcall TBrowserViewer::TBrowserViewer(TComponent* AOwner) :
  1070. TWebBrowserEx(AOwner)
  1071. {
  1072. FComplete = false;
  1073. OnDocumentComplete = DocumentComplete;
  1074. OnBeforeNavigate2 = BeforeNavigate2;
  1075. LoadingPanel = NULL;
  1076. }
  1077. //---------------------------------------------------------------------------
  1078. void __fastcall TBrowserViewer::AddLinkHandler(
  1079. const UnicodeString & Url, TNotifyEvent Handler)
  1080. {
  1081. FHandlers.insert(std::make_pair(Url, Handler));
  1082. }
  1083. //---------------------------------------------------------------------------
  1084. void __fastcall TBrowserViewer::DoContextPopup(const TPoint & MousePos, bool & Handled)
  1085. {
  1086. // Suppress built-in context menu.
  1087. // Is ignored with IDocHostUIHandler. Needs to be overriden by ShowContextMenu.
  1088. Handled = true;
  1089. TWebBrowserEx::DoContextPopup(MousePos, Handled);
  1090. }
  1091. //---------------------------------------------------------------------------
  1092. void __fastcall TBrowserViewer::DocumentComplete(
  1093. TObject * /*Sender*/, const _di_IDispatch /*Disp*/, const OleVariant & /*URL*/)
  1094. {
  1095. SetBrowserDesignModeOff(this);
  1096. FComplete = true;
  1097. if (LoadingPanel != NULL)
  1098. {
  1099. LoadingPanel->Visible = false;
  1100. }
  1101. }
  1102. //---------------------------------------------------------------------------
  1103. void __fastcall TBrowserViewer::BeforeNavigate2(
  1104. TObject * /*Sender*/, const _di_IDispatch /*Disp*/, const OleVariant & AURL,
  1105. const OleVariant & /*Flags*/, const OleVariant & /*TargetFrameName*/,
  1106. const OleVariant & /*PostData*/, const OleVariant & /*Headers*/, WordBool & Cancel)
  1107. {
  1108. // If OnDocumentComplete was not called yet, is has to be our initial message URL,
  1109. // opened using TWebBrowserEx::Navigate(), allow it.
  1110. // Otherwise it's user navigating, block that and open link
  1111. // in an external browser, possibly adding campaign parameters on the way.
  1112. if (FComplete)
  1113. {
  1114. Cancel = 1;
  1115. UnicodeString URL = AURL;
  1116. if (FHandlers.count(URL) > 0)
  1117. {
  1118. FHandlers[URL](this);
  1119. }
  1120. else
  1121. {
  1122. OpenBrowser(URL);
  1123. }
  1124. }
  1125. }
  1126. //---------------------------------------------------------------------------
  1127. void __fastcall TBrowserViewer::NavigateToUrl(const UnicodeString & Url)
  1128. {
  1129. FComplete = false;
  1130. Navigate(Url.c_str());
  1131. }
  1132. //---------------------------------------------------------------------------
  1133. TPanel * __fastcall CreateLabelPanel(TPanel * Parent, const UnicodeString & Label)
  1134. {
  1135. TPanel * Result = CreateBlankPanel(Parent);
  1136. Result->Parent = Parent;
  1137. Result->Align = alClient;
  1138. Result->Caption = Label;
  1139. return Result;
  1140. }
  1141. //---------------------------------------------------------------------------
  1142. TWebBrowserEx * __fastcall CreateBrowserViewer(TPanel * Parent, const UnicodeString & LoadingLabel)
  1143. {
  1144. TBrowserViewer * Result = new TBrowserViewer(Parent);
  1145. // TWebBrowserEx has its own unrelated Name and Parent properties.
  1146. // The name is used in DownloadUpdate().
  1147. static_cast<TWinControl *>(Result)->Name = L"BrowserViewer";
  1148. static_cast<TWinControl *>(Result)->Parent = Parent;
  1149. Result->Align = alClient;
  1150. // Is ignored with IDocHostUIHandler. Needs to be overriden by DOCHOSTUIFLAG_NO3DBORDER in GetHostInfo.
  1151. Result->ControlBorder = cbNone;
  1152. Result->LoadingPanel = CreateLabelPanel(Parent, LoadingLabel);
  1153. return Result;
  1154. }
  1155. //---------------------------------------------------------------------------
  1156. void __fastcall SetBrowserDesignModeOff(TWebBrowserEx * WebBrowser)
  1157. {
  1158. if (DebugAlwaysTrue(WebBrowser->Document2 != NULL))
  1159. {
  1160. WebBrowser->Document2->designMode = L"Off";
  1161. }
  1162. }
  1163. //---------------------------------------------------------------------------
  1164. void __fastcall AddBrowserLinkHandler(TWebBrowserEx * WebBrowser,
  1165. const UnicodeString & Url, TNotifyEvent Handler)
  1166. {
  1167. TBrowserViewer * BrowserViewer = dynamic_cast<TBrowserViewer *>(WebBrowser);
  1168. if (DebugAlwaysTrue(BrowserViewer != NULL))
  1169. {
  1170. BrowserViewer->AddLinkHandler(Url, Handler);
  1171. }
  1172. }
  1173. //---------------------------------------------------------------------------
  1174. void __fastcall NavigateBrowserToUrl(TWebBrowserEx * WebBrowser, const UnicodeString & Url)
  1175. {
  1176. TBrowserViewer * BrowserViewer = dynamic_cast<TBrowserViewer *>(WebBrowser);
  1177. if (DebugAlwaysTrue(BrowserViewer != NULL))
  1178. {
  1179. BrowserViewer->NavigateToUrl(Url);
  1180. }
  1181. }
  1182. //---------------------------------------------------------------------------
  1183. void ReadyBrowserForStreaming(TWebBrowserEx * WebBrowser)
  1184. {
  1185. // This creates TWebBrowserEx::Document, which we need to stream in an in-memory document
  1186. NavigateBrowserToUrl(WebBrowser, L"about:blank");
  1187. // Needs to be followed by WaitBrowserToIdle
  1188. }
  1189. //---------------------------------------------------------------------------
  1190. void WaitBrowserToIdle(TWebBrowserEx * WebBrowser)
  1191. {
  1192. while (WebBrowser->ReadyState < ::READYSTATE_INTERACTIVE)
  1193. {
  1194. Application->ProcessMessages();
  1195. }
  1196. }
  1197. //---------------------------------------------------------------------------
  1198. void HideBrowserScrollbars(TWebBrowserEx * WebBrowser)
  1199. {
  1200. ICustomDoc * CustomDoc = NULL;
  1201. if (DebugAlwaysTrue(WebBrowser->Document != NULL) &&
  1202. SUCCEEDED(WebBrowser->Document->QueryInterface(&CustomDoc)) &&
  1203. DebugAlwaysTrue(CustomDoc != NULL))
  1204. {
  1205. TCustomDocHandler * Handler = new TCustomDocHandler(WebBrowser);
  1206. CustomDoc->SetUIHandler(Handler);
  1207. }
  1208. }
  1209. //---------------------------------------------------------------------------
  1210. UnicodeString GenerateAppHtmlPage(TFont * Font, TPanel * Parent, const UnicodeString & Body, bool Seamless)
  1211. {
  1212. UnicodeString Result =
  1213. L"<!DOCTYPE html>\n"
  1214. L"<meta charset=\"utf-8\">\n"
  1215. L"<html>\n"
  1216. L"<head>\n"
  1217. L"<style>\n"
  1218. L"\n"
  1219. L"body\n"
  1220. L"{\n"
  1221. L" font-family: '" + Font->Name + L"';\n"
  1222. L" margin: " + UnicodeString(Seamless ? L"0" : L"0.5em") + L";\n"
  1223. L" background-color: " + ColorToWebColorStr(Parent->Color) + L";\n" +
  1224. UnicodeString(Seamless ? L" overflow: hidden;\n" : L"") +
  1225. L"}\n"
  1226. L"\n"
  1227. L"body\n"
  1228. L"{\n"
  1229. L" font-size: " + IntToStr(Font->Size) + L"pt;\n"
  1230. L"}\n"
  1231. L"\n"
  1232. L"p\n"
  1233. L"{\n"
  1234. L" margin-top: 0;\n"
  1235. L" margin-bottom: 1em;\n"
  1236. L"}\n"
  1237. L"\n"
  1238. L"a, a:visited, a:hover, a:visited, a:current\n"
  1239. L"{\n"
  1240. L" color: " + ColorToWebColorStr(LinkColor) + L";\n"
  1241. L"}\n"
  1242. L"</style>\n"
  1243. L"</head>\n"
  1244. L"<body>\n" +
  1245. Body +
  1246. L"</body>\n"
  1247. L"</html>\n";
  1248. return Result;
  1249. }
  1250. //---------------------------------------------------------------------------
  1251. void LoadBrowserDocument(TWebBrowserEx * WebBrowser, const UnicodeString & Document)
  1252. {
  1253. std::unique_ptr<TMemoryStream> DocumentStream(new TMemoryStream());
  1254. UTF8String DocumentUTF8 = UTF8String(Document);
  1255. DocumentStream->Write(DocumentUTF8.c_str(), DocumentUTF8.Length());
  1256. DocumentStream->Seek(0, 0);
  1257. // For stream-loaded document, when set only after loading from OnDocumentComplete,
  1258. // browser stops working
  1259. SetBrowserDesignModeOff(WebBrowser);
  1260. TStreamAdapter * DocumentStreamAdapter = new TStreamAdapter(DocumentStream.get(), soReference);
  1261. IPersistStreamInit * PersistStreamInit = NULL;
  1262. if (DebugAlwaysTrue(WebBrowser->Document != NULL) &&
  1263. SUCCEEDED(WebBrowser->Document->QueryInterface(IID_IPersistStreamInit, (void **)&PersistStreamInit)) &&
  1264. DebugAlwaysTrue(PersistStreamInit != NULL))
  1265. {
  1266. PersistStreamInit->Load(static_cast<_di_IStream>(*DocumentStreamAdapter));
  1267. }
  1268. }
  1269. //---------------------------------------------------------------------------
  1270. TComponent * __fastcall FindComponentRecursively(TComponent * Root, const UnicodeString & Name)
  1271. {
  1272. for (int Index = 0; Index < Root->ComponentCount; Index++)
  1273. {
  1274. TComponent * Component = Root->Components[Index];
  1275. if (CompareText(Component->Name, Name) == 0)
  1276. {
  1277. return Component;
  1278. }
  1279. Component = FindComponentRecursively(Component, Name);
  1280. if (Component != NULL)
  1281. {
  1282. return Component;
  1283. }
  1284. }
  1285. return NULL;
  1286. }
  1287. //---------------------------------------------------------------------------
  1288. void __fastcall GetInstrutionsTheme(
  1289. TColor & MainInstructionColor, HFONT & MainInstructionFont, HFONT & InstructionFont)
  1290. {
  1291. MainInstructionColor = Graphics::clNone;
  1292. MainInstructionFont = 0;
  1293. InstructionFont = 0;
  1294. HTHEME Theme = OpenThemeData(0, L"TEXTSTYLE");
  1295. if (Theme != NULL)
  1296. {
  1297. LOGFONT AFont;
  1298. COLORREF AColor;
  1299. memset(&AFont, 0, sizeof(AFont));
  1300. // Using Canvas->Handle in the 2nd argument we can get scaled font,
  1301. // but at this point the form is sometime not scaled yet (difference is particularly for standalone messages like
  1302. // /UninstallCleanup), so the results are inconsistent.
  1303. if (GetThemeFont(Theme, NULL, TEXT_MAININSTRUCTION, 0, TMT_FONT, &AFont) == S_OK)
  1304. {
  1305. MainInstructionFont = CreateFontIndirect(&AFont);
  1306. }
  1307. if (GetThemeColor(Theme, TEXT_MAININSTRUCTION, 0, TMT_TEXTCOLOR, &AColor) == S_OK)
  1308. {
  1309. MainInstructionColor = (TColor)AColor;
  1310. }
  1311. memset(&AFont, 0, sizeof(AFont));
  1312. if (GetThemeFont(Theme, NULL, TEXT_INSTRUCTION, 0, TMT_FONT, &AFont) == S_OK)
  1313. {
  1314. InstructionFont = CreateFontIndirect(&AFont);
  1315. }
  1316. CloseThemeData(Theme);
  1317. }
  1318. }
  1319. //---------------------------------------------------------------------------
  1320. TLocalCustomCommand::TLocalCustomCommand()
  1321. {
  1322. }
  1323. //---------------------------------------------------------------------------
  1324. TLocalCustomCommand::TLocalCustomCommand(
  1325. const TCustomCommandData & Data, const UnicodeString & RemotePath, const UnicodeString & LocalPath) :
  1326. TFileCustomCommand(Data, RemotePath)
  1327. {
  1328. FLocalPath = LocalPath;
  1329. }
  1330. //---------------------------------------------------------------------------
  1331. TLocalCustomCommand::TLocalCustomCommand(const TCustomCommandData & Data,
  1332. const UnicodeString & RemotePath, const UnicodeString & LocalPath, const UnicodeString & FileName,
  1333. const UnicodeString & LocalFileName, const UnicodeString & FileList) :
  1334. TFileCustomCommand(Data, RemotePath, FileName, FileList)
  1335. {
  1336. FLocalPath = LocalPath;
  1337. FLocalFileName = LocalFileName;
  1338. }
  1339. //---------------------------------------------------------------------------
  1340. int __fastcall TLocalCustomCommand::PatternLen(const UnicodeString & Command, int Index)
  1341. {
  1342. int Len;
  1343. if ((Index < Command.Length()) && (Command[Index + 1] == L'\\'))
  1344. {
  1345. Len = 2;
  1346. }
  1347. else if ((Index < Command.Length()) && (Command[Index + 1] == L'^'))
  1348. {
  1349. Len = 3;
  1350. }
  1351. else
  1352. {
  1353. Len = TFileCustomCommand::PatternLen(Command, Index);
  1354. }
  1355. return Len;
  1356. }
  1357. //---------------------------------------------------------------------------
  1358. bool __fastcall TLocalCustomCommand::PatternReplacement(
  1359. int Index, const UnicodeString & Pattern, UnicodeString & Replacement, bool & Delimit)
  1360. {
  1361. bool Result;
  1362. if (Pattern == L"!\\")
  1363. {
  1364. // When used as "!\" in an argument to PowerShell, the trailing \ would escape the ",
  1365. // so we exclude it
  1366. Replacement = ExcludeTrailingBackslash(FLocalPath);
  1367. Result = true;
  1368. }
  1369. else if (Pattern == L"!^!")
  1370. {
  1371. Replacement = FLocalFileName;
  1372. Result = true;
  1373. }
  1374. else
  1375. {
  1376. Result = TFileCustomCommand::PatternReplacement(Index, Pattern, Replacement, Delimit);
  1377. }
  1378. return Result;
  1379. }
  1380. //---------------------------------------------------------------------------
  1381. void __fastcall TLocalCustomCommand::DelimitReplacement(
  1382. UnicodeString & /*Replacement*/, wchar_t /*Quote*/)
  1383. {
  1384. // never delimit local commands
  1385. }
  1386. //---------------------------------------------------------------------------
  1387. bool __fastcall TLocalCustomCommand::HasLocalFileName(const UnicodeString & Command)
  1388. {
  1389. return FindPattern(Command, L'^');
  1390. }
  1391. //---------------------------------------------------------------------------
  1392. bool __fastcall TLocalCustomCommand::IsFileCommand(const UnicodeString & Command)
  1393. {
  1394. return TFileCustomCommand::IsFileCommand(Command) || HasLocalFileName(Command);
  1395. }
  1396. //---------------------------------------------------------------------------
  1397. //---------------------------------------------------------------------------
  1398. typedef std::set<TDataModule *> TImagesModules;
  1399. static TImagesModules ImagesModules;
  1400. static std::map<int, TPngImageList *> AnimationsImages;
  1401. static std::map<int, TImageList *> ButtonImages;
  1402. static std::map<int, TPngImageList *> DialogImages;
  1403. //---------------------------------------------------------------------------
  1404. int __fastcall NormalizePixelsPerInch(int PixelsPerInch)
  1405. {
  1406. if (PixelsPerInch >= 192)
  1407. {
  1408. PixelsPerInch = 192;
  1409. }
  1410. else if (PixelsPerInch >= 144)
  1411. {
  1412. PixelsPerInch = 144;
  1413. }
  1414. else if (PixelsPerInch >= 120)
  1415. {
  1416. PixelsPerInch = 120;
  1417. }
  1418. else
  1419. {
  1420. PixelsPerInch = 96;
  1421. }
  1422. return PixelsPerInch;
  1423. }
  1424. //---------------------------------------------------------------------------
  1425. static int __fastcall NeedImagesModule(TControl * Control)
  1426. {
  1427. int PixelsPerInch = NormalizePixelsPerInch(GetControlPixelsPerInch(Control));
  1428. if (AnimationsImages.find(PixelsPerInch) == AnimationsImages.end())
  1429. {
  1430. TDataModule * ImagesModule;
  1431. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  1432. try
  1433. {
  1434. if (PixelsPerInch == 192)
  1435. {
  1436. ImagesModule = new TAnimations192Module(Application);
  1437. }
  1438. else if (PixelsPerInch == 144)
  1439. {
  1440. ImagesModule = new TAnimations144Module(Application);
  1441. }
  1442. else if (PixelsPerInch == 120)
  1443. {
  1444. ImagesModule = new TAnimations120Module(Application);
  1445. }
  1446. else
  1447. {
  1448. DebugAssert(PixelsPerInch == 96);
  1449. ImagesModule = new TAnimations96Module(Application);
  1450. }
  1451. ImagesModules.insert(ImagesModule);
  1452. TPngImageList * AAnimationImages =
  1453. DebugNotNull(dynamic_cast<TPngImageList *>(ImagesModule->FindComponent(L"AnimationImages")));
  1454. AnimationsImages.insert(std::make_pair(PixelsPerInch, AAnimationImages));
  1455. TImageList * AButtonImages =
  1456. DebugNotNull(dynamic_cast<TImageList *>(ImagesModule->FindComponent(L"ButtonImages")));
  1457. ButtonImages.insert(std::make_pair(PixelsPerInch, AButtonImages));
  1458. TPngImageList * ADialogImages =
  1459. DebugNotNull(dynamic_cast<TPngImageList *>(ImagesModule->FindComponent(L"DialogImages")));
  1460. DialogImages.insert(std::make_pair(PixelsPerInch, ADialogImages));
  1461. }
  1462. __finally
  1463. {
  1464. GUIConfiguration->ChangeResourceModule(ResourceModule);
  1465. }
  1466. }
  1467. return PixelsPerInch;
  1468. }
  1469. //---------------------------------------------------------------------------
  1470. TPngImageList * __fastcall GetAnimationsImages(TControl * Control)
  1471. {
  1472. int PixelsPerInch = NeedImagesModule(Control);
  1473. return DebugNotNull(AnimationsImages[PixelsPerInch]);
  1474. }
  1475. //---------------------------------------------------------------------------
  1476. TImageList * __fastcall GetButtonImages(TControl * Control)
  1477. {
  1478. int PixelsPerInch = NeedImagesModule(Control);
  1479. return DebugNotNull(ButtonImages[PixelsPerInch]);
  1480. }
  1481. //---------------------------------------------------------------------------
  1482. TPngImageList * __fastcall GetDialogImages(TControl * Control)
  1483. {
  1484. int PixelsPerInch = NeedImagesModule(Control);
  1485. return DebugNotNull(DialogImages[PixelsPerInch]);
  1486. }
  1487. //---------------------------------------------------------------------------
  1488. void __fastcall ReleaseImagesModules()
  1489. {
  1490. TImagesModules::iterator i = ImagesModules.begin();
  1491. while (i != ImagesModules.end())
  1492. {
  1493. delete (*i);
  1494. i++;
  1495. }
  1496. ImagesModules.clear();
  1497. }
  1498. //---------------------------------------------------------------------------
  1499. __fastcall TFrameAnimation::TFrameAnimation()
  1500. {
  1501. FFirstFrame = -1;
  1502. }
  1503. //---------------------------------------------------------------------------
  1504. void __fastcall TFrameAnimation::Init(TPaintBox * PaintBox, const UnicodeString & Name)
  1505. {
  1506. FName = Name;
  1507. FPaintBox = PaintBox;
  1508. FPaintBox->ControlStyle = FPaintBox->ControlStyle << csOpaque;
  1509. DebugAssert((FPaintBox->OnPaint == NULL) || (FPaintBox->OnPaint == PaintBoxPaint));
  1510. FPaintBox->OnPaint = PaintBoxPaint;
  1511. SetRescaleFunction(FPaintBox, PaintBoxRescale, reinterpret_cast<TObject *>(this));
  1512. DoInit();
  1513. }
  1514. //---------------------------------------------------------------------------
  1515. void __fastcall TFrameAnimation::DoInit()
  1516. {
  1517. FImageList = GetAnimationsImages(FPaintBox);
  1518. FFirstFrame = -1;
  1519. FFirstLoopFrame = -1;
  1520. FPaintBox->Width = FImageList->Width;
  1521. FPaintBox->Height = FImageList->Height;
  1522. if (!FName.IsEmpty())
  1523. {
  1524. int Frame = 0;
  1525. while (Frame < FImageList->PngImages->Count)
  1526. {
  1527. UnicodeString FrameData = FImageList->PngImages->Items[Frame]->Name;
  1528. UnicodeString FrameName;
  1529. FrameName = CutToChar(FrameData, L'_', false);
  1530. if (SameText(FName, FrameName))
  1531. {
  1532. int FrameIndex = StrToInt(CutToChar(FrameData, L'_', false));
  1533. if (FFirstFrame < 0)
  1534. {
  1535. FFirstFrame = Frame;
  1536. }
  1537. if ((FFirstLoopFrame < 0) && (FrameIndex > 0))
  1538. {
  1539. FFirstLoopFrame = Frame;
  1540. }
  1541. FLastFrame = Frame;
  1542. }
  1543. else
  1544. {
  1545. if (FFirstFrame >= 0)
  1546. {
  1547. // optimization
  1548. break;
  1549. }
  1550. }
  1551. Frame++;
  1552. }
  1553. DebugAssert(FFirstFrame >= 0);
  1554. DebugAssert(FFirstLoopFrame >= 0);
  1555. }
  1556. Stop();
  1557. }
  1558. //---------------------------------------------------------------------------
  1559. void __fastcall TFrameAnimation::PaintBoxRescale(TComponent * /*Sender*/, TObject * Token)
  1560. {
  1561. TFrameAnimation * FrameAnimation = reinterpret_cast<TFrameAnimation *>(Token);
  1562. FrameAnimation->Rescale();
  1563. }
  1564. //---------------------------------------------------------------------------
  1565. void __fastcall TFrameAnimation::Rescale()
  1566. {
  1567. bool Started = (FTimer != NULL) && FTimer->Enabled;
  1568. DoInit();
  1569. if (Started)
  1570. {
  1571. Start();
  1572. }
  1573. }
  1574. //---------------------------------------------------------------------------
  1575. void __fastcall TFrameAnimation::Start()
  1576. {
  1577. if (FFirstFrame >= 0)
  1578. {
  1579. FNextFrameTick = GetTickCount();
  1580. CalculateNextFrameTick();
  1581. if (FTimer == NULL)
  1582. {
  1583. FTimer = new TTimer(GetParentForm(FPaintBox));
  1584. FTimer->Interval = static_cast<int>(GUIUpdateInterval);
  1585. FTimer->OnTimer = Timer;
  1586. }
  1587. else
  1588. {
  1589. // reset timer
  1590. FTimer->Enabled = false;
  1591. FTimer->Enabled = true;
  1592. }
  1593. }
  1594. }
  1595. //---------------------------------------------------------------------------
  1596. void __fastcall TFrameAnimation::Timer(TObject * /*Sender*/)
  1597. {
  1598. Animate();
  1599. }
  1600. //---------------------------------------------------------------------------
  1601. void __fastcall TFrameAnimation::PaintBoxPaint(TObject * Sender)
  1602. {
  1603. if (FFirstFrame >= 0)
  1604. {
  1605. // Double-buffered drawing to prevent flicker (as the images are transparent)
  1606. DebugUsedParam(Sender);
  1607. DebugAssert(FPaintBox == Sender);
  1608. DebugAssert(FPaintBox->ControlStyle.Contains(csOpaque));
  1609. std::unique_ptr<TBitmap> Bitmap(new TBitmap());
  1610. Bitmap->SetSize(FPaintBox->Width, FPaintBox->Height);
  1611. Bitmap->Canvas->Brush->Color = FPaintBox->Color;
  1612. TRect Rect(0, 0, Bitmap->Width, Bitmap->Height);
  1613. Bitmap->Canvas->FillRect(Rect);
  1614. TGraphic * Graphic = GetCurrentImage()->PngImage;
  1615. DebugAssert(Graphic->Width == FPaintBox->Width);
  1616. DebugAssert(Graphic->Height == FPaintBox->Height);
  1617. Bitmap->Canvas->Draw(0, 0, Graphic);
  1618. FPaintBox->Canvas->Draw(0, 0, Bitmap.get());
  1619. }
  1620. FPainted = true;
  1621. }
  1622. //---------------------------------------------------------------------------
  1623. void __fastcall TFrameAnimation::Repaint()
  1624. {
  1625. FPainted = false;
  1626. // If the form is not showing yet, the Paint() is not even called
  1627. FPaintBox->Repaint();
  1628. if (!FPainted)
  1629. {
  1630. // Paint later, alternativelly we may keep trying Repaint() in Animate().
  1631. // See also a hack in TAuthenticateForm::Log.
  1632. FPaintBox->Invalidate();
  1633. }
  1634. }
  1635. //---------------------------------------------------------------------------
  1636. void __fastcall TFrameAnimation::Stop()
  1637. {
  1638. FNextFrameTick = std::numeric_limits<DWORD>::max();
  1639. FCurrentFrame = FFirstFrame;
  1640. Repaint();
  1641. if (FTimer != NULL)
  1642. {
  1643. FTimer->Enabled = false;
  1644. }
  1645. }
  1646. //---------------------------------------------------------------------------
  1647. void __fastcall TFrameAnimation::Animate()
  1648. {
  1649. if (FFirstFrame >= 0)
  1650. {
  1651. // UPGRADE: Use GetTickCount64() when we stop supporting Windows XP.
  1652. DWORD TickCount = GetTickCount();
  1653. // Keep in sync with an opposite condition at the end of the loop.
  1654. // We may skip some frames if we got stalled for a while
  1655. while (TickCount >= FNextFrameTick)
  1656. {
  1657. if (FCurrentFrame >= FLastFrame)
  1658. {
  1659. FCurrentFrame = FFirstLoopFrame;
  1660. }
  1661. else
  1662. {
  1663. FCurrentFrame++;
  1664. }
  1665. CalculateNextFrameTick();
  1666. Repaint();
  1667. }
  1668. }
  1669. }
  1670. //---------------------------------------------------------------------------
  1671. TPngImageCollectionItem * __fastcall TFrameAnimation::GetCurrentImage()
  1672. {
  1673. return FImageList->PngImages->Items[FCurrentFrame];
  1674. }
  1675. //---------------------------------------------------------------------------
  1676. void __fastcall TFrameAnimation::CalculateNextFrameTick()
  1677. {
  1678. TPngImageCollectionItem * ImageItem = GetCurrentImage();
  1679. UnicodeString Duration = ImageItem->Name;
  1680. CutToChar(Duration, L'_', false);
  1681. // skip index (is not really used)
  1682. CutToChar(Duration, L'_', false);
  1683. // This should overflow, when tick count wraps.
  1684. FNextFrameTick += StrToInt(Duration) * 10;
  1685. }
  1686. //---------------------------------------------------------------------------
  1687. //---------------------------------------------------------------------------
  1688. // Hints use:
  1689. // - Cleanup list tooltip (multi line)
  1690. // - Combo edit button
  1691. // - Transfer settings label (multi line, follows label size and font)
  1692. // - HintLabel (hint and persistent hint, multi line)
  1693. // - status bar hints
  1694. //---------------------------------------------------------------------------
  1695. __fastcall TScreenTipHintWindow::TScreenTipHintWindow(TComponent * Owner) :
  1696. THintWindow(Owner)
  1697. {
  1698. FParentPainting = false;
  1699. }
  1700. //---------------------------------------------------------------------------
  1701. int __fastcall TScreenTipHintWindow::GetTextFlags(TControl * Control)
  1702. {
  1703. return DT_LEFT | DT_WORDBREAK | DT_NOPREFIX | Control->DrawTextBiDiModeFlagsReadingOnly();
  1704. }
  1705. //---------------------------------------------------------------------------
  1706. bool __fastcall TScreenTipHintWindow::UseBoldShortHint(TControl * HintControl)
  1707. {
  1708. return
  1709. (dynamic_cast<TTBCustomDockableWindow *>(HintControl) != NULL) ||
  1710. (dynamic_cast<TTBPopupWindow *>(HintControl) != NULL) ||
  1711. (HintControl->Perform(WM_WANTS_SCREEN_TIPS, 0, 0) == 1);
  1712. }
  1713. //---------------------------------------------------------------------------
  1714. bool __fastcall TScreenTipHintWindow::IsPathLabel(TControl * HintControl)
  1715. {
  1716. return (dynamic_cast<TPathLabel *>(HintControl) != NULL);
  1717. }
  1718. //---------------------------------------------------------------------------
  1719. int __fastcall TScreenTipHintWindow::GetMargin(TControl * HintControl, const UnicodeString & Hint)
  1720. {
  1721. int Result;
  1722. if (HasLabelHintPopup(HintControl, Hint) || IsPathLabel(HintControl))
  1723. {
  1724. Result = 3;
  1725. }
  1726. else
  1727. {
  1728. Result = 6;
  1729. }
  1730. Result = ScaleByTextHeight(HintControl, Result);
  1731. return Result;
  1732. }
  1733. //---------------------------------------------------------------------------
  1734. TFont * __fastcall TScreenTipHintWindow::GetFont(TControl * HintControl, const UnicodeString & Hint)
  1735. {
  1736. TFont * Result;
  1737. if (HasLabelHintPopup(HintControl, Hint) || IsPathLabel(HintControl))
  1738. {
  1739. Result = reinterpret_cast<TLabel *>(dynamic_cast<TCustomLabel *>(HintControl))->Font;
  1740. }
  1741. else
  1742. {
  1743. FScaledHintFont.reset(new TFont());
  1744. FScaledHintFont->Assign(Screen->HintFont);
  1745. FScaledHintFont->Size = ScaleByPixelsPerInchFromSystem(FScaledHintFont->Size, HintControl);
  1746. Result = FScaledHintFont.get();
  1747. }
  1748. return Result;
  1749. }
  1750. //---------------------------------------------------------------------------
  1751. void __fastcall TScreenTipHintWindow::CalcHintTextRect(TControl * Control, TCanvas * Canvas, TRect & Rect, const UnicodeString & Hint)
  1752. {
  1753. const int Flags = DT_CALCRECT | GetTextFlags(Control);
  1754. DrawText(Canvas->Handle, Hint.c_str(), -1, &Rect, Flags);
  1755. }
  1756. //---------------------------------------------------------------------------
  1757. TRect __fastcall TScreenTipHintWindow::CalcHintRect(int MaxWidth, const UnicodeString AHint, void * AData)
  1758. {
  1759. TControl * HintControl = GetHintControl(AData);
  1760. int Margin = GetMargin(HintControl, AHint);
  1761. UnicodeString ShortHint;
  1762. UnicodeString LongHint;
  1763. SplitHint(HintControl, AHint, ShortHint, LongHint);
  1764. Canvas->Font->Assign(GetFont(HintControl, AHint));
  1765. const int ScreenTipTextOnlyWidth = ScaleByTextHeight(HintControl, cScreenTipTextOnlyWidth);
  1766. int LongHintMargin = 0; // shut up
  1767. bool HasLongHint = !LongHint.IsEmpty();
  1768. if (HasLongHint)
  1769. {
  1770. // double-margin on the right
  1771. LongHintMargin = (3 * Margin);
  1772. MaxWidth = ScreenTipTextOnlyWidth - LongHintMargin;
  1773. }
  1774. // Multi line short hints can be twice as wide, to not break the individual lines unless really necessary.
  1775. // (login site tree, clean up dialog list, preferences custom command list, persistent hint, etc).
  1776. // And they also can be twice as wide, to not break the individual lines unless really necessary.
  1777. if (ShortHint.Pos(L"\n") > 0)
  1778. {
  1779. MaxWidth *= 2;
  1780. }
  1781. bool HintPopup = HasLabelHintPopup(HintControl, AHint);
  1782. if (HintPopup)
  1783. {
  1784. MaxWidth = HintControl->Width;
  1785. }
  1786. if (UseBoldShortHint(HintControl))
  1787. {
  1788. Canvas->Font->Style = TFontStyles() << fsBold;
  1789. }
  1790. TRect ShortRect(0, 0, MaxWidth, 0);
  1791. CalcHintTextRect(this, Canvas, ShortRect, ShortHint);
  1792. Canvas->Font->Style = TFontStyles();
  1793. TRect Result;
  1794. if (!HasLongHint)
  1795. {
  1796. Result = ShortRect;
  1797. if (HintPopup)
  1798. {
  1799. Result.Right = MaxWidth + 2 * Margin;
  1800. }
  1801. else
  1802. {
  1803. Result.Right += 3 * Margin;
  1804. }
  1805. Result.Bottom += 2 * Margin;
  1806. }
  1807. else
  1808. {
  1809. const int LongIndentation = Margin * 3 / 2;
  1810. TRect LongRect(0, 0, MaxWidth - LongIndentation, 0);
  1811. CalcHintTextRect(this, Canvas, LongRect, LongHint);
  1812. Result.Right = Max(ScreenTipTextOnlyWidth, LongRect.Right + LongIndentation + LongHintMargin);
  1813. Result.Bottom = Margin + ShortRect.Height() + (Margin / 3 * 5) + LongRect.Height() + Margin;
  1814. }
  1815. // VCLCOPY: To counter the increase in THintWindow::ActivateHintData
  1816. Result.Bottom -= 4;
  1817. return Result;
  1818. }
  1819. //---------------------------------------------------------------------------
  1820. void __fastcall TScreenTipHintWindow::SplitHint(
  1821. TControl * HintControl, const UnicodeString & Hint, UnicodeString & ShortHint, UnicodeString & LongHint)
  1822. {
  1823. if (HasLabelHintPopup(HintControl, Hint))
  1824. {
  1825. ShortHint = HintControl->Hint;
  1826. }
  1827. else
  1828. {
  1829. ShortHint = GetShortHint(Hint);
  1830. LongHint = GetLongHintIfAny(Hint);
  1831. }
  1832. }
  1833. //---------------------------------------------------------------------------
  1834. void __fastcall TScreenTipHintWindow::ActivateHintData(const TRect & ARect, const UnicodeString AHint, void * AData)
  1835. {
  1836. FHintControl = GetHintControl(AData);
  1837. SplitHint(FHintControl, AHint, FShortHint, FLongHint);
  1838. FMargin = GetMargin(FHintControl, AHint);
  1839. FHintPopup = HasLabelHintPopup(FHintControl, AHint);
  1840. Canvas->Font->Assign(GetFont(FHintControl, AHint));
  1841. TRect Rect = ARect;
  1842. if (FHintPopup)
  1843. {
  1844. Rect.SetLocation(FHintControl->ClientToScreen(TPoint(-FMargin, -FMargin)));
  1845. }
  1846. if (IsPathLabel(FHintControl))
  1847. {
  1848. Rect.Offset(-FMargin, -FMargin);
  1849. }
  1850. THintWindow::ActivateHintData(Rect, FShortHint, AData);
  1851. }
  1852. //---------------------------------------------------------------------------
  1853. TControl * __fastcall TScreenTipHintWindow::GetHintControl(void * Data)
  1854. {
  1855. return reinterpret_cast<TControl *>(DebugNotNull(Data));
  1856. }
  1857. //---------------------------------------------------------------------------
  1858. UnicodeString __fastcall TScreenTipHintWindow::GetLongHintIfAny(const UnicodeString & AHint)
  1859. {
  1860. UnicodeString Result;
  1861. int P = Pos(L"|", AHint);
  1862. if (P > 0)
  1863. {
  1864. Result = GetLongHint(AHint);
  1865. }
  1866. return Result;
  1867. }
  1868. //---------------------------------------------------------------------------
  1869. void __fastcall TScreenTipHintWindow::Dispatch(void * AMessage)
  1870. {
  1871. TMessage * Message = static_cast<TMessage*>(AMessage);
  1872. switch (Message->Msg)
  1873. {
  1874. case WM_GETTEXTLENGTH:
  1875. if (FParentPainting)
  1876. {
  1877. // make THintWindow::Paint() not paint the Caption
  1878. Message->Result = 0;
  1879. }
  1880. else
  1881. {
  1882. THintWindow::Dispatch(AMessage);
  1883. }
  1884. break;
  1885. default:
  1886. THintWindow::Dispatch(AMessage);
  1887. break;
  1888. }
  1889. }
  1890. //---------------------------------------------------------------------------
  1891. void __fastcall TScreenTipHintWindow::Paint()
  1892. {
  1893. // paint frame/background
  1894. {
  1895. TAutoFlag ParentPaintingFlag(FParentPainting);
  1896. THintWindow::Paint();
  1897. }
  1898. const int Flags = GetTextFlags(this);
  1899. const int Margin = FMargin - 1; // 1 = border
  1900. TRect Rect = ClientRect;
  1901. Rect.Inflate(-Margin, -Margin);
  1902. if (!FHintPopup)
  1903. {
  1904. Rect.Right -= FMargin;
  1905. }
  1906. if (UseBoldShortHint(FHintControl))
  1907. {
  1908. Canvas->Font->Style = TFontStyles() << fsBold;
  1909. }
  1910. DrawText(Canvas->Handle, FShortHint.c_str(), -1, &Rect, Flags);
  1911. TRect ShortRect = Rect;
  1912. DrawText(Canvas->Handle, FShortHint.c_str(), -1, &ShortRect, DT_CALCRECT | Flags);
  1913. Canvas->Font->Style = TFontStyles();
  1914. if (!FLongHint.IsEmpty())
  1915. {
  1916. Rect.Left += FMargin * 3 / 2;
  1917. Rect.Top += ShortRect.Height() + (FMargin / 3 * 5);
  1918. DrawText(Canvas->Handle, FLongHint.c_str(), -1, &Rect, Flags);
  1919. }
  1920. }
  1921. //---------------------------------------------------------------------------
  1922. //---------------------------------------------------------------------------
  1923. __fastcall TNewRichEdit::TNewRichEdit(TComponent * AOwner) :
  1924. TRichEdit(AOwner),
  1925. FLibrary(0)
  1926. {
  1927. }
  1928. //---------------------------------------------------------------------------
  1929. void __fastcall TNewRichEdit::CreateParams(TCreateParams & Params)
  1930. {
  1931. UnicodeString RichEditModuleName(L"MSFTEDIT.DLL");
  1932. long int OldError;
  1933. OldError = SetErrorMode(SEM_NOOPENFILEERRORBOX);
  1934. FLibrary = LoadLibrary(RichEditModuleName.c_str());
  1935. SetErrorMode(OldError);
  1936. // No fallback, MSFTEDIT.DLL is available since Windows XP
  1937. // https://docs.microsoft.com/en-us/archive/blogs/murrays/richedit-versions
  1938. if (FLibrary == 0)
  1939. {
  1940. throw Exception(FORMAT(L"Cannot load %s", (RichEditModuleName)));
  1941. }
  1942. TCustomMemo::CreateParams(Params);
  1943. // MSDN says that we should use MSFTEDIT_CLASS to load Rich Edit 4.1:
  1944. // https://docs.microsoft.com/en-us/windows/win32/controls/about-rich-edit-controls
  1945. // But MSFTEDIT_CLASS is defined as "RICHEDIT50W",
  1946. // so not sure what version we are loading.
  1947. // Seem to work on Windows XP SP3.
  1948. CreateSubClass(Params, MSFTEDIT_CLASS);
  1949. }
  1950. //---------------------------------------------------------------------------
  1951. void __fastcall TNewRichEdit::CreateWnd()
  1952. {
  1953. TRichEdit::CreateWnd();
  1954. SendMessage(Handle, EM_SETEDITSTYLEEX, 0, SES_EX_HANDLEFRIENDLYURL);
  1955. }
  1956. //---------------------------------------------------------------------------
  1957. void __fastcall TNewRichEdit::DestroyWnd()
  1958. {
  1959. TRichEdit::DestroyWnd();
  1960. if (FLibrary != 0)
  1961. {
  1962. FreeLibrary(FLibrary);
  1963. }
  1964. }
  1965. //---------------------------------------------------------------------------
  1966. static int HideAccelFlag(TControl * Control)
  1967. {
  1968. //ask the top level window about its UI state
  1969. while (Control->Parent != NULL)
  1970. {
  1971. Control = Control->Parent;
  1972. }
  1973. int Result;
  1974. if (FLAGSET(Control->Perform(WM_QUERYUISTATE, 0, 0), UISF_HIDEACCEL))
  1975. {
  1976. Result = DT_HIDEPREFIX;
  1977. }
  1978. else
  1979. {
  1980. Result = 0;
  1981. }
  1982. return Result;
  1983. }
  1984. //---------------------------------------------------------------------------
  1985. void __fastcall TUIStateAwareLabel::DoDrawText(TRect & Rect, int Flags)
  1986. {
  1987. if (ShowAccelChar)
  1988. {
  1989. Flags = Flags | HideAccelFlag(this);
  1990. }
  1991. TLabel::DoDrawText(Rect, Flags);
  1992. }
  1993. //---------------------------------------------------------------------------
  1994. void __fastcall FindComponentClass(
  1995. void *, TReader *, const UnicodeString DebugUsedArg(ClassName), TComponentClass & ComponentClass)
  1996. {
  1997. if (ComponentClass == __classid(TLabel))
  1998. {
  1999. ComponentClass = __classid(TUIStateAwareLabel);
  2000. }
  2001. else if (ComponentClass == __classid(TComboBox))
  2002. {
  2003. ComponentClass = __classid(TUIStateAwareComboBox);
  2004. }
  2005. }
  2006. //---------------------------------------------------------------------------
  2007. bool CanShowTimeEstimate(TDateTime StartTime)
  2008. {
  2009. return (SecondsBetween(StartTime, Now()) >= 3);
  2010. }