GUITools.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  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 <Animations.h>
  21. #include <PasTools.hpp>
  22. #include <VCLCommon.h>
  23. //---------------------------------------------------------------------------
  24. #pragma package(smart_init)
  25. //---------------------------------------------------------------------------
  26. extern const UnicodeString PageantTool = L"pageant.exe";
  27. extern const UnicodeString PuttygenTool = L"puttygen.exe";
  28. //---------------------------------------------------------------------------
  29. bool __fastcall FindFile(UnicodeString & Path)
  30. {
  31. bool Result = FileExists(ApiPath(Path));
  32. if (!Result)
  33. {
  34. UnicodeString Paths = GetEnvironmentVariable(L"PATH");
  35. if (!Paths.IsEmpty())
  36. {
  37. UnicodeString NewPath = FileSearch(ExtractFileName(Path), Paths);
  38. Result = !NewPath.IsEmpty();
  39. if (Result)
  40. {
  41. Path = NewPath;
  42. }
  43. }
  44. }
  45. return Result;
  46. }
  47. //---------------------------------------------------------------------------
  48. void __fastcall OpenSessionInPutty(const UnicodeString PuttyPath,
  49. TSessionData * SessionData)
  50. {
  51. UnicodeString Program, AParams, Dir;
  52. SplitCommand(PuttyPath, Program, AParams, Dir);
  53. Program = ExpandEnvironmentVariables(Program);
  54. if (FindFile(Program))
  55. {
  56. AParams = ExpandEnvironmentVariables(AParams);
  57. UnicodeString Password = GUIConfiguration->PuttyPassword ? SessionData->Password : UnicodeString();
  58. TCustomCommandData Data(SessionData, SessionData->UserName, Password);
  59. TRemoteCustomCommand RemoteCustomCommand(Data, SessionData->RemoteDirectory);
  60. TWinInteractiveCustomCommand InteractiveCustomCommand(
  61. &RemoteCustomCommand, L"PuTTY");
  62. UnicodeString Params =
  63. RemoteCustomCommand.Complete(InteractiveCustomCommand.Complete(AParams, false), true);
  64. UnicodeString PuttyParams;
  65. if (!RemoteCustomCommand.IsSiteCommand(AParams))
  66. {
  67. UnicodeString SessionName;
  68. TRegistryStorage * Storage = NULL;
  69. TSessionData * ExportData = NULL;
  70. TRegistryStorage * SourceStorage = NULL;
  71. try
  72. {
  73. Storage = new TRegistryStorage(Configuration->PuttySessionsKey);
  74. Storage->AccessMode = smReadWrite;
  75. // make it compatible with putty
  76. Storage->MungeStringValues = false;
  77. Storage->ForceAnsi = true;
  78. if (Storage->OpenRootKey(true))
  79. {
  80. if (Storage->KeyExists(SessionData->StorageKey))
  81. {
  82. SessionName = SessionData->SessionName;
  83. }
  84. else
  85. {
  86. SourceStorage = new TRegistryStorage(Configuration->PuttySessionsKey);
  87. SourceStorage->MungeStringValues = false;
  88. SourceStorage->ForceAnsi = true;
  89. if (SourceStorage->OpenSubKey(StoredSessions->DefaultSettings->Name, false) &&
  90. Storage->OpenSubKey(GUIConfiguration->PuttySession, true))
  91. {
  92. Storage->Copy(SourceStorage);
  93. Storage->CloseSubKey();
  94. }
  95. ExportData = new TSessionData(L"");
  96. ExportData->Assign(SessionData);
  97. ExportData->Modified = true;
  98. ExportData->Name = GUIConfiguration->PuttySession;
  99. ExportData->Password = L"";
  100. if (SessionData->FSProtocol == fsFTP)
  101. {
  102. if (GUIConfiguration->TelnetForFtpInPutty)
  103. {
  104. ExportData->PuttyProtocol = PuttyTelnetProtocol;
  105. ExportData->PortNumber = TelnetPortNumber;
  106. // PuTTY does not allow -pw for telnet
  107. Password = L"";
  108. }
  109. else
  110. {
  111. ExportData->PuttyProtocol = PuttySshProtocol;
  112. ExportData->PortNumber = SshPortNumber;
  113. }
  114. }
  115. ExportData->Save(Storage, true);
  116. SessionName = GUIConfiguration->PuttySession;
  117. }
  118. }
  119. }
  120. __finally
  121. {
  122. delete Storage;
  123. delete ExportData;
  124. delete SourceStorage;
  125. }
  126. AddToList(PuttyParams, FORMAT(L"-load %s", (EscapePuttyCommandParam(SessionName))), L" ");
  127. }
  128. if (!Password.IsEmpty() && !RemoteCustomCommand.IsPasswordCommand(AParams))
  129. {
  130. AddToList(PuttyParams, FORMAT(L"-pw %s", (EscapePuttyCommandParam(Password))), L" ");
  131. }
  132. AddToList(PuttyParams, Params, L" ");
  133. if (!ExecuteShell(Program, PuttyParams))
  134. {
  135. throw Exception(FMTLOAD(EXECUTE_APP_ERROR, (Program)));
  136. }
  137. }
  138. else
  139. {
  140. throw Exception(FMTLOAD(FILE_NOT_FOUND, (Program)));
  141. }
  142. }
  143. //---------------------------------------------------------------------------
  144. bool __fastcall FindTool(const UnicodeString & Name, UnicodeString & Path)
  145. {
  146. UnicodeString AppPath = IncludeTrailingBackslash(ExtractFilePath(Application->ExeName));
  147. Path = AppPath + Name;
  148. bool Result = true;
  149. if (!FileExists(ApiPath(Path)))
  150. {
  151. Path = AppPath + L"PuTTY\\" + Name;
  152. if (!FileExists(ApiPath(Path)))
  153. {
  154. Path = Name;
  155. if (!FindFile(Path))
  156. {
  157. Result = false;
  158. }
  159. }
  160. }
  161. return Result;
  162. }
  163. //---------------------------------------------------------------------------
  164. bool __fastcall ExecuteShell(const UnicodeString Path, const UnicodeString Params)
  165. {
  166. return ((int)ShellExecute(NULL, L"open", (wchar_t*)Path.data(),
  167. (wchar_t*)Params.data(), NULL, SW_SHOWNORMAL) > 32);
  168. }
  169. //---------------------------------------------------------------------------
  170. bool __fastcall ExecuteShell(const UnicodeString Path, const UnicodeString Params,
  171. //---------------------------------------------------------------------------
  172. static bool __fastcall DoExecuteShell(HWND ApplicationHandle, const UnicodeString Path, const UnicodeString Params,
  173. HANDLE & Handle)
  174. {
  175. bool Result;
  176. TShellExecuteInfoW ExecuteInfo;
  177. memset(&ExecuteInfo, 0, sizeof(ExecuteInfo));
  178. ExecuteInfo.cbSize = sizeof(ExecuteInfo);
  179. ExecuteInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
  180. ExecuteInfo.hwnd = ApplicationHandle;
  181. ExecuteInfo.lpFile = (wchar_t*)Path.data();
  182. ExecuteInfo.lpParameters = (wchar_t*)Params.data();
  183. ExecuteInfo.nShow = SW_SHOW;
  184. Result = (ShellExecuteEx(&ExecuteInfo) != 0);
  185. if (Result)
  186. {
  187. Handle = ExecuteInfo.hProcess;
  188. }
  189. return Result;
  190. }
  191. //---------------------------------------------------------------------------
  192. bool __fastcall ExecuteShell(const UnicodeString Path, const UnicodeString Params,
  193. HANDLE & Handle)
  194. {
  195. return DoExecuteShell(Application->Handle, Path, Params, Handle);
  196. }
  197. //---------------------------------------------------------------------------
  198. bool __fastcall ExecuteShellAndWait(HWND Handle, const UnicodeString Path,
  199. const UnicodeString Params, TProcessMessagesEvent ProcessMessages)
  200. {
  201. HANDLE ProcessHandle;
  202. bool Result = DoExecuteShell(Handle, Path, Params, ProcessHandle);
  203. if (Result)
  204. {
  205. if (ProcessMessages != NULL)
  206. {
  207. unsigned long WaitResult;
  208. do
  209. {
  210. WaitResult = WaitForSingleObject(ProcessHandle, 200);
  211. if (WaitResult == WAIT_FAILED)
  212. {
  213. throw Exception(LoadStr(DOCUMENT_WAIT_ERROR));
  214. }
  215. ProcessMessages();
  216. }
  217. while (WaitResult == WAIT_TIMEOUT);
  218. }
  219. else
  220. {
  221. WaitForSingleObject(ProcessHandle, INFINITE);
  222. }
  223. }
  224. return Result;
  225. }
  226. //---------------------------------------------------------------------------
  227. bool __fastcall ExecuteShellAndWait(HWND Handle, const UnicodeString Command,
  228. TProcessMessagesEvent ProcessMessages)
  229. {
  230. UnicodeString Program, Params, Dir;
  231. SplitCommand(Command, Program, Params, Dir);
  232. return ExecuteShellAndWait(Handle, Program, Params, ProcessMessages);
  233. }
  234. //---------------------------------------------------------------------------
  235. bool __fastcall SpecialFolderLocation(int PathID, UnicodeString & Path)
  236. {
  237. LPITEMIDLIST Pidl;
  238. wchar_t Buf[256];
  239. if (SHGetSpecialFolderLocation(NULL, PathID, &Pidl) == NO_ERROR &&
  240. SHGetPathFromIDList(Pidl, Buf))
  241. {
  242. Path = UnicodeString(Buf);
  243. return true;
  244. }
  245. return false;
  246. }
  247. //---------------------------------------------------------------------------
  248. static UnicodeString __fastcall GetWineHomeFolder()
  249. {
  250. UnicodeString Result;
  251. UnicodeString WineHostHome = GetEnvironmentVariable(L"WINE_HOST_HOME");
  252. if (!WineHostHome.IsEmpty())
  253. {
  254. Result = L"Z:" + FromUnixPath(WineHostHome);
  255. }
  256. else
  257. {
  258. // Should we use WinAPI GetUserName() instead?
  259. UnicodeString UserName = GetEnvironmentVariable(L"USERNAME");
  260. if (!UserName.IsEmpty())
  261. {
  262. Result = L"Z:\\home\\" + UserName;
  263. }
  264. }
  265. if (!DirectoryExists(Result))
  266. {
  267. Result = L"";
  268. }
  269. return Result;
  270. }
  271. //---------------------------------------------------------------------------
  272. UnicodeString __fastcall GetPersonalFolder()
  273. {
  274. UnicodeString Result;
  275. ::SpecialFolderLocation(CSIDL_PERSONAL, Result);
  276. if (IsWine())
  277. {
  278. UnicodeString WineHome = GetWineHomeFolder();
  279. if (!WineHome.IsEmpty())
  280. {
  281. // if at least home exists, use it
  282. Result = WineHome;
  283. // but try to go deeper to "Documents"
  284. UnicodeString WineDocuments =
  285. IncludeTrailingBackslash(WineHome) + L"Documents";
  286. if (DirectoryExists(WineDocuments))
  287. {
  288. Result = WineDocuments;
  289. }
  290. }
  291. }
  292. return Result;
  293. }
  294. //---------------------------------------------------------------------------
  295. UnicodeString __fastcall GetDesktopFolder()
  296. {
  297. UnicodeString Result;
  298. ::SpecialFolderLocation(CSIDL_DESKTOPDIRECTORY, Result);
  299. if (IsWine())
  300. {
  301. UnicodeString WineHome = GetWineHomeFolder();
  302. if (!WineHome.IsEmpty())
  303. {
  304. UnicodeString WineDesktop =
  305. IncludeTrailingBackslash(WineHome) + L"Desktop";
  306. if (DirectoryExists(WineHome))
  307. {
  308. Result = WineDesktop;
  309. }
  310. }
  311. }
  312. return Result;
  313. }
  314. //---------------------------------------------------------------------------
  315. UnicodeString __fastcall UniqTempDir(const UnicodeString BaseDir, const UnicodeString Identity,
  316. bool Mask)
  317. {
  318. DebugAssert(!BaseDir.IsEmpty());
  319. UnicodeString TempDir;
  320. do
  321. {
  322. TempDir = IncludeTrailingBackslash(BaseDir) + Identity;
  323. if (Mask)
  324. {
  325. TempDir += L"?????";
  326. }
  327. else
  328. {
  329. TempDir += IncludeTrailingBackslash(FormatDateTime(L"nnzzz", Now()));
  330. }
  331. }
  332. while (!Mask && DirectoryExists(ApiPath(TempDir)));
  333. return TempDir;
  334. }
  335. //---------------------------------------------------------------------------
  336. bool __fastcall DeleteDirectory(const UnicodeString DirName)
  337. {
  338. TSearchRecChecked sr;
  339. bool retval = true;
  340. if (FindFirstUnchecked(DirName + L"\\*", faAnyFile, sr) == 0) // VCL Function
  341. {
  342. if (FLAGSET(sr.Attr, faDirectory))
  343. {
  344. if (sr.Name != L"." && sr.Name != L"..")
  345. retval = DeleteDirectory(DirName + L"\\" + sr.Name);
  346. }
  347. else
  348. {
  349. retval = DeleteFile(ApiPath(DirName + L"\\" + sr.Name));
  350. }
  351. if (retval)
  352. {
  353. while (FindNextChecked(sr) == 0)
  354. { // VCL Function
  355. if (FLAGSET(sr.Attr, faDirectory))
  356. {
  357. if (sr.Name != L"." && sr.Name != L"..")
  358. retval = DeleteDirectory(DirName + L"\\" + sr.Name);
  359. }
  360. else
  361. {
  362. retval = DeleteFile(ApiPath(DirName + L"\\" + sr.Name));
  363. }
  364. if (!retval) break;
  365. }
  366. }
  367. }
  368. FindClose(sr);
  369. if (retval) retval = RemoveDir(ApiPath(DirName)); // VCL function
  370. return retval;
  371. }
  372. //---------------------------------------------------------------------------
  373. UnicodeString __fastcall FormatDateTimeSpan(const UnicodeString TimeFormat, TDateTime DateTime)
  374. {
  375. UnicodeString Result;
  376. if (int(DateTime) > 0)
  377. {
  378. Result = IntToStr(int(DateTime)) + L", ";
  379. }
  380. // days are decremented, because when there are to many of them,
  381. // "integer overflow" error occurs
  382. Result += FormatDateTime(TimeFormat, DateTime - int(DateTime));
  383. return Result;
  384. }
  385. //---------------------------------------------------------------------------
  386. void __fastcall AddSessionColorImage(
  387. TCustomImageList * ImageList, TColor Color, int MaskIndex)
  388. {
  389. // This overly complex drawing is here to support color button on SiteAdvanced
  390. // dialog. There we use plain TImageList, instead of TPngImageList,
  391. // TButton does not work with transparent images
  392. // (not even TBitmap with Transparent = true)
  393. std::unique_ptr<TBitmap> MaskBitmap(new TBitmap());
  394. ImageList->GetBitmap(MaskIndex, MaskBitmap.get());
  395. std::unique_ptr<TPngImage> MaskImage(new TPngImage());
  396. MaskImage->Assign(MaskBitmap.get());
  397. std::unique_ptr<TPngImage> ColorImage(new TPngImage(COLOR_RGB, 16, ImageList->Width, ImageList->Height));
  398. TColor MaskTransparentColor = MaskImage->Pixels[0][0];
  399. TColor TransparentColor = MaskTransparentColor;
  400. // Expecting that the color to be replaced is in the centre of the image (HACK)
  401. TColor MaskColor = MaskImage->Pixels[ImageList->Width / 2][ImageList->Height / 2];
  402. for (int Y = 0; Y < ImageList->Height; Y++)
  403. {
  404. for (int X = 0; X < ImageList->Width; X++)
  405. {
  406. TColor SourceColor = MaskImage->Pixels[X][Y];
  407. TColor DestColor;
  408. // this branch is pointless as long as MaskTransparentColor and
  409. // TransparentColor are the same
  410. if (SourceColor == MaskTransparentColor)
  411. {
  412. DestColor = TransparentColor;
  413. }
  414. else if (SourceColor == MaskColor)
  415. {
  416. DestColor = Color;
  417. }
  418. else
  419. {
  420. DestColor = SourceColor;
  421. }
  422. ColorImage->Pixels[X][Y] = DestColor;
  423. }
  424. }
  425. std::unique_ptr<TBitmap> Bitmap(new TBitmap());
  426. Bitmap->SetSize(ImageList->Width, ImageList->Height);
  427. ColorImage->AssignTo(Bitmap.get());
  428. ImageList->AddMasked(Bitmap.get(), TransparentColor);
  429. }
  430. //---------------------------------------------------------------------------
  431. void __fastcall SetSubmenu(TTBXCustomItem * Item)
  432. {
  433. class TTBXPublicItem : public TTBXCustomItem
  434. {
  435. public:
  436. __property ItemStyle;
  437. };
  438. TTBXPublicItem * PublicItem = reinterpret_cast<TTBXPublicItem *>(Item);
  439. DebugAssert(PublicItem != NULL);
  440. // See TTBItemViewer.IsPtInButtonPart (called from TTBItemViewer.MouseDown)
  441. PublicItem->ItemStyle = PublicItem->ItemStyle << tbisSubmenu;
  442. }
  443. //---------------------------------------------------------------------------
  444. bool __fastcall IsEligibleForApplyingTabs(
  445. UnicodeString Line, int & TabPos, UnicodeString & Start, UnicodeString & Remaining)
  446. {
  447. bool Result = false;
  448. TabPos = Line.Pos(L"\t");
  449. if (TabPos > 0)
  450. {
  451. Remaining = Line.SubString(TabPos + 1, Line.Length() - TabPos);
  452. // WORKAROUND
  453. // Some translations still use obsolete hack of consecutive tabs to aling the contents.
  454. // Delete these, so that the following check does not fail on this
  455. while (Remaining.SubString(1, 1) == L"\t")
  456. {
  457. Remaining.Delete(1, 1);
  458. }
  459. // We do not have, not support, mutiple tabs on a single line
  460. if (DebugAlwaysTrue(Remaining.Pos(L"\t") == 0))
  461. {
  462. Start = Line.SubString(1, TabPos - 1);
  463. // WORKAROUND
  464. // Previously we padded the string before tab with spaces,
  465. // to aling the contents across multiple lines
  466. Start = Start.TrimRight();
  467. // at least two normal spaces for separation
  468. Start += L" ";
  469. Result = true;
  470. }
  471. }
  472. return Result;
  473. }
  474. //---------------------------------------------------------------------------
  475. static int __fastcall CalculateWidthByLength(UnicodeString Text, void * /*Arg*/)
  476. {
  477. return Text.Length();
  478. }
  479. //---------------------------------------------------------------------------
  480. void __fastcall ApplyTabs(
  481. UnicodeString & Text, wchar_t Padding,
  482. TCalculateWidth CalculateWidth, void * CalculateWidthArg)
  483. {
  484. if (CalculateWidth == NULL)
  485. {
  486. DebugAssert(CalculateWidthArg == NULL);
  487. CalculateWidth = CalculateWidthByLength;
  488. }
  489. std::unique_ptr<TStringList> Lines(TextToStringList(Text));
  490. int MaxWidth = -1;
  491. for (int Index = 0; Index < Lines->Count; Index++)
  492. {
  493. UnicodeString Line = Lines->Strings[Index];
  494. int TabPos;
  495. UnicodeString Start;
  496. UnicodeString Remaining;
  497. if (IsEligibleForApplyingTabs(Line, TabPos, Start, Remaining))
  498. {
  499. int Width = CalculateWidth(Start, CalculateWidthArg);
  500. MaxWidth = Max(MaxWidth, Width);
  501. }
  502. }
  503. // Optimization and also to prevent potential regression for texts without tabs
  504. if (MaxWidth >= 0)
  505. {
  506. for (int Index = 0; Index < Lines->Count; Index++)
  507. {
  508. UnicodeString Line = Lines->Strings[Index];
  509. int TabPos;
  510. UnicodeString Start;
  511. UnicodeString Remaining;
  512. if (IsEligibleForApplyingTabs(Line, TabPos, Start, Remaining))
  513. {
  514. int Width;
  515. while ((Width = CalculateWidth(Start, CalculateWidthArg)) < MaxWidth)
  516. {
  517. int Wider = CalculateWidth(Start + Padding, CalculateWidthArg);
  518. // If padded string is wider than max width by more pixels
  519. // than non-padded string is shorter than max width
  520. if ((Wider > MaxWidth) && ((Wider - MaxWidth) > (MaxWidth - Width)))
  521. {
  522. break;
  523. }
  524. Start += Padding;
  525. }
  526. Lines->Strings[Index] = Start + Remaining;
  527. }
  528. }
  529. Text = Lines->Text;
  530. // remove trailing newline
  531. Text = Text.TrimRight();
  532. }
  533. }
  534. //---------------------------------------------------------------------------
  535. void __fastcall SelectScaledImageList(TImageList * ImageList)
  536. {
  537. TImageList * MatchingList = NULL;
  538. int MachingPixelsPerInch = 0;
  539. int PixelsPerInch = Screen->PixelsPerInch;
  540. for (int Index = 0; Index < ImageList->Owner->ComponentCount; Index++)
  541. {
  542. TImageList * OtherList = dynamic_cast<TImageList *>(ImageList->Owner->Components[Index]);
  543. if ((OtherList != NULL) &&
  544. (OtherList != ImageList) &&
  545. StartsStr(ImageList->Name, OtherList->Name))
  546. {
  547. UnicodeString OtherListPixelsPerInchStr =
  548. OtherList->Name.SubString(
  549. ImageList->Name.Length() + 1, OtherList->Name.Length() - ImageList->Name.Length());
  550. int OtherListPixelsPerInch = StrToInt(OtherListPixelsPerInchStr);
  551. if ((OtherListPixelsPerInch <= PixelsPerInch) &&
  552. ((MatchingList == NULL) ||
  553. (MachingPixelsPerInch < OtherListPixelsPerInch)))
  554. {
  555. MatchingList = OtherList;
  556. MachingPixelsPerInch = OtherListPixelsPerInch;
  557. }
  558. }
  559. }
  560. if (MatchingList != NULL)
  561. {
  562. CopyImageList(ImageList, MatchingList);
  563. }
  564. }
  565. //---------------------------------------------------------------------------
  566. void __fastcall CopyImageList(TImageList * TargetList, TImageList * SourceList)
  567. {
  568. TPngImageList * PngTargetList = dynamic_cast<TPngImageList *>(TargetList);
  569. TPngImageList * PngSourceList = dynamic_cast<TPngImageList *>(SourceList);
  570. TargetList->Clear();
  571. TargetList->Height = SourceList->Height;
  572. TargetList->Width = SourceList->Width;
  573. if ((PngTargetList != NULL) && (PngSourceList != NULL))
  574. {
  575. // AddImages won't copy the names and we need them for
  576. // LoadDialogImage and TFrameAnimation
  577. PngTargetList->PngImages->Assign(PngSourceList->PngImages);
  578. }
  579. else
  580. {
  581. TargetList->AddImages(SourceList);
  582. }
  583. }
  584. //---------------------------------------------------------------------------
  585. void __fastcall CopyDataModule(TDataModule * TargetModule, TDataModule * SourceModule)
  586. {
  587. DebugAssert(TargetModule->ComponentCount == SourceModule->ComponentCount);
  588. typedef std::vector<std::pair<TComponent *, TComponent *> > TComponentPairs;
  589. TComponentPairs ComponentPairs;
  590. for (int Index = 0; Index < TargetModule->ComponentCount; Index++)
  591. {
  592. TComponent * TargetComponent = TargetModule->Components[Index];
  593. TComponent * SourceComponent = SourceModule->FindComponent(TargetComponent->Name);
  594. if (DebugAlwaysTrue(SourceComponent != NULL))
  595. {
  596. ComponentPairs.push_back(std::make_pair(TargetComponent, SourceComponent));
  597. }
  598. }
  599. TComponentPairs::const_iterator Iterator = ComponentPairs.begin();
  600. while (Iterator != ComponentPairs.end())
  601. {
  602. TComponent * TargetComponent = Iterator->first;
  603. TComponent * SourceComponent = Iterator->second;
  604. TargetModule->RemoveComponent(TargetComponent);
  605. SourceModule->RemoveComponent(SourceComponent);
  606. TargetModule->InsertComponent(SourceComponent);
  607. SourceModule->InsertComponent(TargetComponent);
  608. Iterator++;
  609. }
  610. }
  611. //---------------------------------------------------------------------------
  612. void __fastcall LoadDialogImage(TImage * Image, const UnicodeString & ImageName)
  613. {
  614. if (GlyphsModule != NULL)
  615. {
  616. TPngImageList * DialogImages = GlyphsModule->DialogImages;
  617. int Index;
  618. for (Index = 0; Index < DialogImages->PngImages->Count; Index++)
  619. {
  620. TPngImageCollectionItem * PngItem = DialogImages->PngImages->Items[Index];
  621. if (SameText(PngItem->Name, ImageName))
  622. {
  623. Image->Picture->Assign(PngItem->PngImage);
  624. break;
  625. }
  626. }
  627. DebugAssert(Index < DialogImages->PngImages->Count);
  628. }
  629. // When showing an exception from wWinMain, the glyphs module does not exist anymore.
  630. // We expect errors only.
  631. else if (DebugAlwaysTrue(ImageName == L"Error"))
  632. {
  633. Image->Picture->Icon->Handle = LoadIcon(0, IDI_HAND);
  634. }
  635. }
  636. //---------------------------------------------------------------------------
  637. int __fastcall DialogImageSize()
  638. {
  639. return ScaleByPixelsPerInch(32);
  640. }
  641. //---------------------------------------------------------------------------
  642. void __fastcall HideComponentsPanel(TForm * Form)
  643. {
  644. TComponent * Component = DebugNotNull(Form->FindComponent(L"ComponentsPanel"));
  645. TPanel * Panel = DebugNotNull(dynamic_cast<TPanel *>(Component));
  646. DebugAssert(Panel->Align == alBottom);
  647. int Offset = Panel->Height;
  648. Panel->Visible = false;
  649. Form->Height -= Offset;
  650. for (int Index = 0; Index < Form->ControlCount; Index++)
  651. {
  652. TControl * Control = Form->Controls[Index];
  653. // Shift back bottom-anchored controls
  654. // (needed for toolbar panel on Progress window and butons on Preferences dialog),
  655. if ((Control->Align == alNone) &&
  656. Control->Anchors.Contains(akBottom) &&
  657. !Control->Anchors.Contains(akTop))
  658. {
  659. Control->Top += Offset;
  660. }
  661. // Resize back all-anchored controls
  662. // (needed for main panel on Preferences dialog),
  663. if (Control->Anchors.Contains(akBottom) &&
  664. Control->Anchors.Contains(akTop))
  665. {
  666. Control->Height += Offset;
  667. }
  668. }
  669. }
  670. //---------------------------------------------------------------------------
  671. class TBrowserViewer : public TWebBrowserEx
  672. {
  673. public:
  674. __fastcall virtual TBrowserViewer(TComponent* AOwner);
  675. void __fastcall AddLinkHandler(
  676. const UnicodeString & Url, TNotifyEvent Handler);
  677. void __fastcall NavigateToUrl(const UnicodeString & Url);
  678. TControl * LoadingPanel;
  679. protected:
  680. DYNAMIC void __fastcall DoContextPopup(const TPoint & MousePos, bool & Handled);
  681. void __fastcall DocumentComplete(
  682. TObject * Sender, const _di_IDispatch Disp, const OleVariant & URL);
  683. void __fastcall BeforeNavigate2(
  684. TObject * Sender, const _di_IDispatch Disp, const OleVariant & URL,
  685. const OleVariant & Flags, const OleVariant & TargetFrameName,
  686. const OleVariant & PostData, const OleVariant & Headers, WordBool & Cancel);
  687. bool FComplete;
  688. std::map<UnicodeString, TNotifyEvent> FHandlers;
  689. };
  690. //---------------------------------------------------------------------------
  691. __fastcall TBrowserViewer::TBrowserViewer(TComponent* AOwner) :
  692. TWebBrowserEx(AOwner)
  693. {
  694. FComplete = false;
  695. OnDocumentComplete = DocumentComplete;
  696. OnBeforeNavigate2 = BeforeNavigate2;
  697. LoadingPanel = NULL;
  698. }
  699. //---------------------------------------------------------------------------
  700. void __fastcall TBrowserViewer::AddLinkHandler(
  701. const UnicodeString & Url, TNotifyEvent Handler)
  702. {
  703. FHandlers.insert(std::make_pair(Url, Handler));
  704. }
  705. //---------------------------------------------------------------------------
  706. void __fastcall TBrowserViewer::DoContextPopup(const TPoint & MousePos, bool & Handled)
  707. {
  708. // suppress built-in context menu
  709. Handled = true;
  710. TWebBrowserEx::DoContextPopup(MousePos, Handled);
  711. }
  712. //---------------------------------------------------------------------------
  713. void __fastcall TBrowserViewer::DocumentComplete(
  714. TObject * /*Sender*/, const _di_IDispatch /*Disp*/, const OleVariant & /*URL*/)
  715. {
  716. SetBrowserDesignModeOff(this);
  717. FComplete = true;
  718. if (LoadingPanel != NULL)
  719. {
  720. LoadingPanel->Visible = false;
  721. }
  722. }
  723. //---------------------------------------------------------------------------
  724. void __fastcall TBrowserViewer::BeforeNavigate2(
  725. TObject * /*Sender*/, const _di_IDispatch /*Disp*/, const OleVariant & AURL,
  726. const OleVariant & /*Flags*/, const OleVariant & /*TargetFrameName*/,
  727. const OleVariant & /*PostData*/, const OleVariant & /*Headers*/, WordBool & Cancel)
  728. {
  729. // If OnDocumentComplete was not called yet, is has to be our initial message URL,
  730. // opened using TWebBrowserEx::Navigate(), allow it.
  731. // Otherwise it's user navigating, block that and open link
  732. // in an external browser, possibly adding campaign parameters on the way.
  733. if (FComplete)
  734. {
  735. Cancel = 1;
  736. UnicodeString URL = AURL;
  737. if (FHandlers.count(URL) > 0)
  738. {
  739. FHandlers[URL](this);
  740. }
  741. else
  742. {
  743. OpenBrowser(URL);
  744. }
  745. }
  746. }
  747. //---------------------------------------------------------------------------
  748. void __fastcall TBrowserViewer::NavigateToUrl(const UnicodeString & Url)
  749. {
  750. FComplete = false;
  751. Navigate(Url.c_str());
  752. }
  753. //---------------------------------------------------------------------------
  754. TPanel * __fastcall CreateLabelPanel(TPanel * Parent, const UnicodeString & Label)
  755. {
  756. TPanel * Result = CreateBlankPanel(Parent);
  757. Result->Parent = Parent;
  758. Result->Align = alClient;
  759. Result->Caption = Label;
  760. return Result;
  761. }
  762. //---------------------------------------------------------------------------
  763. TWebBrowserEx * __fastcall CreateBrowserViewer(TPanel * Parent, const UnicodeString & LoadingLabel)
  764. {
  765. TBrowserViewer * Result = new TBrowserViewer(Parent);
  766. // TWebBrowserEx has its own unrelated Name and Parent properties.
  767. // The name is used in DownloadUpdate().
  768. static_cast<TWinControl *>(Result)->Name = L"BrowserViewer";
  769. static_cast<TWinControl *>(Result)->Parent = Parent;
  770. Result->Align = alClient;
  771. Result->ControlBorder = cbNone;
  772. Result->LoadingPanel = CreateLabelPanel(Parent, LoadingLabel);
  773. return Result;
  774. }
  775. //---------------------------------------------------------------------------
  776. void __fastcall SetBrowserDesignModeOff(TWebBrowserEx * WebBrowser)
  777. {
  778. if (DebugAlwaysTrue(WebBrowser->Document2 != NULL))
  779. {
  780. WebBrowser->Document2->designMode = L"Off";
  781. }
  782. }
  783. //---------------------------------------------------------------------------
  784. void __fastcall AddBrowserLinkHandler(TWebBrowserEx * WebBrowser,
  785. const UnicodeString & Url, TNotifyEvent Handler)
  786. {
  787. TBrowserViewer * BrowserViewer = dynamic_cast<TBrowserViewer *>(WebBrowser);
  788. if (DebugAlwaysTrue(BrowserViewer != NULL))
  789. {
  790. BrowserViewer->AddLinkHandler(Url, Handler);
  791. }
  792. }
  793. //---------------------------------------------------------------------------
  794. void __fastcall NavigateBrowserToUrl(TWebBrowserEx * WebBrowser, const UnicodeString & Url)
  795. {
  796. TBrowserViewer * BrowserViewer = dynamic_cast<TBrowserViewer *>(WebBrowser);
  797. if (DebugAlwaysTrue(BrowserViewer != NULL))
  798. {
  799. BrowserViewer->NavigateToUrl(Url);
  800. }
  801. }
  802. //---------------------------------------------------------------------------
  803. TLocalCustomCommand::TLocalCustomCommand()
  804. {
  805. }
  806. //---------------------------------------------------------------------------
  807. TLocalCustomCommand::TLocalCustomCommand(const TCustomCommandData & Data,
  808. const UnicodeString & Path) :
  809. TFileCustomCommand(Data, Path)
  810. {
  811. }
  812. //---------------------------------------------------------------------------
  813. TLocalCustomCommand::TLocalCustomCommand(const TCustomCommandData & Data,
  814. const UnicodeString & Path, const UnicodeString & FileName,
  815. const UnicodeString & LocalFileName, const UnicodeString & FileList) :
  816. TFileCustomCommand(Data, Path, FileName, FileList)
  817. {
  818. FLocalFileName = LocalFileName;
  819. }
  820. //---------------------------------------------------------------------------
  821. int __fastcall TLocalCustomCommand::PatternLen(const UnicodeString & Command, int Index)
  822. {
  823. int Len;
  824. if ((Index < Command.Length()) && (Command[Index + 1] == L'^'))
  825. {
  826. Len = 3;
  827. }
  828. else
  829. {
  830. Len = TFileCustomCommand::PatternLen(Command, Index);
  831. }
  832. return Len;
  833. }
  834. //---------------------------------------------------------------------------
  835. bool __fastcall TLocalCustomCommand::PatternReplacement(
  836. const UnicodeString & Pattern, UnicodeString & Replacement, bool & Delimit)
  837. {
  838. bool Result;
  839. if (Pattern == L"!^!")
  840. {
  841. Replacement = FLocalFileName;
  842. Result = true;
  843. }
  844. else
  845. {
  846. Result = TFileCustomCommand::PatternReplacement(Pattern, Replacement, Delimit);
  847. }
  848. return Result;
  849. }
  850. //---------------------------------------------------------------------------
  851. void __fastcall TLocalCustomCommand::DelimitReplacement(
  852. UnicodeString & /*Replacement*/, wchar_t /*Quote*/)
  853. {
  854. // never delimit local commands
  855. }
  856. //---------------------------------------------------------------------------
  857. bool __fastcall TLocalCustomCommand::HasLocalFileName(const UnicodeString & Command)
  858. {
  859. return FindPattern(Command, L'^');
  860. }
  861. //---------------------------------------------------------------------------
  862. bool __fastcall TLocalCustomCommand::IsFileCommand(const UnicodeString & Command)
  863. {
  864. return TFileCustomCommand::IsFileCommand(Command) || HasLocalFileName(Command);
  865. }
  866. //---------------------------------------------------------------------------
  867. //---------------------------------------------------------------------------
  868. __fastcall TFrameAnimation::TFrameAnimation()
  869. {
  870. FFirstFrame = -1;
  871. }
  872. //---------------------------------------------------------------------------
  873. void __fastcall TFrameAnimation::Init(TPaintBox * PaintBox, const UnicodeString & Name)
  874. {
  875. DoInit(PaintBox, NULL, Name, Name.IsEmpty());
  876. }
  877. //---------------------------------------------------------------------------
  878. void __fastcall TFrameAnimation::DoInit(TPaintBox * PaintBox, TPngImageList * ImageList, const UnicodeString & Name, bool Null)
  879. {
  880. FImageList = (ImageList != NULL) ? ImageList : GetAnimationsModule()->AnimationImages;
  881. FFirstFrame = -1;
  882. FFirstLoopFrame = -1;
  883. DebugAssert((PaintBox->OnPaint == NULL) || (PaintBox->OnPaint == PaintBoxPaint));
  884. PaintBox->ControlStyle = PaintBox->ControlStyle << csOpaque;
  885. PaintBox->OnPaint = PaintBoxPaint;
  886. PaintBox->Width = FImageList->Width;
  887. PaintBox->Height = FImageList->Height;
  888. FPaintBox = PaintBox;
  889. if (!Null)
  890. {
  891. int Frame = 0;
  892. while (Frame < FImageList->PngImages->Count)
  893. {
  894. UnicodeString FrameData = FImageList->PngImages->Items[Frame]->Name;
  895. UnicodeString FrameName;
  896. FrameName = CutToChar(FrameData, L'_', false);
  897. if (SameText(Name, FrameName))
  898. {
  899. int FrameIndex = StrToInt(CutToChar(FrameData, L'_', false));
  900. if (FFirstFrame < 0)
  901. {
  902. FFirstFrame = Frame;
  903. }
  904. if ((FFirstLoopFrame < 0) && (FrameIndex > 0))
  905. {
  906. FFirstLoopFrame = Frame;
  907. }
  908. FLastFrame = Frame;
  909. }
  910. else
  911. {
  912. if (FFirstFrame >= 0)
  913. {
  914. // optimization
  915. break;
  916. }
  917. }
  918. Frame++;
  919. }
  920. DebugAssert(FFirstFrame >= 0);
  921. DebugAssert(FFirstLoopFrame >= 0);
  922. }
  923. Stop();
  924. }
  925. //---------------------------------------------------------------------------
  926. void __fastcall TFrameAnimation::Start()
  927. {
  928. if (FFirstFrame >= 0)
  929. {
  930. FNextFrameTick = GetTickCount();
  931. CalculateNextFrameTick();
  932. if (FTimer == NULL)
  933. {
  934. FTimer = new TTimer(GetParentForm(FPaintBox));
  935. FTimer->Interval = static_cast<int>(GUIUpdateInterval);
  936. FTimer->OnTimer = Timer;
  937. }
  938. else
  939. {
  940. // reset timer
  941. FTimer->Enabled = false;
  942. FTimer->Enabled = true;
  943. }
  944. }
  945. }
  946. //---------------------------------------------------------------------------
  947. void __fastcall TFrameAnimation::Timer(TObject * /*Sender*/)
  948. {
  949. Animate();
  950. }
  951. //---------------------------------------------------------------------------
  952. void __fastcall TFrameAnimation::PaintBoxPaint(TObject * Sender)
  953. {
  954. if (FFirstFrame >= 0)
  955. {
  956. // Double-buffered drawing to prevent flicker (as the images are transparent)
  957. DebugUsedParam(Sender);
  958. DebugAssert(FPaintBox == Sender);
  959. DebugAssert(FPaintBox->ControlStyle.Contains(csOpaque));
  960. std::unique_ptr<TBitmap> Bitmap(new TBitmap());
  961. Bitmap->SetSize(FPaintBox->Width, FPaintBox->Height);
  962. Bitmap->Canvas->Brush->Color = FPaintBox->Color;
  963. TRect Rect(0, 0, Bitmap->Width, Bitmap->Height);
  964. Bitmap->Canvas->FillRect(Rect);
  965. TGraphic * Graphic = GetCurrentImage()->PngImage;
  966. // Do not trigger assertion when animation size does not match scaled
  967. // paint box as we do not have scaled animations available yet
  968. DebugAssert((Graphic->Width == FPaintBox->Width) || (Screen->PixelsPerInch != USER_DEFAULT_SCREEN_DPI));
  969. DebugAssert((Graphic->Height == FPaintBox->Height) || (Screen->PixelsPerInch != USER_DEFAULT_SCREEN_DPI));
  970. Bitmap->Canvas->Draw(0, 0, Graphic);
  971. FPaintBox->Canvas->Draw(0, 0, Bitmap.get());
  972. }
  973. FPainted = true;
  974. }
  975. //---------------------------------------------------------------------------
  976. void __fastcall TFrameAnimation::Repaint()
  977. {
  978. FPainted = false;
  979. // Ff the form is not showing yet, the Paint() is not even called
  980. FPaintBox->Repaint();
  981. if (!FPainted)
  982. {
  983. // Paint later, alternativelly we may keep trying Repaint() in Animate().
  984. // See also a hack in TAuthenticateForm::Log.
  985. FPaintBox->Invalidate();
  986. }
  987. }
  988. //---------------------------------------------------------------------------
  989. void __fastcall TFrameAnimation::Stop()
  990. {
  991. FNextFrameTick = std::numeric_limits<DWORD>::max();
  992. FCurrentFrame = FFirstFrame;
  993. Repaint();
  994. if (FTimer != NULL)
  995. {
  996. FTimer->Enabled = false;
  997. }
  998. }
  999. //---------------------------------------------------------------------------
  1000. void __fastcall TFrameAnimation::Animate()
  1001. {
  1002. if (FFirstFrame >= 0)
  1003. {
  1004. // UPGRADE: Use GetTickCount64() when we stop supporting Windows XP.
  1005. DWORD TickCount = GetTickCount();
  1006. // Keep in sync with an opposite condition at the end of the loop.
  1007. // We may skip some frames if we got stalled for a while
  1008. while (TickCount >= FNextFrameTick)
  1009. {
  1010. if (FCurrentFrame >= FLastFrame)
  1011. {
  1012. FCurrentFrame = FFirstLoopFrame;
  1013. }
  1014. else
  1015. {
  1016. FCurrentFrame++;
  1017. }
  1018. CalculateNextFrameTick();
  1019. Repaint();
  1020. }
  1021. }
  1022. }
  1023. //---------------------------------------------------------------------------
  1024. TPngImageCollectionItem * __fastcall TFrameAnimation::GetCurrentImage()
  1025. {
  1026. return FImageList->PngImages->Items[FCurrentFrame];
  1027. }
  1028. //---------------------------------------------------------------------------
  1029. void __fastcall TFrameAnimation::CalculateNextFrameTick()
  1030. {
  1031. TPngImageCollectionItem * ImageItem = GetCurrentImage();
  1032. UnicodeString Duration = ImageItem->Name;
  1033. CutToChar(Duration, L'_', false);
  1034. // skip index (is not really used)
  1035. CutToChar(Duration, L'_', false);
  1036. // This should overflow, when tick count wraps.
  1037. FNextFrameTick += StrToInt(Duration) * 10;
  1038. }
  1039. //---------------------------------------------------------------------------