/* --- Copyright University of Sussex 1996. All rights reserved. ----------
 * File:			C.win32/extern/src/console.c
 * Purpose:			Console I/O
 * Author:			Robert John Duncan, Jul 11 1994 (see revisions)
 */

#include "popcore.h"

static BOOL CALLBACK console_ctrl_handler(DWORD event)
	/*	Handler for console-generated events
	*/
{
	switch (event) {
		case CTRL_C_EVENT:
			pop_signal(POP_SIG_INT);
			return TRUE;

		case CTRL_BREAK_EVENT:
			pop_signal(POP_SIG_INT);
			return TRUE;

		case CTRL_CLOSE_EVENT:
		case CTRL_LOGOFF_EVENT:
		case CTRL_SHUTDOWN_EVENT:
			pop_signal(POP_SIG_TERM);
			/* the signal may have killed us already; however... */
			if (pop_in_console_read) {
				/* pop is trapped in a console read so won't have seen
				   the signal; the only way to interrupt that is by
				   closing the handle
				*/
				CloseHandle(pop_in_console_read);
				/* once we've done that there's no point in trying to
				   continue: wait one second to give pop a chance to
				   clean up and then return FALSE for normal termination
				*/
				Sleep(1000);
				return FALSE;
			}
			else {
				/* wait one second for pop to clean up then, if we're
				   still running, return TRUE to display the End Task
				   dialog
				*/
				Sleep(1000);
				return TRUE;
			}

		default:
			/* what else is there? */
			return FALSE;
	}
}

void pop_init_console(void)
	/*	Initialise the console for Poplog
	*/
{
	static BOOL done = FALSE;
	if (!done)
		done = SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
}

/* --- Revision History ---------------------------------------------------
--- Robert Duncan, Mar 29 1996
		More sophisticated control handler copes better with close events
--- Robert John Duncan, Feb  7 1996
		Took out exception from pop_init_console because it's no longer
		called as part of initialisation but only when a console device is
		first opened.
--- Robert John Duncan, Jan  8 1996
		Mode changes and prompting now done differently in "io.c"
 */
