/*
 * 4m v2.15 (signals.c)
 * (C) Copyright 1990 by Carrick Sean Casey
 * (C) Copyright 1993 by Scott Chasin and Michaeljon Miller
 *
 * 3-24-93 See file COPYING for copyright information.
 *
 * Signal handling
 */

#include "4m.h"
#include "externs.h"
#include "../h/term.h"
#include <signal.h>

/* Note that some of these routines set "continue" to 1. Continue is used */
/* by a few other 4m routines to see if they've been interrupted */

extern SIGTYPE do_exit ();
SIGTYPE askquit ();
SIGTYPE suspend ();

/* The signal stuff is not portable, and should be in unix.c. */

#define	mask(s)	(1 << ((s)-1))

/* set up the signal trappers */


extern int write ();
extern int _filbuf ();


extern void unset_term ();
extern void set_term ();

void dump()
{
    if (!dumb)
        gotoxy(0, lines - 2);

    if (gv.interactive)
        unset_term();

    abort();
    /* NOTREACHED */
}

void trapsignals()
{
 /* exit on a hangup or terminate signal */
    signal(SIGHUP, do_exit);
    signal(SIGTERM, do_exit);

 /* on an interrupt, verify the user wants to quit */
    signal(SIGINT, askquit);

 /* suspend on a stop signal */
    signal(SIGTSTP, suspend);
}


/* handle a stop signal */
/* this technique is something I learned from some other software */
/* someday I need to learn just why it works */

SIGTYPE suspend()
{
    unset_term();
    signal(SIGTSTP, SIG_DFL);

#if defined (sigblock) && defined (setsigmask)
    sigsetmask(sigblock(0) & ~mask(SIGTSTP));
    kill(0, SIGTSTP);
    sigblock(mask(SIGTSTP));
#endif

    signal(SIGTSTP, suspend);
    set_term();
    continued = 1;

}


/* verify that the user wants to quit */

SIGTYPE askquit()
{
    int c;
    static char out[3] = {'\0', '\r', '\n'};

    signal(SIGINT, SIG_IGN);

    if (!dumb) {
        hidecursor();
        gotoxy(0, lines - 2);
        setinverse();
    }
    write(1, "\rReally Quit? ", 14);
    if (!dumb)
        setnormal();
    if ((c = getchar()) == EOF)
        do_exit();
    else {
        out[0] = c;
        write(1, out, 3);
        if (c == 'Y' || c == 'y')
            do_exit();
        else {
            signal(SIGINT, askquit);
            continued = 1;
        }
    }

    if (!dumb) {
        gotoxy(0, lines - 2);
        clear_eol();
        gotoxy(0, lines - 2);
        showcursor();
    }

}
