/*
 * Routines which deal with the characteristics of the terminal.
 * Uses termcap to be as terminal-independent as possible.
 *
 * {{ Someday this should be rewritten to use curses. }}
 */

#ifdef AMIGA
/* Compile with -HPreHeader.q to get "less.h"! */
#else
#include "less.h"
#endif

#if XENIX
#include <sys/types.h>
#include <sys/ioctl.h>
#endif

#ifdef AMIGA
extern int sc_window_spec;   /* user's requested -z */
extern int scroll; /* half-page scroll length */
extern int nrow, ncol;
#else
#if TERMIO
#include <termio.h>
#else
#include <sgtty.h>
#endif
#endif

#ifdef TIOCGWINSZ
#include <sys/ioctl.h>
#else
/*
 * For the Unix PC (ATT 7300 & 3B1):
 * Since WIOCGETD is defined in sys/window.h, we can't use that to decide
 * whether to include sys/window.h.  Use SIGWIND from sys/signal.h instead.
 */
#include <signal.h>
#ifdef SIGWIND
#include <sys/window.h>
#endif
#endif


/*
 * Strings passed to tputs() to do various terminal functions.
 */
static char
        *sc_pad,                /* Pad string */
        *sc_home,               /* Cursor home */
        *sc_addline,            /* Add line, scroll down following lines */
        *sc_lower_left,         /* Cursor to last line, first column */
        *sc_move,               /* General cursor positioning */
        *sc_clear,              /* Clear screen */
        *sc_eol_clear,          /* Clear to end of line */
        *sc_s_in,               /* Enter standout (highlighted) mode */
        *sc_s_out,              /* Exit standout mode */
        *sc_u_in,               /* Enter underline mode */
        *sc_u_out,              /* Exit underline mode */
        *sc_b_in,               /* Enter bold mode */
        *sc_b_out,              /* Exit bold mode */
#ifdef AMIGA
        *sc_it_in,              /* Enter italic mode */
        *sc_it_out,             /* Exit italic mode */
        *sc_nv_in,              /* Enter inverse video mode */
        *sc_nv_out,             /* Exit inverse video mode */
#endif
        *sc_visual_bell,        /* Visual bell (flash screen) sequence */
        *sc_backspace,          /* Backspace cursor */
        *sc_init,               /* Startup terminal initialization */
        *sc_deinit;             /* Exit terminal de-intialization */
#ifdef DUMBTERM
static int dumb;
#endif
static int hard;

public int auto_wrap;           /* Terminal does \r\n when write past margin */
public int ignaw;               /* Terminal ignores \n immediately after wrap */
public int erase_char, kill_char; /* The user's erase and line-kill chars */
public int sc_width, sc_height; /* Height & width of screen */
public int sc_window = -1;      /* window size for forward and backward */
public int bo_width, be_width;  /* Printing width of boldface sequences */
public int ul_width, ue_width;  /* Printing width of underline sequences */
public int so_width, se_width;  /* Printing width of standout sequences */
public int it_width, ie_width;  /* Printing width of italic sequences */
public int nv_width, ne_width;  /* Printing width of inv video sequences */

/*
 * These two variables are sometimes defined in,
 * and needed by, the termcap library.
 * It may be necessary on some systems to declare them extern here.
 */
/*extern*/ short ospeed;        /* Terminal output baud rate */
/*extern*/ char PC;             /* Pad character */

extern int quiet;               /* If VERY_QUIET, use visual bell for bell */
#ifdef DUMBTERM
extern int know_dumb;           /* Don't complain about a dumb terminal */
#endif
extern int back_scroll;
char *tgetstr();
char *tgoto();

/*
 * Change terminal to "raw mode", or restore to "normal" mode.
 * "Raw mode" means
 *      1. An outstanding read will complete on receipt of a single keystroke.
 *      2. Input is not echoed.
 *      3. On output, \n is mapped to \r\n.
 *      4. \t is NOT expanded into spaces.
 *      5. Signal-causing characters such as ctrl-C (interrupt),
 *         etc. are NOT disabled.
 * It doesn't matter whether an input \n is mapped to \r, or vice versa.
 */
#ifdef __STDC__
void raw_mode (int on)
#else
        public void
raw_mode(on)
        int on;
#endif
{
#ifdef AMIGA
        extern int do_echo;

        if (on)
                do_echo = 0;
        else
                do_echo = 1;
        erase_char = 8; /* ^H */
        kill_char = 24; /* ^X */
#else
#if TERMIO
        struct termio s;
        static struct termio save_term;

        if (on)
        {
                /*
                 * Get terminal modes.
                 */
                ioctl(2, TCGETA, &s);

                /*
                 * Save modes and set certain variables dependent on modes.
                 */
                save_term = s;
                ospeed = s.c_cflag & CBAUD;
                erase_char = s.c_cc[VERASE];
                kill_char = s.c_cc[VKILL];

                /*
                 * Set the modes to the way we want them.
                 */
                s.c_lflag &= ~(ICANON|ECHO|ECHOE|ECHOK|ECHONL);
                s.c_oflag |=  (OPOST|ONLCR|TAB3);
                s.c_oflag &= ~(OCRNL|ONOCR|ONLRET);
                s.c_cc[VMIN] = 1;
                s.c_cc[VTIME] = 0;
        } else
        {
                /*
                 * Restore saved modes.
                 */
                s = save_term;
        }
        ioctl(2, TCSETAW, &s);
#else
        struct sgttyb s;
        static struct sgttyb save_term;

        if (on)
        {
                /*
                 * Get terminal modes.
                 */
                ioctl(2, TIOCGETP, &s);

                /*
                 * Save modes and set certain variables dependent on modes.
                 */
                save_term = s;
                ospeed = s.sg_ospeed;
                erase_char = s.sg_erase;
                kill_char = s.sg_kill;

                /*
                 * Set the modes to the way we want them.
                 */
                s.sg_flags |= CBREAK;
                s.sg_flags &= ~(ECHO|XTABS);
        } else
        {
                /*
                 * Restore saved modes.
                 */
                s = save_term;
        }
        ioctl(2, TIOCSETN, &s);
#endif
#endif
}

#ifdef DUMBTERM
        static void
cannot(s)
        char *s;
{
        char message[100];

        if (know_dumb)
                /*
                 * He knows he has a dumb terminal, so don't tell him.
                 */
                return;

        sprintf(message, "WARNING: terminal cannot \"%s\"", s);
        error(message);
}
#endif

#ifdef AMIGA
/*
 * Set forward and backward scrolling limits based upon user's requests
 * and screen size
 */
#ifdef __STDC__
void set_scroll (void)
#else
        public void
set_scroll()
#endif
{
        if (sc_window_spec > 0)
            sc_window = (sc_window_spec < nrow? sc_window_spec: nrow - 1);
        else
            sc_window = nrow - 1;
}
#endif

/*
 * Get terminal capabilities via termcap.
 */
#ifdef __STDC__
void get_term (void)
#else
        public void
get_term()
#endif
{
#ifdef AMIGA
        static char go_to_home[10];

        getrowcol(); /* find out window size */
        scroll = nrow/2;
        set_scroll();

/* I didn't want to port termcap for now, but there is a version
 on fish #14 that someone might want to use */
        sc_pad = "";                /* Pad string */
        sc_home = "\x9b\x31;1H";           /* Cursor home */
        sc_addline = "\x9bL";       /* Add line, scroll down following lines */
        sprintf(go_to_home, "\x9b%d;1H", nrow);
        sc_lower_left = go_to_home;     /* Cursor to last line, first column */
        sc_move = "";               /* General cursor positioning */
        sc_clear = "\f";            /* Clear screen */
        sc_eol_clear = "\x9bK";     /* Clear to end of line */
        sc_s_in = "\x9b\x37m";   /* Enter standout (highlighted) mode */
        sc_s_out = "\x9b\x30m";         /* Exit standout mode */
        sc_u_in = "\x9b\x34m";         /* Enter underline mode */
        sc_u_out = "\x9b\x30m";         /* Exit underline mode */
        sc_b_in = "\x9b\x31m";         /* Enter bold mode */
        sc_b_out = "\x9b\x30m";       /* Exit bold mode */
        sc_it_in = "\x9b\x33m";     /* Enter italic mode */
        sc_it_out = "\x9b\x30m";    /* Exit italic mode */
        sc_nv_in = "\x9b\x37m";     /* Enter inverse video mode */
        sc_nv_out = "\x9b\x30m";    /* Exit inverse video mode */
        /* We define visual_bell to be null, because on the Amiga the
           ordinary BELL signal (^G) does a visual bell.  Thus, in the
           Amiga version of Less, the user's choice is between a visual
           bell (not quiet) and no indicator at all (quiet)
        */
        sc_visual_bell = NULL;    /* Visual bell (flash screen) sequence */
        sc_backspace = "\b";      /* Backspace cursor */
        sc_init = "";               /* Startup terminal initialization */
        sc_deinit = "";             /* Exit terminal de-intialization */
        sc_height = nrow;
        sc_width = ncol;

        so_width = 0;
        it_width = ie_width = nv_width = ne_width =
        be_width = bo_width = ue_width = ul_width = se_width = so_width;

#else
        char termbuf[2048];
        char *sp;
#ifdef TIOCGWINSZ
        struct winsize w;
#else
#ifdef WIOCGETD
        struct uwdata w;
#endif
#endif
        static char sbuf[1024];

        char *getenv();

        /*
         * Find out what kind of terminal this is.
         */
        if (tgetent(termbuf, getenv("TERM")) <= 0)
                dumb = 1;

        /*
         * Get size of the screen.
         */
#ifdef TIOCGWINSZ
        if (ioctl(2, TIOCGWINSZ, &w) == 0 && w.ws_row)
                sc_height = w.ws_row;
        else
#else
#ifdef WIOCGETD
        if (ioctl(2, WIOCGETD, &w) == 0 && w.uw_height)
                sc_height = w.uw_height/w.uw_vs;
        else
#endif
#endif
                sc_height = tgetnum("li");
        if (dumb || sc_height < 0 || tgetflag("hc"))
        {
                /* Oh no, this is a hardcopy terminal. */
                hard = 1;
                sc_height = 24;
        }
        /*
         * This is terrible - the following if "knows" that it is being
         * executed *after* command line and environment options have
         * already been parsed.  Should it be executed in the main program
         * instead?
         */
        if ((sc_window <= 0) || (sc_window >= sc_height))
                sc_window = sc_height-1;

#ifdef TIOCGWINSZ
        if (ioctl(2, TIOCGWINSZ, &w) == 0 && w.ws_col)
                sc_width = w.ws_col;
        else
#ifdef WIOCGETD
        if (ioctl(2, WIOCGETD, &w) == 0 && w.uw_width)
                sc_width = w.uw_width/w.uw_hs;
        else
#endif
#endif
                sc_width = tgetnum("co");
        if (dumb || sc_width < 0)
                sc_width = 80;

        auto_wrap = tgetflag("am");
        ignaw = tgetflag("xn");

        /*
         * Assumes termcap variable "sg" is the printing width of
         * the standout sequence, the end standout sequence,
         * the underline sequence, the end underline sequence,
         * the boldface sequence, and the end boldface sequence.
         */
        if ((so_width = tgetnum("sg")) < 0)
                so_width = 0;
        be_width = bo_width = ue_width = ul_width = se_width = so_width;

        /*
         * Get various string-valued capabilities.
         */
        sp = sbuf;

        sc_pad = (dumb) ? NULL : tgetstr("pc", &sp);
        if (sc_pad != NULL)
                PC = *sc_pad;

        sc_init = (dumb) ? NULL : tgetstr("ti", &sp);
        if (sc_init == NULL)
                sc_init = "";

        sc_deinit= (dumb) ? NULL : tgetstr("te", &sp);
        if (sc_deinit == NULL)
                sc_deinit = "";

        sc_eol_clear = (dumb) ? NULL : tgetstr("ce", &sp);
        if (hard || sc_eol_clear == NULL || *sc_eol_clear == '\0')
        {
                cannot("clear to end of line");
                sc_eol_clear = "";
        }

        sc_clear = (dumb) ? NULL : tgetstr("cl", &sp);
        if (hard || sc_clear == NULL || *sc_clear == '\0')
        {
                cannot("clear screen");
                sc_clear = "\n\n";
        }

        sc_move = (dumb) ? NULL : tgetstr("cm", &sp);
        if (hard || sc_move == NULL || *sc_move == '\0')
        {
                /*
                 * This is not an error here, because we don't
                 * always need sc_move.
                 * We need it only if we don't have home or lower-left.
                 */
                sc_move = "";
        }

        sc_s_in = (dumb) ? NULL : tgetstr("so", &sp);
        if (hard || sc_s_in == NULL)
                sc_s_in = "";

        sc_s_out = (dumb) ? NULL : tgetstr("se", &sp);
        if (hard || sc_s_out == NULL)
                sc_s_out = "";

        sc_u_in = (dumb) ? NULL : tgetstr("us", &sp);
        if (hard || sc_u_in == NULL)
                sc_u_in = sc_s_in;

        sc_u_out = (dumb) ? NULL : tgetstr("ue", &sp);
        if (hard || sc_u_out == NULL)
                sc_u_out = sc_s_out;

        sc_b_in = (dumb) ? NULL : tgetstr("md", &sp);
        if (hard || sc_b_in == NULL)
        {
                sc_b_in = sc_s_in;
                sc_b_out = sc_s_out;
        } else
        {
                sc_b_out = (dumb) ? NULL : tgetstr("me", &sp);
                if (hard || sc_b_out == NULL)
                        sc_b_out = "";
        }

        sc_visual_bell = (dumb) ? NULL : tgetstr("vb", &sp);
        if (hard || sc_visual_bell == NULL)
                sc_visual_bell = "";

        sc_home = (dumb) ? NULL : tgetstr("ho", &sp);
        if (hard || sc_home == NULL || *sc_home == '\0')
        {
                if (*sc_move == '\0')
                {
                        cannot("home cursor");
                        /*
                         * This last resort for sc_home is supposed to
                         * be an up-arrow suggesting moving to the
                         * top of the "virtual screen". (The one in
                         * your imagination as you try to use this on
                         * a hard copy terminal.)
                         */
                        sc_home = "|\b^";
                } else
                {
                        /*
                         * No "home" string,
                         * but we can use "move(0,0)".
                         */
                        strcpy(sp, tgoto(sc_move, 0, 0));
                        sc_home = sp;
                        sp += strlen(sp) + 1;
                }
        }

        sc_lower_left = (dumb) ? NULL : tgetstr("ll", &sp);
        if (hard || sc_lower_left == NULL || *sc_lower_left == '\0')
        {
                if (*sc_move == '\0')
                {
                        cannot("move cursor to lower left of screen");
                        sc_lower_left = "\r";
                } else
                {
                        /*
                         * No "lower-left" string,
                         * but we can use "move(0,last-line)".
                         */
                        strcpy(sp, tgoto(sc_move, 0, sc_height-1));
                        sc_lower_left = sp;
                        sp += strlen(sp) + 1;
                }
        }

        /*
         * To add a line at top of screen and scroll the display down,
         * we use "al" (add line) or "sr" (scroll reverse).
         */
        if (dumb)
                sc_addline = NULL;
        else if ((sc_addline = tgetstr("al", &sp)) == NULL ||
                 *sc_addline == '\0')
                sc_addline = tgetstr("sr", &sp);

        if (hard || sc_addline == NULL || *sc_addline == '\0')
        {
                cannot("scroll backwards");
                sc_addline = "";
                /* Force repaint on any backward movement */
                back_scroll = 0;
        }

        if (dumb || tgetflag("bs"))
                sc_backspace = "\b";
        else
        {
                sc_backspace = tgetstr("bc", &sp);
                if (sc_backspace == NULL || *sc_backspace == '\0')
                        sc_backspace = "\b";
        }
#endif
}


/*
 * Below are the functions which perform all the
 * terminal-specific screen manipulation.
 */


/*
 * Initialize terminal
 */
#ifdef __STDC__
void init (void)
#else
        public void
init()
#endif
{
        tputs(sc_init, sc_height, putchr);
}

/*
 * Deinitialize terminal
 */
#ifdef __STDC__
void deinit (void)
#else
        public void
deinit()
#endif
{
        tputs(sc_deinit, sc_height, putchr);
}

/*
 * Home cursor (move to upper left corner of screen).
 */
#ifdef __STDC__
void home (void)
#else
        public void
home()
#endif
{
        tputs(sc_home, 1, putchr);
}

/*
 * Add a blank line (called with cursor at home).
 * Should scroll the display down.
 */
#ifdef __STDC__
void add_line (void)
#else
        public void
add_line()
#endif
{
        tputs(sc_addline, sc_height, putchr);
}

/*
 * Move cursor to lower left corner of screen.
 */
#ifdef __STDC__
void lower_left (void)
#else
        public void
lower_left()
#endif
{
        tputs(sc_lower_left, 1, putchr);
}

/*
 * Ring the terminal bell.
 */
#ifdef __STDC__
void bell (void)
#else
        public void
bell()
#endif
{
        if (quiet == VERY_QUIET)
                vbell();
        else
                putchr('\7');
}

/*
 * Output the "visual bell", if there is one.
 */
#ifdef __STDC__
void vbell (void)
#else
        public void
vbell()
#endif
{
        if (*sc_visual_bell == '\0')
                return;
        tputs(sc_visual_bell, sc_height, putchr);
}

/*
 * Clear the screen.
 */
#ifdef __STDC__
void clear (void)
#else
        public void
clear()
#endif
{
        tputs(sc_clear, sc_height, putchr);
}

/*
 * Clear from the cursor to the end of the cursor's line.
 * {{ This must not move the cursor. }}
 */
#ifdef __STDC__
void clear_eol (void)
#else
        public void
clear_eol()
#endif
{
        tputs(sc_eol_clear, 1, putchr);
}

/*
 * Begin "standout" (bold, underline, or whatever).
 */
#ifdef __STDC__
void so_enter (void)
#else
        public void
so_enter()
#endif
{
        tputs(sc_s_in, 1, putchr);
}

/*
 * End "standout".
 */
#ifdef __STDC__
void so_exit (void)
#else
        public void
so_exit()
#endif
{
        tputs(sc_s_out, 1, putchr);
}

/*
 * Begin "underline" (hopefully real underlining,
 * otherwise whatever the terminal provides).
 */
#ifdef __STDC__
void ul_enter (void)
#else
        public void
ul_enter()
#endif
{
        tputs(sc_u_in, 1, putchr);
}

/*
 * End "underline".
 */
#ifdef __STDC__
void ul_exit (void)
#else
        public void
ul_exit()
#endif
{
        tputs(sc_u_out, 1, putchr);
}

/*
 * Begin "bold"
 */
#ifdef __STDC__
void bo_enter (void)
#else
        public void
bo_enter()
#endif
{
        tputs(sc_b_in, 1, putchr);
}

/*
 * End "bold".
 */
#ifdef __STDC__
void bo_exit (void)
#else
        public void
bo_exit()
#endif
{
        tputs(sc_b_out, 1, putchr);
}

#ifdef AMIGA
/*
 * Begin "italic" mode
 */
#ifdef __STDC__
void it_enter (void)
#else
        public void
it_enter()
#endif
{
        tputs(sc_it_in, 1, putchr);
}

/*
 * End "italic"
 */
#ifdef __STDC__
void it_exit (void)
#else
        public void
it_exit()
#endif
{
        tputs(sc_it_out, 1, putchr);
}

/*
 * Begin "inverse video"
 */
#ifdef __STDC__
void nv_enter (void)
#else
        public void
nv_enter()
#endif
{
        tputs(sc_nv_in, 1, putchr);
}

/*
 * End "inverse video"
 */
#ifdef __STDC__
void nv_exit (void)
#else
        public void
nv_exit()
#endif
{
        tputs(sc_nv_out, 1, putchr);
}
#endif

/*
 * Erase the character to the left of the cursor
 * and move the cursor left.
 */
#ifdef __STDC__
void backspace (void)
#else
        public void
backspace()
#endif
{
        /*
         * Try to erase the previous character by overstriking with a space.
         */
        tputs(sc_backspace, 1, putchr);
        putchr(' ');
        tputs(sc_backspace, 1, putchr);
}

/*
 * Output a plain backspace, without erasing the previous char.
 */
#ifdef __STDC__
void putbs (void)
#else
        public void
putbs()
#endif
{
        tputs(sc_backspace, 1, putchr);
}
