GUITools.cpp 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <shlobj.h>
  5. #include <Common.h>
  6. #include "GUITools.h"
  7. #include "GUIConfiguration.h"
  8. #include <TextsCore.h>
  9. #include <CoreMain.h>
  10. #include <SessionData.h>
  11. #include <WinInterface.h>
  12. #include <TbxUtils.hpp>
  13. #include <Math.hpp>
  14. #include <WebBrowserEx.hpp>
  15. #include <Tools.h>
  16. #include "PngImageList.hpp"
  17. #include <StrUtils.hpp>
  18. #include <limits>
  19. #include <Glyphs.h>
  20. #include <PasTools.hpp>
  21. #include <VCLCommon.h>
  22. #include <WinApi.h>
  23. #include <Vcl.ScreenTips.hpp>
  24. #include "Animations96.h"
  25. #include "Animations120.h"
  26. #include "Animations144.h"
  27. #include "Animations192.h"
  28. //---------------------------------------------------------------------------
  29. #pragma package(smart_init)
  30. //---------------------------------------------------------------------------
  31. extern const UnicodeString PageantTool = L"pageant.exe";
  32. extern const UnicodeString PuttygenTool = L"puttygen.exe";
  33. //---------------------------------------------------------------------------
  34. bool __fastcall FindFile(UnicodeString & Path)
  35. {
  36. bool Result = FileExists(ApiPath(Path));
  37. if (!Result)
  38. {
  39. UnicodeString ProgramFiles32 = IncludeTrailingBackslash(GetEnvironmentVariable(L"ProgramFiles"));
  40. UnicodeString ProgramFiles64 = IncludeTrailingBackslash(GetEnvironmentVariable(L"ProgramW6432"));
  41. if (!ProgramFiles32.IsEmpty() &&
  42. SameText(Path.SubString(1, ProgramFiles32.Length()), ProgramFiles32) &&
  43. !ProgramFiles64.IsEmpty())
  44. {
  45. UnicodeString Path64 =
  46. ProgramFiles64 + Path.SubString(ProgramFiles32.Length() + 1, Path.Length() - ProgramFiles32.Length());
  47. if (FileExists(ApiPath(Path64)))
  48. {
  49. Path = Path64;
  50. Result = true;
  51. }
  52. }
  53. }
  54. if (!Result)
  55. {
  56. UnicodeString Paths = GetEnvironmentVariable(L"PATH");
  57. if (!Paths.IsEmpty())
  58. {
  59. UnicodeString NewPath = FileSearch(ExtractFileName(Path), Paths);
  60. Result = !NewPath.IsEmpty();
  61. if (Result)
  62. {
  63. Path = NewPath;
  64. }
  65. }
  66. }
  67. return Result;
  68. }
  69. //---------------------------------------------------------------------------
  70. void __fastcall OpenSessionInPutty(const UnicodeString PuttyPath,
  71. TSessionData * SessionData)
  72. {
  73. UnicodeString Program, AParams, Dir;
  74. SplitCommand(PuttyPath, Program, AParams, Dir);
  75. Program = ExpandEnvironmentVariables(Program);
  76. if (FindFile(Program))
  77. {
  78. AParams = ExpandEnvironmentVariables(AParams);
  79. UnicodeString Password = GUIConfiguration->PuttyPassword ? SessionData->Password : UnicodeString();
  80. TCustomCommandData Data(SessionData, SessionData->UserName, Password);
  81. TRemoteCustomCommand RemoteCustomCommand(Data, SessionData->RemoteDirectory);
  82. TWinInteractiveCustomCommand InteractiveCustomCommand(
  83. &RemoteCustomCommand, L"PuTTY", UnicodeString());
  84. UnicodeString Params =
  85. RemoteCustomCommand.Complete(InteractiveCustomCommand.Complete(AParams, false), true);
  86. UnicodeString PuttyParams;
  87. if (!RemoteCustomCommand.IsSiteCommand(AParams))
  88. {
  89. if (IsUWP())
  90. {
  91. if ((SessionData->FSProtocol == fsFTP) && GUIConfiguration->TelnetForFtpInPutty)
  92. {
  93. AddToList(PuttyParams, L"-telnet", L" ");
  94. // PuTTY does not allow -pw for telnet
  95. Password = L"";
  96. }
  97. AddToList(PuttyParams, EscapePuttyCommandParam(SessionData->HostName), L" ");
  98. if (!SessionData->UserName.IsEmpty())
  99. {
  100. AddToList(PuttyParams, FORMAT(L"-l %s", (EscapePuttyCommandParam(SessionData->UserName))), L" ");
  101. }
  102. if ((SessionData->FSProtocol != fsFTP) && (SessionData->PortNumber != SshPortNumber))
  103. {
  104. AddToList(PuttyParams, FORMAT(L"-P %d", (SessionData->PortNumber)), L" ");
  105. }
  106. }
  107. else
  108. {
  109. UnicodeString SessionName;
  110. TRegistryStorage * Storage = NULL;
  111. TSessionData * ExportData = NULL;
  112. TRegistryStorage * SourceStorage = NULL;
  113. try
  114. {
  115. Storage = new TRegistryStorage(Configuration->PuttySessionsKey);
  116. Storage->AccessMode = smReadWrite;
  117. // make it compatible with putty
  118. Storage->MungeStringValues = false;
  119. Storage->ForceAnsi = true;
  120. if (Storage->OpenRootKey(true))
  121. {
  122. if (Storage->KeyExists(SessionData->StorageKey))
  123. {
  124. SessionName = SessionData->SessionName;
  125. }
  126. else
  127. {
  128. SourceStorage = new TRegistryStorage(Configuration->PuttySessionsKey);
  129. SourceStorage->MungeStringValues = false;
  130. SourceStorage->ForceAnsi = true;
  131. if (SourceStorage->OpenSubKey(StoredSessions->DefaultSettings->Name, false) &&
  132. Storage->OpenSubKey(GUIConfiguration->PuttySession, true))
  133. {
  134. Storage->Copy(SourceStorage);
  135. Storage->CloseSubKey();
  136. }
  137. ExportData = new TSessionData(L"");
  138. ExportData->Assign(SessionData);
  139. ExportData->Modified = true;
  140. ExportData->Name = GUIConfiguration->PuttySession;
  141. ExportData->WinTitle = SessionData->SessionName;
  142. ExportData->Password = L"";
  143. if (SessionData->FSProtocol == fsFTP)
  144. {
  145. if (GUIConfiguration->TelnetForFtpInPutty)
  146. {
  147. ExportData->PuttyProtocol = PuttyTelnetProtocol;
  148. ExportData->PortNumber = TelnetPortNumber;
  149. // PuTTY does not allow -pw for telnet
  150. Password = L"";
  151. }
  152. else
  153. {
  154. ExportData->PuttyProtocol = PuttySshProtocol;
  155. ExportData->PortNumber = SshPortNumber;
  156. }
  157. }
  158. ExportData->Save(Storage, true);
  159. SessionName = GUIConfiguration->PuttySession;
  160. }
  161. }
  162. }
  163. __finally
  164. {
  165. delete Storage;
  166. delete ExportData;
  167. delete SourceStorage;
  168. }
  169. UnicodeString LoadSwitch = L"-load";
  170. int P = Params.LowerCase().Pos(LoadSwitch + L" ");
  171. if ((P == 0) || ((P > 1) && (Params[P - 1] != L' ')))
  172. {
  173. AddToList(PuttyParams, FORMAT(L"%s %s", (LoadSwitch, EscapePuttyCommandParam(SessionName))), L" ");
  174. }
  175. }
  176. }
  177. if (!Password.IsEmpty() && !RemoteCustomCommand.IsPasswordCommand(AParams))
  178. {
  179. Password = NormalizeString(Password); // if password is empty, we should quote it always
  180. AddToList(PuttyParams, FORMAT(L"-pw %s", (EscapePuttyCommandParam(Password))), L" ");
  181. }
  182. AddToList(PuttyParams, Params, L" ");
  183. // PuTTY is started in its binary directory to allow relative paths in private key,
  184. // when opening PuTTY's own stored session.
  185. ExecuteShellChecked(Program, PuttyParams, true);
  186. }
  187. else
  188. {
  189. throw Exception(FMTLOAD(FILE_NOT_FOUND, (Program)));
  190. }
  191. }
  192. //---------------------------------------------------------------------------
  193. bool __fastcall FindTool(const UnicodeString & Name, UnicodeString & Path)
  194. {
  195. UnicodeString AppPath = IncludeTrailingBackslash(ExtractFilePath(Application->ExeName));
  196. Path = AppPath + Name;
  197. bool Result = true;
  198. if (!FileExists(ApiPath(Path)))
  199. {
  200. Path = AppPath + L"PuTTY\\" + Name;
  201. if (!FileExists(ApiPath(Path)))
  202. {
  203. Path = Name;
  204. if (!FindFile(Path))
  205. {
  206. Result = false;
  207. }
  208. }
  209. }
  210. return Result;
  211. }
  212. //---------------------------------------------------------------------------
  213. void __fastcall ExecuteTool(const UnicodeString & Name)
  214. {
  215. UnicodeString Path;
  216. if (!FindTool(Name, Path))
  217. {
  218. throw Exception(FMTLOAD(EXECUTE_APP_ERROR, (Name)));
  219. }
  220. ExecuteShellChecked(Path, L"");
  221. }
  222. //---------------------------------------------------------------------------
  223. TObjectList * StartCreationDirectoryMonitorsOnEachDrive(unsigned int Filter, TFileChangedEvent OnChanged)
  224. {
  225. std::unique_ptr<TObjectList> Result(new TObjectList());
  226. for (char Drive = FirstDrive; Drive <= LastDrive; Drive++)
  227. {
  228. std::unique_ptr<TDirectoryMonitor> Monitor(new TDirectoryMonitor(Application));
  229. TDriveInfoRec * DriveInfoRec = DriveInfo->Get(Drive);
  230. if (DriveInfoRec->Valid &&
  231. (DriveInfoRec->DriveType != DRIVE_CDROM) &&
  232. ((DriveInfoRec->DriveType != DRIVE_REMOVABLE) || (Drive >= FirstFixedDrive)))
  233. {
  234. try
  235. {
  236. Monitor->Path = DriveInfo->GetDriveRoot(Drive);
  237. Monitor->WatchSubtree = true;
  238. Monitor->WatchFilters = Filter;
  239. Monitor->OnCreated = OnChanged;
  240. Monitor->OnModified = OnChanged;
  241. Monitor->Active = true;
  242. Result->Add(Monitor.release());
  243. }
  244. catch (Exception & E)
  245. {
  246. // Ignore errors watching not-ready drives
  247. }
  248. }
  249. }
  250. return Result.release();
  251. }
  252. //---------------------------------------------------------------------------
  253. bool __fastcall CopyCommandToClipboard(const UnicodeString & Command)
  254. {
  255. bool Result = UseAlternativeFunction() && IsKeyPressed(VK_CONTROL);
  256. if (Result)
  257. {
  258. TInstantOperationVisualizer Visualizer;
  259. CopyToClipboard(Command);
  260. }
  261. return Result;
  262. }
  263. //---------------------------------------------------------------------------
  264. static bool __fastcall DoExecuteShell(const UnicodeString Path, const UnicodeString Params,
  265. bool ChangeWorkingDirectory, HANDLE * Handle)
  266. {
  267. bool Result = CopyCommandToClipboard(FormatCommand(Path, Params));
  268. if (Result)
  269. {
  270. if (Handle != NULL)
  271. {
  272. *Handle = NULL;
  273. }
  274. }
  275. else
  276. {
  277. UnicodeString Directory = ExtractFilePath(Path);
  278. TShellExecuteInfoW ExecuteInfo;
  279. memset(&ExecuteInfo, 0, sizeof(ExecuteInfo));
  280. ExecuteInfo.cbSize = sizeof(ExecuteInfo);
  281. ExecuteInfo.fMask =
  282. SEE_MASK_FLAG_NO_UI |
  283. FLAGMASK((Handle != NULL), SEE_MASK_NOCLOSEPROCESS);
  284. ExecuteInfo.hwnd = Application->Handle;
  285. ExecuteInfo.lpFile = (wchar_t*)Path.data();
  286. ExecuteInfo.lpParameters = (wchar_t*)Params.data();
  287. ExecuteInfo.lpDirectory = (ChangeWorkingDirectory ? Directory.c_str() : NULL);
  288. ExecuteInfo.nShow = SW_SHOW;
  289. Result = (ShellExecuteEx(&ExecuteInfo) != 0);
  290. if (Result)
  291. {
  292. if (Handle != NULL)
  293. {
  294. *Handle = ExecuteInfo.hProcess;
  295. }
  296. }
  297. }
  298. return Result;
  299. }
  300. //---------------------------------------------------------------------------
  301. void __fastcall ExecuteShellChecked(const UnicodeString Path, const UnicodeString Params, bool ChangeWorkingDirectory)
  302. {
  303. if (!DoExecuteShell(Path, Params, ChangeWorkingDirectory, NULL))
  304. {
  305. throw EOSExtException(FMTLOAD(EXECUTE_APP_ERROR, (Path)));
  306. }
  307. }
  308. //---------------------------------------------------------------------------
  309. void __fastcall ExecuteShellChecked(const UnicodeString Command)
  310. {
  311. UnicodeString Program, Params, Dir;
  312. SplitCommand(Command, Program, Params, Dir);
  313. ExecuteShellChecked(Program, Params);
  314. }
  315. //---------------------------------------------------------------------------
  316. bool __fastcall ExecuteShell(const UnicodeString Path, const UnicodeString Params,
  317. HANDLE & Handle)
  318. {
  319. return DoExecuteShell(Path, Params, false, &Handle);
  320. }
  321. //---------------------------------------------------------------------------
  322. void __fastcall ExecuteShellCheckedAndWait(const UnicodeString Command,
  323. TProcessMessagesEvent ProcessMessages)
  324. {
  325. UnicodeString Program, Params, Dir;
  326. SplitCommand(Command, Program, Params, Dir);
  327. HANDLE ProcessHandle;
  328. bool Result = DoExecuteShell(Program, Params, false, &ProcessHandle);
  329. if (!Result)
  330. {
  331. throw EOSExtException(FMTLOAD(EXECUTE_APP_ERROR, (Program)));
  332. }
  333. else
  334. {
  335. if (ProcessHandle != NULL) // only if command was copied to clipboard only
  336. {
  337. if (ProcessMessages != NULL)
  338. {
  339. unsigned long WaitResult;
  340. do
  341. {
  342. // Same as in ExecuteProcessAndReadOutput
  343. WaitResult = WaitForSingleObject(ProcessHandle, 200);
  344. if (WaitResult == WAIT_FAILED)
  345. {
  346. throw Exception(LoadStr(DOCUMENT_WAIT_ERROR));
  347. }
  348. ProcessMessages();
  349. }
  350. while (WaitResult == WAIT_TIMEOUT);
  351. }
  352. else
  353. {
  354. WaitForSingleObject(ProcessHandle, INFINITE);
  355. }
  356. }
  357. }
  358. }
  359. //---------------------------------------------------------------------------
  360. bool __fastcall SpecialFolderLocation(int PathID, UnicodeString & Path)
  361. {
  362. LPITEMIDLIST Pidl;
  363. wchar_t Buf[256];
  364. if (SHGetSpecialFolderLocation(NULL, PathID, &Pidl) == NO_ERROR &&
  365. SHGetPathFromIDList(Pidl, Buf))
  366. {
  367. Path = UnicodeString(Buf);
  368. return true;
  369. }
  370. return false;
  371. }
  372. //---------------------------------------------------------------------------
  373. UnicodeString __fastcall UniqTempDir(const UnicodeString BaseDir, const UnicodeString Identity,
  374. bool Mask)
  375. {
  376. DebugAssert(!BaseDir.IsEmpty());
  377. UnicodeString TempDir;
  378. do
  379. {
  380. TempDir = IncludeTrailingBackslash(BaseDir) + Identity;
  381. if (Mask)
  382. {
  383. TempDir += L"?????";
  384. }
  385. else
  386. {
  387. TempDir += IncludeTrailingBackslash(FormatDateTime(L"nnzzz", Now()));
  388. }
  389. }
  390. while (!Mask && DirectoryExists(ApiPath(TempDir)));
  391. return TempDir;
  392. }
  393. //---------------------------------------------------------------------------
  394. bool __fastcall DeleteDirectory(const UnicodeString DirName)
  395. {
  396. TSearchRecChecked sr;
  397. bool retval = true;
  398. if (FindFirstUnchecked(DirName + L"\\*", faAnyFile, sr) == 0) // VCL Function
  399. {
  400. if (FLAGSET(sr.Attr, faDirectory))
  401. {
  402. if (sr.Name != L"." && sr.Name != L"..")
  403. retval = DeleteDirectory(DirName + L"\\" + sr.Name);
  404. }
  405. else
  406. {
  407. retval = DeleteFile(ApiPath(DirName + L"\\" + sr.Name));
  408. }
  409. if (retval)
  410. {
  411. while (FindNextChecked(sr) == 0)
  412. { // VCL Function
  413. if (FLAGSET(sr.Attr, faDirectory))
  414. {
  415. if (sr.Name != L"." && sr.Name != L"..")
  416. retval = DeleteDirectory(DirName + L"\\" + sr.Name);
  417. }
  418. else
  419. {
  420. retval = DeleteFile(ApiPath(DirName + L"\\" + sr.Name));
  421. }
  422. if (!retval) break;
  423. }
  424. }
  425. }
  426. FindClose(sr);
  427. if (retval) retval = RemoveDir(ApiPath(DirName)); // VCL function
  428. return retval;
  429. }
  430. //---------------------------------------------------------------------------
  431. void __fastcall AddSessionColorImage(
  432. TCustomImageList * ImageList, TColor Color, int MaskIndex)
  433. {
  434. // This overly complex drawing is here to support color button on SiteAdvanced
  435. // dialog. There we use plain TImageList, instead of TPngImageList,
  436. // TButton does not work with transparent images
  437. // (not even TBitmap with Transparent = true)
  438. std::unique_ptr<TBitmap> MaskBitmap(new TBitmap());
  439. ImageList->GetBitmap(MaskIndex, MaskBitmap.get());
  440. std::unique_ptr<TPngImage> MaskImage(new TPngImage());
  441. MaskImage->Assign(MaskBitmap.get());
  442. std::unique_ptr<TPngImage> ColorImage(new TPngImage(COLOR_RGB, 16, ImageList->Width, ImageList->Height));
  443. TColor MaskTransparentColor = MaskImage->Pixels[0][0];
  444. TColor TransparentColor = MaskTransparentColor;
  445. // Expecting that the color to be replaced is in the centre of the image (HACK)
  446. TColor MaskColor = MaskImage->Pixels[ImageList->Width / 2][ImageList->Height / 2];
  447. for (int Y = 0; Y < ImageList->Height; Y++)
  448. {
  449. for (int X = 0; X < ImageList->Width; X++)
  450. {
  451. TColor SourceColor = MaskImage->Pixels[X][Y];
  452. TColor DestColor;
  453. // this branch is pointless as long as MaskTransparentColor and
  454. // TransparentColor are the same
  455. if (SourceColor == MaskTransparentColor)
  456. {
  457. DestColor = TransparentColor;
  458. }
  459. else if (SourceColor == MaskColor)
  460. {
  461. DestColor = Color;
  462. }
  463. else
  464. {
  465. DestColor = SourceColor;
  466. }
  467. ColorImage->Pixels[X][Y] = DestColor;
  468. }
  469. }
  470. std::unique_ptr<TBitmap> Bitmap(new TBitmap());
  471. Bitmap->SetSize(ImageList->Width, ImageList->Height);
  472. ColorImage->AssignTo(Bitmap.get());
  473. ImageList->AddMasked(Bitmap.get(), TransparentColor);
  474. }
  475. //---------------------------------------------------------------------------
  476. void __fastcall SetSubmenu(TTBXCustomItem * Item)
  477. {
  478. class TTBXPublicItem : public TTBXCustomItem
  479. {
  480. public:
  481. __property ItemStyle;
  482. };
  483. TTBXPublicItem * PublicItem = reinterpret_cast<TTBXPublicItem *>(Item);
  484. DebugAssert(PublicItem != NULL);
  485. // See TTBItemViewer.IsPtInButtonPart (called from TTBItemViewer.MouseDown)
  486. PublicItem->ItemStyle = PublicItem->ItemStyle << tbisSubmenu;
  487. }
  488. //---------------------------------------------------------------------------
  489. bool __fastcall IsEligibleForApplyingTabs(
  490. UnicodeString Line, int & TabPos, UnicodeString & Start, UnicodeString & Remaining)
  491. {
  492. bool Result = false;
  493. TabPos = Line.Pos(L"\t");
  494. if (TabPos > 0)
  495. {
  496. Remaining = Line.SubString(TabPos + 1, Line.Length() - TabPos);
  497. // WORKAROUND
  498. // Some translations still use obsolete hack of consecutive tabs to aling the contents.
  499. // Delete these, so that the following check does not fail on this
  500. while (Remaining.SubString(1, 1) == L"\t")
  501. {
  502. Remaining.Delete(1, 1);
  503. }
  504. // We do not have, not support, mutiple tabs on a single line
  505. if (DebugAlwaysTrue(Remaining.Pos(L"\t") == 0))
  506. {
  507. Start = Line.SubString(1, TabPos - 1);
  508. // WORKAROUND
  509. // Previously we padded the string before tab with spaces,
  510. // to aling the contents across multiple lines
  511. Start = Start.TrimRight();
  512. // at least two normal spaces for separation
  513. Start += L" ";
  514. Result = true;
  515. }
  516. }
  517. return Result;
  518. }
  519. //---------------------------------------------------------------------------
  520. static int __fastcall CalculateWidthByLength(UnicodeString Text, void * /*Arg*/)
  521. {
  522. return Text.Length();
  523. }
  524. //---------------------------------------------------------------------------
  525. void __fastcall ApplyTabs(
  526. UnicodeString & Text, wchar_t Padding,
  527. TCalculateWidth CalculateWidth, void * CalculateWidthArg)
  528. {
  529. if (CalculateWidth == NULL)
  530. {
  531. DebugAssert(CalculateWidthArg == NULL);
  532. CalculateWidth = CalculateWidthByLength;
  533. }
  534. std::unique_ptr<TStringList> Lines(TextToStringList(Text));
  535. int MaxWidth = -1;
  536. for (int Index = 0; Index < Lines->Count; Index++)
  537. {
  538. UnicodeString Line = Lines->Strings[Index];
  539. int TabPos;
  540. UnicodeString Start;
  541. UnicodeString Remaining;
  542. if (IsEligibleForApplyingTabs(Line, TabPos, Start, Remaining))
  543. {
  544. int Width = CalculateWidth(Start, CalculateWidthArg);
  545. MaxWidth = Max(MaxWidth, Width);
  546. }
  547. }
  548. // Optimization and also to prevent potential regression for texts without tabs
  549. if (MaxWidth >= 0)
  550. {
  551. for (int Index = 0; Index < Lines->Count; Index++)
  552. {
  553. UnicodeString Line = Lines->Strings[Index];
  554. int TabPos;
  555. UnicodeString Start;
  556. UnicodeString Remaining;
  557. if (IsEligibleForApplyingTabs(Line, TabPos, Start, Remaining))
  558. {
  559. int Width;
  560. int Iterations = 0;
  561. while ((Width = CalculateWidth(Start, CalculateWidthArg)) < MaxWidth)
  562. {
  563. int Wider = CalculateWidth(Start + Padding, CalculateWidthArg);
  564. // If padded string is wider than max width by more pixels
  565. // than non-padded string is shorter than max width
  566. if ((Wider > MaxWidth) && ((Wider - MaxWidth) > (MaxWidth - Width)))
  567. {
  568. break;
  569. }
  570. Start += Padding;
  571. Iterations++;
  572. // In rare case a tab is zero-width with some strange font (like HYLE)
  573. if (Iterations > 100)
  574. {
  575. break;
  576. }
  577. }
  578. Lines->Strings[Index] = Start + Remaining;
  579. }
  580. }
  581. Text = Lines->Text;
  582. // remove trailing newline
  583. Text = Text.TrimRight();
  584. }
  585. }
  586. //---------------------------------------------------------------------------
  587. static void __fastcall DoSelectScaledImageList(TImageList * ImageList)
  588. {
  589. TImageList * MatchingList = NULL;
  590. int MachingPixelsPerInch = 0;
  591. int PixelsPerInch = GetComponentPixelsPerInch(ImageList);
  592. for (int Index = 0; Index < ImageList->Owner->ComponentCount; Index++)
  593. {
  594. TImageList * OtherList = dynamic_cast<TImageList *>(ImageList->Owner->Components[Index]);
  595. if ((OtherList != NULL) &&
  596. (OtherList != ImageList) &&
  597. StartsStr(ImageList->Name, OtherList->Name))
  598. {
  599. UnicodeString OtherListPixelsPerInchStr =
  600. OtherList->Name.SubString(
  601. ImageList->Name.Length() + 1, OtherList->Name.Length() - ImageList->Name.Length());
  602. int OtherListPixelsPerInch = StrToInt(OtherListPixelsPerInchStr);
  603. if ((OtherListPixelsPerInch <= PixelsPerInch) &&
  604. ((MatchingList == NULL) ||
  605. (MachingPixelsPerInch < OtherListPixelsPerInch)))
  606. {
  607. MatchingList = OtherList;
  608. MachingPixelsPerInch = OtherListPixelsPerInch;
  609. }
  610. }
  611. }
  612. if (MatchingList != NULL)
  613. {
  614. UnicodeString ImageListBackupName = ImageList->Name + IntToStr(USER_DEFAULT_SCREEN_DPI);
  615. if (ImageList->Owner->FindComponent(ImageListBackupName) == NULL)
  616. {
  617. TImageList * ImageListBackup;
  618. TPngImageList * PngImageList = dynamic_cast<TPngImageList *>(ImageList);
  619. if (PngImageList != NULL)
  620. {
  621. ImageListBackup = new TPngImageList(ImageList->Owner);
  622. }
  623. else
  624. {
  625. ImageListBackup = new TImageList(ImageList->Owner);
  626. }
  627. ImageListBackup->Name = ImageListBackupName;
  628. ImageList->Owner->InsertComponent(ImageListBackup);
  629. CopyImageList(ImageListBackup, ImageList);
  630. }
  631. CopyImageList(ImageList, MatchingList);
  632. }
  633. }
  634. //---------------------------------------------------------------------------
  635. static void __fastcall ImageListRescale(TComponent * Sender, TObject * /*Token*/)
  636. {
  637. TImageList * ImageList = DebugNotNull(dynamic_cast<TImageList *>(Sender));
  638. DoSelectScaledImageList(ImageList);
  639. }
  640. //---------------------------------------------------------------------------
  641. void __fastcall SelectScaledImageList(TImageList * ImageList)
  642. {
  643. DoSelectScaledImageList(ImageList);
  644. SetRescaleFunction(ImageList, ImageListRescale);
  645. }
  646. //---------------------------------------------------------------------------
  647. void __fastcall CopyImageList(TImageList * TargetList, TImageList * SourceList)
  648. {
  649. // Maybe this is not necessary, once the TPngImageList::Assign was fixed
  650. TPngImageList * PngTargetList = dynamic_cast<TPngImageList *>(TargetList);
  651. TPngImageList * PngSourceList = dynamic_cast<TPngImageList *>(SourceList);
  652. TargetList->Clear();
  653. TargetList->Height = SourceList->Height;
  654. TargetList->Width = SourceList->Width;
  655. if ((PngTargetList != NULL) && (PngSourceList != NULL))
  656. {
  657. // AddImages won't copy the names and we need them for
  658. // LoadDialogImage and TFrameAnimation
  659. PngTargetList->PngImages->Assign(PngSourceList->PngImages);
  660. }
  661. else
  662. {
  663. TargetList->AddImages(SourceList);
  664. }
  665. }
  666. //---------------------------------------------------------------------------
  667. static bool __fastcall DoLoadDialogImage(TImage * Image, const UnicodeString & ImageName)
  668. {
  669. bool Result = false;
  670. if (GlyphsModule != NULL)
  671. {
  672. TPngImageList * DialogImages = GetDialogImages(Image);
  673. int Index;
  674. for (Index = 0; Index < DialogImages->PngImages->Count; Index++)
  675. {
  676. TPngImageCollectionItem * PngItem = DialogImages->PngImages->Items[Index];
  677. if (SameText(PngItem->Name, ImageName))
  678. {
  679. Image->Picture->Assign(PngItem->PngImage);
  680. break;
  681. }
  682. }
  683. DebugAssert(Index < DialogImages->PngImages->Count);
  684. Result = true;
  685. }
  686. // When showing an exception from wWinMain, the images are released already.
  687. // Non-existence of the glyphs module is just a good indication of that.
  688. // We expect errors only.
  689. else if (ImageName == L"Error")
  690. {
  691. Image->Picture->Icon->Handle = LoadIcon(0, IDI_HAND);
  692. }
  693. // For showing an information about trace files
  694. else if (DebugAlwaysTrue(ImageName == L"Information"))
  695. {
  696. Image->Picture->Icon->Handle = LoadIcon(0, IDI_APPLICATION);
  697. }
  698. return Result;
  699. }
  700. //---------------------------------------------------------------------------
  701. class TDialogImageName : public TObject
  702. {
  703. public:
  704. UnicodeString ImageName;
  705. };
  706. //---------------------------------------------------------------------------
  707. static void __fastcall DialogImageRescale(TComponent * Sender, TObject * Token)
  708. {
  709. TImage * Image = DebugNotNull(dynamic_cast<TImage *>(Sender));
  710. TDialogImageName * DialogImageName = DebugNotNull(dynamic_cast<TDialogImageName *>(Token));
  711. DoLoadDialogImage(Image, DialogImageName->ImageName);
  712. }
  713. //---------------------------------------------------------------------------
  714. void __fastcall LoadDialogImage(TImage * Image, const UnicodeString & ImageName)
  715. {
  716. if (DoLoadDialogImage(Image, ImageName))
  717. {
  718. TDialogImageName * DialogImageName = new TDialogImageName();
  719. DialogImageName->ImageName = ImageName;
  720. SetRescaleFunction(Image, DialogImageRescale, DialogImageName, true);
  721. }
  722. }
  723. //---------------------------------------------------------------------------
  724. int __fastcall DialogImageSize(TForm * Form)
  725. {
  726. return ScaleByPixelsPerInch(32, Form);
  727. }
  728. //---------------------------------------------------------------------------
  729. void __fastcall HideComponentsPanel(TForm * Form)
  730. {
  731. TComponent * Component = DebugNotNull(Form->FindComponent(L"ComponentsPanel"));
  732. TPanel * Panel = DebugNotNull(dynamic_cast<TPanel *>(Component));
  733. DebugAssert(Panel->Align == alBottom);
  734. int Offset = Panel->Height;
  735. Panel->Visible = false;
  736. Panel->Height = 0;
  737. Form->Height -= Offset;
  738. for (int Index = 0; Index < Form->ControlCount; Index++)
  739. {
  740. TControl * Control = Form->Controls[Index];
  741. // Shift back bottom-anchored controls
  742. // (needed for toolbar panel on Progress window and buttons on Preferences dialog),
  743. if ((Control->Align == alNone) &&
  744. Control->Anchors.Contains(akBottom) &&
  745. !Control->Anchors.Contains(akTop))
  746. {
  747. Control->Top += Offset;
  748. }
  749. // Resize back all-anchored controls
  750. // (needed for main panel on Preferences dialog),
  751. if (Control->Anchors.Contains(akBottom) &&
  752. Control->Anchors.Contains(akTop))
  753. {
  754. Control->Height += Offset;
  755. }
  756. }
  757. }
  758. //---------------------------------------------------------------------------
  759. class TBrowserViewer : public TWebBrowserEx
  760. {
  761. public:
  762. __fastcall virtual TBrowserViewer(TComponent* AOwner);
  763. void __fastcall AddLinkHandler(
  764. const UnicodeString & Url, TNotifyEvent Handler);
  765. void __fastcall NavigateToUrl(const UnicodeString & Url);
  766. TControl * LoadingPanel;
  767. protected:
  768. DYNAMIC void __fastcall DoContextPopup(const TPoint & MousePos, bool & Handled);
  769. void __fastcall DocumentComplete(
  770. TObject * Sender, const _di_IDispatch Disp, const OleVariant & URL);
  771. void __fastcall BeforeNavigate2(
  772. TObject * Sender, const _di_IDispatch Disp, const OleVariant & URL,
  773. const OleVariant & Flags, const OleVariant & TargetFrameName,
  774. const OleVariant & PostData, const OleVariant & Headers, WordBool & Cancel);
  775. bool FComplete;
  776. std::map<UnicodeString, TNotifyEvent> FHandlers;
  777. };
  778. //---------------------------------------------------------------------------
  779. __fastcall TBrowserViewer::TBrowserViewer(TComponent* AOwner) :
  780. TWebBrowserEx(AOwner)
  781. {
  782. FComplete = false;
  783. OnDocumentComplete = DocumentComplete;
  784. OnBeforeNavigate2 = BeforeNavigate2;
  785. LoadingPanel = NULL;
  786. }
  787. //---------------------------------------------------------------------------
  788. void __fastcall TBrowserViewer::AddLinkHandler(
  789. const UnicodeString & Url, TNotifyEvent Handler)
  790. {
  791. FHandlers.insert(std::make_pair(Url, Handler));
  792. }
  793. //---------------------------------------------------------------------------
  794. void __fastcall TBrowserViewer::DoContextPopup(const TPoint & MousePos, bool & Handled)
  795. {
  796. // suppress built-in context menu
  797. Handled = true;
  798. TWebBrowserEx::DoContextPopup(MousePos, Handled);
  799. }
  800. //---------------------------------------------------------------------------
  801. void __fastcall TBrowserViewer::DocumentComplete(
  802. TObject * /*Sender*/, const _di_IDispatch /*Disp*/, const OleVariant & /*URL*/)
  803. {
  804. SetBrowserDesignModeOff(this);
  805. FComplete = true;
  806. if (LoadingPanel != NULL)
  807. {
  808. LoadingPanel->Visible = false;
  809. }
  810. }
  811. //---------------------------------------------------------------------------
  812. void __fastcall TBrowserViewer::BeforeNavigate2(
  813. TObject * /*Sender*/, const _di_IDispatch /*Disp*/, const OleVariant & AURL,
  814. const OleVariant & /*Flags*/, const OleVariant & /*TargetFrameName*/,
  815. const OleVariant & /*PostData*/, const OleVariant & /*Headers*/, WordBool & Cancel)
  816. {
  817. // If OnDocumentComplete was not called yet, is has to be our initial message URL,
  818. // opened using TWebBrowserEx::Navigate(), allow it.
  819. // Otherwise it's user navigating, block that and open link
  820. // in an external browser, possibly adding campaign parameters on the way.
  821. if (FComplete)
  822. {
  823. Cancel = 1;
  824. UnicodeString URL = AURL;
  825. if (FHandlers.count(URL) > 0)
  826. {
  827. FHandlers[URL](this);
  828. }
  829. else
  830. {
  831. OpenBrowser(URL);
  832. }
  833. }
  834. }
  835. //---------------------------------------------------------------------------
  836. void __fastcall TBrowserViewer::NavigateToUrl(const UnicodeString & Url)
  837. {
  838. FComplete = false;
  839. Navigate(Url.c_str());
  840. }
  841. //---------------------------------------------------------------------------
  842. TPanel * __fastcall CreateLabelPanel(TPanel * Parent, const UnicodeString & Label)
  843. {
  844. TPanel * Result = CreateBlankPanel(Parent);
  845. Result->Parent = Parent;
  846. Result->Align = alClient;
  847. Result->Caption = Label;
  848. return Result;
  849. }
  850. //---------------------------------------------------------------------------
  851. TWebBrowserEx * __fastcall CreateBrowserViewer(TPanel * Parent, const UnicodeString & LoadingLabel)
  852. {
  853. TBrowserViewer * Result = new TBrowserViewer(Parent);
  854. // TWebBrowserEx has its own unrelated Name and Parent properties.
  855. // The name is used in DownloadUpdate().
  856. static_cast<TWinControl *>(Result)->Name = L"BrowserViewer";
  857. static_cast<TWinControl *>(Result)->Parent = Parent;
  858. Result->Align = alClient;
  859. Result->ControlBorder = cbNone;
  860. Result->LoadingPanel = CreateLabelPanel(Parent, LoadingLabel);
  861. return Result;
  862. }
  863. //---------------------------------------------------------------------------
  864. void __fastcall SetBrowserDesignModeOff(TWebBrowserEx * WebBrowser)
  865. {
  866. if (DebugAlwaysTrue(WebBrowser->Document2 != NULL))
  867. {
  868. WebBrowser->Document2->designMode = L"Off";
  869. }
  870. }
  871. //---------------------------------------------------------------------------
  872. void __fastcall AddBrowserLinkHandler(TWebBrowserEx * WebBrowser,
  873. const UnicodeString & Url, TNotifyEvent Handler)
  874. {
  875. TBrowserViewer * BrowserViewer = dynamic_cast<TBrowserViewer *>(WebBrowser);
  876. if (DebugAlwaysTrue(BrowserViewer != NULL))
  877. {
  878. BrowserViewer->AddLinkHandler(Url, Handler);
  879. }
  880. }
  881. //---------------------------------------------------------------------------
  882. void __fastcall NavigateBrowserToUrl(TWebBrowserEx * WebBrowser, const UnicodeString & Url)
  883. {
  884. TBrowserViewer * BrowserViewer = dynamic_cast<TBrowserViewer *>(WebBrowser);
  885. if (DebugAlwaysTrue(BrowserViewer != NULL))
  886. {
  887. BrowserViewer->NavigateToUrl(Url);
  888. }
  889. }
  890. //---------------------------------------------------------------------------
  891. TComponent * __fastcall FindComponentRecursively(TComponent * Root, const UnicodeString & Name)
  892. {
  893. for (int Index = 0; Index < Root->ComponentCount; Index++)
  894. {
  895. TComponent * Component = Root->Components[Index];
  896. if (CompareText(Component->Name, Name) == 0)
  897. {
  898. return Component;
  899. }
  900. Component = FindComponentRecursively(Component, Name);
  901. if (Component != NULL)
  902. {
  903. return Component;
  904. }
  905. }
  906. return NULL;
  907. }
  908. //---------------------------------------------------------------------------
  909. TLocalCustomCommand::TLocalCustomCommand()
  910. {
  911. }
  912. //---------------------------------------------------------------------------
  913. TLocalCustomCommand::TLocalCustomCommand(
  914. const TCustomCommandData & Data, const UnicodeString & RemotePath, const UnicodeString & LocalPath) :
  915. TFileCustomCommand(Data, RemotePath)
  916. {
  917. FLocalPath = LocalPath;
  918. }
  919. //---------------------------------------------------------------------------
  920. TLocalCustomCommand::TLocalCustomCommand(const TCustomCommandData & Data,
  921. const UnicodeString & RemotePath, const UnicodeString & LocalPath, const UnicodeString & FileName,
  922. const UnicodeString & LocalFileName, const UnicodeString & FileList) :
  923. TFileCustomCommand(Data, RemotePath, FileName, FileList)
  924. {
  925. FLocalPath = LocalPath;
  926. FLocalFileName = LocalFileName;
  927. }
  928. //---------------------------------------------------------------------------
  929. int __fastcall TLocalCustomCommand::PatternLen(const UnicodeString & Command, int Index)
  930. {
  931. int Len;
  932. if ((Index < Command.Length()) && (Command[Index + 1] == L'\\'))
  933. {
  934. Len = 2;
  935. }
  936. else if ((Index < Command.Length()) && (Command[Index + 1] == L'^'))
  937. {
  938. Len = 3;
  939. }
  940. else
  941. {
  942. Len = TFileCustomCommand::PatternLen(Command, Index);
  943. }
  944. return Len;
  945. }
  946. //---------------------------------------------------------------------------
  947. bool __fastcall TLocalCustomCommand::PatternReplacement(
  948. int Index, const UnicodeString & Pattern, UnicodeString & Replacement, bool & Delimit)
  949. {
  950. bool Result;
  951. if (Pattern == L"!\\")
  952. {
  953. // When used as "!\" in an argument to PowerShell, the trailing \ would escpae the ",
  954. // so we exclude it
  955. Replacement = ExcludeTrailingBackslash(FLocalPath);
  956. Result = true;
  957. }
  958. else if (Pattern == L"!^!")
  959. {
  960. Replacement = FLocalFileName;
  961. Result = true;
  962. }
  963. else
  964. {
  965. Result = TFileCustomCommand::PatternReplacement(Index, Pattern, Replacement, Delimit);
  966. }
  967. return Result;
  968. }
  969. //---------------------------------------------------------------------------
  970. void __fastcall TLocalCustomCommand::DelimitReplacement(
  971. UnicodeString & /*Replacement*/, wchar_t /*Quote*/)
  972. {
  973. // never delimit local commands
  974. }
  975. //---------------------------------------------------------------------------
  976. bool __fastcall TLocalCustomCommand::HasLocalFileName(const UnicodeString & Command)
  977. {
  978. return FindPattern(Command, L'^');
  979. }
  980. //---------------------------------------------------------------------------
  981. bool __fastcall TLocalCustomCommand::IsFileCommand(const UnicodeString & Command)
  982. {
  983. return TFileCustomCommand::IsFileCommand(Command) || HasLocalFileName(Command);
  984. }
  985. //---------------------------------------------------------------------------
  986. //---------------------------------------------------------------------------
  987. typedef std::set<TDataModule *> TImagesModules;
  988. static TImagesModules ImagesModules;
  989. static std::map<int, TPngImageList *> AnimationsImages;
  990. static std::map<int, TImageList *> ButtonImages;
  991. static std::map<int, TPngImageList *> DialogImages;
  992. //---------------------------------------------------------------------------
  993. int __fastcall NormalizePixelsPerInch(int PixelsPerInch)
  994. {
  995. if (PixelsPerInch >= 192)
  996. {
  997. PixelsPerInch = 192;
  998. }
  999. else if (PixelsPerInch >= 144)
  1000. {
  1001. PixelsPerInch = 144;
  1002. }
  1003. else if (PixelsPerInch >= 120)
  1004. {
  1005. PixelsPerInch = 120;
  1006. }
  1007. else
  1008. {
  1009. PixelsPerInch = 96;
  1010. }
  1011. return PixelsPerInch;
  1012. }
  1013. //---------------------------------------------------------------------------
  1014. static int __fastcall NeedImagesModule(TControl * Control)
  1015. {
  1016. int PixelsPerInch = NormalizePixelsPerInch(GetControlPixelsPerInch(Control));
  1017. if (AnimationsImages.find(PixelsPerInch) == AnimationsImages.end())
  1018. {
  1019. TDataModule * ImagesModule;
  1020. HANDLE ResourceModule = GUIConfiguration->ChangeToDefaultResourceModule();
  1021. try
  1022. {
  1023. if (PixelsPerInch == 192)
  1024. {
  1025. ImagesModule = new TAnimations192Module(Application);
  1026. }
  1027. else if (PixelsPerInch == 144)
  1028. {
  1029. ImagesModule = new TAnimations144Module(Application);
  1030. }
  1031. else if (PixelsPerInch == 120)
  1032. {
  1033. ImagesModule = new TAnimations120Module(Application);
  1034. }
  1035. else
  1036. {
  1037. DebugAssert(PixelsPerInch == 96);
  1038. ImagesModule = new TAnimations96Module(Application);
  1039. }
  1040. ImagesModules.insert(ImagesModule);
  1041. TPngImageList * AAnimationImages =
  1042. DebugNotNull(dynamic_cast<TPngImageList *>(ImagesModule->FindComponent(L"AnimationImages")));
  1043. AnimationsImages.insert(std::make_pair(PixelsPerInch, AAnimationImages));
  1044. TImageList * AButtonImages =
  1045. DebugNotNull(dynamic_cast<TImageList *>(ImagesModule->FindComponent(L"ButtonImages")));
  1046. ButtonImages.insert(std::make_pair(PixelsPerInch, AButtonImages));
  1047. TPngImageList * ADialogImages =
  1048. DebugNotNull(dynamic_cast<TPngImageList *>(ImagesModule->FindComponent(L"DialogImages")));
  1049. DialogImages.insert(std::make_pair(PixelsPerInch, ADialogImages));
  1050. }
  1051. __finally
  1052. {
  1053. GUIConfiguration->ChangeResourceModule(ResourceModule);
  1054. }
  1055. }
  1056. return PixelsPerInch;
  1057. }
  1058. //---------------------------------------------------------------------------
  1059. TPngImageList * __fastcall GetAnimationsImages(TControl * Control)
  1060. {
  1061. int PixelsPerInch = NeedImagesModule(Control);
  1062. return DebugNotNull(AnimationsImages[PixelsPerInch]);
  1063. }
  1064. //---------------------------------------------------------------------------
  1065. TImageList * __fastcall GetButtonImages(TControl * Control)
  1066. {
  1067. int PixelsPerInch = NeedImagesModule(Control);
  1068. return DebugNotNull(ButtonImages[PixelsPerInch]);
  1069. }
  1070. //---------------------------------------------------------------------------
  1071. TPngImageList * __fastcall GetDialogImages(TControl * Control)
  1072. {
  1073. int PixelsPerInch = NeedImagesModule(Control);
  1074. return DebugNotNull(DialogImages[PixelsPerInch]);
  1075. }
  1076. //---------------------------------------------------------------------------
  1077. void __fastcall ReleaseImagesModules()
  1078. {
  1079. TImagesModules::iterator i = ImagesModules.begin();
  1080. while (i != ImagesModules.end())
  1081. {
  1082. delete (*i);
  1083. i++;
  1084. }
  1085. ImagesModules.clear();
  1086. }
  1087. //---------------------------------------------------------------------------
  1088. __fastcall TFrameAnimation::TFrameAnimation()
  1089. {
  1090. FFirstFrame = -1;
  1091. }
  1092. //---------------------------------------------------------------------------
  1093. void __fastcall TFrameAnimation::Init(TPaintBox * PaintBox, const UnicodeString & Name)
  1094. {
  1095. FName = Name;
  1096. FPaintBox = PaintBox;
  1097. FPaintBox->ControlStyle = FPaintBox->ControlStyle << csOpaque;
  1098. DebugAssert((FPaintBox->OnPaint == NULL) || (FPaintBox->OnPaint == PaintBoxPaint));
  1099. FPaintBox->OnPaint = PaintBoxPaint;
  1100. SetRescaleFunction(FPaintBox, PaintBoxRescale, reinterpret_cast<TObject *>(this));
  1101. DoInit();
  1102. }
  1103. //---------------------------------------------------------------------------
  1104. void __fastcall TFrameAnimation::DoInit()
  1105. {
  1106. FImageList = GetAnimationsImages(FPaintBox);
  1107. FFirstFrame = -1;
  1108. FFirstLoopFrame = -1;
  1109. FPaintBox->Width = FImageList->Width;
  1110. FPaintBox->Height = FImageList->Height;
  1111. if (!FName.IsEmpty())
  1112. {
  1113. int Frame = 0;
  1114. while (Frame < FImageList->PngImages->Count)
  1115. {
  1116. UnicodeString FrameData = FImageList->PngImages->Items[Frame]->Name;
  1117. UnicodeString FrameName;
  1118. FrameName = CutToChar(FrameData, L'_', false);
  1119. if (SameText(FName, FrameName))
  1120. {
  1121. int FrameIndex = StrToInt(CutToChar(FrameData, L'_', false));
  1122. if (FFirstFrame < 0)
  1123. {
  1124. FFirstFrame = Frame;
  1125. }
  1126. if ((FFirstLoopFrame < 0) && (FrameIndex > 0))
  1127. {
  1128. FFirstLoopFrame = Frame;
  1129. }
  1130. FLastFrame = Frame;
  1131. }
  1132. else
  1133. {
  1134. if (FFirstFrame >= 0)
  1135. {
  1136. // optimization
  1137. break;
  1138. }
  1139. }
  1140. Frame++;
  1141. }
  1142. DebugAssert(FFirstFrame >= 0);
  1143. DebugAssert(FFirstLoopFrame >= 0);
  1144. }
  1145. Stop();
  1146. }
  1147. //---------------------------------------------------------------------------
  1148. void __fastcall TFrameAnimation::PaintBoxRescale(TComponent * /*Sender*/, TObject * Token)
  1149. {
  1150. TFrameAnimation * FrameAnimation = reinterpret_cast<TFrameAnimation *>(Token);
  1151. FrameAnimation->Rescale();
  1152. }
  1153. //---------------------------------------------------------------------------
  1154. void __fastcall TFrameAnimation::Rescale()
  1155. {
  1156. bool Started = (FTimer != NULL) && FTimer->Enabled;
  1157. DoInit();
  1158. if (Started)
  1159. {
  1160. Start();
  1161. }
  1162. }
  1163. //---------------------------------------------------------------------------
  1164. void __fastcall TFrameAnimation::Start()
  1165. {
  1166. if (FFirstFrame >= 0)
  1167. {
  1168. FNextFrameTick = GetTickCount();
  1169. CalculateNextFrameTick();
  1170. if (FTimer == NULL)
  1171. {
  1172. FTimer = new TTimer(GetParentForm(FPaintBox));
  1173. FTimer->Interval = static_cast<int>(GUIUpdateInterval);
  1174. FTimer->OnTimer = Timer;
  1175. }
  1176. else
  1177. {
  1178. // reset timer
  1179. FTimer->Enabled = false;
  1180. FTimer->Enabled = true;
  1181. }
  1182. }
  1183. }
  1184. //---------------------------------------------------------------------------
  1185. void __fastcall TFrameAnimation::Timer(TObject * /*Sender*/)
  1186. {
  1187. Animate();
  1188. }
  1189. //---------------------------------------------------------------------------
  1190. void __fastcall TFrameAnimation::PaintBoxPaint(TObject * Sender)
  1191. {
  1192. if (FFirstFrame >= 0)
  1193. {
  1194. // Double-buffered drawing to prevent flicker (as the images are transparent)
  1195. DebugUsedParam(Sender);
  1196. DebugAssert(FPaintBox == Sender);
  1197. DebugAssert(FPaintBox->ControlStyle.Contains(csOpaque));
  1198. std::unique_ptr<TBitmap> Bitmap(new TBitmap());
  1199. Bitmap->SetSize(FPaintBox->Width, FPaintBox->Height);
  1200. Bitmap->Canvas->Brush->Color = FPaintBox->Color;
  1201. TRect Rect(0, 0, Bitmap->Width, Bitmap->Height);
  1202. Bitmap->Canvas->FillRect(Rect);
  1203. TGraphic * Graphic = GetCurrentImage()->PngImage;
  1204. DebugAssert(Graphic->Width == FPaintBox->Width);
  1205. DebugAssert(Graphic->Height == FPaintBox->Height);
  1206. Bitmap->Canvas->Draw(0, 0, Graphic);
  1207. FPaintBox->Canvas->Draw(0, 0, Bitmap.get());
  1208. }
  1209. FPainted = true;
  1210. }
  1211. //---------------------------------------------------------------------------
  1212. void __fastcall TFrameAnimation::Repaint()
  1213. {
  1214. FPainted = false;
  1215. // If the form is not showing yet, the Paint() is not even called
  1216. FPaintBox->Repaint();
  1217. if (!FPainted)
  1218. {
  1219. // Paint later, alternativelly we may keep trying Repaint() in Animate().
  1220. // See also a hack in TAuthenticateForm::Log.
  1221. FPaintBox->Invalidate();
  1222. }
  1223. }
  1224. //---------------------------------------------------------------------------
  1225. void __fastcall TFrameAnimation::Stop()
  1226. {
  1227. FNextFrameTick = std::numeric_limits<DWORD>::max();
  1228. FCurrentFrame = FFirstFrame;
  1229. Repaint();
  1230. if (FTimer != NULL)
  1231. {
  1232. FTimer->Enabled = false;
  1233. }
  1234. }
  1235. //---------------------------------------------------------------------------
  1236. void __fastcall TFrameAnimation::Animate()
  1237. {
  1238. if (FFirstFrame >= 0)
  1239. {
  1240. // UPGRADE: Use GetTickCount64() when we stop supporting Windows XP.
  1241. DWORD TickCount = GetTickCount();
  1242. // Keep in sync with an opposite condition at the end of the loop.
  1243. // We may skip some frames if we got stalled for a while
  1244. while (TickCount >= FNextFrameTick)
  1245. {
  1246. if (FCurrentFrame >= FLastFrame)
  1247. {
  1248. FCurrentFrame = FFirstLoopFrame;
  1249. }
  1250. else
  1251. {
  1252. FCurrentFrame++;
  1253. }
  1254. CalculateNextFrameTick();
  1255. Repaint();
  1256. }
  1257. }
  1258. }
  1259. //---------------------------------------------------------------------------
  1260. TPngImageCollectionItem * __fastcall TFrameAnimation::GetCurrentImage()
  1261. {
  1262. return FImageList->PngImages->Items[FCurrentFrame];
  1263. }
  1264. //---------------------------------------------------------------------------
  1265. void __fastcall TFrameAnimation::CalculateNextFrameTick()
  1266. {
  1267. TPngImageCollectionItem * ImageItem = GetCurrentImage();
  1268. UnicodeString Duration = ImageItem->Name;
  1269. CutToChar(Duration, L'_', false);
  1270. // skip index (is not really used)
  1271. CutToChar(Duration, L'_', false);
  1272. // This should overflow, when tick count wraps.
  1273. FNextFrameTick += StrToInt(Duration) * 10;
  1274. }
  1275. //---------------------------------------------------------------------------
  1276. //---------------------------------------------------------------------------
  1277. // Hints use:
  1278. // - Cleanup list tooltip (multi line)
  1279. // - Combo edit button
  1280. // - Transfer settings label (multi line, follows label size and font)
  1281. // - HintLabel (hint and persistent hint, multipline)
  1282. // - status bar hints
  1283. //---------------------------------------------------------------------------
  1284. __fastcall TScreenTipHintWindow::TScreenTipHintWindow(TComponent * Owner) :
  1285. THintWindow(Owner)
  1286. {
  1287. FParentPainting = false;
  1288. }
  1289. //---------------------------------------------------------------------------
  1290. int __fastcall TScreenTipHintWindow::GetTextFlags(TControl * Control)
  1291. {
  1292. return DT_LEFT | DT_WORDBREAK | DT_NOPREFIX | Control->DrawTextBiDiModeFlagsReadingOnly();
  1293. }
  1294. //---------------------------------------------------------------------------
  1295. bool __fastcall TScreenTipHintWindow::UseBoldShortHint(TControl * HintControl)
  1296. {
  1297. return
  1298. (dynamic_cast<TTBCustomDockableWindow *>(HintControl) != NULL) ||
  1299. (dynamic_cast<TTBPopupWindow *>(HintControl) != NULL);
  1300. }
  1301. //---------------------------------------------------------------------------
  1302. bool __fastcall TScreenTipHintWindow::IsPathLabel(TControl * HintControl)
  1303. {
  1304. return (dynamic_cast<TPathLabel *>(HintControl) != NULL);
  1305. }
  1306. //---------------------------------------------------------------------------
  1307. bool __fastcall TScreenTipHintWindow::IsHintPopup(TControl * HintControl, const UnicodeString & Hint)
  1308. {
  1309. TLabel * HintLabel = dynamic_cast<TLabel *>(HintControl);
  1310. return (HintLabel != NULL) && HasLabelHintPopup(HintLabel, Hint);
  1311. }
  1312. //---------------------------------------------------------------------------
  1313. int __fastcall TScreenTipHintWindow::GetMargin(TControl * HintControl, const UnicodeString & Hint)
  1314. {
  1315. int Result;
  1316. if (IsHintPopup(HintControl, Hint) || IsPathLabel(HintControl))
  1317. {
  1318. Result = 3;
  1319. }
  1320. else
  1321. {
  1322. Result = 6;
  1323. }
  1324. Result = ScaleByTextHeight(HintControl, Result);
  1325. return Result;
  1326. }
  1327. //---------------------------------------------------------------------------
  1328. TFont * __fastcall TScreenTipHintWindow::GetFont(TControl * HintControl, const UnicodeString & Hint)
  1329. {
  1330. TFont * Result;
  1331. if (IsHintPopup(HintControl, Hint) || IsPathLabel(HintControl))
  1332. {
  1333. Result = reinterpret_cast<TLabel *>(dynamic_cast<TCustomLabel *>(HintControl))->Font;
  1334. }
  1335. else
  1336. {
  1337. FScaledHintFont.reset(new TFont());
  1338. FScaledHintFont->Assign(Screen->HintFont);
  1339. FScaledHintFont->Size = ScaleByPixelsPerInchFromSystem(FScaledHintFont->Size, HintControl);
  1340. Result = FScaledHintFont.get();
  1341. }
  1342. return Result;
  1343. }
  1344. //---------------------------------------------------------------------------
  1345. void __fastcall TScreenTipHintWindow::CalcHintTextRect(TControl * Control, TCanvas * Canvas, TRect & Rect, const UnicodeString & Hint)
  1346. {
  1347. const int Flags = DT_CALCRECT | GetTextFlags(Control);
  1348. DrawText(Canvas->Handle, Hint.c_str(), -1, &Rect, Flags);
  1349. }
  1350. //---------------------------------------------------------------------------
  1351. TRect __fastcall TScreenTipHintWindow::CalcHintRect(int MaxWidth, const UnicodeString AHint, void * AData)
  1352. {
  1353. TControl * HintControl = GetHintControl(AData);
  1354. int Margin = GetMargin(HintControl, AHint);
  1355. const UnicodeString ShortHint = GetShortHint(AHint);
  1356. const UnicodeString LongHint = GetLongHintIfAny(AHint);
  1357. Canvas->Font->Assign(GetFont(HintControl, AHint));
  1358. const int ScreenTipTextOnlyWidth = ScaleByTextHeight(HintControl, cScreenTipTextOnlyWidth);
  1359. if (!LongHint.IsEmpty())
  1360. {
  1361. // double-margin on the right
  1362. MaxWidth = ScreenTipTextOnlyWidth - (3 * Margin);
  1363. }
  1364. // Multi line short hints can be twice as wide, to not break the individual lines unless really necessary.
  1365. // (login site tree, clean up dialog list, preferences custom command list, persistent hint, etc).
  1366. // And they also can be twice as wide, to not break the individual lines unless really necessary.
  1367. if (ShortHint.Pos(L"\n") > 0)
  1368. {
  1369. MaxWidth *= 2;
  1370. }
  1371. bool HintPopup = IsHintPopup(HintControl, AHint);
  1372. if (HintPopup)
  1373. {
  1374. MaxWidth = HintControl->Width;
  1375. }
  1376. if (UseBoldShortHint(HintControl))
  1377. {
  1378. Canvas->Font->Style = TFontStyles() << fsBold;
  1379. }
  1380. TRect ShortRect(0, 0, MaxWidth, 0);
  1381. CalcHintTextRect(this, Canvas, ShortRect, ShortHint);
  1382. Canvas->Font->Style = TFontStyles();
  1383. TRect Result;
  1384. if (LongHint.IsEmpty())
  1385. {
  1386. Result = ShortRect;
  1387. if (HintPopup)
  1388. {
  1389. Result.Right = MaxWidth + 2 * Margin;
  1390. }
  1391. else
  1392. {
  1393. Result.Right += 3 * Margin;
  1394. }
  1395. Result.Bottom += 2 * Margin;
  1396. }
  1397. else
  1398. {
  1399. const int LongIndentation = Margin * 3 / 2;
  1400. TRect LongRect(0, 0, MaxWidth - LongIndentation, 0);
  1401. CalcHintTextRect(this, Canvas, LongRect, LongHint);
  1402. Result.Right = ScreenTipTextOnlyWidth;
  1403. Result.Bottom = Margin + ShortRect.Height() + (Margin / 3 * 5) + LongRect.Height() + Margin;
  1404. }
  1405. // VCLCOPY: To counter the increase in THintWindow::ActivateHintData
  1406. Result.Bottom -= 4;
  1407. return Result;
  1408. }
  1409. //---------------------------------------------------------------------------
  1410. void __fastcall TScreenTipHintWindow::ActivateHintData(const TRect & ARect, const UnicodeString AHint, void * AData)
  1411. {
  1412. FShortHint = GetShortHint(AHint);
  1413. FLongHint = GetLongHintIfAny(AHint);
  1414. FHintControl = GetHintControl(AData);
  1415. FMargin = GetMargin(FHintControl, AHint);
  1416. FHintPopup = IsHintPopup(FHintControl, AHint);
  1417. Canvas->Font->Assign(GetFont(FHintControl, AHint));
  1418. TRect Rect = ARect;
  1419. if (FHintPopup)
  1420. {
  1421. Rect.SetLocation(FHintControl->ClientToScreen(TPoint(-FMargin, -FMargin)));
  1422. }
  1423. if (IsPathLabel(FHintControl))
  1424. {
  1425. Rect.Offset(-FMargin, -FMargin);
  1426. }
  1427. THintWindow::ActivateHintData(Rect, FShortHint, AData);
  1428. }
  1429. //---------------------------------------------------------------------------
  1430. TControl * __fastcall TScreenTipHintWindow::GetHintControl(void * Data)
  1431. {
  1432. return reinterpret_cast<TControl *>(DebugNotNull(Data));
  1433. }
  1434. //---------------------------------------------------------------------------
  1435. UnicodeString __fastcall TScreenTipHintWindow::GetLongHintIfAny(const UnicodeString & AHint)
  1436. {
  1437. UnicodeString Result;
  1438. int P = Pos(L"|", AHint);
  1439. if (P > 0)
  1440. {
  1441. Result = GetLongHint(AHint);
  1442. }
  1443. return Result;
  1444. }
  1445. //---------------------------------------------------------------------------
  1446. void __fastcall TScreenTipHintWindow::Dispatch(void * AMessage)
  1447. {
  1448. TMessage * Message = static_cast<TMessage*>(AMessage);
  1449. switch (Message->Msg)
  1450. {
  1451. case WM_GETTEXTLENGTH:
  1452. if (FParentPainting)
  1453. {
  1454. // make THintWindow::Paint() not paint the Caption
  1455. Message->Result = 0;
  1456. }
  1457. else
  1458. {
  1459. THintWindow::Dispatch(AMessage);
  1460. }
  1461. break;
  1462. default:
  1463. THintWindow::Dispatch(AMessage);
  1464. break;
  1465. }
  1466. }
  1467. //---------------------------------------------------------------------------
  1468. void __fastcall TScreenTipHintWindow::Paint()
  1469. {
  1470. // paint frame/background
  1471. {
  1472. TAutoFlag ParentPaintingFlag(FParentPainting);
  1473. THintWindow::Paint();
  1474. }
  1475. const int Flags = GetTextFlags(this);
  1476. const int Margin = FMargin - 1; // 1 = border
  1477. TRect Rect = ClientRect;
  1478. Rect.Inflate(-Margin, -Margin);
  1479. if (!FHintPopup)
  1480. {
  1481. Rect.Right -= FMargin;
  1482. }
  1483. if (UseBoldShortHint(FHintControl))
  1484. {
  1485. Canvas->Font->Style = TFontStyles() << fsBold;
  1486. }
  1487. DrawText(Canvas->Handle, FShortHint.c_str(), -1, &Rect, Flags);
  1488. TRect ShortRect = Rect;
  1489. DrawText(Canvas->Handle, FShortHint.c_str(), -1, &ShortRect, DT_CALCRECT | Flags);
  1490. Canvas->Font->Style = TFontStyles();
  1491. if (!FLongHint.IsEmpty())
  1492. {
  1493. Rect.Left += FMargin * 3 / 2;
  1494. Rect.Top += ShortRect.Height() + (FMargin / 3 * 5);
  1495. DrawText(Canvas->Handle, FLongHint.c_str(), -1, &Rect, Flags);
  1496. }
  1497. }
  1498. //---------------------------------------------------------------------------
  1499. //---------------------------------------------------------------------------
  1500. __fastcall TNewRichEdit::TNewRichEdit(TComponent * AOwner) :
  1501. TRichEdit(AOwner),
  1502. FLibrary(0)
  1503. {
  1504. }
  1505. //---------------------------------------------------------------------------
  1506. void __fastcall TNewRichEdit::CreateParams(TCreateParams & Params)
  1507. {
  1508. UnicodeString RichEditModuleName(L"MSFTEDIT.DLL");
  1509. long int OldError;
  1510. OldError = SetErrorMode(SEM_NOOPENFILEERRORBOX);
  1511. FLibrary = LoadLibrary(RichEditModuleName.c_str());
  1512. SetErrorMode(OldError);
  1513. // No fallback, MSFTEDIT.DLL is available since Windows XP
  1514. // https://blogs.msdn.microsoft.com/murrays/2006/10/13/richedit-versions/
  1515. if (FLibrary == 0)
  1516. {
  1517. throw Exception(FORMAT(L"Cannot load %s", (RichEditModuleName)));
  1518. }
  1519. TCustomMemo::CreateParams(Params);
  1520. // MSDN says that we should use MSFTEDIT_CLASS to load Rich Edit 4.1:
  1521. // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787873.aspx
  1522. // But MSFTEDIT_CLASS is defined as "RICHEDIT50W",
  1523. // so not sure what version we are loading.
  1524. // Seem to work on Windows XP SP3.
  1525. CreateSubClass(Params, MSFTEDIT_CLASS);
  1526. }
  1527. //---------------------------------------------------------------------------
  1528. void __fastcall TNewRichEdit::CreateWnd()
  1529. {
  1530. TRichEdit::CreateWnd();
  1531. SendMessage(Handle, EM_SETEDITSTYLEEX, 0, SES_EX_HANDLEFRIENDLYURL);
  1532. }
  1533. //---------------------------------------------------------------------------
  1534. void __fastcall TNewRichEdit::DestroyWnd()
  1535. {
  1536. TRichEdit::DestroyWnd();
  1537. if (FLibrary != 0)
  1538. {
  1539. FreeLibrary(FLibrary);
  1540. }
  1541. }