/*
 *	Universal Terminal Interface -- Clearing
 *
 *	(c) 1997 Martin Mares, <mj@ericsson.cz>
 */

#include <stdio.h>
#include <string.h>

#include "termint.h"

/* Screen clearing */

int
try_cls(void)
{
  int cls = 0;
  int mapsize = rows * columns;

  if (!BOOL(ERASES_WITH_BACK_COLOR) &&
      cls_color == default_color &&
      !cls_attrs)
    cls = 1;
  else if (BOOL(ERASES_WITH_BACK_COLOR) && !cls_attrs)
    {
      send_attrs(cls_attrs, cls_color);
      cls = 1;
    }
  if (CTRL(EMULATE_CLS))
    cls = 0;
  if (cls)
    {
      if (STR(CLEAR_SCREEN))
	{
	  TR("Sending physical CLS\n");
	  send(STR(CLEAR_SCREEN));
	}
      else if (STR(CLEAR_TO_EOS))
	{
	  TR("Using CLREOS to clear screen\n");
	  cgoto(0,0);
	  send(STR(CLEAR_TO_EOS));
	}
      else
	cls = 0;
    }
  if (cls)
    {
      memset(aold, cls_attrs, mapsize);
      memset(kold, cls_color, mapsize);
      memset(cold, ' ', mapsize);
    }
  return cls;
}

void
Tcls(void)
{
  int mapsize = rows * columns;

  cls_color = write_color;
  cls_attrs = write_attrs;
  memset(anew, cls_attrs, mapsize);
  memset(cnew, ' ', mapsize);
  memset(knew, cls_color, mapsize);
  if (!try_cls())
    {
      TR("CLS attempt failed, using redraw\t");
      force_redraw();
      Trefresh();
    }
  else
    darken_all();
}

void
Tclean(void)
{
  write_color = default_color;
  write_attrs = 0;
  Tcls();
}

/* Filling of a region with a character */

static void
Tfill0(int r, int c, int h, int w, word with)
{
  int pos0, pos1, q;
  byte ch = with;
  byte at = write_attrs;

  if (with & 0xff00)			/* A graphic character */
    {
      ch = gfx_chars[ch];
      at |= ATTR_ALTERNATE & supported_attrs;
    }
  TR("Filling %d.%d/%d.%d with %02x/%02x\n", r, c, h, w, ch, at);
  light(r, c, h, w);
  pos0 = r * columns + c;
  while (h--)
    {
      pos1 = pos0;
      for(q=0; q<w; q++)
	{
	  cnew[pos1] = ch;
	  anew[pos1] = at;
	  knew[pos1] = write_color;
	  pos1++;
	}
      pos0 += columns;
    }
}

void
Tfill(int r, int c, int h, int w, word with)
{
  if (!with)
    with = ' ';
  if (with == ' ')
    Tclear(r, c, h, w);
  else
    Tfill0(r+ww_r0, c+ww_c0, h, w, with);
}

/* Clearing of a region */

void
Tclear(int r, int c, int h, int w)
{
  r += ww_r0;
  c += ww_c0;
  if (!r && !c && h == rows && w == columns)
    Tcls();
  else					/* Regions not supported yet */
    Tfill0(r, c, h, w, ' ');
}

/* Casting a shadow */

void
Tshadow(int r, int c, int h, int w)
{
  int pos0, pos1, q;

  r += ww_r0;
  c += ww_c0;
  TR("Shadowing %d.%d/%d.%d with %02x/%02x\n", r, c, h, w, write_attrs, write_color);
  light(r, c, h, w);
  pos0 = r * columns + c;
  while (h--)
    {
      pos1 = pos0;
      for(q=0; q<w; q++)
	{
	  anew[pos1] = (anew[pos1] & ATTR_ALTERNATE) | write_attrs;
	  knew[pos1] = write_color;
	  pos1++;
	}
      pos0 += columns;
    }
}
