GUITools.cpp 69 KB

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