unit Main;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  StdCtrls, OleCtrls, SHDocVw, Menus, ieConst, IEDocHostUIHandler,
  xBase, xProcess, ComCtrls, ActiveX, About, URLMon;

type
  TMainForm = class(TForm)
    GroupBox1: TGroupBox;
    WebBrowser: TWebBrowser;
    MainMenu1: TMainMenu;
    PopupMenu1: TPopupMenu;
    File1: TMenuItem;
    Help1: TMenuItem;
    About1: TMenuItem;
    Exit1: TMenuItem;
    SaveItem: TMenuItem;
    PrintItem: TMenuItem;
    ProcessItem: TMenuItem;
    procedure Exit1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure WebBrowserNavigateComplete2(Sender: TObject;
      const pDisp: IDispatch; var URL: OleVariant);
    procedure ProcessItemClick(Sender: TObject);
    procedure SaveItemClick(Sender: TObject);
    procedure PrintItemClick(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure About1Click(Sender: TObject);
  private
    FHtmlDocument: THTMLDocument;
  public
  end;

var
  MainForm: TMainForm;
  FDocHostUIHandler: TDocHostUIHandler;
  FOldText: String;

implementation

{$R *.dfm}
{$R Resources.res}

procedure TMainForm.FormCreate(Sender: TObject);
begin
  {Wait untill WebBrowser object will be ready for work}
  while WebBrowser.ReadyState <> READYSTATE_COMPLETE do
    Application.ProcessMessages;

  {Init HTML PopupMenu handler}
  FDocHostUIHandler := TDocHostUIHandler.Create;
  FDocHostUIHandler.FWebBrowser := WebBrowser;

  {Init THTMLDocument}
  FHtmlDocument := THtmlDocument.Create(WebBrowser);
end;

procedure TMainForm.FormDestroy(Sender: TObject);
begin
  FDocHostUIHandler.Free;
  FHtmlDocument.Free;
end;

procedure TMainForm.WebBrowserNavigateComplete2(Sender: TObject;
  const pDisp: IDispatch; var URL: OleVariant);
var
  hr: HResult;
  CustDoc: ICustomDoc;
begin
  hr := WebBrowser.Document.QueryInterface(ICustomDoc, CustDoc);
  if hr = S_OK then
    CustDoc.SetUIHandler(FDocHostUIHandler);
end;

procedure TMainForm.Exit1Click(Sender: TObject);
begin
  Close;
end;

procedure TMainForm.ProcessItemClick(Sender: TObject);
var
  Text: String;
  Memo: TMemo;
begin
  Memo := TMemo.Create(nil);
  Memo.Visible := False;
  Memo.Parent := Self;
  Memo.PasteFromClipboard;
  Text := xProcessData(Memo.Text);
  Memo.Free;

  if FOldText <> Text then begin
    FHtmlDocument.Clear;
    FHtmlDocument.AddData(Text);
    FHtmlDocument.Show;
  end;
  FOldText := Text;
end;

procedure TMainForm.SaveItemClick(Sender: TObject);
begin
  FHtmlDocument.SaveToFile;
end;

procedure TMainForm.PrintItemClick(Sender: TObject);
begin
  FHtmlDocument.Print;
end;

procedure TMainForm.About1Click(Sender: TObject);
begin
  with TAboutForm.Create(Self) do begin
    ShowModal;
    Free;
  end;
end;

initialization
  OleInitialize(nil);

finalization
  OleUninitialize;

end.
