//		  ÚÄÄÄÄÄÄÄ¿
//	ÄÄÄÄÄÄÄÄÄ>³ AVNER ³
//	ÄÄÄÄÄÄÄÄÄ>³  BEN  ³ÄÄÄÄÄÄ> Software Engineering Method
//		  ÀÄÄÄÄÄÄÄÙ
//	10 Dov-Hoz st. Tel-Aviv 63416 Israel tel. 972-3-221535

// The Screen NAVigator, ver 1.20 August 1990
// Copyright (c) 1990 by Avner Ben
// Snav is not, and never was, free software.
// for conditions for use refer to file "copyrigh.txt"

// The Screen Navigator is an object-oriented device-independent
// character-graphics driver package, written in the C++ language,
// distributed in the form of C++ source code.
// For further information refer to the documentation files.

// The user may not omit this text, from the beginning of the file, to
// the line of asterisks below.

/***************************************************************************/

// package nucleus part 4 - source code.
// This file defines the generic "shape", and some specific derivatives.

// History:
// 13.3.90 avner ben seperated from snav2.
// 11.9.90 last update by avner ben
// for further details refer to documentation.

// Site history (of this copy):
// __.__.__ ____________ : __________________.

#ifndef SNAV3_C
#define SNAV3_C
#endif

#include "/mtad/snav/snav0.hpp"
#include "/mtad/snav/snav1.hpp"
#include "/mtad/snav/snav2.hpp"
#include "/mtad/snav/snav3.hpp"

////////////////////////// line-drawing primitives

shape_segment :: shape_segment(direction &indir, color_ind *incolor)
{
	dir=indir;
	if (incolor) {
		color=new color_ind;
		*color=*incolor;
	} else color=NULL;
}

shape_segment :: ~shape_segment(void)
{ if (color) delete color; }

void shape_segment :: set_dir(direction &indir)
{ dir=indir; }

void shape_segment :: set_color(color_ind *inclr)
{
	if (!inclr) return;
	if (!color) color=new color_ind;
	*color=*inclr;
}

direction& shape_segment :: ask_dir(void)
{
	static direction result;
	result=dir;
	return result;
}

shape_segment * arc :: new_copy(void)
{ return new arc(*this); }

void shape_segment :: turn(void)
{ dir.clockwise(); }

void shape_segment :: invert(void)
{ dir.opposite(); }

void arc :: list(panel *scr, point_pos *pt)
{ scr->arclist(pt,len,dir,wgt,tipped,color); }

void arc :: clear(panel *scr, point_pos *pt)
{ scr->arcclr(pt,len,dir); }

void arc :: contract(void)
{ if (len) len--; }

void arc :: expand(void)
{ len++; }

void arc :: toggle_tip(void)
{ tipped=!tipped; }

void arc :: set_len(int inlen)
{ len=inlen; }

void arc :: set_wgt(weight_d &inwgt)
{ wgt=inwgt; }

void arc :: mask(weight_d &other_wgt)
{ wgt.mask(other_wgt); }

weight_d& arc :: ask_wgt(void)
{
	static weight_d result;
	result=wgt;
	return result;
}

shape_segment * display_string :: new_copy(void)
{ return new display_string(s,dir,align,color); }

void display_string :: list(panel *scr, point_pos *pt)
{ scr->put_s(s,pt,&dir); }

void display_string :: clear(panel *scr, point_pos *pt)
{ scr->arcclr(pt,strlen(s),dir); }

void display_string :: contract(void)
{
	if (!*s) return;
	for (char *t=s; *t; t++) continue;
	*(t-1)='\0';
}

void display_string :: expand(void)
{
	char *t=new char[strlen(s)+2];
	strcpy(t,s);
	strcat(t," ");
	delete s; s=t;
}

void display_string :: set_len(int inlen)
{
	if (inlen==strlen(s)) ;
	else if (inlen<0) ;
	else if (inlen<strlen(s)) s[inlen]='\0';
	else {
		char *t=new char[inlen+1];
		strcpy(t,s);
		for (int i=strlen(s); i<inlen; i++)
			strcat(t," ");
		delete s; s=t;
	}
}

weight_d& display_string :: ask_wgt(void)
{
	static weight_d result;
	result=twgwgt;	// 0:0
	return result;
}

stroke :: stroke(shape_segment *src, boolean pen_down) : offset(0,0)
{
	if (src) item=src->new_copy();
	else item=new arc(1,rt); // just in case
	pendn=pen_down;
	suc=NULL;
}

stroke :: stroke(int inlen, direction &indir, weight_d &inwgt,
 boolean intip, color_ind *incolor, boolean pen_down) : offset(1,1)
{
	item=new arc(inlen, indir, inwgt, intip, incolor);
	pendn=pen_down;
	suc=NULL;
}

stroke :: stroke(char *s, direction &dir, direction &align, color_ind *color,
 boolean pen_down) : offset(1,1)
{
	item=new display_string(s,dir,align,color);
	pendn=pen_down;
	suc=NULL;
}

stroke :: ~stroke(void)
{ delete item; } // must have one

void stroke :: toggle_pen()
{ pendn=!pendn; }

boolean stroke :: pen_is_down()
{ return pendn; }

void stroke :: list(panel *scr, point_pos *pt)
{
	if (item->ask_len() && dirval()) {
		if (pendn) item->list(scr,pt);
		pt->move(item->ask_dir(),item->ask_len()-1);
	}
}

void stroke :: clear(panel *scr, point_pos *pt)
{
	if (item->ask_len() && dirval()) {
		if (pendn) item->clear(scr,pt);
		pt->move(item->ask_dir(),item->ask_len()-1);
	}
}

void stroke :: contract(void)
 { item->contract(); }

void stroke :: expand(void)
 { item->expand(); }

void stroke :: turn(void)
 { item->turn(); }

void stroke :: invert(void)
 { item->invert(); }

void stroke :: toggle_tip(void)
 { item->toggle_tip(); }

void stroke :: set_len(int inlen)
 { item->set_len(inlen); }

void stroke :: set_wgt(weight_d &inwgt)
 { item->set_wgt(inwgt); }

void stroke :: mask(weight_d &other_wgt)
 { item->mask(other_wgt); }

boolean stroke :: homogeneous(void)
 { return item->homogeneous(); }

boolean stroke :: can_point(void)
 { return item->can_point(); }

boolean stroke :: has_weight(void)
 { return item->has_weight(); }

///////////////////////////// shape drawing ///////////////////////////////

shape :: shape(stroke *sk, char *inname)
{
	stsk=ensk=sk;
	sname=new char[strlen(inname)+1]; strcpy(sname,inname);
}

void shape :: append_stroke(stroke *sk)
{
	if (!sk) return;				       // caller's bug
	stroke *lastsk=ensk;
	if (!stsk) stsk=ensk=sk;
	else if (sk->dirval()==ensk->dirval() && (sk->wgt())()==(ensk->wgt())()
	 && (sk->color() == ensk->color() || sk->color() && ensk->color()
	 && *(sk->color())==*(ensk->color())))	     // redundant?
		if (sk->len()>1)
			if (sk->pendn!=ensk->pendn)
				// not redundant - accept!
				ensk=ensk->suc=sk;
			// redundant - weld!
			else ensk->set_len(ensk->len()+sk->len());
		// redundant arcs of length 1 are bugs
		else;
	else ensk=ensk->suc=sk;
	if (sk!=ensk) { delete sk; return; }
	// compute offset from base
	if (lastsk) {
		sk->offset=lastsk->offset;
		(sk->offset).move(sk->dir(),sk->len()-1);
	}
	// fill-in axis_weight, when scan started in midline (tracing shape)
	stroke *sk0;
	if ((sk->wgt())() && !(sk->wgt().y() && sk->wgt().x()))
		if (lastsk && lastsk->pen_is_down())
			sk->mask(lastsk->wgt());
		else for (sk0=stsk; sk0; sk0=sk0->suc)
			if (sk0->offset==sk->offset)
				{ sk->mask(sk0->wgt()); break; }
}

void shape :: append_stroke(point_pos &offset)
{
	for (direction dir; dir(); dir++)
		if (offset.how_far(dir))
			append_stroke(new stroke(offset.how_far(dir)+1,dir,twgwgt,FALSE,0,FALSE));
}

shape :: ~shape()
{
	if (stsk) {
		stroke *suc=stsk->suc;
		for (; stsk; stsk=suc) {
			suc=stsk->suc;
			delete stsk;
		}
	}
}

void shape :: list(panel *scr, point_pos *pt0, boolean stay)
{
	point_pos pt=*pt0;
	for (stroke *sk=stsk; sk; sk=sk->suc)
		sk->list(scr,&pt);
	if (!stay) *pt0=pt;
}

void shape :: clear(panel *scr, point_pos *pt0, boolean stay)
{
	point_pos pt=*pt0;
	for (stroke *sk=stsk; sk; sk=sk->suc)
		sk->clear(scr,&pt);
	if (!stay) *pt0=pt;
}

point_pos& shape :: where(void)
{ // offest of end from start

	tmpt1=point_pos(1,1);
	for (stroke *sk=stsk; sk; sk=sk->suc)
		tmpt1.move(sk->dir(),sk->len()-1);
	return tmpt1;
}

void shape :: posit(point_pos &offset)
{ // add dummi move to offset from start.

	point_pos pt=(0,0);
	pt-=where(); pt+=offset;
	append_stroke(pt);
}

void shape :: posit_start(void)
{ // add dummi move to start point

	point_pos pt=(0,0);
	pt-=where();
	append_stroke(pt);
}

point_pos& shape :: area(void)
{ // size of rectangle covered by shape

	int sty=32767, eny=0, stx=32767, enx=0;
	point_pos pt(1,1);
	for (stroke *sk=stsk; sk; sk=sk->suc) {
		pt.move(sk->dir(),sk->len()-1);
		if (sk->pen_is_down()) {
			if (pt.y()<sty) sty=pt.y();
			if (pt.y()>eny) eny=pt.y();
			if (pt.x()<stx) stx=pt.x();
			if (pt.x()>enx) enx=pt.x();
		}
	}
	if (sty>eny) tmpt2=point_pos(0,0);
	else tmpt2=point_pos(eny-sty+1,enx-stx+1);
	return tmpt2;
}

boolean shape :: occupied(point_pos &where)
{ // tell if covering point

	point_pos pt(1,1);
	int sty, eny, stx, enx;
	for (stroke *sk=stsk; sk; sk=sk->suc) {
		point_pos stpt=pt;
		pt.move(sk->dir(),sk->len()-1);
		sty=stpt.y(); eny=pt.y();
		if (sty>eny) { int i=sty; sty=eny; eny=i; }
		stx=stpt.x(); enx=pt.x();
		if (stx>enx) { int i=stx; stx=enx; enx=i; }
		if (sk->pen_is_down()) {
			if (sty<=where.y() && where.y()<=eny
			&& stx<=where.x() && where.x()<=enx)
				return TRUE;
		}
	}
	return FALSE;
}

/*********************** pattern recognition **************************/

void tracing :: clear_landmarks()
{
	if (!stmark) return;
	landmark *suc=stmark->suc;
	for (; stmark; stmark=suc) {
		suc=stmark->suc;
		delete stmark;
	}
}

tracing :: tracing(panel *scr, point_pos *cursor) : shape(NULL,"trace")
{ // "probe constructor"
  /////////////// experimental code! //////////////

	stmark=NULL;
	point_pos pt=*cursor;
	// beginning and end of scan are complicated, in an attempt to
	// preserve arcs of length 1, to be lost in a "general" algorithm.
	intersection godir=scr->gowhere(&pt); if (!godir()) return;
	// disregrad neighbours
	char c=scr->get_c(&pt); intersection avdir=alph->cdir(c);
	direction dir=avdir.ask_first();
	if (!(godir>=!dir)) avdir-=!dir;
	(mark(&pt,&avdir))->proceed(&avdir,&dir); // initialize, no mark
	landmark *mrk;
	point_pos offset(0,0);
	while (dir()) {
		if (offset.y() || offset.x()) {
			shape::append_stroke(offset);
			offset=point_pos(0,0);
		}
		mrk=append_stroke(scr,&pt,&dir);
		if (mrk) mrk->proceed(&avdir,&dir);
		if (!dir()) { // finished first pass. reposition to pending intersection
			for (mrk=stmark; mrk; mrk=mrk->suc)
				if (mrk->dirleft()) { // directions left unexplored here
					offset=mrk->pos; offset-=pt;
					pt=mrk->pos;
					dir=nodir; avdir=mrk->dirleft;
					dir=avdir.ask_first();
					break;
				}
		}
	}
	// resolve missing axis_weight (in single-line shapes)
	for (stroke *sk=stsk; sk; sk=sk->succ()) {
		weight_d wgt=sk->wgt();
		if (wgt() && !(wgt.y() && wgt.x())) {
			if (!wgt.y()) wgt.replace(hdim,wgt.x());
			if (!wgt.x()) wgt.replace(vdim,wgt.y());
			sk->set_wgt(wgt);
		}
	}
	clear_landmarks();
}

landmark * tracing :: append_stroke(panel *scr, point_pos *cursor, direction *curdir)
{ // phase in "probe constructor" - read next arc
  ///////////// experimental code! ////////////

	char c=scr->get_c(cursor); if (c==' ') return NULL;
	intersection avdir=alph->cdir(c);
	if (!(avdir>=*curdir)) return NULL;	// double-tipped not supported
	if (avdir.unary()) return NULL; 	// double-tipped not supported
	color_ind clr=scr->get_color(cursor);
	clr.normalize();
	weight_d wgt(alph->cweight(c));
	stroke *sk=new stroke(1,*curdir,wgt,FALSE,&clr,TRUE);
	landmark *mrk;
	for (mrk=NULL; !mrk;) {    // stop when we get to junction - let caller decide
		for (mrk=stmark; mrk; mrk=mrk->suc)
			if (mrk->pos==*cursor) break;
		if (mrk) {					    // dejavue
			if (sk->len()>1)
				mrk->dirleft-=!(*curdir); // ain't coming back
			avdir=mrk->dirleft;
			if (mrk->dirleft>=*curdir) {
				mrk->dirleft-=*curdir;
				mrk=NULL;		    // passing through
			}
		} else if (!avdir.unary())		    // unmarked branch
			if (avdir>=*curdir) {		   // mark and proceed
				avdir-=*curdir;
				mark(cursor,&avdir);
				avdir+=*curdir;
			} else mrk=mark(cursor,&avdir);        // can't decide
		if (!alph->ccont(scr->get_c(cursor),
		 scr->succ_c(curdir,cursor),*curdir)
		 || (scr->get_color(cursor)).ask_for_clr()!=clr.forgnd)
			mrk=mark(cursor,&avdir);  // end of arc
		else {	      // get next
			cursor->move(*curdir); sk->expand();
			char c=scr->get_c(cursor); avdir=alph->cdir(c);
			avdir-=!(*curdir);		  // ain't coming back
		}
	}
	if ((alph->cdir(scr->get_c(cursor))).unary())		     // tipped
		sk->toggle_tip();
	shape::append_stroke(sk);
	return mrk;
}

landmark :: landmark(point_pos *pt, intersection *avdir)
 : pos(*pt), dirstart(*avdir), dirleft(*avdir)
{ suc=NULL; }

void landmark :: proceed(intersection *avdir, direction *curdir)
{ // solve amiguity. more than one path open from point.

	if (dirleft())
		if (dirleft>=*curdir) ; 			   // continue
		else *curdir=dirleft.ask_first();		       // turn
	else *curdir=nodir;				    // end of the road
	*avdir=dirleft;
}

landmark * tracing :: mark(point_pos *cursor, intersection *avdir)
{ // add cursor to intesections-left-to-explore list

	landmark *mrk;
	if (!stmark)
		mrk=stmark=new landmark(cursor,avdir);
	else {
		for (mrk=stmark; mrk->suc; mrk=mrk->suc)
			if (mrk->pos==*cursor) break;	    // we've been here
		if (mrk->pos!=*cursor)				     // append
			mrk=mrk->suc=new landmark(cursor,avdir);
	}
	return(mrk);
}

/*********************** sample regular shapes *************************/

oblong :: oblong(int wd, int hgt, weight_d &wgt)
 : shape(NULL,"oblong")
{
	// allocate two sides - the rest is for the lister
	direction dir;
	append_stroke(new stroke(wd,dir,wgt)); dir.clockwise();
	append_stroke(new stroke(hgt,dir,wgt));
}

void oblong :: list(panel *scr, point_pos *pt0)
{
	point_pos pt=*pt0;
	for (int i=1; i<=2; i++) {
		shape::list(scr,&pt,FALSE);
		stsk->invert();
		stsk->succ()->invert();
	}
}

void oblong :: clear(panel *scr, point_pos *pt0)
{
	point_pos pt=*pt0;
	for (int i=1; i<=2; i++) {
		shape::clear(scr,&pt,FALSE);
		stsk->invert();
		stsk->succ()->invert();
	}
}

/******************** sample shape including string *******************/

display_box :: display_box(char *s, point_pos &size, weight_d &wgt,
 direction &pendir, direction &align) : shape(NULL,"display_box")
{
	// experimental code. presently does not support vertical title

	// allocate all sides in advance
	direction dir;
	for (int i=1; i<=2; i++) {
		append_stroke(new stroke(size.x(),dir,wgt));
		dir.clockwise();
		append_stroke(new stroke(size.y(),dir,wgt));
		dir.clockwise();
	}
	if (!*s) return;
	int len=strlen(s), lmax=size.x()-2;
	if (len>lmax) len=lmax;
	// offset
	point_pos pt(0,0);
	// only horizontal part of decision tree installed
	if (align==lt)
		if (pendir==rt) pt.setx(1);
		else pt.setx(lmax-len+1);
	else if (align==rt)
		if (pendir==lt) pt.setx(lmax);
		else pt.setx(lmax-len+1);
	else // nodir
		if (pendir==rt) pt.setx((lmax-len)/2);
		else pt.setx(lmax-(lmax-len)/2+1);
	append_stroke(pt);
	// string
	append_stroke(new stroke(s,pendir,align));
	if (len>strlen(s)) ensk->set_len(len);
}

