/*
 *------------------------------------------------------------------
 *
 * $Source: /afs/net.mit.edu/dev/project/techinfodev/src/srv_ti/RCS/disp.c,v $
 * $Revision: 3.2 $
 * $Date: 93/02/03 11:19:07 $
 * $State: Exp $
 * $Author: thorne $
 * $Locker:  $
 *
 * $Log:	disp.c,v $
 * Revision 3.2  93/02/03  11:19:07  thorne
 * new release
 * 
 * Revision 1.2  92/08/25  17:09:09  ark
 * Saber & WAIS cleanup
 * 
 * 
 * Revision 1.1  92/08/24  15:45:45  ark
 * WAIS searching added to client & server (J command)
 * 
 * Revision 1.0  92/07/10  12:32:00  ark
 * Initial revision
 * 
 * Revision 1.1  91/07/15  10:39:58  thorne
 * Initial revision
 * 
 *------------------------------------------------------------------
 */

#ifndef lint
#ifndef SABER
static char *rcsid_foo_c = "$Header: /afs/net.mit.edu/dev/project/techinfodev/src/srv_ti/RCS/disp.c,v 3.2 93/02/03 11:19:07 thorne Exp $";
#endif  SABER
#endif  lint
/*
 * disp.c -- a windower/displayer that uses curses. 
 *
 */
/*
  Copyright (C) 1989 by the Massachusetts Institute of Technology

   Export of this software from the United States of America is assumed
   to require a specific license from the United States Government.
   It is the responsibility of any person or organization contemplating
   export to obtain such a license before exporting.

WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
distribute this software and its documentation for any purpose and
without fee is hereby granted, provided that the above copyright
notice appear in all copies and that both that copyright notice and
this permission notice appear in supporting documentation, and that
the name of M.I.T. not be used in advertising or publicity pertaining
to distribution of the software without specific, written prior
permission.  M.I.T. makes no representations about the suitability of
this software for any purpose.  It is provided "as is" without express
or implied warranty.

  */

#include <sys/time.h>
#include <stdio.h>
#include <curses.h>
#include <signal.h>
#ifdef SOLARIS
#include <termios.h>
#endif
#include "pdb.h"
#include "disp.h"

#define	WIN_TOP		2
#define	MAX_TXT_HEAD	16

#define	TXT_LLEN	192
#define	D_POINTER	0x1
#define	MAX_HEADLEN	80

#define	pointer_active()	(disp_flags & D_POINTER)

static int      curses_active = NO;

static char     Msg[MAX_HEADLEN];
static char     ErrMsg[MAX_HEADLEN];

static int      disp_changed = NO;

static int      old_line[MAXBACK];
static int      old_ptr[MAXBACK];
static int      old_MENU[MAXBACK];
extern char **buf;
extern int title_fld_len;

/*
 * The folling argument stuff isn't very pretty, buts its relatively
 * portable. 
 */

#define	VAR_ARG_LIST a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16
#define	VAR_ARG_DECL long

static void
more_msg(str)
	char            str[];
{
	mvaddstr(LINES - 1, 0, str);
	addstr(" --More--"), clrtoeol();
	flush(), refresh();
	getchar();
}

/* VARARGS1 */
disp_msgnow(fmt, VAR_ARG_LIST)
	char           *fmt;
	VAR_ARG_DECL    VAR_ARG_LIST;
{
	char            buf[256];

	sprintf(buf, fmt, VAR_ARG_LIST);
	if (curses_active) {
		if (*buf == '@')
			more_msg(buf + 1);
		else {
			mvaddstr(LINES - 1, 0, buf), clrtoeol();
			refresh(), flush();
		}
	} else
		putstr(buf);
	disp_changed++;
}

/* VARARGS1 */
disp_setmsg(fmt, VAR_ARG_LIST)
	char           *fmt;
	VAR_ARG_DECL    VAR_ARG_LIST;
{
	char            buf[256];

	if (curses_active && *Msg)
		more_msg(Msg);
	sprintf(buf, fmt, VAR_ARG_LIST);
	buf[MAX_HEADLEN] = '\0';
	if (curses_active)
		strcpy(Msg, buf);
	else
		putstr(buf);
	disp_changed++;
}

/* VARARGS1 */
disp_errmsg(fmt, VAR_ARG_LIST)
	char           *fmt;
	VAR_ARG_DECL    VAR_ARG_LIST;
{
	char            buf[256];

	if (curses_active && *ErrMsg)
		more_msg(ErrMsg);
	sprintf(buf, fmt, VAR_ARG_LIST);
	buf[MAX_HEADLEN] = '\0';
	strcpy(ErrMsg, buf);
	if (curses_active)
		strcpy(ErrMsg, buf);
	else
		putstr(buf);
	disp_changed++;
}

disp_syserr(str)
	char            str[];
{
	extern int      errno, sys_nerr;
	extern char    *sys_errlist[];

	if (errno >= sys_nerr)
		disp_errmsg("%s: falure code %d", str, errno);
	else
		disp_errmsg("%s: %s", str, sys_errlist[errno]);
}


/*--------------------------------------------------------------------------*/

static int      disp_numline,	/* Num of lines in text buffer */
                disp_curline;	/* Current (top of screen) line */
static int      disp_flags;
static char     disp_heading[MAX_TXT_HEAD][TXT_LLEN];
static int      disp_numhead;
static char     disp_title[300];
static char    *(*display_func) ();

static int      screen_num,	/* Number of screens of text */
                screen_cur;	/* Current screen # we're on */
static int      window_len;	/* Current length of our pager window */
static int      so_line, so_col,/* defines a standout region */
                so_len;		/* in the display window */
static int      pointer_line = 0,	/* Current line in window */
                pointer_col = 0;
static int samedisp;  /* for use with the find(word) cmd */    

static char     help_msg[] =
"Main, Return, Find, Outline, Info, Path, Search, Lookup, Advanced, World, Help, Quit";
static char     scroll_msg[] =
"  Type Up, Down, Top, Bottom, or use the left and right arrow keys to scroll";
void
disp_clear_headings(){
  if (disp_numhead != 0) {
    disp_numhead = 0;
    disp_changed++;
    window_len = LINES - (WIN_TOP + 4);
}
}
static /* why is this done like this ? */
clear_headings()
{
	int             i;

	for (i = 0; i < MAX_TXT_HEAD; i++)
		*disp_heading[i] = '\0';
	window_len = LINES - (WIN_TOP + 4); /*  ? */
	disp_numhead = 0;
	disp_changed++;
}

int
disp_numlines()
{
return disp_numline;
}

void
disp_set(lines, disp_func)
	int             lines;
	char           *(*disp_func) (int);
{
	/*
	 * First reset stuff... 
	 */

	if (disp_is_nlist()) {
		disp_save_wind(LIST);
		disp_save_set(0,0); /* why ?? */
	}
	clear_headings();
	disp_curline = 0;
	disp_flags = 0;

	/*
	 * Now set up new displayer... 
	 */
	samedisp = FALSE; /* for use with the find(word) cmd */
	disp_numline = lines;
	display_func = disp_func;
	disp_changed++;
}

extern char    *nlist_fmt_line();
extern char    *textbuf_line();
extern char    *server_line();
extern char    *hist_text_line();

int
disp_is_hist()
{				/* is the current displayer the history
				 * list */
	if (display_func == hist_text_line)
		return TRUE;
	else
		return FALSE;
}
int
disp_is_serv()
{				/* is the current displayer the server
				 * list */
	if (display_func == server_line)
		return TRUE;
	else
		return FALSE;
}


int
disp_is_nlist()
{				/* is the current displayer the nlist
				 * displayer */
	if (display_func == nlist_fmt_line)
		return TRUE;
	else
		return FALSE;
}
int
disp_is_text()
{				/* is the current displayer the text
				 * displayer */
	if (display_func == textbuf_line)
		return TRUE;
	else
		return FALSE;
}
void
disp_set_heading(hn, str) /* this was originally written so that individual 
heading lines could be replaced. Now all heading lines must be set */
	int             hn;
	char            str[];
{
	if (hn >= MAX_TXT_HEAD)
		return;
	/* if (!*disp_heading[hn]) { need to force hn == disp_numhead */
		if (window_len < 2)
			return;
		window_len--;
		disp_numhead++;
	/* } */
	if (hn < 0)
		hn = hn + MAX_TXT_HEAD;
	if (*str == '\\') {
		int             i;
		for (str++, i = 0; i < TXT_LLEN; i++)
			disp_heading[hn][i] = *str;
	} else
		bcopy(str, disp_heading[hn], TXT_LLEN);
	disp_changed++;
}

void
disp_use_pointer(int pcol)
{
	disp_flags |= D_POINTER;
	pointer_col = pcol;
  /*      pointer_line = 0;  */
}
void
disp_ptr_on()
{				/* change the status of pointeractive */
	disp_flags |= D_POINTER;
}
void
disp_ptr_off()
{				/* change the status of pointeractive */
	disp_flags &= ~D_POINTER;  
}
void
disp_page_up(int pagecnt)
{
	if (screen_cur == 1)
		return;
	if (pointer_active())
		pointer_line = 0;
	disp_curline -= !pagecnt ? window_len : pagecnt * window_len;

}


void
disp_page_dn(int pagecnt)
{
	if (screen_cur == screen_num)
		return;
	if (pointer_active())
		pointer_line = 0;
	disp_curline += !pagecnt ? window_len : pagecnt * window_len;
}

void
disp_pointer_up(int cnt)
{
	if (!pointer_active())
		return;
	pointer_line -= cnt;
	if (pointer_line < 0 && screen_cur != 1) {
		disp_curline -= window_len;
		pointer_line = window_len - 1;
	}
	if (pointer_line < 0)	/* */
		pointer_line = 0;
}


void
disp_pointer_dn(int cnt)
{
	if (!pointer_active())
		return;
	pointer_line += cnt;
	if (pointer_line >= window_len && screen_cur != screen_num) {
		disp_curline += window_len;
		pointer_line = 0;
	}
	if (disp_pointer_index() > (disp_numline - 1))	/* */
		disp_pointer_set(disp_numline - 1);
}

void
disp_goto_top()
{
	disp_curline = 0;
	if (pointer_active())
		pointer_line = 0;
}

void
disp_goto_bot()
{
	disp_curline = disp_numline + 1;
	if (pointer_active())
		disp_pointer_set(disp_numline - 1);
}

static void
fixup_markers()
{				/* make sure we are on the right page ? */
	int             abs_ptr;

	/*
	 * First, make sure disp_curline pust us on an even screen boundry. 
	 */

	if (pointer_active()) {
		abs_ptr = disp_pointer_index();
		disp_curline = abs_ptr;
	}
	if (disp_curline < 0)
		disp_curline = 0;
	else if (disp_curline >= disp_numline)
		disp_curline = disp_numline - 1;
	if (disp_curline % window_len)
		disp_curline -= disp_curline % window_len;

	/*
	 * Figure out screen info. 
	 */

	screen_num = disp_numline / window_len;
	if (disp_numline % window_len)
		screen_num++;
	screen_cur = disp_curline / window_len + 1;


	if (pointer_active())
		pointer_line = abs_ptr - disp_curline;;

}

void
disp_pointer_set(int index)
{
	if (index <= disp_numline)
		pointer_line = index - disp_curline;
	else
	  pointer_line = disp_numline;
	/* Gross movement to right page... */
	fixup_markers();	/* Realign things. */

      }

int
disp_pointer_index()
{
	return disp_curline + pointer_line;
}

void
disp_set_title(char *str)
{
int len,maxspace,dif;
long secs;
char line[150];

time(&secs);  /* dont keep getting this */
len = strlen(str);
maxspace = COLS - 22; /* leaving room for "Techinfo  " + date */
if (len > maxspace) 
  sprintf(line,"%*.*s...",(maxspace-3),(maxspace-3),str);
else
  {
    dif = maxspace - len;
    sprintf(line,"%*.*s%*.*s%*.*s",(dif/2),(dif/2),"",(len),(len),str,(dif/2),(dif/2),"");
  }
sprintf(disp_title,"%s  %-*.*s  %10.10s",THENAME,(maxspace),(maxspace),line,ctime(&secs));
}

void
disp_redraw()
{
	clearok(stdscr, TRUE);
	disp_changed++;
}

/*
 * Locate and highlight the given string.  If null or empty, search for the
 * last string we searched for.  Return 1 upon sucess, 0 on error. 
 */

int
disp_search(char *str)
{
	static char     old_str[64] = "";
	static int      srch_line, srch_col;

	int             line, len, found_line = 0;
	char           *cp, *txtline;

	if (!str || !*str) {
		if (!*old_str) {
			disp_setmsg("%s","Find requires a string to be given as a parameter");
			return 0;
		}
		if (!samedisp) {
		  srch_line = 0;
		  srch_col = -1; }
		str = old_str;
	} else {
		srch_line = 0;
		srch_col = -1;
	}
	samedisp = TRUE;
	len = strlen(str);
	if (str != old_str)
		strcpy(old_str, str);
	disp_msgnow("Searching for \"%s\"...", str);

	for (line = srch_line; line <= disp_numline; line++) {
		cp = txtline = (*display_func) (line);
		if (line == srch_line && srch_col != -1)
			cp += srch_col + 1;
		while (*cp) {
			if (!strncasecmp(str, cp, len)) {
				found_line = line;
				break;
			}
			cp++;
		}
		if (found_line)
			break;
	}
	if (!found_line) {
		disp_setmsg("No match found for \"%s\"", str);
		return 0;
	}
	/* disp_setmsg("Found occurrence of \"%s\" at line %d, column %d.",
		    str, found_line + 1, cp - txtline); */
	disp_curline = found_line;
	if (pointer_active())
		disp_pointer_set(found_line);

	so_line = srch_line = found_line;
	so_col = srch_col = (cp - txtline);
	so_len = len;
	return 1;
}
int
disp_search_col(char *str, int col)
{
	static char     old_str[64] = "";
	static int      srch_line, srch_col;

	int             line, len, found_line = 0;
	char           *cp, *txtline;

	if (!str || !*str) {
		if (!*old_str) {
			disp_setmsg("Scan requires a string as a parameter");
			return 0;
		}
		if (!samedisp) {
		  srch_line = 0;
		  srch_col = -1; }
		str = old_str;
	} else {
		srch_line = 0;
		srch_col = col;
	}
	samedisp = TRUE;
	len = strlen(str);
	if (str != old_str)
		strcpy(old_str, str);
	disp_msgnow("Searching for \"%s\"...", str);

	for (line = srch_line; line <= disp_numline; line++) {
		cp = txtline = (*display_func) (line);
		cp += srch_col;
		if (!strncasecmp(str, cp, len)) {
			found_line = line;
			break;
		}
	}
	if (!found_line) {
		disp_setmsg("No match found for \"%s\"", str);
		return 0;
	}
	/* disp_setmsg("Found occurrence of \"%s\" at line %d, column %d.",
		    str, found_line + 1, cp - txtline); */
	disp_curline = found_line;
	if (pointer_active())
		disp_pointer_set(found_line);

	so_line = srch_line = found_line;
	so_col = srch_col = (cp - txtline);
	so_len = len;
	return 1;
}

static char     prompt[] = "Command: ";

static void
do_redraw_window()
{
	int             i, numhead;
	int             curline, curdispline, linecnt;

	move(0, 0);
	printw("%-*.*s",(COLS),(COLS), disp_title);
	move(1, 0);
	for (i = 0; i < COLS; i++)
		addch('=');

	for (i = numhead = 0; i < disp_numhead; i++)
		if (*disp_heading[i]) {
			move(WIN_TOP + numhead, 0);
			addstr(disp_heading[i]), clrtoeol();
			numhead++;
		}
	for (linecnt = 0; linecnt < window_len; linecnt++) {
		char           *txtline;

		curline = linecnt + WIN_TOP + numhead;
		move(curline, 0);

		curdispline = linecnt + disp_curline;

		if (display_func)
			txtline = (*display_func) (curdispline);
		else
			txtline = "<no active displayer!>";

		addstr(txtline);
		clrtoeol();

		if (so_len && linecnt + disp_curline == so_line) {
			move(linecnt + WIN_TOP + numhead, so_col);
			standout();
			printw("%.*s", so_len, &txtline[so_col]);
			standend();
			so_len = 0;
			move(linecnt + WIN_TOP + numhead + 1, 0);
		}
	}

	clrtobot();
	move(LINES - 4, 0);
	for (i = 0; i < COLS; i++)
		addch('=');

	if (*ErrMsg)
		move(LINES - 4, 0), printw("===[ %s ]", ErrMsg);
	else if (screen_num > 1)
	  move(LINES - 4, 0), printw("===========================[  Page %d of %d. ]================", screen_cur,screen_num);
	mvaddstr(LINES - 2, 0, help_msg);	
	if (screen_num > 1)
	  mvaddstr(LINES - 1, 0, *Msg ? Msg : scroll_msg), clrtoeol();
	else
	  mvaddstr(LINES - 1, 0, *Msg ? Msg : ""), clrtoeol();
	*ErrMsg = *Msg = '\0';
	mvaddstr(LINES - 3, 0, prompt), clrtoeol();
}

void
disp_save_set(num,menu)		/* saves the current top line number and
				 * pointer */
	int             num;
        int             menu;
{
	old_line[num] = disp_curline;
	old_ptr[num] = pointer_line;
	old_MENU[num] = menu;
}

int
disp_ret_set(num)		/* retreives + sets the current top line
				 * number and pointer */
	int             num;
{
	disp_curline = old_line[num];
	pointer_line = old_ptr[num];
	return(old_MENU[num]);
}

static int      numline[5];	/* variables to hold screen settings */
static int      curline[5];

void
disp_save_wind(int type)
{				/* save window settings */
	numline[type] = disp_numline;
	curline[type] = disp_curline;
}
void
disp_ret_wind(int type)
{				/* retreive window settings */
	disp_numline = numline[type];
	disp_curline = curline[type];
        screen_num = disp_numline / window_len;
	if (disp_numline % window_len)
		screen_num++;
	screen_cur = disp_curline / window_len + 1; 
}

void
disp_update()
{
	static int      o_disp_curline = -1, o_disp_numline = -1, o_window_len = -1;

	static int      old_pointer_line = 0;

	fixup_markers();
	if (disp_changed ||
	    disp_curline != o_disp_curline ||
	    disp_numline != o_disp_numline ||
	    window_len != o_window_len) {

		/*
		 * need to test so_{vars} also 
		 */

		disp_changed = NO;
		o_disp_curline = disp_curline;
		o_disp_numline = disp_numline;
		o_window_len = window_len;
		do_redraw_window();
	}
	if (pointer_active()) {
		if (old_pointer_line)
			mvaddch(old_pointer_line, pointer_col, ' ');
		old_pointer_line = pointer_line + WIN_TOP + disp_numhead;
		mvaddch(old_pointer_line, pointer_col, '>');
	} 
	move(LINES - 3, sizeof(prompt) - 1), clrtoeol();
	refresh(), flush();
}

void
disp_init()
{
	static char	*stdoutbuf;

	if (!curses_active)
		initscr();
	else {
		free(stdoutbuf);
		endwin(), initscr();
	}

#ifdef DECMIPS
  crmode();
#else
  cbreak(); 
#endif       /* cbreak() or crmode() for decmips */
	noecho(), nonl();

	/*
	 * Approximate line-buffering, but this is clearly better, since it
	 * won't flush for a few chars that just move the cursor around. 
	 */

	if (COLS > 200)  /*  kludge for bad resize info from procomm/ibm  */
	  COLS = 80;
	if (LINES > 200)
	  LINES = 24;  
	stdoutbuf = domalloc((unsigned) COLS);
	setbuffer(stdout, stdoutbuf, COLS);
	title_fld_len = COLS - 54;
	if (!curses_active)
		disp_set(0, 0);

	curses_active++;
}

void
disp_shutdown()
{
	clear();
	refresh();
	flush(); 
	endwin();
	flush();

}

void
disp_resize()
{ /* got this code from Chris VanHaren - OLH */
    struct winsize ws;
    int lines;
    int cols;
    signal(SIGWINCH, SIG_IGN);
    /*  Find out the new size.  */
    if (ioctl(fileno(stdout), TIOCGWINSZ, &ws) != -1)
      {
          if (ws.ws_row != 0)
            lines = ws.ws_row;
          if (ws.ws_col != 0)
            cols = ws.ws_col;
      }
          LINES = lines;
          COLS = cols;
    title_fld_len = COLS - 54;

    disp_init();
    window_len = LINES - (WIN_TOP + 4) - disp_numhead;
    disp_changed++;
    disp_update();
  /*  ttyio_reposition(LINES - 2, sizeof(prompt)); */
    signal(SIGWINCH, disp_resize);
  }


