GUITools.cpp 99 KB

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