/*-
 * Copyright (c) 1993, 1994
 *	The Regents of the University of California.  All rights reserved.
 * Copyright (c) 1994, 1995
 *	Keith Bostic.  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
 *	California, Berkeley and its contributors.
 * 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 REGENTS AND CONTRIBUTORS ``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 REGENTS OR CONTRIBUTORS 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.
 */

#ifndef lint
static char sccsid[] = "@(#)sex_util.c	9.5 (Berkeley) 1/23/95";
#endif /* not lint */

#include <sys/types.h>
#include <sys/queue.h>
#include <sys/time.h>

#include <bitstring.h>
#include <errno.h>
#include <limits.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>

#include "compat.h"
#include <curses.h>
#include <db.h>
#include <regex.h>

#include "vi.h"
#include "excmd.h"
#include "sex_screen.h"

/*
 * sex_tsetup --
 *	Set up the ex terminal.
 */
int
sex_tsetup(sp, tp)
	SCR *sp;
	struct termios *tp;
{
	struct termios t;

	if (!F_ISSET(sp->gp, G_STDIN_TTY))
		return (0);

	if (tcgetattr(STDIN_FILENO, tp)) {
		msgq(sp, M_SYSERR, "tcgetattr");
		return (1);
	}

	/*
	 * Turn on canonical mode, with normal input and output processing.
	 * Start with the original terminal settings as the user probably
	 * had them (including any local extensions) set correctly for the
	 * current terminal.
	 *
	 * !!!
	 * We can't get everything that we need portably; for example, ONLCR,
	 * mapping <newline> to <carriage-return> on output isn't required
	 * by POSIX 1003.1b-1993.  If this turns out to be a problem, then
	 * we'll either have to play some games on the mapping, or we'll have
	 * to make all ex printf's output \r\n instead of \n.
	 */
	t = sp->gp->original_termios;
	t.c_lflag |= ECHO|ECHOE|ECHOK|ICANON|IEXTEN|ISIG;
#ifdef ECHOCTL
	t.c_lflag |= ECHOCTL;
#endif
#ifdef ECHOKE
	t.c_lflag |= ECHOKE;
#endif
	t.c_iflag |= ICRNL;
	t.c_oflag |= OPOST;
#ifdef ONLCR
	t.c_oflag |= ONLCR;
#endif

	if (tcsetattr(STDIN_FILENO, TCSADRAIN | TCSASOFT, &t)) {
		msgq(sp, M_SYSERR, "tcsetattr");
		return (1);
	}
	return (0);
}
	
/*
 * sex_tteardown --
 *	Tear down the ex terminal.
 */
int
sex_tteardown(sp, tp)
	SCR *sp;
	struct termios *tp;
{
	if (!F_ISSET(sp->gp, G_STDIN_TTY))
		return (0);
	if (tcsetattr(STDIN_FILENO, TCSADRAIN | TCSASOFT, tp)) {
		msgq(sp, M_SYSERR, "tcsetattr");
		return (1);
	}
	return (0);
}

/*
 * sex_termcap --
 *	Ex termcap commands.
 */
void
sex_termcap(sp, action)
	SCR *sp;
	enum termact action;
{
	SEX_PRIVATE *sxp;
	int cnt;

	sxp = SXP(sp);

	/* Initialize termcap if not done yet. */
	if (!sxp->term_init) {
		sex_terminit(sp);
		if (sxp->UP != NULL && sxp->CM != NULL)
			tputs(tgoto(sxp->CM,
			    0, O_VAL(sp, O_LINES) - 1), 1, vi_putchar);
	}

	switch (action) {
	case EX_TERM_SCROLL:
		/* Move the cursor up one line if that's possible. */
		if (sxp->UP != NULL)
			(void)tputs(SXP(sp)->UP, 1, vi_putchar);
		else if (sxp->CM != NULL)
			(void)tputs(tgoto(sxp->CM,
			    0, O_VAL(sp, O_LINES) - 2), 1, vi_putchar);
		else
			return;
		/* FALLTHROUGH */
	case EX_TERM_CE:
		/* Clear to the end of the line. */
		(void)putchar('\r');
		if (sxp->CE != NULL)
			(void)tputs(SXP(sp)->CE, 1, vi_putchar);
		else {
			for (cnt = 0; cnt < MAX_CHARACTER_COLUMNS; ++cnt)
				(void)putchar(' ');
			(void)putchar('\r');
		}
		break;
	default:
		abort();
	}
	(void)fflush(stdout);
}

/*
 * sex_bell --
 *	Ring the bell.
 */
int
sex_bell(sp)
	SCR *sp;
{
	(void)write(STDOUT_FILENO, "\07", 1);		/* \a */
	return (0);
}

int
sex_busy(sp, msg)
	SCR *sp;
	char const *msg;
{
	(void)fprintf(sp->stdfp, "%s\n", msg);
	(void)fflush(sp->stdfp);
	return (0);
}

/*
 * sex_optchange --
 *	Screen specific "option changed" routine.
 */
int
sex_optchange(sp, opt)
	SCR *sp;
	int opt;
{
	return (0);
}

/*
 * sex_suspend --
 *	Suspend an ex screen.
 */
int
sex_suspend(sp)
	SCR *sp;
{
	struct termios t;
	GS *gp;
	int rval;

	rval = 0;

	/* Save current terminal settings, and restore the original ones. */
	gp = sp->gp;
	if (F_ISSET(gp, G_STDIN_TTY)) {
		if (tcgetattr(STDIN_FILENO, &t)) {
			msgq(sp, M_SYSERR, "suspend: tcgetattr");
			return (1);
		}
		if (F_ISSET(gp, G_TERMIOS_SET) && tcsetattr(STDIN_FILENO,
		    TCSASOFT | TCSADRAIN, &gp->original_termios)) {
			msgq(sp, M_SYSERR, "suspend: tcsetattr original");
			return (1);
		}
	}

	/* Push out any waiting messages. */
	(void)sex_refresh(sp);

	/* Stop the process group. */
	if (kill(0, SIGTSTP)) {
		msgq(sp, M_SYSERR, "suspend: kill");
		rval = 1;
	}

	/* Time passes ... */

	/* Restore current terminal settings. */
	if (F_ISSET(gp, G_STDIN_TTY) &&
	    tcsetattr(STDIN_FILENO, TCSASOFT | TCSADRAIN, &t)) {
		msgq(sp, M_SYSERR, "suspend: tcsetattr current");
		rval = 1;
	}
	return (rval);
}

/*
 * sex_terminit --
 *	Initialize the termcap strings used by ex.
 */
void
sex_terminit(sp)
	SCR *sp;
{
	SEX_PRIVATE *sxp;
	size_t len;
	char *s, *t, buf[128], tbuf[2048];

	sxp = SXP(sp);
	sxp->term_init = 1;

	/* Get the termcap entry. */
	if (tgetent(tbuf, O_STR(sp, O_TERM)) != 1)
		return;

	/* Get CE. */
	t = buf;
	if ((t = tgetstr("ce", &t)) != NULL && (len = strlen(t)) != 0) {
		MALLOC_NOMSG(sp, s, char *, len + 1);
		if (s != NULL) {
			memmove(s, buf, len);
			s[len] = '\0';
			sxp->CE = s;
		}
	}

	/* Get CM. */
	t = buf;
	if ((t = tgetstr("cm", &t)) != NULL && (len = strlen(t)) != 0) {
		MALLOC_NOMSG(sp, s, char *, len + 1);
		if (s != NULL) {
			memmove(s, buf, len);
			s[len] = '\0';
			sxp->CM = s;
		}
	}

	/* Get SE. */
	t = buf;
	if ((t = tgetstr("se", &t)) != NULL && (len = strlen(t)) != 0) {
		MALLOC_NOMSG(sp, s, char *, len + 1);
		if (s != NULL) {
			memmove(s, buf, len);
			s[len] = '\0';
			sxp->SE = s;
		}
	}

	/* Get SO. */
	t = buf;
	if ((t = tgetstr("so", &t)) != NULL && (len = strlen(t)) != 0) {
		MALLOC_NOMSG(sp, s, char *, len + 1);
		if (s != NULL) {
			memmove(s, buf, len);
			s[len] = '\0';
			sxp->SO = s;
		}
	}

	/* SE and SO are paired. */
	if (sxp->SE == NULL || sxp->SO == NULL) {
		if (sxp->SE != NULL) {
			free(sxp->SE);
			sxp->SE = NULL;
		}
		if (sxp->SO != NULL) {
			free(sxp->SO);
			sxp->SO = NULL;
		}
	}

	/* Get UP. */
	t = buf;
	if ((t = tgetstr("up", &t)) != NULL && (len = strlen(t)) != 0) {
		MALLOC_NOMSG(sp, s, char *, len + 1);
		if (s != NULL) {
			memmove(s, buf, len);
			s[len] = '\0';
			sxp->UP = s;
		}
	}
}
