/*
**	termEmulationProcess.c
**
**	Terminal emulation process
**
**	Copyright © 1990-1995 by Olaf `Olsen' Barthel
**		All Rights Reserved
*/

#include "termGlobal.h"

STATIC struct Process *EmulationProcess;

STATIC VOID __saveds
EmulationProcessEntry(VOID)
{
	if(TerminalQueue = CreateMsgQueue(NULL,40))
	{
		ULONG		 Mask = SIG_KILL | TerminalQueue -> SigMask;
		struct DataMsg	*Msg;
		struct MsgQueue	*Queue = TerminalQueue;
		BOOLEAN		 Done = FALSE;

		EmulationProcess = (struct Process *)FindTask(NULL);

		Signal(ThisProcess,SIG_HANDSHAKE);

		do
		{
			if(Wait(Mask) & SIG_KILL)
			{
				Forbid();

				TerminalQueue = NULL;

				Permit();

				break;
			}

			ObtainSemaphore(&TerminalSemaphore);

			ClearCursor();

			while(Msg = GetMsgItem(TerminalQueue))
			{
					/* Remember the data. */

				if(RememberOutput)
					RememberOutputText(Msg -> Data,Msg -> Size);

				(*ConProcessData)(Msg -> Data,Msg -> Size);

				DeleteMsgItem(Msg);

				if(SetSignal(0,0) & SIG_KILL)
				{
					Forbid();

					TerminalQueue = NULL;

					Permit();

					Done = TRUE;

					break;
				}
			}

			DrawCursor();

			ReleaseSemaphore(&TerminalSemaphore);
		}
		while(!Done);

		while(Msg = GetMsgItem(Queue))
			DeleteMsgItem(Msg);

		DeleteMsgQueue(Queue);
	}

	Forbid();

	EmulationProcess = NULL;

	Signal(ThisProcess,SIG_HANDSHAKE);
}

VOID
DeleteEmulationProcess()
{
	if(EmulationProcess)
	{
		Forbid();

		Signal(EmulationProcess,SIG_KILL);

		ClrSignal(SIG_HANDSHAKE);

		Wait(SIG_HANDSHAKE);

		Permit();
	}
}

BOOLEAN
CreateEmulationProcess()
{
	if(!EmulationProcess)
	{
		Forbid();

		if(CreateNewProcTags(
			NP_Name,	"term Emulation Process",
			NP_Priority,	SysBase -> ThisTask -> tc_Node . ln_Pri,
			NP_Entry,	EmulationProcessEntry,
			NP_StackSize,	6000,
			NP_WindowPtr,	Window,
		TAG_DONE))
		{
			ClrSignal(SIG_HANDSHAKE);

			Wait(SIG_HANDSHAKE);
		}

		Permit();
	}

	if(EmulationProcess)
		return(TRUE);
	else
		return(FALSE);
}
