1
0

GUITools.cpp 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582
  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 <HistoryComboBox.hpp>
  25. #include <vssym32.h>
  26. #include <DateUtils.hpp>
  27. #include <IOUtils.hpp>
  28. #include <Queue.h>
  29. #include "Animations96.h"
  30. #include "Animations120.h"
  31. #include "Animations144.h"
  32. #include "Animations192.h"
  33. //---------------------------------------------------------------------------
  34. #pragma package(smart_init)
  35. //---------------------------------------------------------------------------
  36. extern const UnicodeString PageantTool = L"pageant.exe";
  37. extern const UnicodeString PuttygenTool = L"puttygen.exe";
  38. //---------------------------------------------------------------------------
  39. bool __fastcall FindFile(UnicodeString & Path)
  40. {
  41. bool Result = FileExistsFix(Path);
  42. if (!Result)
  43. {
  44. UnicodeString ProgramFiles32 = IncludeTrailingBackslash(GetEnvironmentVariable(L"ProgramFiles"));
  45. UnicodeString ProgramFiles64 = IncludeTrailingBackslash(GetEnvironmentVariable(L"ProgramW6432"));
  46. if (!ProgramFiles32.IsEmpty() &&
  47. SameText(Path.SubString(1, ProgramFiles32.Length()), ProgramFiles32) &&
  48. !ProgramFiles64.IsEmpty())
  49. {
  50. UnicodeString Path64 =
  51. ProgramFiles64 + Path.SubString(ProgramFiles32.Length() + 1, Path.Length() - ProgramFiles32.Length());
  52. if (FileExists(ApiPath(Path64)))
  53. {
  54. Path = Path64;
  55. Result = true;
  56. }
  57. }
  58. }
  59. if (!Result && SameText(ExtractFileName(Path), Path))
  60. {
  61. UnicodeString Paths = GetEnvironmentVariable(L"PATH");
  62. if (!Paths.IsEmpty())
  63. {
  64. UnicodeString NewPath = FileSearch(Path, Paths);
  65. Result = !NewPath.IsEmpty();
  66. if (Result)
  67. {
  68. Path = NewPath;
  69. }
  70. else
  71. {
  72. // Basically the same what FileSearch does, except for FileExistsFix.
  73. // Once this proves working, we can ged rid of the FileSearch call.
  74. while (!Result && !Paths.IsEmpty())
  75. {
  76. UnicodeString P = CutToChar(Paths, L';', false);
  77. // Not using CombinePaths as it throws on an invalid path and PATH is not under our control
  78. NewPath = IncludeTrailingBackslash(P) + Path;
  79. Result = FileExistsFix(NewPath);
  80. if (Result)
  81. {
  82. Path = NewPath;
  83. }
  84. }
  85. }
  86. }
  87. }
  88. return Result;
  89. }
  90. //---------------------------------------------------------------------------
  91. bool DoesSessionExistInPutty(const UnicodeString & StorageKey)
  92. {
  93. std::unique_ptr<TRegistryStorage> Storage(new TRegistryStorage(Configuration->PuttySessionsKey));
  94. Storage->ConfigureForPutty();
  95. return Storage->OpenRootKey(true) && Storage->KeyExists(StorageKey);
  96. }
  97. //---------------------------------------------------------------------------
  98. bool __fastcall ExportSessionToPutty(TSessionData * SessionData, bool ReuseExisting, const UnicodeString & SessionName)
  99. {
  100. bool Result = true;
  101. std::unique_ptr<TRegistryStorage> Storage(new TRegistryStorage(Configuration->PuttySessionsKey));
  102. Storage->AccessMode = smReadWrite;
  103. Storage->ConfigureForPutty();
  104. if (Storage->OpenRootKey(true))
  105. {
  106. Result = ReuseExisting && Storage->KeyExists(SessionData->StorageKey);
  107. if (Result)
  108. {
  109. AppLogFmt(L"Reusing existing PuTTY session: %s", (SessionData->StorageKey));
  110. }
  111. else
  112. {
  113. std::unique_ptr<TRegistryStorage> SourceStorage(new TRegistryStorage(Configuration->PuttySessionsKey));
  114. SourceStorage->ConfigureForPutty();
  115. if (SourceStorage->OpenSubKey(StoredSessions->DefaultSettings->Name, false) &&
  116. Storage->OpenSubKey(SessionName, true))
  117. {
  118. Storage->Copy(SourceStorage.get());
  119. Storage->CloseSubKey();
  120. }
  121. std::unique_ptr<TSessionData> ExportData(new TSessionData(L""));
  122. ExportData->Assign(SessionData);
  123. ExportData->Modified = true;
  124. ExportData->Name = SessionName;
  125. ExportData->WinTitle = SessionData->SessionName;
  126. ExportData->Password = L"";
  127. if (SessionData->FSProtocol == fsFTP)
  128. {
  129. if (GUIConfiguration->TelnetForFtpInPutty)
  130. {
  131. ExportData->PuttyProtocol = PuttyTelnetProtocol;
  132. ExportData->PortNumber = TelnetPortNumber;
  133. }
  134. else
  135. {
  136. ExportData->PuttyProtocol = PuttySshProtocol;
  137. ExportData->PortNumber = SshPortNumber;
  138. }
  139. }
  140. ExportData->Save(Storage.get(), true);
  141. AppLogFmt(L"Exported site settings to PuTTY session: %s", (SessionName));
  142. }
  143. }
  144. return Result;
  145. }
  146. //---------------------------------------------------------------------------
  147. class TPuttyCleanupThread : public TSimpleThread
  148. {
  149. public:
  150. static void Schedule();
  151. static void Finalize();
  152. protected:
  153. virtual void __fastcall Execute();
  154. virtual void __fastcall Terminate();
  155. bool __fastcall Finished();
  156. void DoSchedule();
  157. private:
  158. TDateTime FTimer;
  159. static TPuttyCleanupThread * FInstance;
  160. static std::unique_ptr<TCriticalSection> FSection;
  161. };
  162. //---------------------------------------------------------------------------
  163. std::unique_ptr<TCriticalSection> TPuttyCleanupThread::FSection(TraceInitPtr(new TCriticalSection()));
  164. TPuttyCleanupThread * TPuttyCleanupThread::FInstance;
  165. //---------------------------------------------------------------------------
  166. void TPuttyCleanupThread::Schedule()
  167. {
  168. TGuard Guard(FSection.get());
  169. if (FInstance == NULL)
  170. {
  171. FInstance = new TPuttyCleanupThread();
  172. FInstance->DoSchedule();
  173. FInstance->Start();
  174. }
  175. else
  176. {
  177. FInstance->DoSchedule();
  178. }
  179. }
  180. //---------------------------------------------------------------------------
  181. void TPuttyCleanupThread::Finalize()
  182. {
  183. while (true)
  184. {
  185. {
  186. TGuard Guard(FSection.get());
  187. if (FInstance == NULL)
  188. {
  189. return;
  190. }
  191. }
  192. Sleep(100);
  193. }
  194. }
  195. //---------------------------------------------------------------------------
  196. void __fastcall TPuttyCleanupThread::Execute()
  197. {
  198. try
  199. {
  200. std::unique_ptr<TStrings> Sessions(new TStringList());
  201. bool Continue = true;
  202. do
  203. {
  204. {
  205. TGuard Guard(FSection.get());
  206. std::unique_ptr<TRegistryStorage> Storage(new TRegistryStorage(Configuration->PuttySessionsKey));
  207. Storage->AccessMode = smReadWrite;
  208. Storage->ConfigureForPutty();
  209. std::unique_ptr<TStringList> Sessions2(new TStringList());
  210. if (Storage->OpenRootKey(true))
  211. {
  212. std::unique_ptr<TStrings> SubKeys(new TStringList());
  213. Storage->GetSubKeyNames(SubKeys.get());
  214. for (int Index = 0; Index < SubKeys->Count; Index++)
  215. {
  216. UnicodeString SessionName = SubKeys->Strings[Index];
  217. if (StartsStr(GUIConfiguration->PuttySession, SessionName))
  218. {
  219. Sessions2->Add(SessionName);
  220. }
  221. }
  222. Sessions2->Sort();
  223. if (!Sessions->Equals(Sessions2.get()))
  224. {
  225. // Just in case new sessions from another WinSCP instance are added, delay the cleanup
  226. // (to avoid having to implement some inter-process communication).
  227. // Both instances will attempt to do the cleanup, but that not a problem
  228. Sessions->Assign(Sessions2.get());
  229. DoSchedule();
  230. }
  231. }
  232. if (FTimer < Now())
  233. {
  234. for (int Index = 0; Index < Sessions->Count; Index++)
  235. {
  236. UnicodeString SessionName = Sessions->Strings[Index];
  237. Storage->RecursiveDeleteSubKey(SessionName);
  238. }
  239. Continue = false;
  240. }
  241. }
  242. if (Continue)
  243. {
  244. Sleep(1000);
  245. }
  246. }
  247. while (Continue);
  248. }
  249. __finally
  250. {
  251. TGuard Guard(FSection.get());
  252. FInstance = NULL;
  253. }
  254. }
  255. //---------------------------------------------------------------------------
  256. void __fastcall TPuttyCleanupThread::Terminate()
  257. {
  258. DebugFail();
  259. }
  260. //---------------------------------------------------------------------------
  261. bool __fastcall TPuttyCleanupThread::Finished()
  262. {
  263. // self-destroy
  264. return TSimpleThread::Finished() || true;
  265. }
  266. //---------------------------------------------------------------------------
  267. void TPuttyCleanupThread::DoSchedule()
  268. {
  269. FTimer = IncSecond(Now(), 10);
  270. }
  271. //---------------------------------------------------------------------------
  272. class TPuttyPasswordThread : public TSimpleThread
  273. {
  274. public:
  275. TPuttyPasswordThread(const UnicodeString & Password, const UnicodeString & PipeName);
  276. virtual __fastcall ~TPuttyPasswordThread();
  277. protected:
  278. virtual void __fastcall Execute();
  279. virtual void __fastcall Terminate();
  280. virtual bool __fastcall Finished();
  281. private:
  282. HANDLE FPipe;
  283. AnsiString FPassword;
  284. void DoSleep(int & Timeout);
  285. };
  286. //---------------------------------------------------------------------------
  287. TPuttyPasswordThread::TPuttyPasswordThread(const UnicodeString & Password, const UnicodeString & PipeName)
  288. {
  289. DWORD OpenMode = PIPE_ACCESS_OUTBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE;
  290. DWORD PipeMode = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_NOWAIT | PIPE_REJECT_REMOTE_CLIENTS;
  291. DWORD BufferSize = 16 * 1024;
  292. FPipe = CreateNamedPipe(PipeName.c_str(), OpenMode, PipeMode, 1, BufferSize, BufferSize, NMPWAIT_USE_DEFAULT_WAIT, NULL);
  293. if (FPipe == INVALID_HANDLE_VALUE)
  294. {
  295. throw EOSExtException(L"Cannot create password pipe");
  296. }
  297. FPassword = AnsiString(Password);
  298. Start();
  299. }
  300. //---------------------------------------------------------------------------
  301. __fastcall TPuttyPasswordThread::~TPuttyPasswordThread()
  302. {
  303. DebugAlwaysTrue(FFinished);
  304. AppLog(L"Disconnecting and closing password pipe");
  305. DisconnectNamedPipe(FPipe);
  306. CloseHandle(FPipe);
  307. }
  308. //---------------------------------------------------------------------------
  309. void __fastcall TPuttyPasswordThread::Terminate()
  310. {
  311. // noop - the thread always self-terminates
  312. }
  313. //---------------------------------------------------------------------------
  314. bool __fastcall TPuttyPasswordThread::Finished()
  315. {
  316. return true;
  317. }
  318. //---------------------------------------------------------------------------
  319. void TPuttyPasswordThread::DoSleep(int & Timeout)
  320. {
  321. unsigned int Step = 50;
  322. Sleep(Step);
  323. Timeout -= Step;
  324. if (Timeout <= 0)
  325. {
  326. AppLog(L"Timeout waiting for PuTTY");
  327. }
  328. }
  329. //---------------------------------------------------------------------------
  330. void __fastcall TPuttyPasswordThread::Execute()
  331. {
  332. AppLog(L"Waiting for PuTTY to connect to password pipe");
  333. int Timeout = MSecsPerSec * SecsPerMin;
  334. while (Timeout > 0)
  335. {
  336. if (ConnectNamedPipe(FPipe, NULL))
  337. {
  338. AppLog(L"Password pipe is ready");
  339. }
  340. else
  341. {
  342. int Error = GetLastError();
  343. if (Error == ERROR_PIPE_CONNECTED)
  344. {
  345. AppLog(L"PuTTY has connected to password pipe");
  346. int Pos = 0;
  347. while ((Timeout > 0) && (Pos < FPassword.Length()))
  348. {
  349. DWORD Written = 0;
  350. if (!WriteFile(FPipe, FPassword.c_str() + Pos, FPassword.Length() - Pos, &Written, NULL))
  351. {
  352. AppLog(L"Error writting password pipe");
  353. Timeout = 0;
  354. }
  355. else
  356. {
  357. Pos += Written;
  358. if (Pos >= FPassword.Length())
  359. {
  360. FlushFileBuffers(FPipe);
  361. AppLog(L"Complete password was written to pipe");
  362. Timeout = 0;
  363. }
  364. else
  365. {
  366. AppLog(L"Part of password was written to pipe");
  367. DoSleep(Timeout);
  368. }
  369. }
  370. }
  371. }
  372. else if (Error == ERROR_PIPE_LISTENING)
  373. {
  374. DoSleep(Timeout);
  375. }
  376. else
  377. {
  378. AppLogFmt(L"Password pipe error %d", (Error));
  379. Timeout = 0;
  380. }
  381. }
  382. }
  383. }
  384. //---------------------------------------------------------------------------
  385. void SplitPuttyCommand(UnicodeString & Program, UnicodeString & Params)
  386. {
  387. // See also TSiteAdvancedDialog::PuttySettingsButtonClick
  388. UnicodeString Dir;
  389. SplitCommand(GUIConfiguration->PuttyPath, Program, Params, Dir);
  390. Program = ExpandEnvironmentVariables(Program);
  391. Params = ExpandEnvironmentVariables(Params);
  392. }
  393. //---------------------------------------------------------------------------
  394. UnicodeString FindPuttyPath()
  395. {
  396. UnicodeString Program, Params;
  397. SplitPuttyCommand(Program, Params);
  398. if (!FindFile(Program))
  399. {
  400. throw Exception(FMTLOAD(EXECUTE_APP_ERROR, (Program)));
  401. }
  402. return Program;
  403. }
  404. //---------------------------------------------------------------------------
  405. unsigned int PipeCounter = 0;
  406. //---------------------------------------------------------------------------
  407. void OpenSessionInPutty(TSessionData * SessionData)
  408. {
  409. // putty does not support resolving environment variables in session settings
  410. SessionData->ExpandEnvironmentVariables();
  411. UnicodeString Program, AParams;
  412. SplitPuttyCommand(Program, AParams);
  413. AppLogFmt(L"PuTTY program: %s", (Program));
  414. AppLogFmt(L"Params: %s", (AParams));
  415. if (FindFile(Program))
  416. {
  417. UnicodeString Password;
  418. if (GUIConfiguration->PuttyPassword)
  419. {
  420. // Passphrase has precendence, as it's more likely entered by user during authentication, hence more likely really needed.
  421. if (!SessionData->Passphrase.IsEmpty())
  422. {
  423. Password = SessionData->Passphrase;
  424. }
  425. else if (!SessionData->Password.IsEmpty())
  426. {
  427. Password = SessionData->Password;
  428. }
  429. }
  430. TCustomCommandData Data(SessionData, SessionData->UserName, Password);
  431. TLocalCustomCommand LocalCustomCommand(Data, SessionData->RemoteDirectory, SessionData->LocalDirectory);
  432. TWinInteractiveCustomCommand InteractiveCustomCommand(
  433. &LocalCustomCommand, L"PuTTY", UnicodeString());
  434. UnicodeString Params =
  435. LocalCustomCommand.Complete(InteractiveCustomCommand.Complete(AParams, false), true);
  436. UnicodeString PuttyParams;
  437. AppLogFmt(L"Expanded params: %s", (Params));
  438. if (!LocalCustomCommand.IsSiteCommand(AParams))
  439. {
  440. {
  441. bool SessionList = false;
  442. std::unique_ptr<THierarchicalStorage> SourceHostKeyStorage(Configuration->CreateScpStorage(SessionList));
  443. std::unique_ptr<THierarchicalStorage> TargetHostKeyStorage(new TRegistryStorage(Configuration->PuttyRegistryStorageKey));
  444. TargetHostKeyStorage->Explicit = true;
  445. TargetHostKeyStorage->AccessMode = smReadWrite;
  446. std::unique_ptr<TStoredSessionList> HostKeySessionList(new TStoredSessionList());
  447. HostKeySessionList->OwnsObjects = false;
  448. HostKeySessionList->Add(SessionData);
  449. int Imported = TStoredSessionList::ImportHostKeys(SourceHostKeyStorage.get(), TargetHostKeyStorage.get(), HostKeySessionList.get(), false);
  450. AppLogFmt(L"Imported host keys: %d", (Imported));
  451. }
  452. if (IsUWP())
  453. {
  454. bool Telnet = (SessionData->FSProtocol == fsFTP) && GUIConfiguration->TelnetForFtpInPutty;
  455. if (Telnet)
  456. {
  457. AddToList(PuttyParams, L"-telnet", L" ");
  458. // PuTTY does not allow -pw for telnet
  459. Password = L"";
  460. }
  461. AddToList(PuttyParams, EscapePuttyCommandParam(SessionData->HostName), L" ");
  462. if (!SessionData->UserName.IsEmpty())
  463. {
  464. AddToList(PuttyParams, FORMAT(L"-l %s", (EscapePuttyCommandParam(SessionData->UserName))), L" ");
  465. }
  466. if ((SessionData->FSProtocol != fsFTP) && (SessionData->PortNumber != SshPortNumber))
  467. {
  468. AddToList(PuttyParams, FORMAT(L"-P %d", (SessionData->PortNumber)), L" ");
  469. }
  470. if (!Telnet)
  471. {
  472. UnicodeString PublicKeyFile = SessionData->ResolvePublicKeyFile();
  473. if (!PublicKeyFile.IsEmpty())
  474. {
  475. AddToList(PuttyParams, FORMAT(L"-i \"%s\"", (PublicKeyFile)), L" ");
  476. }
  477. AddToList(PuttyParams, (SessionData->TryAgent ? L"-agent" : L"-noagent"), L" ");
  478. if (SessionData->TryAgent)
  479. {
  480. AddToList(PuttyParams, (SessionData->AgentFwd ? L"-A" : L"-a"), L" ");
  481. }
  482. if (SessionData->Compression)
  483. {
  484. AddToList(PuttyParams, L"-C", L" ");
  485. }
  486. AddToList(PuttyParams, L"-2", L" ");
  487. if (!SessionData->LogicalHostName.IsEmpty())
  488. {
  489. AddToList(PuttyParams, FORMAT(L"-loghost \"%s\"", (SessionData->LogicalHostName)), L" ");
  490. }
  491. }
  492. if (SessionData->AddressFamily == afIPv4)
  493. {
  494. AddToList(PuttyParams, L"-4", L" ");
  495. }
  496. else if (SessionData->AddressFamily == afIPv6)
  497. {
  498. AddToList(PuttyParams, L"-6", L" ");
  499. }
  500. AppLogFmt(L"Using command-line instead of stored session in UWP: %s", (PuttyParams));
  501. }
  502. else
  503. {
  504. UnicodeString SessionName;
  505. UnicodeString PuttySession = GUIConfiguration->PuttySession;
  506. int Uniq = 1;
  507. while (DoesSessionExistInPutty(PuttySession))
  508. {
  509. Uniq++;
  510. PuttySession = FORMAT(L"%s (%d)", (GUIConfiguration->PuttySession, Uniq));
  511. }
  512. if (ExportSessionToPutty(SessionData, true, PuttySession))
  513. {
  514. SessionName = SessionData->SessionName;
  515. }
  516. else
  517. {
  518. SessionName = PuttySession;
  519. TPuttyCleanupThread::Schedule();
  520. if ((SessionData->FSProtocol == fsFTP) &&
  521. GUIConfiguration->TelnetForFtpInPutty)
  522. {
  523. // PuTTY does not allow -pw for telnet
  524. Password = L"";
  525. }
  526. }
  527. UnicodeString LoadSwitch = L"-load";
  528. int P = Params.LowerCase().Pos(LoadSwitch + L" ");
  529. if ((P == 0) || ((P > 1) && (Params[P - 1] != L' ')))
  530. {
  531. AddToList(PuttyParams, FORMAT(L"%s %s", (LoadSwitch, EscapePuttyCommandParam(SessionName))), L" ");
  532. }
  533. }
  534. }
  535. if (!Password.IsEmpty() && !LocalCustomCommand.IsPasswordCommand(AParams))
  536. {
  537. Password = NormalizeString(Password); // if password is empty, we should quote it always
  538. bool UsePuttyPwFile;
  539. if (GUIConfiguration->UsePuttyPwFile == asAuto)
  540. {
  541. UsePuttyPwFile = false;
  542. if (SameText(ExtractFileName(Program), OriginalPuttyExecutable))
  543. {
  544. unsigned int Version = GetFileVersion(Program);
  545. if (Version != static_cast<unsigned int>(-1))
  546. {
  547. int MajorVersion = HIWORD(Version);
  548. int MinorVersion = LOWORD(Version);
  549. if (CalculateCompoundVersion(MajorVersion, MinorVersion) >= CalculateCompoundVersion(0, 77))
  550. {
  551. UsePuttyPwFile = true;
  552. }
  553. }
  554. }
  555. }
  556. else
  557. {
  558. UsePuttyPwFile = (GUIConfiguration->UsePuttyPwFile == asOn);
  559. }
  560. UnicodeString PasswordParam;
  561. if (UsePuttyPwFile)
  562. {
  563. PipeCounter++;
  564. UnicodeString PipeName = FORMAT(L"\\\\.\\PIPE\\WinSCPPuTTYPassword.%.8x.%.8x.%.4x", (GetCurrentProcessId(), PipeCounter, rand()));
  565. new TPuttyPasswordThread(Password, PipeName);
  566. PasswordParam = FORMAT(L"-pwfile \"%s\"", (PipeName));
  567. }
  568. else
  569. {
  570. PasswordParam = FORMAT(L"-pw %s", (EscapePuttyCommandParam(Password)));
  571. }
  572. AddToList(PuttyParams, PasswordParam, L" ");
  573. }
  574. AddToList(PuttyParams, Params, L" ");
  575. // PuTTY is started in its binary directory to allow relative paths in private key,
  576. // when opening PuTTY's own stored session.
  577. ExecuteShellChecked(Program, PuttyParams, true);
  578. }
  579. else
  580. {
  581. throw Exception(FMTLOAD(FILE_NOT_FOUND, (Program)));
  582. }
  583. }
  584. //---------------------------------------------------------------------------
  585. bool __fastcall FindTool(const UnicodeString & Name, UnicodeString & Path)
  586. {
  587. UnicodeString AppPath = IncludeTrailingBackslash(ExtractFilePath(Application->ExeName));
  588. Path = AppPath + Name;
  589. bool Result = true;
  590. if (!FileExists(ApiPath(Path)))
  591. {
  592. Path = AppPath + L"PuTTY\\" + Name;
  593. if (!FileExists(ApiPath(Path)))
  594. {
  595. Path = Name;
  596. if (!FindFile(Path))
  597. {
  598. Result = false;
  599. }
  600. }
  601. }
  602. return Result;
  603. }
  604. //---------------------------------------------------------------------------
  605. void __fastcall ExecuteTool(const UnicodeString & Name)
  606. {
  607. UnicodeString Path;
  608. if (!FindTool(Name, Path))
  609. {
  610. throw Exception(FMTLOAD(EXECUTE_APP_ERROR, (Name)));
  611. }
  612. ExecuteShellChecked(Path, L"");
  613. }
  614. //---------------------------------------------------------------------------
  615. TObjectList * StartCreationDirectoryMonitorsOnEachDrive(unsigned int Filter, TFileChangedEvent OnChanged)
  616. {
  617. std::unique_ptr<TStrings> Drives(new TStringList());
  618. std::unique_ptr<TStrings> DDDrives(CommaTextToStringList(WinConfiguration->DDDrives));
  619. UnicodeString ExcludedDrives;
  620. for (int Index = 0; Index < DDDrives->Count; Index++)
  621. {
  622. UnicodeString S = Trim(DDDrives->Strings[Index]);
  623. if (!S.IsEmpty() && (S[1] == L'-'))
  624. {
  625. S = Trim(S.SubString(2, S.Length() - 1));
  626. if (!S.IsEmpty())
  627. {
  628. ExcludedDrives += S[1];
  629. }
  630. }
  631. else
  632. {
  633. Drives->Add(S);
  634. }
  635. }
  636. for (char Drive = FirstDrive; Drive <= LastDrive; Drive++)
  637. {
  638. if (ExcludedDrives.Pos(Drive) == 0)
  639. {
  640. // Not calling ReadDriveStatus(... dsSize), relying on drive ready status cached by the background thread
  641. TDriveInfoRec * DriveInfoRec = DriveInfo->Get(Drive);
  642. if (DriveInfoRec->Valid && DriveInfoRec->DriveReady &&
  643. (DriveInfoRec->DriveType != DRIVE_CDROM) &&
  644. ((DriveInfoRec->DriveType != DRIVE_REMOVABLE) || (Drive >= DriveInfo->FirstFixedDrive)))
  645. {
  646. Drives->Add(Drive);
  647. }
  648. }
  649. }
  650. std::unique_ptr<TObjectList> Result(new TObjectList());
  651. for (int Index = 0; Index < Drives->Count; Index++)
  652. {
  653. UnicodeString Drive = Drives->Strings[Index];
  654. std::unique_ptr<TDirectoryMonitor> Monitor(new TDirectoryMonitor(Application));
  655. try
  656. {
  657. Monitor->Path = DriveInfo->GetDriveRoot(Drive);
  658. Monitor->WatchSubtree = true;
  659. Monitor->WatchFilters = Filter;
  660. Monitor->OnCreated = OnChanged;
  661. Monitor->OnModified = OnChanged;
  662. Monitor->Active = true;
  663. Result->Add(Monitor.release());
  664. }
  665. catch (Exception & E)
  666. {
  667. // Ignore errors watching not-ready drives
  668. }
  669. }
  670. return Result.release();
  671. }
  672. //---------------------------------------------------------------------------
  673. bool DontCopyCommandToClipboard = false;
  674. //---------------------------------------------------------------------------
  675. bool __fastcall CopyCommandToClipboard(const UnicodeString & Command)
  676. {
  677. bool Result = !DontCopyCommandToClipboard && UseAlternativeFunction() && IsKeyPressed(VK_CONTROL);
  678. if (Result)
  679. {
  680. TInstantOperationVisualizer Visualizer;
  681. AppLogFmt(L"Copied command to the clipboard: %s", (Command));
  682. CopyToClipboard(Command);
  683. }
  684. return Result;
  685. }
  686. //---------------------------------------------------------------------------
  687. static bool __fastcall DoExecuteShell(const UnicodeString Path, const UnicodeString Params,
  688. bool ChangeWorkingDirectory, HANDLE * Handle)
  689. {
  690. bool Result = CopyCommandToClipboard(FormatCommand(Path, Params));
  691. if (Result)
  692. {
  693. if (Handle != NULL)
  694. {
  695. *Handle = NULL;
  696. }
  697. }
  698. else
  699. {
  700. UnicodeString Directory = ExtractFilePath(Path);
  701. TShellExecuteInfoW ExecuteInfo;
  702. memset(&ExecuteInfo, 0, sizeof(ExecuteInfo));
  703. ExecuteInfo.cbSize = sizeof(ExecuteInfo);
  704. ExecuteInfo.fMask =
  705. SEE_MASK_FLAG_NO_UI |
  706. FLAGMASK((Handle != NULL), SEE_MASK_NOCLOSEPROCESS);
  707. ExecuteInfo.hwnd = Application->Handle;
  708. ExecuteInfo.lpFile = (wchar_t*)Path.data();
  709. ExecuteInfo.lpParameters = (wchar_t*)Params.data();
  710. ExecuteInfo.lpDirectory = (ChangeWorkingDirectory ? Directory.c_str() : NULL);
  711. ExecuteInfo.nShow = SW_SHOW;
  712. AppLogFmt(L"Executing program \"%s\" with params: %s", (Path, Params));
  713. Result = (ShellExecuteEx(&ExecuteInfo) != 0);
  714. if (Result)
  715. {
  716. if (Handle != NULL)
  717. {
  718. *Handle = ExecuteInfo.hProcess;
  719. }
  720. }
  721. }
  722. return Result;
  723. }
  724. //---------------------------------------------------------------------------
  725. void __fastcall ExecuteShellChecked(const UnicodeString Path, const UnicodeString Params, bool ChangeWorkingDirectory)
  726. {
  727. if (!DoExecuteShell(Path, Params, ChangeWorkingDirectory, NULL))
  728. {
  729. throw EOSExtException(FMTLOAD(EXECUTE_APP_ERROR, (Path)));
  730. }
  731. }
  732. //---------------------------------------------------------------------------
  733. void __fastcall ExecuteShellChecked(const UnicodeString Command)
  734. {
  735. UnicodeString Program, Params, Dir;
  736. SplitCommand(Command, Program, Params, Dir);
  737. ExecuteShellChecked(Program, Params);
  738. }
  739. //---------------------------------------------------------------------------
  740. bool __fastcall ExecuteShell(const UnicodeString Path, const UnicodeString Params,
  741. HANDLE & Handle)
  742. {
  743. return DoExecuteShell(Path, Params, false, &Handle);
  744. }
  745. //---------------------------------------------------------------------------
  746. void __fastcall ExecuteShellCheckedAndWait(const UnicodeString Command,
  747. TProcessMessagesEvent ProcessMessages)
  748. {
  749. UnicodeString Program, Params, Dir;
  750. SplitCommand(Command, Program, Params, Dir);
  751. HANDLE ProcessHandle;
  752. bool Result = DoExecuteShell(Program, Params, false, &ProcessHandle);
  753. if (!Result)
  754. {
  755. throw EOSExtException(FMTLOAD(EXECUTE_APP_ERROR, (Program)));
  756. }
  757. else
  758. {
  759. if (ProcessHandle != NULL) // only if command was copied to clipboard only
  760. {
  761. if (ProcessMessages != NULL)
  762. {
  763. unsigned long WaitResult;
  764. do
  765. {
  766. // Same as in ExecuteProcessAndReadOutput
  767. WaitResult = WaitForSingleObject(ProcessHandle, 50);
  768. if (WaitResult == WAIT_FAILED)
  769. {
  770. throw Exception(LoadStr(DOCUMENT_WAIT_ERROR));
  771. }
  772. ProcessMessages();
  773. }
  774. while (WaitResult == WAIT_TIMEOUT);
  775. }
  776. else
  777. {
  778. WaitForSingleObject(ProcessHandle, INFINITE);
  779. }
  780. }
  781. }
  782. }
  783. //---------------------------------------------------------------------------
  784. bool __fastcall SpecialFolderLocation(int PathID, UnicodeString & Path)
  785. {
  786. LPITEMIDLIST Pidl;
  787. wchar_t Buf[256];
  788. if (SHGetSpecialFolderLocation(NULL, PathID, &Pidl) == NO_ERROR &&
  789. SHGetPathFromIDList(Pidl, Buf))
  790. {
  791. Path = UnicodeString(Buf);
  792. return true;
  793. }
  794. return false;
  795. }
  796. //---------------------------------------------------------------------------
  797. UnicodeString __fastcall UniqTempDir(const UnicodeString BaseDir, const UnicodeString Identity,
  798. bool Mask)
  799. {
  800. DebugAssert(!BaseDir.IsEmpty());
  801. UnicodeString TempDir;
  802. do
  803. {
  804. TempDir = IncludeTrailingBackslash(BaseDir) + Identity;
  805. if (Mask)
  806. {
  807. TempDir += L"?????";
  808. }
  809. else
  810. {
  811. TempDir += IncludeTrailingBackslash(FormatDateTime(L"nnzzz", Now()));
  812. }
  813. }
  814. while (!Mask && DirectoryExists(ApiPath(TempDir)));
  815. return TempDir;
  816. }
  817. //---------------------------------------------------------------------------
  818. class TSessionColors : public TComponent
  819. {
  820. public:
  821. __fastcall TSessionColors(TComponent * Owner) : TComponent(Owner)
  822. {
  823. Name = QualifiedClassName();
  824. }
  825. static TSessionColors * __fastcall Retrieve(TComponent * Component)
  826. {
  827. TSessionColors * SessionColors = dynamic_cast<TSessionColors *>(Component->FindComponent(QualifiedClassName()));
  828. if (SessionColors == NULL)
  829. {
  830. SessionColors = new TSessionColors(Component);
  831. }
  832. return SessionColors;
  833. }
  834. typedef std::map<TColor, int> TColorMap;
  835. TColorMap ColorMap;
  836. };
  837. //---------------------------------------------------------------------------
  838. int __fastcall GetSessionColorImage(
  839. TCustomImageList * ImageList, TColor Color, int MaskIndex)
  840. {
  841. TSessionColors * SessionColors = TSessionColors::Retrieve(ImageList);
  842. int Result;
  843. TSessionColors::TColorMap::const_iterator I = SessionColors->ColorMap.find(Color);
  844. if (I != SessionColors->ColorMap.end())
  845. {
  846. Result = I->second;
  847. }
  848. else
  849. {
  850. // This overly complex drawing is here to support color button on SiteAdvanced
  851. // dialog. There we use plain TImageList, instead of TPngImageList,
  852. // TButton does not work with transparent images
  853. // (not even TBitmap with Transparent = true)
  854. std::unique_ptr<TBitmap> MaskBitmap(new TBitmap());
  855. ImageList->GetBitmap(MaskIndex, MaskBitmap.get());
  856. std::unique_ptr<TPngImage> MaskImage(new TPngImage());
  857. MaskImage->Assign(MaskBitmap.get());
  858. std::unique_ptr<TPngImage> ColorImage(new TPngImage(COLOR_RGB, 16, ImageList->Width, ImageList->Height));
  859. TColor MaskTransparentColor = MaskImage->Pixels[0][0];
  860. TColor TransparentColor = MaskTransparentColor;
  861. // Expecting that the color to be replaced is in the centre of the image (HACK)
  862. TColor MaskColor = MaskImage->Pixels[ImageList->Width / 2][ImageList->Height / 2];
  863. for (int Y = 0; Y < ImageList->Height; Y++)
  864. {
  865. for (int X = 0; X < ImageList->Width; X++)
  866. {
  867. TColor SourceColor = MaskImage->Pixels[X][Y];
  868. TColor DestColor;
  869. // this branch is pointless as long as MaskTransparentColor and
  870. // TransparentColor are the same
  871. if (SourceColor == MaskTransparentColor)
  872. {
  873. DestColor = TransparentColor;
  874. }
  875. else if (SourceColor == MaskColor)
  876. {
  877. DestColor = Color;
  878. }
  879. else
  880. {
  881. DestColor = SourceColor;
  882. }
  883. ColorImage->Pixels[X][Y] = DestColor;
  884. }
  885. }
  886. std::unique_ptr<TBitmap> Bitmap(new TBitmap());
  887. Bitmap->SetSize(ImageList->Width, ImageList->Height);
  888. ColorImage->AssignTo(Bitmap.get());
  889. Result = ImageList->AddMasked(Bitmap.get(), TransparentColor);
  890. SessionColors->ColorMap.insert(std::make_pair(Color, Result));
  891. }
  892. return Result;
  893. }
  894. //---------------------------------------------------------------------------
  895. void __fastcall RegenerateSessionColorsImageList(TCustomImageList * ImageList, int MaskIndex)
  896. {
  897. TSessionColors * SessionColors = TSessionColors::Retrieve(ImageList);
  898. std::vector<TColor> Colors;
  899. size_t FixedImages = static_cast<size_t>(ImageList->Count);
  900. Colors.resize(FixedImages + SessionColors->ColorMap.size());
  901. TSessionColors::TColorMap::const_iterator I = SessionColors->ColorMap.begin();
  902. while (I != SessionColors->ColorMap.end())
  903. {
  904. DebugAssert(Colors[I->second] == TColor());
  905. Colors[I->second] = I->first;
  906. I++;
  907. }
  908. TSessionColors::TColorMap ColorMap = SessionColors->ColorMap;
  909. SessionColors->ColorMap.clear();
  910. for (size_t Index = 0; Index < Colors.size(); Index++)
  911. {
  912. bool IsFixedImageIndex = (Index < FixedImages);
  913. DebugAssert((Colors[Index] == TColor()) == IsFixedImageIndex);
  914. if (!IsFixedImageIndex)
  915. {
  916. GetSessionColorImage(ImageList, Colors[Index], MaskIndex);
  917. }
  918. }
  919. DebugAssert(SessionColors->ColorMap == ColorMap);
  920. }
  921. //---------------------------------------------------------------------------
  922. void __fastcall SetSubmenu(TTBXCustomItem * Item, bool Enable)
  923. {
  924. class TTBXPublicItem : public TTBXCustomItem
  925. {
  926. public:
  927. __property ItemStyle;
  928. };
  929. TTBXPublicItem * PublicItem = reinterpret_cast<TTBXPublicItem *>(Item);
  930. DebugAssert(PublicItem != NULL);
  931. // See TTBItemViewer.IsPtInButtonPart (called from TTBItemViewer.MouseDown)
  932. if (Enable)
  933. {
  934. PublicItem->ItemStyle = PublicItem->ItemStyle << tbisSubmenu;
  935. }
  936. else
  937. {
  938. PublicItem->ItemStyle = PublicItem->ItemStyle >> tbisSubmenu;
  939. }
  940. }
  941. //---------------------------------------------------------------------------
  942. bool __fastcall IsEligibleForApplyingTabs(
  943. UnicodeString Line, int & TabPos, UnicodeString & Start, UnicodeString & Remaining)
  944. {
  945. bool Result = false;
  946. TabPos = Line.Pos(L"\t");
  947. if (TabPos > 0)
  948. {
  949. Remaining = Line.SubString(TabPos + 1, Line.Length() - TabPos);
  950. // WORKAROUND
  951. // Some translations still use obsolete hack of consecutive tabs to aling the contents.
  952. // Delete these, so that the following check does not fail on this
  953. while (Remaining.SubString(1, 1) == L"\t")
  954. {
  955. Remaining.Delete(1, 1);
  956. }
  957. // We do not have, not support, mutiple tabs on a single line
  958. if (DebugAlwaysTrue(Remaining.Pos(L"\t") == 0))
  959. {
  960. Start = Line.SubString(1, TabPos - 1);
  961. // WORKAROUND
  962. // Previously we padded the string before tab with spaces,
  963. // to aling the contents across multiple lines
  964. Start = Start.TrimRight();
  965. // at least two normal spaces for separation
  966. Start += L" ";
  967. Result = true;
  968. }
  969. }
  970. return Result;
  971. }
  972. //---------------------------------------------------------------------------
  973. static int __fastcall CalculateWidthByLength(UnicodeString Text, void * /*Arg*/)
  974. {
  975. return Text.Length();
  976. }
  977. //---------------------------------------------------------------------------
  978. void __fastcall ApplyTabs(
  979. UnicodeString & Text, wchar_t Padding,
  980. TCalculateWidth CalculateWidth, void * CalculateWidthArg)
  981. {
  982. if (CalculateWidth == NULL)
  983. {
  984. DebugAssert(CalculateWidthArg == NULL);
  985. CalculateWidth = CalculateWidthByLength;
  986. }
  987. std::unique_ptr<TStringList> Lines(TextToStringList(Text));
  988. int MaxWidth = -1;
  989. for (int Index = 0; Index < Lines->Count; Index++)
  990. {
  991. UnicodeString Line = Lines->Strings[Index];
  992. int TabPos;
  993. UnicodeString Start;
  994. UnicodeString Remaining;
  995. if (IsEligibleForApplyingTabs(Line, TabPos, Start, Remaining))
  996. {
  997. int Width = CalculateWidth(Start, CalculateWidthArg);
  998. MaxWidth = Max(MaxWidth, Width);
  999. }
  1000. }
  1001. // Optimization and also to prevent potential regression for texts without tabs
  1002. if (MaxWidth >= 0)
  1003. {
  1004. for (int Index = 0; Index < Lines->Count; Index++)
  1005. {
  1006. UnicodeString Line = Lines->Strings[Index];
  1007. int TabPos;
  1008. UnicodeString Start;
  1009. UnicodeString Remaining;
  1010. if (IsEligibleForApplyingTabs(Line, TabPos, Start, Remaining))
  1011. {
  1012. int Width;
  1013. int Iterations = 0;
  1014. while ((Width = CalculateWidth(Start, CalculateWidthArg)) < MaxWidth)
  1015. {
  1016. int Wider = CalculateWidth(Start + Padding, CalculateWidthArg);
  1017. // If padded string is wider than max width by more pixels
  1018. // than non-padded string is shorter than max width
  1019. if ((Wider > MaxWidth) && ((Wider - MaxWidth) > (MaxWidth - Width)))
  1020. {
  1021. break;
  1022. }
  1023. Start += Padding;
  1024. Iterations++;
  1025. // In rare case a tab is zero-width with some strange font (like HYLE)
  1026. if (Iterations > 100)
  1027. {
  1028. break;
  1029. }
  1030. }
  1031. Lines->Strings[Index] = Start + Remaining;
  1032. }
  1033. }
  1034. Text = Lines->Text;
  1035. // remove trailing newline
  1036. Text = Text.TrimRight();
  1037. }
  1038. }
  1039. //---------------------------------------------------------------------------
  1040. static void __fastcall DoSelectScaledImageList(TImageList * ImageList)
  1041. {
  1042. TImageList * MatchingList = NULL;
  1043. int MachingPixelsPerInch = 0;
  1044. int PixelsPerInch = LargerPixelsPerInch(GetComponentPixelsPerInch(ImageList), WinConfiguration->LargerToolbar);
  1045. for (int Index = 0; Index < ImageList->Owner->ComponentCount; Index++)
  1046. {
  1047. TImageList * OtherList = dynamic_cast<TImageList *>(ImageList->Owner->Components[Index]);
  1048. if ((OtherList != NULL) &&
  1049. (OtherList != ImageList) &&
  1050. StartsStr(ImageList->Name, OtherList->Name))
  1051. {
  1052. UnicodeString OtherListPixelsPerInchStr =
  1053. OtherList->Name.SubString(
  1054. ImageList->Name.Length() + 1, OtherList->Name.Length() - ImageList->Name.Length());
  1055. int OtherListPixelsPerInch = StrToInt(OtherListPixelsPerInchStr);
  1056. if ((OtherListPixelsPerInch <= PixelsPerInch) &&
  1057. ((MatchingList == NULL) ||
  1058. (MachingPixelsPerInch < OtherListPixelsPerInch)))
  1059. {
  1060. MatchingList = OtherList;
  1061. MachingPixelsPerInch = OtherListPixelsPerInch;
  1062. }
  1063. }
  1064. }
  1065. if (MatchingList != NULL)
  1066. {
  1067. UnicodeString ImageListBackupName = ImageList->Name + IntToStr(USER_DEFAULT_SCREEN_DPI);
  1068. if (ImageList->Owner->FindComponent(ImageListBackupName) == NULL)
  1069. {
  1070. TImageList * ImageListBackup;
  1071. TPngImageList * PngImageList = dynamic_cast<TPngImageList *>(ImageList);
  1072. if (PngImageList != NULL)
  1073. {
  1074. ImageListBackup = new TPngImageList(ImageList->Owner);
  1075. }
  1076. else
  1077. {
  1078. ImageListBackup = new TImageList(ImageList->Owner);
  1079. }
  1080. ImageListBackup->Name = ImageListBackupName;
  1081. ImageList->Owner->InsertComponent(ImageListBackup);
  1082. CopyImageList(ImageListBackup, ImageList);
  1083. }
  1084. CopyImageList(ImageList, MatchingList);
  1085. }
  1086. }
  1087. //---------------------------------------------------------------------------
  1088. static void __fastcall ImageListRescale(TComponent * Sender, TObject * /*Token*/)
  1089. {
  1090. TImageList * ImageList = DebugNotNull(dynamic_cast<TImageList *>(Sender));
  1091. DoSelectScaledImageList(ImageList);
  1092. }
  1093. //---------------------------------------------------------------------------
  1094. void __fastcall SelectScaledImageList(TImageList * ImageList)
  1095. {
  1096. DoSelectScaledImageList(ImageList);
  1097. SetRescaleFunction(ImageList, ImageListRescale);
  1098. }
  1099. //---------------------------------------------------------------------------
  1100. void __fastcall CopyImageList(TImageList * TargetList, TImageList * SourceList)
  1101. {
  1102. // Maybe this is not necessary, once the TPngImageList::Assign was fixed.
  1103. // But if we ever use Assign, make sure the target keeps its Scaled property.
  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. // from XE6 Vcl.ScreenTips.pas, but absent in 11
  2092. const cScreenTipTextOnlyWidth = 210;
  2093. const int ScreenTipTextOnlyWidth = ScaleByTextHeight(HintControl, cScreenTipTextOnlyWidth);
  2094. int LongHintMargin = 0; // shut up
  2095. bool HasLongHint = !LongHint.IsEmpty();
  2096. if (HasLongHint)
  2097. {
  2098. // double-margin on the right
  2099. LongHintMargin = (3 * Margin);
  2100. MaxWidth = ScreenTipTextOnlyWidth - LongHintMargin;
  2101. }
  2102. // Multi line short hints can be twice as wide, to not break the individual lines unless really necessary.
  2103. // (login site tree, clean up dialog list, preferences custom command list, persistent hint, etc).
  2104. // And they also can be twice as wide, to not break the individual lines unless really necessary.
  2105. if (ShortHint.Pos(L"\n") > 0)
  2106. {
  2107. MaxWidth *= 2;
  2108. }
  2109. bool HintPopup = HasLabelHintPopup(HintControl, AHint);
  2110. if (HintPopup)
  2111. {
  2112. MaxWidth = HintControl->Width;
  2113. }
  2114. if (UseBoldShortHint(HintControl))
  2115. {
  2116. Canvas->Font->Style = TFontStyles() << fsBold;
  2117. }
  2118. TRect ShortRect(0, 0, MaxWidth, 0);
  2119. CalcHintTextRect(this, Canvas, ShortRect, ShortHint);
  2120. Canvas->Font->Style = TFontStyles();
  2121. TRect Result;
  2122. if (!HasLongHint)
  2123. {
  2124. Result = ShortRect;
  2125. if (HintPopup)
  2126. {
  2127. Result.Right = MaxWidth + 2 * Margin;
  2128. }
  2129. else
  2130. {
  2131. Result.Right += 3 * Margin;
  2132. }
  2133. Result.Bottom += 2 * Margin;
  2134. }
  2135. else
  2136. {
  2137. const int LongIndentation = Margin * 3 / 2;
  2138. TRect LongRect(0, 0, MaxWidth - LongIndentation, 0);
  2139. CalcHintTextRect(this, Canvas, LongRect, LongHint);
  2140. Result.Right = Max(ScreenTipTextOnlyWidth, LongRect.Right + LongIndentation + LongHintMargin);
  2141. Result.Bottom = Margin + ShortRect.Height() + (Margin / 3 * 5) + LongRect.Height() + Margin;
  2142. }
  2143. // VCLCOPY: To counter the increase in THintWindow::ActivateHintData
  2144. Result.Bottom -= 4;
  2145. return Result;
  2146. }
  2147. //---------------------------------------------------------------------------
  2148. void __fastcall TScreenTipHintWindow::SplitHint(
  2149. TControl * HintControl, const UnicodeString & Hint, UnicodeString & ShortHint, UnicodeString & LongHint)
  2150. {
  2151. if (HasLabelHintPopup(HintControl, Hint))
  2152. {
  2153. ShortHint = HintControl->Hint;
  2154. }
  2155. else
  2156. {
  2157. ShortHint = GetShortHint(Hint);
  2158. LongHint = GetLongHintIfAny(Hint);
  2159. }
  2160. }
  2161. //---------------------------------------------------------------------------
  2162. void __fastcall TScreenTipHintWindow::ActivateHintData(const TRect & ARect, const UnicodeString AHint, void * AData)
  2163. {
  2164. FHintControl = GetHintControl(AData);
  2165. SplitHint(FHintControl, AHint, FShortHint, FLongHint);
  2166. FMargin = GetMargin(FHintControl, AHint);
  2167. FHintPopup = HasLabelHintPopup(FHintControl, AHint);
  2168. Canvas->Font->Assign(GetFont(FHintControl, AHint));
  2169. TRect Rect = ARect;
  2170. if (FHintPopup)
  2171. {
  2172. Rect.SetLocation(FHintControl->ClientToScreen(TPoint(-FMargin, -FMargin)));
  2173. }
  2174. if (IsPathLabel(FHintControl))
  2175. {
  2176. Rect.Offset(-FMargin, -FMargin);
  2177. }
  2178. THintWindow::ActivateHintData(Rect, FShortHint, AData);
  2179. }
  2180. //---------------------------------------------------------------------------
  2181. TControl * __fastcall TScreenTipHintWindow::GetHintControl(void * Data)
  2182. {
  2183. return reinterpret_cast<TControl *>(DebugNotNull(Data));
  2184. }
  2185. //---------------------------------------------------------------------------
  2186. UnicodeString __fastcall TScreenTipHintWindow::GetLongHintIfAny(const UnicodeString & AHint)
  2187. {
  2188. UnicodeString Result;
  2189. int P = Pos(L"|", AHint);
  2190. if (P > 0)
  2191. {
  2192. Result = GetLongHint(AHint);
  2193. }
  2194. return Result;
  2195. }
  2196. //---------------------------------------------------------------------------
  2197. void __fastcall TScreenTipHintWindow::Dispatch(void * AMessage)
  2198. {
  2199. TMessage * Message = static_cast<TMessage*>(AMessage);
  2200. switch (Message->Msg)
  2201. {
  2202. case WM_GETTEXTLENGTH:
  2203. if (FParentPainting)
  2204. {
  2205. // make THintWindow::Paint() not paint the Caption
  2206. Message->Result = 0;
  2207. }
  2208. else
  2209. {
  2210. THintWindow::Dispatch(AMessage);
  2211. }
  2212. break;
  2213. default:
  2214. THintWindow::Dispatch(AMessage);
  2215. break;
  2216. }
  2217. }
  2218. //---------------------------------------------------------------------------
  2219. void __fastcall TScreenTipHintWindow::Paint()
  2220. {
  2221. // paint frame/background
  2222. {
  2223. TAutoFlag ParentPaintingFlag(FParentPainting);
  2224. THintWindow::Paint();
  2225. }
  2226. const int Flags = GetTextFlags(this);
  2227. const int Margin = FMargin - 1; // 1 = border
  2228. TRect Rect = ClientRect;
  2229. Rect.Inflate(-Margin, -Margin);
  2230. if (!FHintPopup)
  2231. {
  2232. Rect.Right -= FMargin;
  2233. }
  2234. if (UseBoldShortHint(FHintControl))
  2235. {
  2236. Canvas->Font->Style = TFontStyles() << fsBold;
  2237. }
  2238. DrawText(Canvas->Handle, FShortHint.c_str(), -1, &Rect, Flags);
  2239. TRect ShortRect = Rect;
  2240. DrawText(Canvas->Handle, FShortHint.c_str(), -1, &ShortRect, DT_CALCRECT | Flags);
  2241. Canvas->Font->Style = TFontStyles();
  2242. if (!FLongHint.IsEmpty())
  2243. {
  2244. Rect.Left += FMargin * 3 / 2;
  2245. Rect.Top += ShortRect.Height() + (FMargin / 3 * 5);
  2246. DrawText(Canvas->Handle, FLongHint.c_str(), -1, &Rect, Flags);
  2247. }
  2248. }
  2249. //---------------------------------------------------------------------------
  2250. static int HideAccelFlag(TControl * Control)
  2251. {
  2252. //ask the top level window about its UI state
  2253. while (Control->Parent != NULL)
  2254. {
  2255. Control = Control->Parent;
  2256. }
  2257. int Result;
  2258. if (FLAGSET(Control->Perform(WM_QUERYUISTATE, 0, 0), UISF_HIDEACCEL))
  2259. {
  2260. Result = DT_HIDEPREFIX;
  2261. }
  2262. else
  2263. {
  2264. Result = 0;
  2265. }
  2266. return Result;
  2267. }
  2268. //---------------------------------------------------------------------------
  2269. __fastcall TUIStateAwareLabel::TUIStateAwareLabel(TComponent * AOwner) :
  2270. TLabel(AOwner)
  2271. {
  2272. }
  2273. //---------------------------------------------------------------------------
  2274. void __fastcall TUIStateAwareLabel::DoDrawText(TRect & Rect, int Flags)
  2275. {
  2276. if (ShowAccelChar)
  2277. {
  2278. Flags = Flags | HideAccelFlag(this);
  2279. }
  2280. TLabel::DoDrawText(Rect, Flags);
  2281. }
  2282. //---------------------------------------------------------------------------
  2283. void __fastcall TUIStateAwareLabel::Dispatch(void * AMessage)
  2284. {
  2285. TMessage * Message = static_cast<TMessage*>(AMessage);
  2286. // WORKAROUND: Particularly when focusing csDropDownList-style combobox via label, there's no visual feedback
  2287. // that the combobox was selected (strangely, there is, when the previous focus was on TTreeView).
  2288. // For consistency, we enable focus display for all controls types (like checkboxes).
  2289. if (Message->Msg == CM_DIALOGCHAR)
  2290. {
  2291. bool WasFocused = (FocusControl != NULL) ? FocusControl->Focused() : false;
  2292. TLabel::Dispatch(AMessage);
  2293. if (!WasFocused && (FocusControl != NULL) && FocusControl->Focused())
  2294. {
  2295. TCustomForm * ParentForm = GetParentForm(this);
  2296. if (ParentForm != NULL)
  2297. {
  2298. ParentForm->Perform(WM_CHANGEUISTATE, MAKELONG(UIS_CLEAR, UISF_HIDEFOCUS), 0);
  2299. }
  2300. }
  2301. }
  2302. else
  2303. {
  2304. TLabel::Dispatch(AMessage);
  2305. }
  2306. }
  2307. //---------------------------------------------------------------------------
  2308. void __fastcall FindComponentClass(
  2309. void *, TReader *, const UnicodeString DebugUsedArg(ClassName), TComponentClass & ComponentClass)
  2310. {
  2311. if (ComponentClass == __classid(TLabel))
  2312. {
  2313. ComponentClass = __classid(TUIStateAwareLabel);
  2314. }
  2315. else if (ComponentClass == __classid(TComboBox))
  2316. {
  2317. ComponentClass = __classid(TUIStateAwareComboBox);
  2318. }
  2319. }
  2320. //---------------------------------------------------------------------------
  2321. bool CanShowTimeEstimate(TDateTime StartTime)
  2322. {
  2323. return (SecondsBetween(StartTime, Now()) >= 3);
  2324. }
  2325. //---------------------------------------------------------------------------
  2326. class TSystemRequiredThread : public TSignalThread
  2327. {
  2328. public:
  2329. TSystemRequiredThread();
  2330. void Required();
  2331. protected:
  2332. virtual bool __fastcall WaitForEvent();
  2333. virtual void __fastcall ProcessEvent();
  2334. private:
  2335. bool FRequired;
  2336. TDateTime FLastRequired;
  2337. };
  2338. //---------------------------------------------------------------------------
  2339. std::unique_ptr<TCriticalSection> SystemRequiredThreadSection(TraceInitPtr(new TCriticalSection()));
  2340. TSystemRequiredThread * SystemRequiredThread = NULL;
  2341. //---------------------------------------------------------------------------
  2342. TSystemRequiredThread::TSystemRequiredThread() :
  2343. TSignalThread(true), FRequired(false)
  2344. {
  2345. }
  2346. //---------------------------------------------------------------------------
  2347. void TSystemRequiredThread::Required()
  2348. {
  2349. // guarded in SystemRequired()
  2350. FLastRequired = Now();
  2351. TriggerEvent();
  2352. }
  2353. //---------------------------------------------------------------------------
  2354. bool __fastcall TSystemRequiredThread::WaitForEvent()
  2355. {
  2356. const int ExpireInterval = 5000;
  2357. bool Result = (TSignalThread::WaitForEvent(ExpireInterval) > 0);
  2358. if (!Result && !FTerminated)
  2359. {
  2360. TGuard Guard(SystemRequiredThreadSection.get());
  2361. if (!FTerminated && FRequired &&
  2362. (MilliSecondsBetween(Now(), FLastRequired) > ExpireInterval))
  2363. {
  2364. AppLog(L"System is not required");
  2365. SetThreadExecutionState(ES_CONTINUOUS);
  2366. FLastRequired = TDateTime();
  2367. FRequired = false;
  2368. }
  2369. }
  2370. return Result;
  2371. }
  2372. //---------------------------------------------------------------------------
  2373. void __fastcall TSystemRequiredThread::ProcessEvent()
  2374. {
  2375. TGuard Guard(SystemRequiredThreadSection.get());
  2376. if (!FRequired &&
  2377. (FLastRequired != TDateTime()))
  2378. {
  2379. AppLog(L"System is required");
  2380. SetThreadExecutionState(ES_SYSTEM_REQUIRED | ES_CONTINUOUS);
  2381. FRequired = true;
  2382. }
  2383. }
  2384. //---------------------------------------------------------------------------
  2385. void SystemRequired()
  2386. {
  2387. if (IsWin11())
  2388. {
  2389. TGuard Guard(SystemRequiredThreadSection.get());
  2390. if (SystemRequiredThread == NULL)
  2391. {
  2392. AppLog(L"Starting system required thread");
  2393. SystemRequiredThread = new TSystemRequiredThread();
  2394. SystemRequiredThread->Start();
  2395. }
  2396. SystemRequiredThread->Required();
  2397. }
  2398. else
  2399. {
  2400. SetThreadExecutionState(ES_SYSTEM_REQUIRED);
  2401. }
  2402. }
  2403. //---------------------------------------------------------------------------
  2404. void GUIFinalize()
  2405. {
  2406. TPuttyCleanupThread::Finalize();
  2407. TSystemRequiredThread * Thread;
  2408. {
  2409. TGuard Guard(SystemRequiredThreadSection.get());
  2410. Thread = SystemRequiredThread;
  2411. SystemRequiredThread = NULL;
  2412. }
  2413. if (Thread != NULL)
  2414. {
  2415. AppLog(L"Stopping system required thread");
  2416. Thread->Terminate();
  2417. Thread->WaitFor();
  2418. delete Thread;
  2419. }
  2420. }
  2421. //---------------------------------------------------------------------------
  2422. TCustomImageList * TreeViewImageList(TPngImageList * ImageList)
  2423. {
  2424. // WORKAROUND Prevent DPI scaling, see TCustomTreeView.SetImages
  2425. ImageList->Scaled = true;
  2426. return ImageList;
  2427. }