unit Console;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, ExtCtrls;

type
  TFormConsole = class(TForm)
    Memo1: TMemo;
    Panel1: TPanel;
    btnClear: TButton;
    LblKey: TLabel;
    lblChr: TLabel;
    procedure btnClearClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure Memo1KeyPress(Sender: TObject; var Key: Char);
  private
    FShowOnOutput:boolean;
  public
    property ShowOnOutput: boolean read FShowOnOutput write FShowOnOutput;
  end;

var
  FormConsole: TFormConsole;
  StdinKey : Char = #0;
  StdinBuf : string;

procedure Stdout(S: string);
function gets: string;
function getc: Char;

implementation

uses
  Rubies,
{$IFDEF PHIEMBED}
  PhiMainUnit,
{$ELSE}
  Pythia,
{$ENDIF}
  Browser;

{$R *.dfm}

{$I LFToCRLF.pas}

procedure Stdout(S: string);
begin
  S := LFToCRLF(S);
  with FormConsole.Memo1, Lines do
  begin
    SelStart := Length(Text);
    SelText := S;
    SelLength := 0;
    Application.ProcessMessages;
  end;
  //[ap-dev:0904]
  if FormConsole.ShowOnOutput
    and not FormConsole.Visible
    and not Browser.InExecCustom
  then FormConsole.Show;
end;

function gets: string;
var
  term_p: Boolean;
begin
  FormConsole.Show;
  term_p := False;
  repeat
    if not PhiAlive then
    begin
      result := '';
      Exit;
    end;
    if StdinKey = #4{\C-d} then
    begin
      term_p := True;
      SetLength(StdinBuf, Length(StdinBuf)-1);
      Break;
    end;
    WaitMessage;
    Application.ProcessMessages;
  until StdinKey = #13;
  result := StdinBuf;
  if not term_p then result[Length(StdinBuf)] := #10;
  StdinBuf := '';
  StdinKey := #0;
end;

function getc: Char;
begin
  FormConsole.Show;
  while StdinKey = #0 do
  begin
    if not PhiAlive then
    begin
      result := #0;
      Exit;
    end;
    WaitMessage;
    Application.ProcessMessages;
  end;
  result := StdinKey;
  StdinBuf := '';
  StdinKey := #0;
end;

procedure TFormConsole.btnClearClick(Sender: TObject);
begin
  Memo1.Clear;
end;

procedure TFormConsole.FormClose(Sender: TObject;
  var Action: TCloseAction);
begin
  if FormBrowser.Visible then
    Action := caMinimize
  else
  begin
    Action := caNone;
    FormBrowser.Show;
  end;
end;

procedure TFormConsole.Memo1KeyPress(Sender: TObject; var Key: Char);
begin
  LblKey.Caption := IntToHex(Integer(Key), 2);
  StdinKey := Key;
  StdinBuf := StdinBuf + StdinKey;
end;

end.
