GUITools.cpp 68 KB

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