GUITools.cpp 72 KB

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