GUITools.cpp 69 KB

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