/*
**	$Id: TextDisplay.cpp 1.7 1995/12/03 12:16:23 olsen Exp olsen $
**
**	:ts=4
*/

/*
 * Amiga changes copyright © 1995 by Olaf Barthel, All Rights Reserved
 *
 * Copyright (c) 1992, 1993 Arno Augustin, Frank Hoering, University of
 * Erlangen-Nuremberg, Germany.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	Erlangen-Nuremberg, Germany.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
 * EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software has not been validated by the ``Bundesamt fuer Zulassungen in
 * der Telekommunikation'' of the ``Deutsche Bundepost Telekom'' and thus
 * must not be used for accessing the BTX-Network of the Telekom in Germany.
 *
 * Diese Software hat keine Zulassung durch das Bundesamt fuer Zulassungen in
 * der Telekommunikation der Deutschen Bundespost Telekom und darf daher nicht
 * am Netz der Deutschen Bundespost Telekom in Deutschland betrieben werden.
 */

/****************************************************************************/

#include <clib/intuition_protos.h>
#include <clib/graphics_protos.h>
#include <clib/utility_protos.h>
#include <clib/keymap_protos.h>
#include <clib/exec_protos.h>
#include <clib/dos_protos.h>
#include <clib/macros.h>

#ifdef __SASC
#include <pragmas/intuition_pragmas.h>
#include <pragmas/graphics_pragmas.h>
#include <pragmas/utility_pragmas.h>
#include <pragmas/keymap_pragmas.h>
#include <pragmas/exec_pragmas.h>
#include <pragmas/dos_pragmas.h>

extern struct IntuitionBase *IntuitionBase;
extern struct GfxBase		*GfxBase;
extern struct ExecBase		*SysBase;
extern struct DosLibrary	*DOSBase;
extern struct Library		*KeymapBase;
extern struct Library		*UtilityBase;
#endif	// __SASC

#include <string.h>
#include <stdio.h>

/****************************************************************************/

#ifndef _TEXTDISPLAY_HPP
#include "TextDisplay.hpp"
#endif

#ifndef _FONT_H
#include "Font.h"
#endif

#ifndef _RAWKEYS_H
#include "RawKeys.h"
#endif

/****************************************************************************/

#define SPREAD(v) ((((ULONG)v) << 24) | (((ULONG)v) << 16) | (((ULONG)v) << 8) | ((ULONG)v))

TextDisplay::TextDisplay()
{
	Window	= NULL;
	Font	= NULL;
}

TextDisplay::~TextDisplay()
{
	Close();
}

VOID TextDisplay::Close(VOID)
{
	if(Window)
	{
		CloseWindow(Window);
		Window = NULL;
	}

	if(Font)
	{
		CloseFont(Font);
		Font = NULL;
	}
}

LONG TextDisplay::Open(STRPTR PubScreenName,int XScale,int YScale,BOOL DirectRender)
{
	extern struct GfxBase *GfxBase;

	struct TextAttr SystemText;

	SystemText.ta_Name	= GfxBase->DefaultFont->tf_Message.mn_Node.ln_Name;
	SystemText.ta_YSize	= GfxBase->DefaultFont->tf_YSize;
	SystemText.ta_Style	= GfxBase->DefaultFont->tf_Style;
	SystemText.ta_Flags	= GfxBase->DefaultFont->tf_Flags;

	if(Font = OpenFont(&SystemText))
	{
		FontWidth	= Font->tf_XSize;
		FontHeight	= Font->tf_YSize;

		if(Window = OpenWindowTags(NULL,
			WA_DragBar,				TRUE,
			WA_DepthGadget,			TRUE,
			WA_CloseGadget,			TRUE,
			WA_Title,				"xBTX",
			WA_InnerWidth,			40 * FontWidth,
			WA_InnerHeight,			24 * FontHeight,
			WA_RMBTrap,				TRUE,
			WA_IDCMP,				IDCMP_MOUSEBUTTONS | IDCMP_RAWKEY | IDCMP_CLOSEWINDOW,
			WA_Activate,			TRUE,
			WA_AutoAdjust,			FALSE,
			WA_PubScreenName,		PubScreenName,
			WA_PubScreenFallBack,	TRUE,
		TAG_DONE))
		{
			struct DrawInfo *DrawInfo;

			if(DrawInfo = GetScreenDrawInfo(Window -> WScreen))
			{
				FgPen	= DrawInfo -> dri_Pens[TEXTPEN];
				BgPen	= DrawInfo -> dri_Pens[BACKGROUNDPEN];

				MaxPen	= MAX(FgPen,BgPen);

				RPort = Window->RPort;

				SetFont(RPort,Font);

				SetMaxPen(RPort,MaxPen);

				SetABPenDrMd(RPort,BgPen,0,JAM1);
				RectFill(RPort,Window->BorderLeft,Window->BorderTop,Window->Width - (Window->BorderRight+1),Window->Height - (Window->BorderBottom+1));

				SetABPenDrMd(RPort,FgPen,BgPen,JAM2);

				WindowPort = Window->UserPort;
				WindowMask = 1UL << WindowPort->mp_SigBit;

				FreeScreenDrawInfo(Window -> WScreen,DrawInfo);

				ScreenToFront(Window->WScreen);

				return(0);
			}

			CloseWindow(Window);
			Window = NULL;
		}
		else
		{
			CloseFont(Font);
			Font = NULL;
		}
	}

	return(-1);
}

VOID TextDisplay::PutLine(STRPTR Line)
{
	if(Line)
	{
		int i,len;

		SetAPen(RPort,BgPen);
		RectFill(RPort,Window->BorderLeft,Window->BorderTop + PutIndex * FontHeight,Window->Width - (Window->BorderRight + 1),Window->BorderTop + (PutIndex + 1) * FontHeight - 1);
		SetAPen(RPort,FgPen);

		if((len = (int)strlen(Line)) > 40)
			len = 40;

		for(i = 0 ; i < len ; i++)
			xputc(Line[i],0,i,PutIndex,0,0,0,0,7,0);

		PutIndex = (WORD)((PutIndex + 1) % (*rows));
	}
	else
	{
		PutIndex = 0;
		xclearscreen();
	}
}

void TextDisplay::xputc(int c,int s,int x,int y,int xdouble,int ydouble,int underline,int d,int fg,int bg)
{
   static unsigned char supp_map[96] =
      { ' ', 0xa1, 0xa2, 0xa3, '$', 0xa5, '#', 0xa7, 0xa4, '`', '\"', 0xab,
	0, 0, 0, 0, 0xb0, 0xb1, 0xb2, 0xb3, 0xd7, 0xb5, 0xb6, 0xb7, 0xf7,
	'\'', '\"', 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0, 0x60, 0x27, 0, '~',
	0xaf, 0, 0, 0x22, 0x22, 0xb0, 0, 0, 0x22, 0xb8, 0, 0xad, 0xb9, 0xae,
	0xa9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xc6, 0, 0, 0, 0, 0,
	0, 0, 0xd8, 0, 0, 0xfe, 0, 0, 0, 0, 0xe6, 0, 0, 0, 0, 0, 0, 0, 0xf8,
	0, 0xdf, 0xde, 0, 0, 0 };

   static unsigned char diacritical_map[26*2][16] = {
    { 0, 0xc0, 0xc1, 0xc2, 0xc3, 0, 0, 0, 0xc4, 0xc4, 0xc5, 0, 0, 0xc4, 0, 0 },
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },     /* B */
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xc7, 0, 0, 0, 0 },
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },  /* D */
    { 0, 0xc8, 0xc9, 0xca, 0, 0, 0, 0, 0xcb, 0xcb, 0, 0, 0, 0xcb, 0, 0 },
    { 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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /* t */
    { 0, 0xf9, 0xfa, 0xfb, 0, 0, 0, 0, 0xfc, 0xfc, 0, 0, 0, 0xfc, 0, 0 },
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
    { 0, 0, 0xfd, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 0, 0, 0xff, 0, 0 },  /* y */
    { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } };

	if(x<0 || y<0 || x>39 || y>(*rows)-1)
		return;
	else
	{
		UBYTE Char;

		/* ASCII out of  1st supplementary set of mosaic characters */
		if(s==SUP1 && c>=0x40 && c<=0x5f)
			Char = (UBYTE)c;
		else
			Char = (UBYTE)' ';

		/* supplementary set of graphic characters */
		if(s==SUPP && supp_map[c-0x20])
			Char = (UBYTE)supp_map[c-0x20];
		else
		{
			/* composed characters, diacritical marks (page 123) */
			if(s==PRIM)
			{
				if(!d)
					Char = (UBYTE)c;  /* ASCII character */
				else
				{
					if(d>=0x40 && d<=0x4f)
					{
						if(c>=0x41 && c<=0x5a && diacritical_map[c-0x41][d&0xf])
							Char = (UBYTE)diacritical_map[c-0x41][d&0xf];
						else
						{
							if(c>=0x61 && c<=0x7a && diacritical_map[c-0x61+26][d&0xf])
								Char = (UBYTE)diacritical_map[c-0x61+26][d&0xf];
						}
					}
				}
			}
		}

		PutChar(Char,x,y);

		if(xdouble)
		{
			PutChar((UBYTE)' ',x + 1,y);

			if(ydouble)
			{
				PutChar((UBYTE)' ',x,y + 1);
				PutChar((UBYTE)' ',x + 1,y + 1);
			}
		}
		else
		{
			if(ydouble)
				PutChar((UBYTE)' ',x,y + 1);
		}
	}
}

void TextDisplay::xclearscreen()
{
	SetAPen(RPort,BgPen);
	RectFill(RPort,Window->BorderLeft,Window->BorderTop,Window->Width - (Window->BorderRight + 1),Window->Height - (Window->BorderBottom + 1));
	SetAPen(RPort,FgPen);
}

void TextDisplay::xcursor(int x,int y)
{
	SetABPenDrMd(RPort,(ULONG)~0,0,JAM1 | COMPLEMENT);
	SetMaxPen(RPort,(ULONG)~0);

	RectFill(RPort,Window->BorderLeft + x*FontWidth,Window->BorderTop + y*FontHeight,Window->BorderLeft + x*FontWidth + FontWidth-1,Window->BorderTop + y*FontHeight + FontHeight-1);

	SetMaxPen(RPort,MaxPen);
	SetABPenDrMd(RPort,FgPen,BgPen,JAM2);
}

/******************************************************************************/

ULONG TextDisplay::WaitMask(VOID)
{
	return(WindowMask);
}

LONG TextDisplay::Waiting(VOID)
{
	if(WaitingChar == -1)
	{
		struct IntuiMessage *Message;

		while(Message = (struct IntuiMessage *)GetMsg(WindowPort))
		{
			if(Message->Class == IDCMP_RAWKEY)
			{
				if((WaitingChar = (WORD)MapKey(Message)) >= 0)
				{
					ReplyMsg((struct Message *)Message);

					return(1);
				}
			}
			else
			{
				if(Message->Class == IDCMP_CLOSEWINDOW)
				{
					ReplyMsg((struct Message *)Message);

					WaitingChar = '\033';

					return(1);
				}
			}

			ReplyMsg((struct Message *)Message);
		}

		return(0);
	}
	else
		return(1);
}

LONG TextDisplay::GetChar(VOID)
{
	if(WaitingChar == -1)
	{
		struct IntuiMessage *Message;

		while(Message = (struct IntuiMessage *)GetMsg(WindowPort))
		{
			if(Message->Class == IDCMP_RAWKEY)
			{
				LONG Result = MapKey(Message);

				ReplyMsg((struct Message *)Message);

				return(Result);
			}
			else
			{
				if(Message->Class == IDCMP_CLOSEWINDOW)
				{
					ReplyMsg((struct Message *)Message);

					return('\033');
				}
			}

			ReplyMsg((struct Message *)Message);
		}

		return(-1);
	}
	else
	{
		LONG Result = WaitingChar;

		WaitingChar = -1;

		return(Result);
	}
}

LONG TextDisplay::MapKey(struct IntuiMessage *Message)
{
	static LONG Table[][2] =
	{
		RAWKEY_CursorUp,	KEY_CursorUp,
		RAWKEY_CursorDown,	KEY_CursorDown,
		RAWKEY_CursorRight, KEY_CursorRight,
		RAWKEY_CursorLeft,	KEY_CursorLeft,

		RAWKEY_Help,		KEY_Help,

		RAWKEY_F1,			-1,
		RAWKEY_F2,			-1,
		RAWKEY_F3,			-1,
		RAWKEY_F4,			-1,
		RAWKEY_F5,			-1,
		RAWKEY_F6,			-1,
		RAWKEY_F7,			-1,
		RAWKEY_F8,			-1,
		RAWKEY_F9,			-1,
		RAWKEY_F10, 		-1,

		-1
	};

	UBYTE Buffer[10];
	LONG i;

	for(i = 0 ; Table[i][0] != -1 ; i++)
	{
		if((Message->Code & ~IECODE_UP_PREFIX) == Table[i][0])
		{
			if(Message->Code & IECODE_UP_PREFIX)
				return(-1);
			else
				return(Table[i][1]);
		}
	}

	Event.ie_Class		= IECLASS_RAWKEY;
	Event.ie_SubClass 	= 0;
	Event.ie_Code 		= Message->Code;
	Event.ie_Qualifier	= Message->Qualifier;
	Event.ie_EventAddress = (APTR *) *((ULONG *)Message->IAddress);

	Buffer[0] = 0;

	if(MapRawKey(&Event,(char *)&Buffer[0],10,(struct KeyMap *)NULL) > 0)
		return(Buffer[0]);
	else
		return(-1);
}

VOID TextDisplay::PutChar(UBYTE c,int x,int y)
{
	Move(RPort,Window->BorderLeft + x * FontWidth,Window->BorderTop + y * FontHeight + RPort->TxBaseline);
	Text(RPort,(STRPTR)&c,1);
}
