GUITools.cpp 78 KB

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