GUITools.cpp 85 KB

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