------------------------------------------------------------------------------
-- USER IO                                                                  --
--                                                                          --
-- Part of TextTools                                                        --
-- Designed and Programmed by Ken O. Burtch                                 --
--                                                                          --
------------------------------------------------------------------------------
--                                                                          --
--                 Copyright (C) 1999-2007 Ken O. Burtch                    --
--                                                                          --
-- This is free software;  you can  redistribute it  and/or modify it under --
-- terms of the  GNU General Public License as published  by the Free Soft- --
-- ware  Foundation;  either version 2,  or (at your option) any later ver- --
-- sion.  This is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
-- for  more details.  You should have  received  a copy of the GNU General --
-- Public License  distributed with this;  see file COPYING.  If not, write --
-- to  the Free Software Foundation,  59 Temple Place - Suite 330,  Boston, --
-- MA 02111-1307, USA.                                                      --
--                                                                          --
-- As a special exception,  if other files  instantiate  generics from this --
-- unit, or you link  this unit with other files  to produce an executable, --
-- this  unit  does not  by itself cause  the resulting  executable  to  be --
-- covered  by the  GNU  General  Public  License.  This exception does not --
-- however invalidate  any other reasons why  the executable file  might be --
-- covered by the  GNU Public License.                                      --
--                                                                          --
-- This is maintained at http://www.pegasoft.ca/tt.html                     --
--                                                                          --
------------------------------------------------------------------------------
-- Design notes:
--   1. Errors are only returned at startup and shutdown (with the
--      exception of constraint errors and the like.)
--   2. As much as possible, the package supports both logical and
--      real pen/text attributes.  Unless you really need to use the
--      actual attribute (eg. RGB), use the logical one (ColourName's).

with common; use common;
  pragma Elaborate( common ); -- remind Ada that Common elaborates first
with os; use os;
with Ada.Calendar;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;

package userio is

  ---> Definitions of Important Control Characters
  --
  -- These maybe represented by more than one key (see C sources)

  NullKey   : constant character := character'val(  0); -- no keypress
  LeftKey   : constant character := character'val(  8); -- left arrow
  RightKey  : constant character := character'val( 21); -- right arrow
  UpKey     : constant character := character'val( 11); -- up key
  DownKey   : constant character := character'val( 10); -- down key
  HomeKey   : constant character := character'val( 25); -- home key (& ctrl-y)
  PageUpKey : constant character := character'val( 16); -- page up (& ctrl-p)
  PageDownKey:constant character := character'val( 14); -- page up (& ctrl-n)
  EndKey    : constant character := character'val(  5); -- end key (& ctrl-e)
  ClearKey  : constant character := character'val( 24); -- clear (ctrl-x)
  DeleteKey : constant character := character'val(127); -- delete/backspace
  CopyKey   : constant character := character'val(  2); -- copy key (& ctrl-b)
  PasteKey  : constant character := character'val( 22); -- paste key (ctrl-v)
  ReturnKey : constant character := character'val( 13); -- ok
  TabKey    : constant character := character'val(  9); -- ok
  BackKey   : constant character := character'val( 20); -- backtab (& ctrl-t)
  HelpKey   : constant character := character'val( 27); -- help key (F1/ESC)
  MacroKey  : constant character := character'val(  1); -- do  mac (F2/ctrl-a)
  RedrawKey : constant character := character'val( 12); -- redraw scrn (ctr-l)
  MarkKey   : constant character := character'val( 30); -- mark key (ctrl-r)
  CSearchKey: constant character := character'val( 29); -- fwd chr search (ctrl-])

---> Error Codes
--
-- (none, yet)


---> Housekeeping
--
-- LastError = error

  procedure StartupUserIO;
  pragma export( C, StartupUserIO, "startup_userio" );

  procedure IdleUserIO( IdlePeriod : in Duration );

  procedure ShutdownUserIO;
  pragma export( C, ShutdownUserIO, "shutdown_userio" );

  procedure ResetUserIO; -- for Windows refresh desktop
  pragma export( C, ResetUserIO, "reset_userio" );

  procedure BlueBackground( blueOn : boolean );

  -- Set the default background to blue or black.  On startup, it's
  -- blue.
  -- Errors: none

  function IsBlueBackground return boolean;
  -- return whether background is blue or black
  -- Errors: none

  ---> Terminal Info
  --
  -- True device independance is difficult: these calls let you determine
  -- if the I/O devices support some general features.

  type ADisplayInfoRec is record                      -- (eg. for vt-100)
       fields : natural;    -- count of number of fields (>=8)    (eg. 8)
       TextBased : boolean; -- true if a text-based display    (eg. true)
       H_Res  : natural;    -- horizontal resolution           (eg.   80)
       V_Res  : natural;    -- vertical resolution             (eg.   24)
       C_Res  : natural;    -- R/G/B bits (0=N/A)              (eg.    0)
       P_Len  : natural;    -- length of the palette (0=N/A)   (eg.    0)
       D_Buf  : natural;    -- total number of display buffers (eg.    1)
       S_Res  : natural;    -- sound resolution (0=N/A)        (eg.    0)
       Y_Res  : natural;    -- sound voices/channels (0=N/A)   (eg.    0)
  end record;

  procedure GetDisplayInfo( info : in out ADisplayInfoRec );
  pragma export( C, GetDisplayInfo, "get_display_info" );

  type AnInputInfoRec is record                        -- (eg for vt-100)
       fields       : natural; -- count of number of fields (>=4) (eg. 4)
       HasKeyboard  : boolean; -- true if has active keyboard (eg.  true)
       HasDirection : boolean; -- true if has direction device(eg. false)
       HasVelocity  : boolean; -- true if dir dev can do velocity (eg.false)
       HasLocator   : boolean; -- true if has locator device  (eg. false)
  end record;

  procedure GetInputInfo( info : in out AnInputInfoRec );
  pragma export( C, GetInputInfo, "get_input_info" );

---> Pen and Palette Attributes
--
-- APenColourName is a shortform for a particular colour
-- ARGBComponent is the percentage of a colour component
-- APaletteEntryNumber is for access the colour palette

  type APenColourName is (None, Outline, ScrollBack, ScrollThumb,
       ThermBack, ThermFore, White, Red, Purple, Green, Blue, Yellow, Black );
  pragma convention( C, APenColourName );

  subtype ARGBComponent is float;
  subtype APaletteColour is natural;

  -- Setting the current pen colour
  procedure SetPenColour( name : APenColourName );
  pragma export( C, SetPenColour, "set_pen_colour" );
  procedure SetPenColour( redC, greenC, blueC : ARGBComponent );
  procedure SetPenColour( colour : APaletteColour );

  -- Setting palette colours (if device has palettes)
  procedure SetPaletteColour( colour : APaletteColour; name : APenColourName );
  procedure SetPaletteColour( colour : APaletteColour; redC, greenC, blueC
    : ARGBComponent );

  -- Getting the current pen colour
  function  GetPenColour return APenColourName;
  pragma export( C, GetPenColour, "get_pen_colour" );
  procedure GetPenColour( redC, greenC, blueC : in out ARGBComponent );
  function  GetPenColour return APaletteColour;
  function GetPenColour( colour : APaletteColour ) return APenColourName;
  -- not written
  --  procedure GetPenColour( colour : APaletteColour; redC, greenC, blueC
  --                                                   : in out ARGBComponent );

-- Getting palette colours (if device has palettes)
  procedure GetPaletteColour( colour : APaletteColour; redC, greenC, blueC
    : in out ARGBComponent );
  function  GetPaletteColour( colour : APaletteColour ) return APenColourName;
  function  FindPaletteColour( redC, greenC, blueC : ARGBComponent )
    return APaletteColour;

procedure GetPenPos( x, y : out integer );
pragma export( C, GetPenPos, "get_pen_pos" );

procedure GetPixel( x, y : integer; redC, greenC, blueC : out ARGBComponent );
procedure SetPenSize( p : Points );
function  GetPenSize return Points;

-- Turtle Graphics

procedure SetPenAngle( angle : float );
procedure ChangePenAngle( degrees : float );
function  GetPenAngle return float;
procedure DrawForward( dist : float );

---> Text attributes
--
-- TextStyles describe the type of text to be drawn

type ATextStyle is (Normal, Bold, Underline, Italic, BoldUnderline,
     BoldItalic, ItalicUnderline, BoldItalicUnderline, Success, Failure,
     Warning, Status, Citation, SectionHeading, SubHeading, Heading, Title,
     Emphasis, Input, Marquee, Headline, FinePrint, DefinedTerm, Footnote,
     ToAddress, FromAddress, SubScript, SuperScript );

  -- Text Styles
  procedure SetTextStyle( style : ATextStyle );
  function  GetTextStyle return ATextStyle;

  -- Text Colour
  procedure SetTextColour( name : APenColourName );
  function  GetTextColour return APenColourName;

  -- Text Font
  procedure SetTextFont( font : in string; size : natural := 0 );
  procedure SetTextFont( fonts : in StrList.Vector; size : natural := 0 );
  procedure GetTextFont( font : out Unbounded_String; size : out natural );
  procedure GetFontNameList( TheList : out StrList.Vector);
  procedure GetFontSizeList( Font : in String; TheList : out StrList.Vector);

  -- Text Sizes (always 1 pixel each for text screens)

  function GetTextHeight( ch : character ) return integer;
  function GetTextHeight( s  : string) return integer;
  function GetTextWidth( ch : character ) return integer;
  function GetTextWidth( s  : string ) return integer;
    pragma Inline( GetTextHeight );
    pragma Inline( GetTextWidth );

  ---> Sound Functions
  --
  -- This is strickly a draft.

  subtype AVoice is natural; -- voice number
  subtype ASound is APathName; -- sound path
  subtype ASong  is natural; -- song number

  -- Digital Sound
  procedure PlaySound( sound : ASound );
  procedure PlaySound( voice : AVoice; sound : ASound;
                       angle      : float := 0.0;
                       volume     : float := 100.0;
                       freqchange : float := 0.0 );
  procedure StopSound( voice : AVoice );
  procedure StopSounds;

  -- Songs
  procedure PlaySong( song : ASong );
  procedure StopSong;

  -- Misc Functions
  function  GetFreeVoice return AVoice;
  function  GetMasterVolume return float;
  procedure SetMasterVolume( volume : float );


  ---> Misc I/O Functions
  --
  -- BeepStyles describe the type of beep to be used

  type BeepStyles is (Normal, Success, Failure, Warning, Status, BadInput,
       HourChime, QuarterChime1, QuarterChime2, QuarterChime3, Alarm,
       NewMail, LowPower, Startup, Shutdown );

  procedure MoveToGlobal( x, y : in integer );
  pragma export( C, MoveToGlobal, "move_to_global" );
  procedure MoveForward( dist : float );
  procedure Beep( style : BeepStyles );
  procedure Cls;
    pragma Import( C, Cls, "Cls" );      -- Curses move/clrtobot
  procedure FlushKeys;                   -- Curses' flushinp
    pragma Import( C, FlushKeys, "FlushKeys" );
  --procedure Refresh;                     -- Curses' refresh
  --  pragma Import( C, Refresh, "Refresh" );


  ---> Basic Input
  --
  -- Modeled on three device types:
  -- 1. ASCII Input Device (eg. keyboard) -- required
  -- 2. Location Device    (eg. mouse)
  -- 3. Direction Device   (eg. joystick)
  --
  -- On demand functions (avoids input event handling):
  --
  -- Mouse location is especially useful

  subtype ADirection is float; -- 0 to 360 degrees
  subtype AVelocity  is float; -- 0 to 100 percent

  function Keypress( shortblock : boolean ) return character;
      -- get key, null if none; shortblock uses half-delay
  procedure GetKey( c : out character ); -- get key, wait if none
  pragma export( C, GetKey, "get_key" );
  procedure GetLocation( x, y : out integer ); -- get mouse
  procedure GetDirection( direction : out ADirection;
                          velocity : out AVelocity ); -- get joystick

  ---> Input Event Handling
  --
  -- Assumes that there is only one data entry stream and one locator
  -- stream (may represent the input of more than one device).  OS events
  -- handled by core_system's IPC.
  --
  -- NullInput       - return with no wait on GetInput
  -- KeyInput        - given key was pressed
  -- HeldKeyInput    - give key is being held (may not be supported)
  -- DirectionInput  - direction and distance (eg. joystick)
  -- LocationInput   - a pair of coordinates (eg. change in mouse)
  -- ButtonDownInput - button being pressed (eg. mouse or joystick)
  -- ButtonUpInput   - button being released (eg. mouse or joystick)
  -- MoveInput       - mouse moved
  -- HeartBeatInput  - "application busy" event for screen savers, etc.
  -- UserInput       - user-defined event

  type AnInput is (NullInput, KeyInput, HeldKeyInput, DirectionInput,
       LocationInput, ButtonDownInput, ButtonUpInput, HeartBeatInput,
       MoveInput, UserInput);
  pragma convention( C, AnInput );

  type AnInputRecord (InputType : AnInput := NullInput) is record
       TimeStamp : Ada.Calendar.Time; -- time of the event
       case InputType is
       when NullInput         => null;                   -- no data
       when KeyInput          => Key        : character; -- key typed
       when HeldKeyInput      => HeldKey    : character; -- key held
       when DirectionInput    => Direction  : ADirection;-- dir/degrees
                                 Velocity   : AVelocity; -- 0...100%
       when LocationInput     => X, Y       : integer;   -- location/grid
       when ButtonDownInput   => DownButton : integer;   -- button pressed
                                 DownLocationX : integer;
                                 DownLocationY : integer;
       when ButtonUpInput     => UpButton   : integer;   -- button released
                                 UpLocationX : integer;
                                 UpLocationY : integer;
       when HeartBeatInput    => null;                   -- no data
       when MoveInput         => MoveLocationX : integer;  -- moved
                                 MoveLocationY : integer;
       when UserInput         => id         : long_integer; -- user defined
       end case;
  end record;
  type AResponseTime is (Blocking, -- Wait Indefinitely for input
                         Erratic,  -- Give up after a fraction of a sec.
                         Instant   -- Give up immediately
  );
  pragma convention( C, AResponseTime );

  -- Standard Calls
   procedure GetInput( e : out AnInputRecord; response : AResponseTime
     := Blocking );
  --pragma export( CPP, GetInput, "get_input" );

  procedure SetInput( e : AnInputRecord; usetime : boolean := false );
  --pragma export( CPP, SetInput, "set_input" );

  procedure HeartBeat; -- shorthand call for SetInput( SomeHeartBeatRec );
  pragma export( C, Heartbeat, "heart_beat" );

  procedure SetInputString( s : string ); -- post string to input queue

  procedure FlushInput;
  pragma export( C, FlushInput, "flush_input" );

  function  GetInputLength return Natural;
  pragma export( C, GetInputLength, "get_input_length" );

  procedure WaitFor( ticks : integer ); -- wait, handling any input
  pragma export( C, WaitFor, "wait_for" );


  ---> Text Output
  --

  procedure Draw( s : string );
  procedure Draw( s : in string; fieldwidth : integer; elipsis:boolean := false );
  procedure DrawEdit( s : in String; fieldwidth : integer; am:boolean );
  procedure Draw( c : character );
  procedure Draw( i : integer );
  procedure Draw( l : long_integer );
  procedure Draw( f : float );
  procedure DrawLn;
  pragma export( C, DrawLn, "draw_ln" );

  -- Intended for C++ since Ada can't mangle names

  procedure DrawCoord( r : ARect );

  --- Error Output
  --
  -- Work the same as Draw commands, but automatically position themselves
  -- on the screen and switch text style to normal for visibility.

  procedure DrawErr( s : string );        -- write a string
  procedure DrawErr( i : integer );       -- write an integer
  procedure DrawErr( l : long_integer );  -- write a long integer
  procedure DrawErr( i : AnInputRecord ); -- dump an input record
  procedure DrawErrLn;                    -- move to next free error line
  pragma export( C, DrawErrLn, "draw_errln" );

  ---> Basic Pen Drawing
  --
  -- Works with the assumption of 80x24 grid.

  -- Line Drawing functions
  procedure DrawLine( x1, y1, x2, y2 : in integer );
  pragma export( CPP, DrawLine, "draw_line" );

  procedure DrawHorizontalLine( x1, x2, y1 : in integer );
  pragma export( CPP, DrawHorizontalLine, "draw_horizontal_line" );

  procedure DrawVerticalLine( y1, y2, x1 : in integer );
  pragma export( CPP, DrawVerticalLine, "draw_vertical_line" );

  -- Rectangle Drawing functions

  procedure FrameRect( r : in ARect );
  pragma export( CPP, FrameRect, "frame_rect" );

  procedure FrameRect3D( r : in ARect );
  pragma export( CPP, FrameRect3D, "frame_rect_3d" );

  procedure FramedRect( r : in ARect; ForeColour,BackColour:in APenColourName);
  pragma export( CPP, FramedRect, "framed_rect" );

  procedure FillRect( r : in ARect; Colour : in APenColourName );
  pragma export( CPP, FillRect, "fill_rect" );

  procedure PaintRect( r : in ARect );
  pragma export( CPP, PaintRect, "paint_rect" );

  procedure EraseRect( r : in ARect );
  pragma export( CPP, EraseRect, "erase_rect" );

-- Circle/Oval drawing functions
procedure FrameOval( r : in ARect ) renames FrameRect;
procedure FramedOval( r : in ARect; ForeColour, BackColour : in APenColourName)
   renames FramedRect;
procedure FillOval( r : ARect; Colour : in APenColourName ) renames FillRect;
procedure PaintOval( r : ARect ) renames PaintRect;
procedure EraseOval( r : ARect ) renames EraseRect;


---> Region Drawing functions
--
-- For some future day when you can draw to all windows.

subtype ARegion is RectList.Set; -- just a list of rectangles

-- Region Allocation
-- allocate
-- deallocate
procedure ClearRegion( region : in out ARegion ) renames RectList.Clear;

  -- Defining Regions
procedure SetRectRegion( region : in out ARegion; rect : ARect );

  -- Manipulating and Testing Regions

procedure OffsetRegion( region : in out ARegion; dx, dy : integer );
  --procedure InsetRegion( region : in out ARegion );
procedure InRegion( x, y : integer; region : in out ARegion; result : out boolean );
procedure InRegion( r : ARect; region : in out ARegion; result : out boolean );
procedure InRegion( r, region : in out ARegion; result : out boolean );

procedure AddRect( region : in out ARegion; r : ARect ) renames
  RectList.Insert;
procedure AddRegion( region, region2add : in out ARegion );
--procedure SubRegion( region, region2sub : in out ARegion );

-- procedure SetClipRegion( r : in out ARegion );
-- Not yet written.

---> Pictures
--
subtype APictureID is natural;
NoPictureID : constant APictureID := 0;

function  RegisterPicture( path : string ) return APictureID;
--function  CopyPicture( id : APictureID ) return APictureID;
--procedure ClearPicture( id : APictureID );
--procedure InsetPicture( id : APictureID, dx, dy : integer );
function  SavePicture( path, title : in String; bounds : ARect )
    return APictureID;
procedure DrawPicture( picture : APictureID; bounds : ARect );
procedure ScreenDump;

---> Caching/Spooling support
--
-- In part to support Curses' caching, and in part to allow clients in
-- a client/server scenario to optimize their drawing.  On displays
-- that don't use caching, has no effect.

procedure WaitToReveal; -- enable spooling/caching
pragma export( C, WaitToReveal, "wait_to_reveal" );

procedure Reveal;       -- spooling/caching complete
pragma export( C, Reveal, "reveal" );

procedure RevealNow;    -- forced revealing, no effect on reveal nesting
pragma export( C, RevealNow, "reveal_now" );

private
   pragma Inline( GetPenColour );
   pragma Inline( SetTextStyle );
   pragma Inline( GetTextStyle );
   pragma Inline( MoveToGlobal );
end userio;
