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