/* Hey, emacs, this is -*- C -*- code.  */

/* view-vga - view a map using the linux vgalib

Copyright (C) 1992 D P Gymer

This is free software; you can redistribute it and/or modify it under the
   terms of the GNU General Public License as published by the Free Software
   Foundation; either version 2 of the License, or (at your option) any later
   version.

This program is distributed in the hope that it will be useful, but WITHOUT
   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
   more details.  */

/* $Id: view-vga.c,v 0.3.2.0 1992/06/11 22:30:07 dpg Alpha dpg $ */

#include <signal.h>
#include <stdlib.h>
#include <termios.h>
#include <vgalinux.h>

#include "view.h"

/* Maximum mode number.  */
#define MAX_SCREEN_DEV	8

/* This is 0 if we are not displaying a VGA mode, or the number of colors in
   use if we are.  */
static int colors = 0;

/* Get a keypress.  */
int
readkey (void)
{
  return vga_getch ();
}

/* Plot a pixmap pixel.  */
void
plot_pixel (int x, int y, COLOR color)
{
  vga_setcolor (color);
  vga_drawpixel (x, y);
}

/* Initialize the display.  Return 0 iff everything goes okay.  */
int
init_display (int *width, int *height, int *num_colors, const char *screen_dev_s)
{
  struct termios tp1;
  struct termios tp2;
  int screen_dev;

  tcgetattr (1, &tp1);
  screen_dev = screen_dev_s ? atoi (screen_dev_s) : 8;
  if (screen_dev < 1 || screen_dev > MAX_SCREEN_DEV)
    return 1;
  vga_setmode (screen_dev);
  tcgetattr (1, &tp2);
  tp2.c_cc[VINTR] = tp1.c_cc[VINTR];
  tp2.c_cc[VQUIT] = tp1.c_cc[VQUIT];
  tcsetattr (1, TCSANOW, &tp2);
  *width = vga_getxdim ();
  *height = vga_getydim ();

  colors = vga_getcolors ();
  if (colors == 16)
    colors = 8;
  *num_colors = colors;

  return 0;
}

/* Set the palette up on the display.  Return 0 iff no problems.  We also
   clear the display, since anything on there is probably going to look
   pretty wierd in new colors!  */
int
set_colors (PALETTE *pal)
{
  clear ();

  while (pal)
    {
      vga_setpalette (pal->number, pal->color.red * 63 / MAXRGBVAL,
		      pal->color.green * 63 / MAXRGBVAL,
		      pal->color.blue * 63 / MAXRGBVAL);
      pal = pal->next;
    }

  return 0;
}

void
tidy_display (void)
{
  if (colors)
    {
      vga_setmode (TEXT);
      colors = 0;
    }
}
