GUITools.cpp 69 KB

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