GUITools.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  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. //---------------------------------------------------------------------------
  18. #pragma package(smart_init)
  19. //---------------------------------------------------------------------------
  20. extern const UnicodeString PageantTool = L"pageant.exe";
  21. extern const UnicodeString PuttygenTool = L"puttygen.exe";
  22. //---------------------------------------------------------------------------
  23. bool __fastcall FindFile(UnicodeString & Path)
  24. {
  25. bool Result = FileExists(ApiPath(Path));
  26. if (!Result)
  27. {
  28. int Len = GetEnvironmentVariable(L"PATH", NULL, 0);
  29. if (Len > 0)
  30. {
  31. UnicodeString Paths;
  32. Paths.SetLength(Len - 1);
  33. GetEnvironmentVariable(L"PATH", Paths.c_str(), Len);
  34. UnicodeString NewPath = FileSearch(ExtractFileName(Path), Paths);
  35. Result = !NewPath.IsEmpty();
  36. if (Result)
  37. {
  38. Path = NewPath;
  39. }
  40. }
  41. }
  42. return Result;
  43. }
  44. //---------------------------------------------------------------------------
  45. bool __fastcall FileExistsEx(UnicodeString Path)
  46. {
  47. return FindFile(Path);
  48. }
  49. //---------------------------------------------------------------------------
  50. void __fastcall OpenSessionInPutty(const UnicodeString PuttyPath,
  51. TSessionData * SessionData)
  52. {
  53. UnicodeString Program, AParams, Dir;
  54. SplitCommand(PuttyPath, Program, AParams, Dir);
  55. Program = ExpandEnvironmentVariables(Program);
  56. if (FindFile(Program))
  57. {
  58. AParams = ExpandEnvironmentVariables(AParams);
  59. UnicodeString Password = GUIConfiguration->PuttyPassword ? SessionData->Password : UnicodeString();
  60. TCustomCommandData Data(SessionData, SessionData->UserName, Password);
  61. TRemoteCustomCommand RemoteCustomCommand(Data, SessionData->RemoteDirectory);
  62. TWinInteractiveCustomCommand InteractiveCustomCommand(
  63. &RemoteCustomCommand, L"PuTTY");
  64. UnicodeString Params =
  65. RemoteCustomCommand.Complete(InteractiveCustomCommand.Complete(AParams, false), true);
  66. if (!RemoteCustomCommand.IsSiteCommand(AParams))
  67. {
  68. UnicodeString SessionName;
  69. TRegistryStorage * Storage = NULL;
  70. TSessionData * ExportData = NULL;
  71. TRegistryStorage * SourceStorage = NULL;
  72. try
  73. {
  74. Storage = new TRegistryStorage(Configuration->PuttySessionsKey);
  75. Storage->AccessMode = smReadWrite;
  76. // make it compatible with putty
  77. Storage->MungeStringValues = false;
  78. Storage->ForceAnsi = true;
  79. if (Storage->OpenRootKey(true))
  80. {
  81. if (Storage->KeyExists(SessionData->StorageKey))
  82. {
  83. SessionName = SessionData->SessionName;
  84. }
  85. else
  86. {
  87. SourceStorage = new TRegistryStorage(Configuration->PuttySessionsKey);
  88. SourceStorage->MungeStringValues = false;
  89. SourceStorage->ForceAnsi = true;
  90. if (SourceStorage->OpenSubKey(StoredSessions->DefaultSettings->Name, false) &&
  91. Storage->OpenSubKey(GUIConfiguration->PuttySession, true))
  92. {
  93. Storage->Copy(SourceStorage);
  94. Storage->CloseSubKey();
  95. }
  96. ExportData = new TSessionData(L"");
  97. ExportData->Assign(SessionData);
  98. ExportData->Modified = true;
  99. ExportData->Name = GUIConfiguration->PuttySession;
  100. ExportData->Password = L"";
  101. if (SessionData->FSProtocol == fsFTP)
  102. {
  103. if (GUIConfiguration->TelnetForFtpInPutty)
  104. {
  105. ExportData->PuttyProtocol = PuttyTelnetProtocol;
  106. ExportData->PortNumber = TelnetPortNumber;
  107. // PuTTY does not allow -pw for telnet
  108. Password = L"";
  109. }
  110. else
  111. {
  112. ExportData->PuttyProtocol = PuttySshProtocol;
  113. ExportData->PortNumber = SshPortNumber;
  114. }
  115. }
  116. ExportData->Save(Storage, true);
  117. SessionName = GUIConfiguration->PuttySession;
  118. }
  119. }
  120. }
  121. __finally
  122. {
  123. delete Storage;
  124. delete ExportData;
  125. delete SourceStorage;
  126. }
  127. AddToList(Params, FORMAT(L"-load %s", (EscapePuttyCommandParam(SessionName))), L" ");
  128. }
  129. if (!Password.IsEmpty() && !RemoteCustomCommand.IsPasswordCommand(AParams))
  130. {
  131. AddToList(Params, FORMAT(L"-pw %s", (EscapePuttyCommandParam(Password))), L" ");
  132. }
  133. if (!ExecuteShell(Program, Params))
  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. HANDLE & Handle)
  172. {
  173. bool Result;
  174. TShellExecuteInfoW ExecuteInfo;
  175. memset(&ExecuteInfo, 0, sizeof(ExecuteInfo));
  176. ExecuteInfo.cbSize = sizeof(ExecuteInfo);
  177. ExecuteInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
  178. ExecuteInfo.hwnd = Application->Handle;
  179. ExecuteInfo.lpFile = (wchar_t*)Path.data();
  180. ExecuteInfo.lpParameters = (wchar_t*)Params.data();
  181. ExecuteInfo.nShow = SW_SHOW;
  182. Result = (ShellExecuteEx(&ExecuteInfo) != 0);
  183. if (Result)
  184. {
  185. Handle = ExecuteInfo.hProcess;
  186. }
  187. return Result;
  188. }
  189. //---------------------------------------------------------------------------
  190. bool __fastcall ExecuteShellAndWait(HWND Handle, const UnicodeString Path,
  191. const UnicodeString Params, TProcessMessagesEvent ProcessMessages)
  192. {
  193. bool Result;
  194. TShellExecuteInfoW ExecuteInfo;
  195. memset(&ExecuteInfo, 0, sizeof(ExecuteInfo));
  196. ExecuteInfo.cbSize = sizeof(ExecuteInfo);
  197. ExecuteInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
  198. ExecuteInfo.hwnd = Handle;
  199. ExecuteInfo.lpFile = (wchar_t*)Path.data();
  200. ExecuteInfo.lpParameters = (wchar_t*)Params.data();
  201. ExecuteInfo.nShow = SW_SHOW;
  202. Result = (ShellExecuteEx(&ExecuteInfo) != 0);
  203. if (Result)
  204. {
  205. if (ProcessMessages != NULL)
  206. {
  207. unsigned long WaitResult;
  208. do
  209. {
  210. WaitResult = WaitForSingleObject(ExecuteInfo.hProcess, 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(ExecuteInfo.hProcess, 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. UnicodeString TempDir;
  319. do
  320. {
  321. TempDir = BaseDir.IsEmpty() ? SystemTemporaryDirectory() : BaseDir;
  322. TempDir = IncludeTrailingBackslash(TempDir) + 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. assert(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 (ALWAYS_TRUE(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. assert(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. class TBrowserViewer : public TWebBrowserEx
  536. {
  537. public:
  538. __fastcall virtual TBrowserViewer(TComponent* AOwner);
  539. void __fastcall AddLinkHandler(
  540. const UnicodeString & Url, TNotifyEvent Handler);
  541. TControl * LoadingPanel;
  542. protected:
  543. DYNAMIC void __fastcall DoContextPopup(const TPoint & MousePos, bool & Handled);
  544. void __fastcall DocumentComplete(
  545. TObject * Sender, const _di_IDispatch Disp, const OleVariant & URL);
  546. void __fastcall BeforeNavigate2(
  547. TObject * Sender, const _di_IDispatch Disp, const OleVariant & URL,
  548. const OleVariant & Flags, const OleVariant & TargetFrameName,
  549. const OleVariant & PostData, const OleVariant & Headers, WordBool & Cancel);
  550. bool FComplete;
  551. std::map<UnicodeString, TNotifyEvent> FHandlers;
  552. };
  553. //---------------------------------------------------------------------------
  554. __fastcall TBrowserViewer::TBrowserViewer(TComponent* AOwner) :
  555. TWebBrowserEx(AOwner)
  556. {
  557. FComplete = false;
  558. OnDocumentComplete = DocumentComplete;
  559. OnBeforeNavigate2 = BeforeNavigate2;
  560. LoadingPanel = NULL;
  561. }
  562. //---------------------------------------------------------------------------
  563. void __fastcall TBrowserViewer::AddLinkHandler(
  564. const UnicodeString & Url, TNotifyEvent Handler)
  565. {
  566. FHandlers.insert(std::make_pair(Url, Handler));
  567. }
  568. //---------------------------------------------------------------------------
  569. void __fastcall TBrowserViewer::DoContextPopup(const TPoint & MousePos, bool & Handled)
  570. {
  571. // suppress built-in context menu
  572. Handled = true;
  573. TWebBrowserEx::DoContextPopup(MousePos, Handled);
  574. }
  575. //---------------------------------------------------------------------------
  576. void __fastcall TBrowserViewer::DocumentComplete(
  577. TObject * /*Sender*/, const _di_IDispatch /*Disp*/, const OleVariant & /*URL*/)
  578. {
  579. SetBrowserDesignModeOff(this);
  580. FComplete = true;
  581. if (LoadingPanel != NULL)
  582. {
  583. LoadingPanel->Visible = false;
  584. }
  585. }
  586. //---------------------------------------------------------------------------
  587. void __fastcall TBrowserViewer::BeforeNavigate2(
  588. TObject * /*Sender*/, const _di_IDispatch /*Disp*/, const OleVariant & AURL,
  589. const OleVariant & /*Flags*/, const OleVariant & /*TargetFrameName*/,
  590. const OleVariant & /*PostData*/, const OleVariant & /*Headers*/, WordBool & Cancel)
  591. {
  592. // If OnDocumentComplete was not called yet, is has to be our initial message URL,
  593. // opened using TWebBrowserEx::Navigate(), allow it.
  594. // Otherwise it's user navigating, block that and open link
  595. // in an external browser, possibly adding campaign parameters on the way.
  596. if (FComplete)
  597. {
  598. Cancel = 1;
  599. UnicodeString URL = AURL;
  600. if (FHandlers.count(URL) > 0)
  601. {
  602. FHandlers[URL](this);
  603. }
  604. else
  605. {
  606. OpenBrowser(URL);
  607. }
  608. }
  609. }
  610. //---------------------------------------------------------------------------
  611. TWebBrowserEx * __fastcall CreateBrowserViewer(TPanel * Parent, const UnicodeString & LoadingLabel)
  612. {
  613. TBrowserViewer * Result = new TBrowserViewer(Parent);
  614. // TWebBrowserEx has its own unrelated Name and Parent properties
  615. static_cast<TWinControl *>(Result)->Name = L"BrowserViewer";
  616. static_cast<TWinControl *>(Result)->Parent = Parent;
  617. Result->Align = alClient;
  618. Result->ControlBorder = cbNone;
  619. TPanel * LoadingPanel = new TPanel(Parent);
  620. LoadingPanel->Parent = Parent;
  621. LoadingPanel->BevelOuter = bvNone;
  622. LoadingPanel->BevelInner = bvNone; // default
  623. LoadingPanel->Align = alClient;
  624. LoadingPanel->Caption = LoadingLabel;
  625. Result->LoadingPanel = LoadingPanel;
  626. return Result;
  627. }
  628. //---------------------------------------------------------------------------
  629. void __fastcall SetBrowserDesignModeOff(TWebBrowserEx * WebBrowser)
  630. {
  631. if (ALWAYS_TRUE(WebBrowser->Document2 != NULL))
  632. {
  633. WebBrowser->Document2->designMode = L"Off";
  634. }
  635. }
  636. //---------------------------------------------------------------------------
  637. void __fastcall AddBrowserLinkHandler(TWebBrowserEx * WebBrowser,
  638. const UnicodeString & Url, TNotifyEvent Handler)
  639. {
  640. TBrowserViewer * BrowserViewer = dynamic_cast<TBrowserViewer *>(WebBrowser);
  641. if (ALWAYS_TRUE(BrowserViewer != NULL))
  642. {
  643. BrowserViewer->AddLinkHandler(Url, Handler);
  644. }
  645. }
  646. //---------------------------------------------------------------------------
  647. TLocalCustomCommand::TLocalCustomCommand()
  648. {
  649. }
  650. //---------------------------------------------------------------------------
  651. TLocalCustomCommand::TLocalCustomCommand(const TCustomCommandData & Data,
  652. const UnicodeString & Path) :
  653. TFileCustomCommand(Data, Path)
  654. {
  655. }
  656. //---------------------------------------------------------------------------
  657. TLocalCustomCommand::TLocalCustomCommand(const TCustomCommandData & Data,
  658. const UnicodeString & Path, const UnicodeString & FileName,
  659. const UnicodeString & LocalFileName, const UnicodeString & FileList) :
  660. TFileCustomCommand(Data, Path, FileName, FileList)
  661. {
  662. FLocalFileName = LocalFileName;
  663. }
  664. //---------------------------------------------------------------------------
  665. int __fastcall TLocalCustomCommand::PatternLen(const UnicodeString & Command, int Index)
  666. {
  667. int Len;
  668. if ((Index < Command.Length()) && (Command[Index + 1] == L'^'))
  669. {
  670. Len = 3;
  671. }
  672. else
  673. {
  674. Len = TFileCustomCommand::PatternLen(Command, Index);
  675. }
  676. return Len;
  677. }
  678. //---------------------------------------------------------------------------
  679. bool __fastcall TLocalCustomCommand::PatternReplacement(
  680. const UnicodeString & Pattern, UnicodeString & Replacement, bool & Delimit)
  681. {
  682. bool Result;
  683. if (Pattern == L"!^!")
  684. {
  685. Replacement = FLocalFileName;
  686. Result = true;
  687. }
  688. else
  689. {
  690. Result = TFileCustomCommand::PatternReplacement(Pattern, Replacement, Delimit);
  691. }
  692. return Result;
  693. }
  694. //---------------------------------------------------------------------------
  695. void __fastcall TLocalCustomCommand::DelimitReplacement(
  696. UnicodeString & /*Replacement*/, wchar_t /*Quote*/)
  697. {
  698. // never delimit local commands
  699. }
  700. //---------------------------------------------------------------------------
  701. bool __fastcall TLocalCustomCommand::HasLocalFileName(const UnicodeString & Command)
  702. {
  703. return FindPattern(Command, L'^');
  704. }
  705. //---------------------------------------------------------------------------
  706. bool __fastcall TLocalCustomCommand::IsFileCommand(const UnicodeString & Command)
  707. {
  708. return TFileCustomCommand::IsFileCommand(Command) || HasLocalFileName(Command);
  709. }