GUITools.cpp 76 KB

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