GUITools.cpp 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059
  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. static 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 = static_cast<const wchar_t *>(Path.data());
  710. ExecuteInfo.lpParameters = static_cast<const 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 DebugUsedArg(dwID), POINT *, IUnknown *, IDispatch *)
  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 DebugUsedArg(dwID), IOleInPlaceActiveObject *, IOleCommandTarget *, IOleInPlaceFrame *, IOleInPlaceUIWindow *)
  1293. {
  1294. return E_NOTIMPL;
  1295. }
  1296. virtual HRESULT STDMETHODCALLTYPE HideUI()
  1297. {
  1298. return E_NOTIMPL;
  1299. }
  1300. virtual HRESULT STDMETHODCALLTYPE UpdateUI()
  1301. {
  1302. return E_NOTIMPL;
  1303. }
  1304. virtual HRESULT STDMETHODCALLTYPE EnableModeless(BOOL DebugUsedArg(fEnable))
  1305. {
  1306. return E_NOTIMPL;
  1307. }
  1308. virtual HRESULT STDMETHODCALLTYPE OnDocWindowActivate(BOOL DebugUsedArg(fActivate))
  1309. {
  1310. return E_NOTIMPL;
  1311. }
  1312. virtual HRESULT STDMETHODCALLTYPE OnFrameWindowActivate(BOOL DebugUsedArg(fActivate))
  1313. {
  1314. return E_NOTIMPL;
  1315. }
  1316. virtual HRESULT STDMETHODCALLTYPE ResizeBorder(LPCRECT, IOleInPlaceUIWindow *, BOOL DebugUsedArg(fRameWindow))
  1317. {
  1318. return E_NOTIMPL;
  1319. }
  1320. virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator(LPMSG, const GUID * DebugUsedArg(pguidCmdGroup), DWORD DebugUsedArg(nCmdID))
  1321. {
  1322. return E_NOTIMPL;
  1323. }
  1324. virtual HRESULT STDMETHODCALLTYPE GetOptionKeyPath(LPOLESTR * DebugUsedArg(pchKey), DWORD DebugUsedArg(dw))
  1325. {
  1326. return E_NOTIMPL;
  1327. }
  1328. virtual HRESULT STDMETHODCALLTYPE GetDropTarget(IDropTarget *, IDropTarget **)
  1329. {
  1330. return E_NOTIMPL;
  1331. }
  1332. virtual HRESULT STDMETHODCALLTYPE GetExternal(IDispatch **)
  1333. {
  1334. return E_NOTIMPL;
  1335. }
  1336. virtual HRESULT STDMETHODCALLTYPE TranslateUrl(DWORD DebugUsedArg(dwTranslate), OLECHAR * DebugUsedArg(pchURLIn), OLECHAR ** DebugUsedArg(ppchURLOut))
  1337. {
  1338. return E_NOTIMPL;
  1339. }
  1340. virtual HRESULT STDMETHODCALLTYPE FilterDataObject(IDataObject *, IDataObject **)
  1341. {
  1342. return E_NOTIMPL;
  1343. }
  1344. };
  1345. //---------------------------------------------------------------------------
  1346. // Included only here as it defines ambiguous LONG_PTR, causing INVALID_HANDLE_VALUE to be unusable
  1347. #include <WebBrowserEx.hpp>
  1348. //---------------------------------------------------------------------------
  1349. class TBrowserViewer : public TWebBrowserEx
  1350. {
  1351. public:
  1352. __fastcall virtual TBrowserViewer(TComponent* AOwner);
  1353. void __fastcall AddLinkHandler(
  1354. const UnicodeString & Url, TNotifyEvent Handler);
  1355. void __fastcall NavigateToUrl(const UnicodeString & Url);
  1356. TControl * LoadingPanel;
  1357. protected:
  1358. DYNAMIC void __fastcall DoContextPopup(const TPoint & MousePos, bool & Handled);
  1359. void __fastcall DocumentComplete(
  1360. TObject * Sender, const _di_IDispatch Disp, const OleVariant & URL);
  1361. void __fastcall BeforeNavigate2(
  1362. TObject * Sender, const _di_IDispatch Disp, const OleVariant & URL,
  1363. const OleVariant & Flags, const OleVariant & TargetFrameName,
  1364. const OleVariant & PostData, const OleVariant & Headers, WordBool & Cancel);
  1365. bool FComplete;
  1366. std::map<UnicodeString, TNotifyEvent> FHandlers;
  1367. };
  1368. //---------------------------------------------------------------------------
  1369. __fastcall TBrowserViewer::TBrowserViewer(TComponent* AOwner) :
  1370. TWebBrowserEx(AOwner)
  1371. {
  1372. FComplete = false;
  1373. OnDocumentComplete = DocumentComplete;
  1374. OnBeforeNavigate2 = BeforeNavigate2;
  1375. LoadingPanel = NULL;
  1376. }
  1377. //---------------------------------------------------------------------------
  1378. void __fastcall TBrowserViewer::AddLinkHandler(
  1379. const UnicodeString & Url, TNotifyEvent Handler)
  1380. {
  1381. FHandlers.insert(std::make_pair(Url, Handler));
  1382. }
  1383. //---------------------------------------------------------------------------
  1384. void __fastcall TBrowserViewer::DoContextPopup(const TPoint & MousePos, bool & Handled)
  1385. {
  1386. // Suppress built-in context menu.
  1387. // Is ignored with IDocHostUIHandler. Needs to be overriden by ShowContextMenu.
  1388. Handled = true;
  1389. TWebBrowserEx::DoContextPopup(MousePos, Handled);
  1390. }
  1391. //---------------------------------------------------------------------------
  1392. void __fastcall TBrowserViewer::DocumentComplete(
  1393. TObject * /*Sender*/, const _di_IDispatch /*Disp*/, const OleVariant & /*URL*/)
  1394. {
  1395. SetBrowserDesignModeOff(this);
  1396. FComplete = true;
  1397. if (LoadingPanel != NULL)
  1398. {
  1399. LoadingPanel->Visible = false;
  1400. }
  1401. }
  1402. //---------------------------------------------------------------------------
  1403. void __fastcall TBrowserViewer::BeforeNavigate2(
  1404. TObject * /*Sender*/, const _di_IDispatch /*Disp*/, const OleVariant & AURL,
  1405. const OleVariant & /*Flags*/, const OleVariant & /*TargetFrameName*/,
  1406. const OleVariant & /*PostData*/, const OleVariant & /*Headers*/, WordBool & Cancel)
  1407. {
  1408. // If OnDocumentComplete was not called yet, is has to be our initial message URL,
  1409. // opened using TWebBrowserEx::Navigate(), allow it.
  1410. // Otherwise it's user navigating, block that and open link
  1411. // in an external browser, possibly adding campaign parameters on the way.
  1412. if (FComplete)
  1413. {
  1414. Cancel = 1;
  1415. UnicodeString URL = AURL;
  1416. if (FHandlers.count(URL) > 0)
  1417. {
  1418. FHandlers[URL](this);
  1419. }
  1420. else
  1421. {
  1422. OpenBrowser(URL);
  1423. }
  1424. }
  1425. }
  1426. //---------------------------------------------------------------------------
  1427. void __fastcall TBrowserViewer::NavigateToUrl(const UnicodeString & Url)
  1428. {
  1429. FComplete = false;
  1430. Navigate(Url.c_str());
  1431. }
  1432. //---------------------------------------------------------------------------
  1433. TWebBrowserEx * __fastcall CreateBrowserViewer(TPanel * Parent, const UnicodeString & LoadingLabel)
  1434. {
  1435. TBrowserViewer * Result = new TBrowserViewer(Parent);
  1436. // TWebBrowserEx has its own unrelated Name and Parent properties.
  1437. // The name is used in DownloadUpdate().
  1438. static_cast<TWinControl *>(Result)->Name = L"BrowserViewer";
  1439. static_cast<TWinControl *>(Result)->Parent = Parent;
  1440. Result->Align = alClient;
  1441. // Is ignored with IDocHostUIHandler. Needs to be overriden by DOCHOSTUIFLAG_NO3DBORDER in GetHostInfo.
  1442. Result->ControlBorder = cbNone;
  1443. Result->LoadingPanel = CreateLabelPanel(Parent, LoadingLabel);
  1444. return Result;
  1445. }
  1446. //---------------------------------------------------------------------------
  1447. void __fastcall SetBrowserDesignModeOff(TWebBrowserEx * WebBrowser)
  1448. {
  1449. if (DebugAlwaysTrue(WebBrowser->Document2 != NULL))
  1450. {
  1451. WebBrowser->Document2->designMode = L"Off";
  1452. }
  1453. }
  1454. //---------------------------------------------------------------------------
  1455. void __fastcall AddBrowserLinkHandler(TWebBrowserEx * WebBrowser,
  1456. const UnicodeString & Url, TNotifyEvent Handler)
  1457. {
  1458. TBrowserViewer * BrowserViewer = dynamic_cast<TBrowserViewer *>(WebBrowser);
  1459. if (DebugAlwaysTrue(BrowserViewer != NULL))
  1460. {
  1461. BrowserViewer->AddLinkHandler(Url, Handler);
  1462. }
  1463. }
  1464. //---------------------------------------------------------------------------
  1465. void __fastcall NavigateBrowserToUrl(TWebBrowserEx * WebBrowser, const UnicodeString & Url)
  1466. {
  1467. TBrowserViewer * BrowserViewer = dynamic_cast<TBrowserViewer *>(WebBrowser);
  1468. if (DebugAlwaysTrue(BrowserViewer != NULL))
  1469. {
  1470. BrowserViewer->NavigateToUrl(Url);
  1471. }
  1472. }
  1473. //---------------------------------------------------------------------------
  1474. void ReadyBrowserForStreaming(TWebBrowserEx * WebBrowser)
  1475. {
  1476. // This creates TWebBrowserEx::Document, which we need to stream in an in-memory document
  1477. NavigateBrowserToUrl(WebBrowser, L"about:blank");
  1478. // Needs to be followed by WaitBrowserToIdle
  1479. }
  1480. //---------------------------------------------------------------------------
  1481. void WaitBrowserToIdle(TWebBrowserEx * WebBrowser)
  1482. {
  1483. while (WebBrowser->ReadyState < ::READYSTATE_INTERACTIVE)
  1484. {
  1485. Application->ProcessMessages();
  1486. }
  1487. }
  1488. //---------------------------------------------------------------------------
  1489. void HideBrowserScrollbars(TWebBrowserEx * WebBrowser)
  1490. {
  1491. ICustomDoc * CustomDoc = NULL;
  1492. if (DebugAlwaysTrue(WebBrowser->Document != NULL) &&
  1493. SUCCEEDED(WebBrowser->Document->QueryInterface(&CustomDoc)) &&
  1494. DebugAlwaysTrue(CustomDoc != NULL))
  1495. {
  1496. TCustomDocHandler * Handler = new TCustomDocHandler(WebBrowser, CustomDoc);
  1497. CustomDoc->SetUIHandler(Handler);
  1498. }
  1499. }
  1500. //---------------------------------------------------------------------------
  1501. bool CopyTextFromBrowser(TWebBrowserEx * WebBrowser, UnicodeString & Text)
  1502. {
  1503. WebBrowser->SelectAll();
  1504. WebBrowser->CopyToClipBoard();
  1505. bool Result = NonEmptyTextFromClipboard(Text);
  1506. WebBrowser->DoCommand(L"UNSELECT");
  1507. return Result;
  1508. }
  1509. //---------------------------------------------------------------------------
  1510. TPanel * CreateBlankPanel(TComponent * Owner)
  1511. {
  1512. TPanel * Panel = new TPanel(Owner);
  1513. Panel->BevelOuter = bvNone;
  1514. Panel->BevelInner = bvNone; // default
  1515. Panel->BevelKind = bkNone;
  1516. Panel->Color = clWindow;
  1517. return Panel;
  1518. }
  1519. //---------------------------------------------------------------------------
  1520. TPanel * CreateLabelPanel(TPanel * Parent, const UnicodeString & Label)
  1521. {
  1522. TPanel * Result = CreateBlankPanel(Parent);
  1523. Result->Parent = Parent;
  1524. Result->Align = alClient;
  1525. Result->Caption = Label;
  1526. return Result;
  1527. }
  1528. //---------------------------------------------------------------------------
  1529. UnicodeString GenerateAppHtmlPage(TFont * Font, TPanel * Parent, const UnicodeString & Body, bool Seamless)
  1530. {
  1531. UnicodeString Result =
  1532. L"<!DOCTYPE html>\n"
  1533. L"<meta charset=\"utf-8\">\n"
  1534. L"<html>\n"
  1535. L"<head>\n"
  1536. L"<style>\n"
  1537. L"\n"
  1538. L"body\n"
  1539. L"{\n"
  1540. L" font-family: '" + Font->Name + L"';\n"
  1541. L" margin: " + UnicodeString(Seamless ? L"0" : L"0.5em") + L";\n"
  1542. L" color: " + ColorToWebColorStr(Parent->Font->Color) + L";\n"
  1543. L" background-color: " + ColorToWebColorStr(Parent->Color) + L";\n" +
  1544. UnicodeString(Seamless ? L" overflow: hidden;\n" : L"") +
  1545. L" font-size: " + IntToStr(Font->Size) + L"pt;\n"
  1546. L"}\n"
  1547. L"\n"
  1548. L"p\n"
  1549. L"{\n"
  1550. L" margin-top: 0;\n"
  1551. L" margin-bottom: 1em;\n"
  1552. L"}\n"
  1553. L"\n"
  1554. L"a, a:visited, a:hover, a:visited, a:current\n"
  1555. L"{\n"
  1556. L" color: " + ColorToWebColorStr(GetLinkColor(Parent)) + L";\n"
  1557. L"}\n"
  1558. L"</style>\n"
  1559. L"</head>\n"
  1560. L"<body>\n" +
  1561. Body +
  1562. L"</body>\n"
  1563. L"</html>\n";
  1564. return Result;
  1565. }
  1566. //---------------------------------------------------------------------------
  1567. void LoadBrowserDocument(TWebBrowserEx * WebBrowser, const UnicodeString & Document)
  1568. {
  1569. std::unique_ptr<TMemoryStream> DocumentStream(new TMemoryStream());
  1570. UTF8String DocumentUTF8 = UTF8String(Document);
  1571. DocumentStream->Write(DocumentUTF8.c_str(), DocumentUTF8.Length());
  1572. DocumentStream->Seek(0, 0);
  1573. // For stream-loaded document, when set only after loading from OnDocumentComplete,
  1574. // browser stops working
  1575. SetBrowserDesignModeOff(WebBrowser);
  1576. TStreamAdapter * DocumentStreamAdapter = new TStreamAdapter(DocumentStream.get(), soReference);
  1577. IPersistStreamInit * PersistStreamInit = NULL;
  1578. if (DebugAlwaysTrue(WebBrowser->Document != NULL) &&
  1579. SUCCEEDED(WebBrowser->Document->QueryInterface(IID_IPersistStreamInit, (void **)&PersistStreamInit)) &&
  1580. DebugAlwaysTrue(PersistStreamInit != NULL))
  1581. {
  1582. PersistStreamInit->Load(static_cast<_di_IStream>(*DocumentStreamAdapter));
  1583. PersistStreamInit->Release();
  1584. }
  1585. }
  1586. //---------------------------------------------------------------------------
  1587. TComponent * __fastcall FindComponentRecursively(TComponent * Root, const UnicodeString & Name)
  1588. {
  1589. for (int Index = 0; Index < Root->ComponentCount; Index++)
  1590. {
  1591. TComponent * Component = Root->Components[Index];
  1592. if (CompareText(Component->Name, Name) == 0)
  1593. {
  1594. return Component;
  1595. }
  1596. Component = FindComponentRecursively(Component, Name);
  1597. if (Component != NULL)
  1598. {
  1599. return Component;
  1600. }
  1601. }
  1602. return NULL;
  1603. }
  1604. //---------------------------------------------------------------------------
  1605. void __fastcall GetInstrutionsTheme(
  1606. TColor & MainInstructionColor, HFONT & MainInstructionFont, HFONT & InstructionFont)
  1607. {
  1608. MainInstructionColor = Graphics::clNone;
  1609. MainInstructionFont = 0;
  1610. InstructionFont = 0;
  1611. HTHEME Theme = OpenThemeData(0, L"TEXTSTYLE");
  1612. if (Theme != NULL)
  1613. {
  1614. LOGFONT AFont;
  1615. COLORREF AColor;
  1616. memset(&AFont, 0, sizeof(AFont));
  1617. // Using Canvas->Handle in the 2nd argument we can get scaled font,
  1618. // but at this point the form is sometime not scaled yet (difference is particularly for standalone messages like
  1619. // /UninstallCleanup), so the results are inconsistent.
  1620. if (GetThemeFont(Theme, NULL, TEXT_MAININSTRUCTION, 0, TMT_FONT, &AFont) == S_OK)
  1621. {
  1622. MainInstructionFont = CreateFontIndirect(&AFont);
  1623. }
  1624. if (GetThemeColor(Theme, TEXT_MAININSTRUCTION, 0, TMT_TEXTCOLOR, &AColor) == S_OK)
  1625. {
  1626. MainInstructionColor = (TColor)AColor;
  1627. }
  1628. memset(&AFont, 0, sizeof(AFont));
  1629. if (GetThemeFont(Theme, NULL, TEXT_INSTRUCTION, 0, TMT_FONT, &AFont) == S_OK)
  1630. {
  1631. InstructionFont = CreateFontIndirect(&AFont);
  1632. }
  1633. CloseThemeData(Theme);
  1634. }
  1635. }
  1636. //---------------------------------------------------------------------------
  1637. TLocalCustomCommand::TLocalCustomCommand()
  1638. {
  1639. }
  1640. //---------------------------------------------------------------------------
  1641. TLocalCustomCommand::TLocalCustomCommand(
  1642. const TCustomCommandData & Data, const UnicodeString & RemotePath, const UnicodeString & LocalPath) :
  1643. TFileCustomCommand(Data, RemotePath)
  1644. {
  1645. FLocalPath = LocalPath;
  1646. }
  1647. //---------------------------------------------------------------------------
  1648. TLocalCustomCommand::TLocalCustomCommand(const TCustomCommandData & Data,
  1649. const UnicodeString & RemotePath, const UnicodeString & LocalPath, const UnicodeString & FileName,
  1650. const UnicodeString & LocalFileName, const UnicodeString & FileList) :
  1651. TFileCustomCommand(Data, RemotePath, FileName, FileList)
  1652. {
  1653. FLocalPath = LocalPath;
  1654. FLocalFileName = LocalFileName;
  1655. }
  1656. //---------------------------------------------------------------------------
  1657. int __fastcall TLocalCustomCommand::PatternLen(const UnicodeString & Command, int Index)
  1658. {
  1659. int Len;
  1660. if ((Index < Command.Length()) && (Command[Index + 1] == L'\\'))
  1661. {
  1662. Len = 2;
  1663. }
  1664. else if ((Index < Command.Length()) && (Command[Index + 1] == L'^'))
  1665. {
  1666. Len = 3;
  1667. }
  1668. else
  1669. {
  1670. Len = TFileCustomCommand::PatternLen(Command, Index);
  1671. }
  1672. return Len;
  1673. }
  1674. //---------------------------------------------------------------------------
  1675. bool __fastcall TLocalCustomCommand::PatternReplacement(
  1676. int Index, const UnicodeString & Pattern, UnicodeString & Replacement, bool & Delimit)
  1677. {
  1678. bool Result;
  1679. if (Pattern == L"!\\")
  1680. {
  1681. // When used as "!\" in an argument to PowerShell, the trailing \ would escape the ",
  1682. // so we exclude it
  1683. Replacement = ExcludeTrailingBackslash(FLocalPath);
  1684. Result = true;
  1685. }
  1686. else if (Pattern == L"!^!")
  1687. {
  1688. Replacement = FLocalFileName;
  1689. Result = true;
  1690. }
  1691. else
  1692. {
  1693. Result = TFileCustomCommand::PatternReplacement(Index, Pattern, Replacement, Delimit);
  1694. }
  1695. return Result;
  1696. }
  1697. //---------------------------------------------------------------------------
  1698. void __fastcall TLocalCustomCommand::DelimitReplacement(
  1699. UnicodeString & /*Replacement*/, wchar_t /*Quote*/)
  1700. {
  1701. // never delimit local commands
  1702. }
  1703. //---------------------------------------------------------------------------
  1704. bool __fastcall TLocalCustomCommand::HasLocalFileName(const UnicodeString & Command)
  1705. {
  1706. return FindPattern(Command, L'^');
  1707. }
  1708. //---------------------------------------------------------------------------
  1709. bool __fastcall TLocalCustomCommand::IsFileCommand(const UnicodeString & Command)
  1710. {
  1711. return TFileCustomCommand::IsFileCommand(Command) || HasLocalFileName(Command);
  1712. }
  1713. //---------------------------------------------------------------------------
  1714. //---------------------------------------------------------------------------
  1715. typedef std::set<TDataModule *> TImagesModules;
  1716. static TImagesModules ImagesModules;
  1717. static std::map<int, TPngImageList *> AnimationsImages;
  1718. static std::map<int, TImageList *> ButtonImages;
  1719. static std::map<int, TPngImageList *> DialogImages;
  1720. //---------------------------------------------------------------------------
  1721. int __fastcall DoNormalizePixelsPerInch(int PixelsPerInch, bool Larger)
  1722. {
  1723. if (PixelsPerInch >= 192)
  1724. {
  1725. PixelsPerInch = 192;
  1726. }
  1727. else if (PixelsPerInch >= 144)
  1728. {
  1729. PixelsPerInch = Larger ? 192 : 144;
  1730. }
  1731. else if (PixelsPerInch >= 120)
  1732. {
  1733. PixelsPerInch = Larger ? 144 : 120;
  1734. }
  1735. else
  1736. {
  1737. PixelsPerInch = Larger ? 120 : 96;
  1738. }
  1739. return PixelsPerInch;
  1740. }
  1741. //---------------------------------------------------------------------------
  1742. int NormalizePixelsPerInch(int PixelsPerInch)
  1743. {
  1744. return DoNormalizePixelsPerInch(PixelsPerInch, false);
  1745. }
  1746. //---------------------------------------------------------------------------
  1747. int LargerPixelsPerInch(int PixelsPerInch, int Larger)
  1748. {
  1749. int Result = PixelsPerInch;
  1750. while (Larger > 0)
  1751. {
  1752. Result = DoNormalizePixelsPerInch(Result, true);
  1753. Larger--;
  1754. }
  1755. return Result;
  1756. }
  1757. //---------------------------------------------------------------------------
  1758. static int __fastcall NeedImagesModule(TControl * Control)
  1759. {
  1760. int PixelsPerInch = NormalizePixelsPerInch(GetControlPixelsPerInch(Control));
  1761. if (AnimationsImages.find(PixelsPerInch) == AnimationsImages.end())
  1762. {
  1763. TDataModule * ImagesModule;
  1764. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  1765. try
  1766. {
  1767. if (PixelsPerInch == 192)
  1768. {
  1769. ImagesModule = new TAnimations192Module(Application);
  1770. }
  1771. else if (PixelsPerInch == 144)
  1772. {
  1773. ImagesModule = new TAnimations144Module(Application);
  1774. }
  1775. else if (PixelsPerInch == 120)
  1776. {
  1777. ImagesModule = new TAnimations120Module(Application);
  1778. }
  1779. else
  1780. {
  1781. DebugAssert(PixelsPerInch == 96);
  1782. ImagesModule = new TAnimations96Module(Application);
  1783. }
  1784. ImagesModules.insert(ImagesModule);
  1785. TPngImageList * AAnimationImages =
  1786. DebugNotNull(dynamic_cast<TPngImageList *>(ImagesModule->FindComponent(L"AnimationImages")));
  1787. AnimationsImages.insert(std::make_pair(PixelsPerInch, AAnimationImages));
  1788. TImageList * AButtonImages =
  1789. DebugNotNull(dynamic_cast<TImageList *>(ImagesModule->FindComponent(L"ButtonImages")));
  1790. ButtonImages.insert(std::make_pair(PixelsPerInch, AButtonImages));
  1791. TPngImageList * ADialogImages =
  1792. DebugNotNull(dynamic_cast<TPngImageList *>(ImagesModule->FindComponent(L"DialogImages")));
  1793. DialogImages.insert(std::make_pair(PixelsPerInch, ADialogImages));
  1794. }
  1795. __finally
  1796. {
  1797. GUIConfiguration->ChangeResourceModule(ResourceModule);
  1798. }
  1799. }
  1800. return PixelsPerInch;
  1801. }
  1802. //---------------------------------------------------------------------------
  1803. TPngImageList * __fastcall GetAnimationsImages(TControl * Control)
  1804. {
  1805. int PixelsPerInch = NeedImagesModule(Control);
  1806. return DebugNotNull(AnimationsImages[PixelsPerInch]);
  1807. }
  1808. //---------------------------------------------------------------------------
  1809. TImageList * __fastcall GetButtonImages(TControl * Control)
  1810. {
  1811. int PixelsPerInch = NeedImagesModule(Control);
  1812. return DebugNotNull(ButtonImages[PixelsPerInch]);
  1813. }
  1814. //---------------------------------------------------------------------------
  1815. TPngImageList * __fastcall GetDialogImages(TControl * Control)
  1816. {
  1817. int PixelsPerInch = NeedImagesModule(Control);
  1818. return DebugNotNull(DialogImages[PixelsPerInch]);
  1819. }
  1820. //---------------------------------------------------------------------------
  1821. void __fastcall ReleaseImagesModules()
  1822. {
  1823. TImagesModules::iterator i = ImagesModules.begin();
  1824. while (i != ImagesModules.end())
  1825. {
  1826. delete (*i);
  1827. i++;
  1828. }
  1829. ImagesModules.clear();
  1830. }
  1831. //---------------------------------------------------------------------------
  1832. __fastcall TFrameAnimation::TFrameAnimation()
  1833. {
  1834. FFirstFrame = -1;
  1835. }
  1836. //---------------------------------------------------------------------------
  1837. void __fastcall TFrameAnimation::Init(TPaintBox * PaintBox, const UnicodeString & Name)
  1838. {
  1839. FName = Name;
  1840. FPaintBox = PaintBox;
  1841. FPaintBox->ControlStyle = FPaintBox->ControlStyle << csOpaque;
  1842. DebugAssert((FPaintBox->OnPaint == NULL) || (FPaintBox->OnPaint == PaintBoxPaint));
  1843. FPaintBox->OnPaint = PaintBoxPaint;
  1844. SetRescaleFunction(FPaintBox, PaintBoxRescale, reinterpret_cast<TObject *>(this));
  1845. DoInit();
  1846. }
  1847. //---------------------------------------------------------------------------
  1848. void __fastcall TFrameAnimation::DoInit()
  1849. {
  1850. FImageList = GetAnimationsImages(FPaintBox);
  1851. FFirstFrame = -1;
  1852. FFirstLoopFrame = -1;
  1853. FPaintBox->Width = FImageList->Width;
  1854. FPaintBox->Height = FImageList->Height;
  1855. if (!FName.IsEmpty())
  1856. {
  1857. int Frame = 0;
  1858. while (Frame < FImageList->PngImages->Count)
  1859. {
  1860. UnicodeString FrameData = FImageList->PngImages->Items[Frame]->Name;
  1861. UnicodeString FrameName;
  1862. FrameName = CutToChar(FrameData, L'_', false);
  1863. if (SameText(FName, FrameName))
  1864. {
  1865. int FrameIndex = StrToInt(CutToChar(FrameData, L'_', false));
  1866. if (FFirstFrame < 0)
  1867. {
  1868. FFirstFrame = Frame;
  1869. }
  1870. if ((FFirstLoopFrame < 0) && (FrameIndex > 0))
  1871. {
  1872. FFirstLoopFrame = Frame;
  1873. }
  1874. FLastFrame = Frame;
  1875. }
  1876. else
  1877. {
  1878. if (FFirstFrame >= 0)
  1879. {
  1880. // optimization
  1881. break;
  1882. }
  1883. }
  1884. Frame++;
  1885. }
  1886. DebugAssert(FFirstFrame >= 0);
  1887. DebugAssert(FFirstLoopFrame >= 0);
  1888. }
  1889. Stop();
  1890. }
  1891. //---------------------------------------------------------------------------
  1892. void __fastcall TFrameAnimation::PaintBoxRescale(TComponent * /*Sender*/, TObject * Token)
  1893. {
  1894. TFrameAnimation * FrameAnimation = reinterpret_cast<TFrameAnimation *>(Token);
  1895. FrameAnimation->Rescale();
  1896. }
  1897. //---------------------------------------------------------------------------
  1898. void __fastcall TFrameAnimation::Rescale()
  1899. {
  1900. bool Started = (FTimer != NULL) && FTimer->Enabled;
  1901. DoInit();
  1902. if (Started)
  1903. {
  1904. Start();
  1905. }
  1906. }
  1907. //---------------------------------------------------------------------------
  1908. void __fastcall TFrameAnimation::Start()
  1909. {
  1910. if (FFirstFrame >= 0)
  1911. {
  1912. FNextFrameTick = GetTickCount();
  1913. CalculateNextFrameTick();
  1914. if (FTimer == NULL)
  1915. {
  1916. FTimer = new TTimer(GetParentForm(FPaintBox));
  1917. FTimer->Interval = static_cast<int>(GUIUpdateInterval);
  1918. FTimer->OnTimer = Timer;
  1919. }
  1920. else
  1921. {
  1922. // reset timer
  1923. FTimer->Enabled = false;
  1924. FTimer->Enabled = true;
  1925. }
  1926. }
  1927. }
  1928. //---------------------------------------------------------------------------
  1929. void __fastcall TFrameAnimation::Timer(TObject * /*Sender*/)
  1930. {
  1931. Animate();
  1932. }
  1933. //---------------------------------------------------------------------------
  1934. void __fastcall TFrameAnimation::PaintBoxPaint(TObject * Sender)
  1935. {
  1936. if (FFirstFrame >= 0)
  1937. {
  1938. // Double-buffered drawing to prevent flicker (as the images are transparent)
  1939. DebugUsedParam(Sender);
  1940. DebugAssert(FPaintBox == Sender);
  1941. DebugAssert(FPaintBox->ControlStyle.Contains(csOpaque));
  1942. std::unique_ptr<TBitmap> Bitmap(new TBitmap());
  1943. Bitmap->SetSize(FPaintBox->Width, FPaintBox->Height);
  1944. Bitmap->Canvas->Brush->Color = FPaintBox->Color;
  1945. TRect Rect(0, 0, Bitmap->Width, Bitmap->Height);
  1946. Bitmap->Canvas->FillRect(Rect);
  1947. TGraphic * Graphic = GetCurrentImage()->PngImage;
  1948. DebugAssert(Graphic->Width == FPaintBox->Width);
  1949. DebugAssert(Graphic->Height == FPaintBox->Height);
  1950. Bitmap->Canvas->Draw(0, 0, Graphic);
  1951. FPaintBox->Canvas->Draw(0, 0, Bitmap.get());
  1952. }
  1953. FPainted = true;
  1954. }
  1955. //---------------------------------------------------------------------------
  1956. void __fastcall TFrameAnimation::Repaint()
  1957. {
  1958. FPainted = false;
  1959. // If the form is not showing yet, the Paint() is not even called
  1960. FPaintBox->Repaint();
  1961. if (!FPainted)
  1962. {
  1963. // Paint later, alternatively we may keep trying Repaint() in Animate().
  1964. // See also a hack in TAuthenticateForm::Log.
  1965. FPaintBox->Invalidate();
  1966. }
  1967. }
  1968. //---------------------------------------------------------------------------
  1969. void __fastcall TFrameAnimation::Stop()
  1970. {
  1971. FNextFrameTick = std::numeric_limits<DWORD>::max();
  1972. FCurrentFrame = FFirstFrame;
  1973. Repaint();
  1974. if (FTimer != NULL)
  1975. {
  1976. FTimer->Enabled = false;
  1977. }
  1978. }
  1979. //---------------------------------------------------------------------------
  1980. void __fastcall TFrameAnimation::Animate()
  1981. {
  1982. if (FFirstFrame >= 0)
  1983. {
  1984. // UPGRADE: Use GetTickCount64() when we stop supporting Windows XP.
  1985. DWORD TickCount = GetTickCount();
  1986. // Keep in sync with an opposite condition at the end of the loop.
  1987. // We may skip some frames if we got stalled for a while
  1988. while (TickCount >= FNextFrameTick)
  1989. {
  1990. if (FCurrentFrame >= FLastFrame)
  1991. {
  1992. FCurrentFrame = FFirstLoopFrame;
  1993. }
  1994. else
  1995. {
  1996. FCurrentFrame++;
  1997. }
  1998. CalculateNextFrameTick();
  1999. Repaint();
  2000. }
  2001. }
  2002. }
  2003. //---------------------------------------------------------------------------
  2004. TPngImageCollectionItem * __fastcall TFrameAnimation::GetCurrentImage()
  2005. {
  2006. return FImageList->PngImages->Items[FCurrentFrame];
  2007. }
  2008. //---------------------------------------------------------------------------
  2009. void __fastcall TFrameAnimation::CalculateNextFrameTick()
  2010. {
  2011. TPngImageCollectionItem * ImageItem = GetCurrentImage();
  2012. UnicodeString Duration = ImageItem->Name;
  2013. CutToChar(Duration, L'_', false);
  2014. // skip index (is not really used)
  2015. CutToChar(Duration, L'_', false);
  2016. // This should overflow, when tick count wraps.
  2017. FNextFrameTick += StrToInt(Duration) * 10;
  2018. }
  2019. //---------------------------------------------------------------------------
  2020. //---------------------------------------------------------------------------
  2021. // Hints use:
  2022. // - Cleanup list tooltip (multi line)
  2023. // - Combo edit button
  2024. // - Transfer settings label (multi line, follows label size and font)
  2025. // - HintLabel (hint and persistent hint, multi line)
  2026. // - status bar hints
  2027. //---------------------------------------------------------------------------
  2028. __fastcall TScreenTipHintWindow::TScreenTipHintWindow(TComponent * Owner) :
  2029. THintWindow(Owner)
  2030. {
  2031. FParentPainting = false;
  2032. }
  2033. //---------------------------------------------------------------------------
  2034. int __fastcall TScreenTipHintWindow::GetTextFlags(TControl * Control)
  2035. {
  2036. return DT_LEFT | DT_WORDBREAK | DT_NOPREFIX | Control->DrawTextBiDiModeFlagsReadingOnly();
  2037. }
  2038. //---------------------------------------------------------------------------
  2039. bool __fastcall TScreenTipHintWindow::UseBoldShortHint(TControl * HintControl)
  2040. {
  2041. return
  2042. (dynamic_cast<TTBCustomDockableWindow *>(HintControl) != NULL) ||
  2043. (dynamic_cast<TTBPopupWindow *>(HintControl) != NULL) ||
  2044. (HintControl->Perform(WM_WANTS_SCREEN_TIPS, 0, 0) == 1);
  2045. }
  2046. //---------------------------------------------------------------------------
  2047. bool __fastcall TScreenTipHintWindow::IsPathLabel(TControl * HintControl)
  2048. {
  2049. return (dynamic_cast<TPathLabel *>(HintControl) != NULL);
  2050. }
  2051. //---------------------------------------------------------------------------
  2052. int __fastcall TScreenTipHintWindow::GetMargin(TControl * HintControl, const UnicodeString & Hint)
  2053. {
  2054. int Result;
  2055. if (HasLabelHintPopup(HintControl, Hint) || IsPathLabel(HintControl))
  2056. {
  2057. Result = 3;
  2058. }
  2059. else
  2060. {
  2061. Result = 6;
  2062. }
  2063. Result = ScaleByTextHeight(HintControl, Result);
  2064. return Result;
  2065. }
  2066. //---------------------------------------------------------------------------
  2067. TFont * __fastcall TScreenTipHintWindow::GetFont(TControl * HintControl, const UnicodeString & Hint)
  2068. {
  2069. TFont * Result;
  2070. if (HasLabelHintPopup(HintControl, Hint) || IsPathLabel(HintControl))
  2071. {
  2072. Result = reinterpret_cast<TLabel *>(dynamic_cast<TCustomLabel *>(HintControl))->Font;
  2073. }
  2074. else
  2075. {
  2076. FScaledHintFont.reset(new TFont());
  2077. FScaledHintFont->Assign(Screen->HintFont);
  2078. FScaledHintFont->Size = ScaleByPixelsPerInchFromSystem(FScaledHintFont->Size, HintControl);
  2079. Result = FScaledHintFont.get();
  2080. }
  2081. return Result;
  2082. }
  2083. //---------------------------------------------------------------------------
  2084. void __fastcall TScreenTipHintWindow::CalcHintTextRect(TControl * Control, TCanvas * Canvas, TRect & Rect, const UnicodeString & Hint)
  2085. {
  2086. const int Flags = DT_CALCRECT | GetTextFlags(Control);
  2087. DrawText(Canvas->Handle, Hint.c_str(), -1, &Rect, Flags);
  2088. }
  2089. //---------------------------------------------------------------------------
  2090. TRect __fastcall TScreenTipHintWindow::CalcHintRect(int MaxWidth, const UnicodeString AHint, void * AData)
  2091. {
  2092. TControl * HintControl = GetHintControl(AData);
  2093. int Margin = GetMargin(HintControl, AHint);
  2094. UnicodeString ShortHint;
  2095. UnicodeString LongHint;
  2096. SplitHint(HintControl, AHint, ShortHint, LongHint);
  2097. Canvas->Font->Assign(GetFont(HintControl, AHint));
  2098. // from XE6 Vcl.ScreenTips.pas, but absent in 11
  2099. const int cScreenTipTextOnlyWidth = 210;
  2100. const int ScreenTipTextOnlyWidth = ScaleByTextHeight(HintControl, cScreenTipTextOnlyWidth);
  2101. int LongHintMargin = 0; // shut up
  2102. bool HasLongHint = !LongHint.IsEmpty();
  2103. if (HasLongHint)
  2104. {
  2105. // double-margin on the right
  2106. LongHintMargin = (3 * Margin);
  2107. MaxWidth = ScreenTipTextOnlyWidth - LongHintMargin;
  2108. }
  2109. // Multi line short hints can be twice as wide, to not break the individual lines unless really necessary.
  2110. // (login site tree, clean up dialog list, preferences custom command list, persistent hint, etc).
  2111. // And they also can be twice as wide, to not break the individual lines unless really necessary.
  2112. if (ShortHint.Pos(L"\n") > 0)
  2113. {
  2114. MaxWidth *= 2;
  2115. }
  2116. bool HintPopup = HasLabelHintPopup(HintControl, AHint);
  2117. if (HintPopup)
  2118. {
  2119. MaxWidth = HintControl->Width;
  2120. }
  2121. if (UseBoldShortHint(HintControl))
  2122. {
  2123. Canvas->Font->Style = TFontStyles() << fsBold;
  2124. }
  2125. TRect ShortRect(0, 0, MaxWidth, 0);
  2126. CalcHintTextRect(this, Canvas, ShortRect, ShortHint);
  2127. Canvas->Font->Style = TFontStyles();
  2128. TRect Result;
  2129. if (!HasLongHint)
  2130. {
  2131. Result = ShortRect;
  2132. if (HintPopup)
  2133. {
  2134. Result.Right = MaxWidth + 2 * Margin;
  2135. }
  2136. else
  2137. {
  2138. Result.Right += 3 * Margin;
  2139. }
  2140. Result.Bottom += 2 * Margin;
  2141. }
  2142. else
  2143. {
  2144. const int LongIndentation = Margin * 3 / 2;
  2145. TRect LongRect(0, 0, MaxWidth - LongIndentation, 0);
  2146. CalcHintTextRect(this, Canvas, LongRect, LongHint);
  2147. Result.Right = Max(ScreenTipTextOnlyWidth, LongRect.Right + LongIndentation + LongHintMargin);
  2148. Result.Bottom = Margin + ShortRect.Height() + (Margin / 3 * 5) + LongRect.Height() + Margin;
  2149. }
  2150. // VCLCOPY: To counter the increase in THintWindow::ActivateHintData
  2151. Result.Bottom -= 4;
  2152. return Result;
  2153. }
  2154. //---------------------------------------------------------------------------
  2155. void __fastcall TScreenTipHintWindow::SplitHint(
  2156. TControl * HintControl, const UnicodeString & Hint, UnicodeString & ShortHint, UnicodeString & LongHint)
  2157. {
  2158. if (HasLabelHintPopup(HintControl, Hint))
  2159. {
  2160. ShortHint = HintControl->Hint;
  2161. }
  2162. else
  2163. {
  2164. ShortHint = GetShortHint(Hint);
  2165. LongHint = GetLongHintIfAny(Hint);
  2166. }
  2167. }
  2168. //---------------------------------------------------------------------------
  2169. void __fastcall TScreenTipHintWindow::ActivateHintData(const TRect & ARect, const UnicodeString AHint, void * AData)
  2170. {
  2171. FHintControl = GetHintControl(AData);
  2172. SplitHint(FHintControl, AHint, FShortHint, FLongHint);
  2173. FMargin = GetMargin(FHintControl, AHint);
  2174. FHintPopup = HasLabelHintPopup(FHintControl, AHint);
  2175. Canvas->Font->Assign(GetFont(FHintControl, AHint));
  2176. TRect Rect = ARect;
  2177. if (FHintPopup)
  2178. {
  2179. Rect.SetLocation(FHintControl->ClientToScreen(TPoint(-FMargin, -FMargin)));
  2180. }
  2181. if (IsPathLabel(FHintControl))
  2182. {
  2183. Rect.Offset(-FMargin, -FMargin);
  2184. }
  2185. THintWindow::ActivateHintData(Rect, FShortHint, AData);
  2186. }
  2187. //---------------------------------------------------------------------------
  2188. TControl * __fastcall TScreenTipHintWindow::GetHintControl(void * Data)
  2189. {
  2190. return reinterpret_cast<TControl *>(DebugNotNull(Data));
  2191. }
  2192. //---------------------------------------------------------------------------
  2193. UnicodeString __fastcall TScreenTipHintWindow::GetLongHintIfAny(const UnicodeString & AHint)
  2194. {
  2195. UnicodeString Result;
  2196. int P = Pos(L"|", AHint);
  2197. if (P > 0)
  2198. {
  2199. Result = GetLongHint(AHint);
  2200. }
  2201. return Result;
  2202. }
  2203. //---------------------------------------------------------------------------
  2204. void __fastcall TScreenTipHintWindow::Dispatch(void * AMessage)
  2205. {
  2206. TMessage * Message = static_cast<TMessage*>(AMessage);
  2207. switch (Message->Msg)
  2208. {
  2209. case WM_GETTEXTLENGTH:
  2210. if (FParentPainting)
  2211. {
  2212. // make THintWindow::Paint() not paint the Caption
  2213. Message->Result = 0;
  2214. }
  2215. else
  2216. {
  2217. THintWindow::Dispatch(AMessage);
  2218. }
  2219. break;
  2220. default:
  2221. THintWindow::Dispatch(AMessage);
  2222. break;
  2223. }
  2224. }
  2225. //---------------------------------------------------------------------------
  2226. void __fastcall TScreenTipHintWindow::Paint()
  2227. {
  2228. // paint frame/background
  2229. {
  2230. TAutoFlag ParentPaintingFlag(FParentPainting);
  2231. THintWindow::Paint();
  2232. }
  2233. const int Flags = GetTextFlags(this);
  2234. const int Margin = FMargin - 1; // 1 = border
  2235. TRect Rect = ClientRect;
  2236. Rect.Inflate(-Margin, -Margin);
  2237. if (!FHintPopup)
  2238. {
  2239. Rect.Right -= FMargin;
  2240. }
  2241. if (UseBoldShortHint(FHintControl))
  2242. {
  2243. Canvas->Font->Style = TFontStyles() << fsBold;
  2244. }
  2245. DrawText(Canvas->Handle, FShortHint.c_str(), -1, &Rect, Flags);
  2246. TRect ShortRect = Rect;
  2247. DrawText(Canvas->Handle, FShortHint.c_str(), -1, &ShortRect, DT_CALCRECT | Flags);
  2248. Canvas->Font->Style = TFontStyles();
  2249. if (!FLongHint.IsEmpty())
  2250. {
  2251. Rect.Left += FMargin * 3 / 2;
  2252. Rect.Top += ShortRect.Height() + (FMargin / 3 * 5);
  2253. DrawText(Canvas->Handle, FLongHint.c_str(), -1, &Rect, Flags);
  2254. }
  2255. }
  2256. //---------------------------------------------------------------------------
  2257. static int HideAccelFlag(TControl * Control)
  2258. {
  2259. //ask the top level window about its UI state
  2260. while (Control->Parent != NULL)
  2261. {
  2262. Control = Control->Parent;
  2263. }
  2264. int Result;
  2265. if (FLAGSET(Control->Perform(WM_QUERYUISTATE, 0, 0), UISF_HIDEACCEL))
  2266. {
  2267. Result = DT_HIDEPREFIX;
  2268. }
  2269. else
  2270. {
  2271. Result = 0;
  2272. }
  2273. return Result;
  2274. }
  2275. //---------------------------------------------------------------------------
  2276. //---------------------------------------------------------------------------
  2277. class TDarkUxThemeStyle : public TUxThemeStyle
  2278. {
  2279. public:
  2280. static TDarkUxThemeStyle * Instance();
  2281. protected:
  2282. virtual bool __fastcall DoDrawText(
  2283. HDC DC, const TThemedElementDetails & Details, const UnicodeString S, TRect & R, TTextFormat Flags,
  2284. const TStyleTextOptions & Options, int DPI);
  2285. private:
  2286. static std::unique_ptr<TDarkUxThemeStyle> FInstance;
  2287. };
  2288. //---------------------------------------------------------------------------
  2289. std::unique_ptr<TDarkUxThemeStyle> TDarkUxThemeStyle::FInstance;
  2290. //---------------------------------------------------------------------------
  2291. TDarkUxThemeStyle * TDarkUxThemeStyle::Instance()
  2292. {
  2293. if (FInstance.get() == NULL)
  2294. {
  2295. FInstance.reset(new TDarkUxThemeStyle());
  2296. }
  2297. return FInstance.get();
  2298. }
  2299. //---------------------------------------------------------------------------
  2300. bool __fastcall TDarkUxThemeStyle::DoDrawText(
  2301. HDC DC, const TThemedElementDetails & Details, const UnicodeString S, TRect & R, TTextFormat Flags,
  2302. const TStyleTextOptions & AOptions, int DPI)
  2303. {
  2304. TStyleTextOptions Options = AOptions;
  2305. Options.TextColor = GetWindowTextColor(GetBtnFaceColor());
  2306. Options.Flags << stfTextColor;
  2307. return TUxThemeStyle::DoDrawText(DC, Details, S, R, Flags, Options, DPI);
  2308. }
  2309. //---------------------------------------------------------------------------
  2310. //---------------------------------------------------------------------------
  2311. // For controls that need both custom VCL theme style and custom Windows theme.
  2312. // Currently the checkbox (custom VCL theme for light caption and custom Windows theme for dark more checkbox bitmaps).
  2313. // Current this handles only "button" theme.
  2314. // It's a singleton and can be used only for controls that share the same Windows theme (curently used with "explorer").
  2315. class TDarkExplorerUxThemeStyle : public TDarkUxThemeStyle
  2316. {
  2317. public:
  2318. static const UnicodeString ThemeName;
  2319. virtual __fastcall TDarkExplorerUxThemeStyle();
  2320. virtual __fastcall ~TDarkExplorerUxThemeStyle();
  2321. void SetControl(TWinControl * Control);
  2322. protected:
  2323. virtual NativeUInt __fastcall GetTheme(TThemedElement Element);
  2324. virtual NativeUInt __fastcall GetThemeForDPI(TThemedElement Element, int DPI);
  2325. virtual void __fastcall UpdateThemes();
  2326. virtual bool __fastcall DoDrawText(
  2327. HDC DC, const TThemedElementDetails & Details, const UnicodeString S, TRect & R, TTextFormat Flags,
  2328. const TStyleTextOptions & Options, int DPI);
  2329. protected:
  2330. typedef std::map<int, NativeUInt> TThemes;
  2331. TThemes FThemes;
  2332. bool FInitialized;
  2333. HWND FControlHandle;
  2334. int FTextFlags;
  2335. bool DoGetTheme(TThemedElement Element, int DPI, NativeUInt & Result);
  2336. void Clear();
  2337. };
  2338. //---------------------------------------------------------------------------
  2339. const UnicodeString TDarkExplorerUxThemeStyle::ThemeName = L"explorer";
  2340. //---------------------------------------------------------------------------
  2341. __fastcall TDarkExplorerUxThemeStyle::TDarkExplorerUxThemeStyle()
  2342. {
  2343. FControlHandle = NULL;
  2344. FTextFlags = 0;
  2345. FInitialized = true;
  2346. }
  2347. //---------------------------------------------------------------------------
  2348. __fastcall TDarkExplorerUxThemeStyle::~TDarkExplorerUxThemeStyle()
  2349. {
  2350. Clear();
  2351. }
  2352. //---------------------------------------------------------------------------
  2353. void TDarkExplorerUxThemeStyle::SetControl(TWinControl * Control)
  2354. {
  2355. // Handle is safer than a pointer
  2356. if (Control->HandleAllocated())
  2357. {
  2358. FControlHandle = Control->Handle;
  2359. // WORKAROUND - VCL does not hide accelerator of custom-styled (at least) checkboxes
  2360. FTextFlags = HideAccelFlag(Control);
  2361. }
  2362. else
  2363. {
  2364. FControlHandle = 0;
  2365. FTextFlags = 0;
  2366. }
  2367. }
  2368. //---------------------------------------------------------------------------
  2369. NativeUInt __fastcall TDarkExplorerUxThemeStyle::GetTheme(TThemedElement Element)
  2370. {
  2371. NativeUInt Result;
  2372. if (!DoGetTheme(Element, 0, Result))
  2373. {
  2374. Result = TDarkUxThemeStyle::GetTheme(Element);
  2375. }
  2376. return Result;
  2377. }
  2378. //---------------------------------------------------------------------------
  2379. NativeUInt __fastcall TDarkExplorerUxThemeStyle::GetThemeForDPI(TThemedElement Element, int DPI)
  2380. {
  2381. NativeUInt Result;
  2382. if (!DoGetTheme(Element, DPI, Result))
  2383. {
  2384. Result = TDarkUxThemeStyle::GetThemeForDPI(Element, DPI);
  2385. }
  2386. return Result;
  2387. }
  2388. //---------------------------------------------------------------------------
  2389. bool TDarkExplorerUxThemeStyle::DoGetTheme(TThemedElement Element, int DPI, NativeUInt & Result)
  2390. {
  2391. bool Handle = DebugAlwaysTrue(FControlHandle != 0) && DebugAlwaysTrue(Element == teButton);
  2392. if (Handle)
  2393. {
  2394. if (DPI == 0)
  2395. {
  2396. DPI = Screen->PixelsPerInch;
  2397. }
  2398. TThemes::const_iterator ITheme = FThemes.find(DPI);
  2399. if (ITheme != FThemes.end())
  2400. {
  2401. Result = ITheme->second;
  2402. }
  2403. else
  2404. {
  2405. if (!UseThemes())
  2406. {
  2407. Result = 0;
  2408. }
  2409. else
  2410. {
  2411. HTHEME Theme;
  2412. const wchar_t * ClassName = L"button";
  2413. if (!IsWin10() || !IsWin10Build(15063) || (DPI == Screen->PixelsPerInch))
  2414. {
  2415. Theme = OpenThemeData(FControlHandle, ClassName);
  2416. }
  2417. else
  2418. {
  2419. Theme = OpenThemeDataForDpi(FControlHandle, ClassName, DPI);
  2420. }
  2421. Result = reinterpret_cast<NativeUInt>(Theme);
  2422. }
  2423. FThemes.insert(std::make_pair(DPI, Result));
  2424. }
  2425. }
  2426. return Result;
  2427. }
  2428. //---------------------------------------------------------------------------
  2429. void TDarkExplorerUxThemeStyle::Clear()
  2430. {
  2431. TThemes Themes;
  2432. // TUxThemeStyle.UnloadThemeData implementation (FThemeDataUnLoading) imply
  2433. // that GetTheme might be called while unloading, so protecting against that
  2434. FThemes.swap(Themes);
  2435. TThemes::iterator I = Themes.begin();
  2436. while (I != Themes.end())
  2437. {
  2438. CloseThemeData(reinterpret_cast<HTHEME>(I->second));
  2439. ++I;
  2440. }
  2441. }
  2442. //---------------------------------------------------------------------------
  2443. void __fastcall TDarkExplorerUxThemeStyle::UpdateThemes()
  2444. {
  2445. TDarkUxThemeStyle::UpdateThemes();
  2446. // This is only ever called from the constructor, where FThemes is not initialized yet.
  2447. // It's not called for theme updates, as it is called only for the detault global app theme instance.
  2448. if (DebugAlwaysFalse(FInitialized))
  2449. {
  2450. Clear();
  2451. }
  2452. }
  2453. //---------------------------------------------------------------------------
  2454. bool __fastcall TDarkExplorerUxThemeStyle::DoDrawText(
  2455. HDC DC, const TThemedElementDetails & Details, const UnicodeString S, TRect & R, TTextFormat Flags,
  2456. const TStyleTextOptions & Options, int DPI)
  2457. {
  2458. int TextFlags = FTextFlags;
  2459. if (FLAGSET(TextFlags, DT_HIDEPREFIX))
  2460. {
  2461. TextFlags -= DT_HIDEPREFIX;
  2462. Flags << tfHidePrefix;
  2463. }
  2464. DebugAssert(TextFlags == 0);
  2465. DebugUsedParam(TextFlags);
  2466. return TDarkUxThemeStyle::DoDrawText(DC, Details, S, R, Flags, Options, DPI);
  2467. }
  2468. //---------------------------------------------------------------------------
  2469. static std::unique_ptr<TDarkExplorerUxThemeStyle> DarkExplorerUxThemeStyle;
  2470. //---------------------------------------------------------------------------
  2471. //---------------------------------------------------------------------------
  2472. // Based on:
  2473. // https://stackoverflow.com/q/6912424/850848
  2474. // https://stackoverflow.com/q/4685863/850848
  2475. class TUIStateAwareLabel : public TLabel
  2476. {
  2477. public:
  2478. __fastcall virtual TUIStateAwareLabel(TComponent * AOwner);
  2479. protected:
  2480. DYNAMIC void __fastcall DoDrawText(TRect & Rect, int Flags);
  2481. virtual void __fastcall Dispatch(void * AMessage);
  2482. };
  2483. //---------------------------------------------------------------------------
  2484. TLabel * CreateLabel(TComponent * AOwner)
  2485. {
  2486. return new TUIStateAwareLabel(AOwner);
  2487. }
  2488. //---------------------------------------------------------------------------
  2489. __fastcall TUIStateAwareLabel::TUIStateAwareLabel(TComponent * AOwner) :
  2490. TLabel(AOwner)
  2491. {
  2492. }
  2493. //---------------------------------------------------------------------------
  2494. void __fastcall TUIStateAwareLabel::DoDrawText(TRect & Rect, int Flags)
  2495. {
  2496. if (ShowAccelChar)
  2497. {
  2498. Flags = Flags | HideAccelFlag(this);
  2499. }
  2500. TLabel::DoDrawText(Rect, Flags);
  2501. }
  2502. //---------------------------------------------------------------------------
  2503. void __fastcall TUIStateAwareLabel::Dispatch(void * AMessage)
  2504. {
  2505. TMessage * Message = static_cast<TMessage*>(AMessage);
  2506. // WORKAROUND: Particularly when focusing csDropDownList-style combobox via label, there's no visual feedback
  2507. // that the combobox was selected (strangely, there is, when the previous focus was on TTreeView).
  2508. // For consistency, we enable focus display for all controls types (like checkboxes).
  2509. if (Message->Msg == CM_DIALOGCHAR)
  2510. {
  2511. bool WasFocused = (FocusControl != NULL) ? FocusControl->Focused() : false;
  2512. TLabel::Dispatch(AMessage);
  2513. if (!WasFocused && (FocusControl != NULL) && FocusControl->Focused())
  2514. {
  2515. TCustomForm * ParentForm = GetParentForm(this);
  2516. if (ParentForm != NULL)
  2517. {
  2518. ParentForm->Perform(WM_CHANGEUISTATE, MAKELONG(UIS_CLEAR, UISF_HIDEFOCUS), 0);
  2519. }
  2520. }
  2521. }
  2522. else
  2523. {
  2524. TLabel::Dispatch(AMessage);
  2525. }
  2526. }
  2527. //---------------------------------------------------------------------------
  2528. //---------------------------------------------------------------------------
  2529. template<typename T>
  2530. bool HandleMessageByDarkStyleHook(TMessage & Msg, TWinControl * Control, std::unique_ptr<T> & StyleHook)
  2531. {
  2532. bool Result = false;
  2533. if (Control->HandleAllocated() &&
  2534. !Control->ComponentState.Contains(csDestroying) &&
  2535. !Control->ControlState.Contains(csDestroyingHandle) &&
  2536. !Control->ControlStyle.Contains(csOverrideStylePaint) &&
  2537. UseDarkModeForControl(Control))
  2538. {
  2539. if (StyleHook.get() == NULL)
  2540. {
  2541. StyleHook.reset(new T(Control));
  2542. }
  2543. Result = StyleHook->HandleMessage(Msg);
  2544. }
  2545. return Result;
  2546. }
  2547. //---------------------------------------------------------------------------
  2548. void SetColorModeTheme(TWinControl * Control, const UnicodeString & DarkSubAppName)
  2549. {
  2550. if (UseDarkModeForControl(Control))
  2551. {
  2552. SetDarkModeTheme(Control, DarkSubAppName);
  2553. }
  2554. }
  2555. //---------------------------------------------------------------------------
  2556. void SetExplorerTheme(TWinControl * Button)
  2557. {
  2558. SetColorModeTheme(Button, TDarkExplorerUxThemeStyle::ThemeName);
  2559. }
  2560. //---------------------------------------------------------------------------
  2561. //---------------------------------------------------------------------------
  2562. class TDarkGroupBoxStyleHook : public TGroupBoxStyleHook
  2563. {
  2564. public:
  2565. __fastcall virtual TDarkGroupBoxStyleHook(TWinControl * AControl) :
  2566. TGroupBoxStyleHook(AControl)
  2567. {
  2568. }
  2569. protected:
  2570. virtual TCustomStyleServices * __fastcall StyleServices()
  2571. {
  2572. return TDarkUxThemeStyle::Instance();
  2573. }
  2574. };
  2575. //---------------------------------------------------------------------------
  2576. class TGroupBoxEx : public TGroupBox
  2577. {
  2578. protected:
  2579. virtual void __fastcall PaintWindow(HDC DC);
  2580. virtual void __fastcall WndProc(TMessage & Msg);
  2581. private:
  2582. std::unique_ptr<TDarkGroupBoxStyleHook> FStyleHook;
  2583. };
  2584. //---------------------------------------------------------------------------
  2585. void __fastcall TGroupBoxEx::WndProc(TMessage & Msg)
  2586. {
  2587. if (!HandleMessageByDarkStyleHook(Msg, this, FStyleHook))
  2588. {
  2589. TGroupBox::WndProc(Msg);
  2590. }
  2591. }
  2592. //---------------------------------------------------------------------------
  2593. void __fastcall TGroupBoxEx::PaintWindow(HDC DC)
  2594. {
  2595. if (UseDarkModeForControl(this))
  2596. {
  2597. std::unique_ptr<TCanvas> Canvas(new TCanvas());
  2598. Canvas->Handle = DC;
  2599. Canvas->Font = Font;
  2600. TRect Rect = ClientRect;
  2601. Canvas->Brush->Style = bsSolid;
  2602. Canvas->Brush->Color = GetBtnFaceColor();
  2603. Canvas->FillRect(Rect);
  2604. }
  2605. TGroupBox::PaintWindow(DC);
  2606. }
  2607. //---------------------------------------------------------------------------
  2608. //---------------------------------------------------------------------------
  2609. class TDarkCheckBoxStyleHook : public TCheckBoxStyleHook
  2610. {
  2611. public:
  2612. __fastcall virtual TDarkCheckBoxStyleHook(TWinControl * AControl);
  2613. protected:
  2614. virtual void __fastcall PaintBackground(TCanvas * Canvas);
  2615. virtual TCustomStyleServices * __fastcall StyleServices();
  2616. };
  2617. //---------------------------------------------------------------------------
  2618. class TCheckBoxEx : public TCheckBox
  2619. {
  2620. public:
  2621. __fastcall virtual TCheckBoxEx(TComponent * AOwner);
  2622. protected:
  2623. virtual void __fastcall WndProc(TMessage & Msg);
  2624. virtual void __fastcall CreateWnd();
  2625. private:
  2626. std::unique_ptr<TDarkCheckBoxStyleHook> FStyleHook;
  2627. };
  2628. //---------------------------------------------------------------------------
  2629. TCheckBox * CreateCheckBox(TComponent * AOwner)
  2630. {
  2631. return new TCheckBoxEx(AOwner);
  2632. }
  2633. //---------------------------------------------------------------------------
  2634. __fastcall TDarkCheckBoxStyleHook::TDarkCheckBoxStyleHook(TWinControl * AControl) :
  2635. TCheckBoxStyleHook(AControl)
  2636. {
  2637. }
  2638. //---------------------------------------------------------------------------
  2639. void __fastcall TDarkCheckBoxStyleHook::PaintBackground(TCanvas * Canvas)
  2640. {
  2641. Canvas->Brush->Style = bsSolid;
  2642. Canvas->Brush->Color = GetBtnFaceColor();
  2643. Canvas->FillRect(Rect(0, 0, Control->Width, Control->Height));
  2644. }
  2645. //---------------------------------------------------------------------------
  2646. TCustomStyleServices * __fastcall TDarkCheckBoxStyleHook::StyleServices()
  2647. {
  2648. if (DarkExplorerUxThemeStyle.get() == NULL)
  2649. {
  2650. DarkExplorerUxThemeStyle.reset(new TDarkExplorerUxThemeStyle());
  2651. }
  2652. DarkExplorerUxThemeStyle->SetControl(Control);
  2653. return DarkExplorerUxThemeStyle.get();
  2654. }
  2655. //---------------------------------------------------------------------------
  2656. //---------------------------------------------------------------------------
  2657. __fastcall TCheckBoxEx::TCheckBoxEx(TComponent * AOwner) :
  2658. TCheckBox(AOwner)
  2659. {
  2660. }
  2661. //---------------------------------------------------------------------------
  2662. void __fastcall TCheckBoxEx::CreateWnd()
  2663. {
  2664. TCheckBox::CreateWnd();
  2665. SetColorModeTheme(this, TDarkExplorerUxThemeStyle::ThemeName);
  2666. }
  2667. //---------------------------------------------------------------------------
  2668. void __fastcall TCheckBoxEx::WndProc(TMessage & Msg)
  2669. {
  2670. if (!HandleMessageByDarkStyleHook(Msg, this, FStyleHook))
  2671. {
  2672. TCheckBox::WndProc(Msg);
  2673. }
  2674. }
  2675. //---------------------------------------------------------------------------
  2676. //---------------------------------------------------------------------------
  2677. class TButtonEx : public TButton
  2678. {
  2679. public:
  2680. __fastcall virtual TButtonEx(TComponent * AOwner);
  2681. protected:
  2682. virtual void __fastcall CreateWnd();
  2683. };
  2684. //---------------------------------------------------------------------------
  2685. __fastcall TButtonEx::TButtonEx(TComponent * AOwner) :
  2686. TButton(AOwner)
  2687. {
  2688. }
  2689. //---------------------------------------------------------------------------
  2690. void __fastcall TButtonEx::CreateWnd()
  2691. {
  2692. TButton::CreateWnd();
  2693. SetExplorerTheme(this);
  2694. }
  2695. //---------------------------------------------------------------------------
  2696. TButton * CreateButton(TComponent * AOwner)
  2697. {
  2698. return new TButtonEx(AOwner);
  2699. }
  2700. //---------------------------------------------------------------------------
  2701. //---------------------------------------------------------------------------
  2702. class TEditEx : public TEdit
  2703. {
  2704. public:
  2705. __fastcall virtual TEditEx(TComponent * AOwner);
  2706. protected:
  2707. virtual void __fastcall CreateWnd();
  2708. };
  2709. //---------------------------------------------------------------------------
  2710. __fastcall TEditEx::TEditEx(TComponent * AOwner) :
  2711. TEdit(AOwner)
  2712. {
  2713. }
  2714. //---------------------------------------------------------------------------
  2715. void __fastcall TEditEx::CreateWnd()
  2716. {
  2717. TEdit::CreateWnd();
  2718. SetColorModeTheme(this, L"CFD");
  2719. }
  2720. //---------------------------------------------------------------------------
  2721. TEdit * CreateEdit(TComponent * AOwner)
  2722. {
  2723. return new TEditEx(AOwner);
  2724. }
  2725. //---------------------------------------------------------------------------
  2726. //---------------------------------------------------------------------------
  2727. class TMemoEx : public TMemo
  2728. {
  2729. public:
  2730. __fastcall virtual TMemoEx(TComponent * AOwner);
  2731. protected:
  2732. virtual void __fastcall CreateWnd();
  2733. };
  2734. //---------------------------------------------------------------------------
  2735. __fastcall TMemoEx::TMemoEx(TComponent * AOwner) :
  2736. TMemo(AOwner)
  2737. {
  2738. }
  2739. //---------------------------------------------------------------------------
  2740. void __fastcall TMemoEx::CreateWnd()
  2741. {
  2742. TMemo::CreateWnd();
  2743. SetColorModeTheme(this, L"CFD");
  2744. }
  2745. //---------------------------------------------------------------------------
  2746. TMemo * CreateMemo(TComponent * AOwner)
  2747. {
  2748. return new TMemoEx(AOwner);
  2749. }
  2750. //---------------------------------------------------------------------------
  2751. //---------------------------------------------------------------------------
  2752. void __fastcall FindComponentClass(
  2753. void *, TReader *, const UnicodeString DebugUsedArg(ClassName), TComponentClass & ComponentClass)
  2754. {
  2755. if (ComponentClass == __classid(TLabel))
  2756. {
  2757. ComponentClass = __classid(TUIStateAwareLabel);
  2758. }
  2759. else if (ComponentClass == __classid(TComboBox))
  2760. {
  2761. ComponentClass = __classid(TUIStateAwareComboBox);
  2762. }
  2763. else if (ComponentClass == __classid(TGroupBox))
  2764. {
  2765. ComponentClass = __classid(TGroupBoxEx);
  2766. }
  2767. else if (ComponentClass == __classid(TCheckBox))
  2768. {
  2769. ComponentClass = __classid(TCheckBoxEx);
  2770. }
  2771. else if (ComponentClass == __classid(TButton))
  2772. {
  2773. ComponentClass = __classid(TButtonEx);
  2774. }
  2775. else if (ComponentClass == __classid(TEdit))
  2776. {
  2777. ComponentClass = __classid(TEditEx);
  2778. }
  2779. else if (ComponentClass == __classid(TMemo))
  2780. {
  2781. ComponentClass = __classid(TMemoEx);
  2782. }
  2783. }
  2784. //---------------------------------------------------------------------------
  2785. bool CanShowTimeEstimate(TDateTime StartTime)
  2786. {
  2787. return (SecondsBetween(StartTime, Now()) >= 3);
  2788. }
  2789. //---------------------------------------------------------------------------
  2790. class TSystemRequiredThread : public TSignalThread
  2791. {
  2792. public:
  2793. TSystemRequiredThread();
  2794. void Required();
  2795. protected:
  2796. virtual bool __fastcall WaitForEvent();
  2797. virtual void __fastcall ProcessEvent();
  2798. private:
  2799. bool FRequired;
  2800. TDateTime FLastRequired;
  2801. };
  2802. //---------------------------------------------------------------------------
  2803. static std::unique_ptr<TCriticalSection> SystemRequiredThreadSection(TraceInitPtr(new TCriticalSection()));
  2804. static TSystemRequiredThread * SystemRequiredThread = NULL;
  2805. //---------------------------------------------------------------------------
  2806. TSystemRequiredThread::TSystemRequiredThread() :
  2807. TSignalThread(true), FRequired(false)
  2808. {
  2809. }
  2810. //---------------------------------------------------------------------------
  2811. void TSystemRequiredThread::Required()
  2812. {
  2813. // guarded in SystemRequired()
  2814. FLastRequired = Now();
  2815. TriggerEvent();
  2816. }
  2817. //---------------------------------------------------------------------------
  2818. bool __fastcall TSystemRequiredThread::WaitForEvent()
  2819. {
  2820. const int ExpireInterval = 5000;
  2821. bool Result = (TSignalThread::WaitForEvent(ExpireInterval) > 0);
  2822. if (!Result && !FTerminated)
  2823. {
  2824. TGuard Guard(SystemRequiredThreadSection.get());
  2825. if (!FTerminated && FRequired &&
  2826. (MilliSecondsBetween(Now(), FLastRequired) > ExpireInterval))
  2827. {
  2828. AppLog(L"System is not required");
  2829. SetThreadExecutionState(ES_CONTINUOUS);
  2830. FLastRequired = TDateTime();
  2831. FRequired = false;
  2832. }
  2833. }
  2834. return Result;
  2835. }
  2836. //---------------------------------------------------------------------------
  2837. void __fastcall TSystemRequiredThread::ProcessEvent()
  2838. {
  2839. TGuard Guard(SystemRequiredThreadSection.get());
  2840. if (!FRequired &&
  2841. (FLastRequired != TDateTime()))
  2842. {
  2843. AppLog(L"System is required");
  2844. SetThreadExecutionState(ES_SYSTEM_REQUIRED | ES_CONTINUOUS);
  2845. FRequired = true;
  2846. }
  2847. }
  2848. //---------------------------------------------------------------------------
  2849. void SystemRequired()
  2850. {
  2851. if (IsWin11())
  2852. {
  2853. TGuard Guard(SystemRequiredThreadSection.get());
  2854. if (SystemRequiredThread == NULL)
  2855. {
  2856. AppLog(L"Starting system required thread");
  2857. SystemRequiredThread = new TSystemRequiredThread();
  2858. SystemRequiredThread->Start();
  2859. }
  2860. SystemRequiredThread->Required();
  2861. }
  2862. else
  2863. {
  2864. SetThreadExecutionState(ES_SYSTEM_REQUIRED);
  2865. }
  2866. }
  2867. //---------------------------------------------------------------------------
  2868. void GUIFinalize()
  2869. {
  2870. TPuttyCleanupThread::Finalize();
  2871. TSystemRequiredThread * Thread;
  2872. {
  2873. TGuard Guard(SystemRequiredThreadSection.get());
  2874. Thread = SystemRequiredThread;
  2875. SystemRequiredThread = NULL;
  2876. }
  2877. if (Thread != NULL)
  2878. {
  2879. AppLog(L"Stopping system required thread");
  2880. Thread->Terminate();
  2881. Thread->WaitFor();
  2882. delete Thread;
  2883. }
  2884. }
  2885. //---------------------------------------------------------------------------
  2886. TCustomImageList * TreeViewImageList(TPngImageList * ImageList)
  2887. {
  2888. // WORKAROUND Prevent DPI scaling, see TCustomTreeView.SetImages
  2889. ImageList->Scaled = true;
  2890. return ImageList;
  2891. }