/*	XGLisztView.cpp
 *
 *		Mondo-useful List view.  Meant to be subclassed to handle
 *	your specific list contents.
 */

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

  XGLisztView.cpp Copyright 1998-1999 Sassafras Software Inc.

  YAAF is Copyright 1997-1999 by William Woody.

  Redistribution and use in source and binary forms, with or without 
  modification, are permitted provided that the following conditions 
  are met:

  Redistributions of source code must retain the above copyright notice, 
  this list of conditions and the following disclaimer.

  Neither the name of the copyright holder or other contributors may
  be used to promote products derived from this software without
  specific written prior permission.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 
  BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 
  ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
  SOFTWARE.
  
  Contact:   woody@alumni.caltech.edu
  Web page:  http://www.pandawave.com/yaaf/

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

#include <XConfig.h>
#include <XScroll.h>
#include <XMessages.h>
#include <XDraw.h>
#include <XTimer.h>
#include <XLisztView.h>
#include <string.h>


static unsigned int nice_number (unsigned int ceiling);


/************************************************************************/
/*																		*/
/*	Construction/Destruction											*/
/*																		*/
/************************************************************************/

/*$	XGLisztView::XGLisztView
 *
 *		Build me
 */

XGLisztView::XGLisztView (XGView *owner, XGArgStream &stream) : XGView(owner,stream)
{
	fDrawing = 0;
	fAnchor = -1;
	fTypeAheadLen = 0;

	if (!(fHeight = stream.ReadInteger())) {
		XGDraw draw(this);
		SetCellHeight(draw.GetFontHeight());
	}

	fMultiSel = stream.ReadBoolean();
	fSorting = !stream.ReadBoolean();
}

/*$	XGLisztView::~XGLisztView
 *
 *		Delete me
 */

XGLisztView::~XGLisztView ()
{

}

long XGLisztView::GetSelect (void)
{
	long i;

	for (i = 0; i < fList.Length(); i++) {
		if (fList[i].selected)
			return(i);
	}
	return(-1);
}

bool XGLisztView::GetSelect (long ix)
{
	if (ix >= 0 && ix < fList.Length())
		return(fList[ix].selected);
	return(false);
}

long XGLisztView::GetSelect (long *a)
{
	long i, count;

	count = 0;
	for (i = 0; i < fList.Length(); i++) {
		if (fList[i].selected) {
			count++;
			if (a)
				*a++ = i;
		}
	}
	return(count);
}

void XGLisztView::SetSelect (XGLisztSelect select)
{
	SetSelect(0, 0x7FFFFFFF, select);
}

void XGLisztView::SetSelect (long start, long stop, XGLisztSelect select)
{
	long ix, h;
	XRect r;
	bool seld;

	if (start > stop) {
		ix = start;
		start = stop;
		stop = ix;
	}
	if (start < 0)
		start = 0;
	if (stop >= fList.Length())
		stop = fList.Length() - 1;
	if (start <= stop) {
		if (select == KLisztSelectChange) {
			for (ix = start; ix <= stop; ix++)
				fList[ix].selected = !fList[ix].selected;
			if (fDrawing == 0) {
				r = GetCellRect(start, stop - start + 1);
				InvalView(&r);
				UpdateView();
			}
		} else {
			h = GetCellHeight();
			if (fDrawing == 0)
				r = GetCellRect(start);
			seld = select;
			for (ix = start; ix <= stop; ix++) {
				if (fList[ix].selected != seld) {
					fList[ix].selected = seld;
					if (fDrawing == 0) {
						InvalView(&r);
						UpdateView();
					}
				}
				OffsetRect(&r, 0, h);
			}
		}
		DoDispatch(KLisztSelect, GetViewID(), NULL);
	}
}

void XGLisztView::SetSelect (long ix, XGLisztSelect select)
{
	XGScrollView *v;
	long x, y, h;
	XRect r;
	bool seld;

	if (ix >= 0 && ix < fList.Length()) {
		if (select == KLisztSelectChange)
			seld = !fList[ix].selected;
		else
			seld = select;
		if (fList[ix].selected != seld) {
			fList[ix].selected = seld;
			if (fDrawing == 0) {
				v = dynamic_cast<XGScrollView *>(GetParent());
				v->GetScrollValue(&x, &y);
				r = GetContentRect();
				h = GetCellHeight();
				r.top -= (y - ix) * h;
				r.bottom = r.top + h;
				InvalView(&r);
				UpdateView();
			}
			DoDispatch(KLisztSelect, GetViewID(), &ix);
		}
	}
}

void XGLisztView::SetSelect (long count, long *a, XGLisztSelect select)
{
	if (a) {
		while (--count >= 0)
			SetSelect(*a++, select);
	}
}

void XGLisztView::SelectOne (long ix)
{
	if (ix >= 0) {
		if (!fMultiSel) {
			long cur = GetSelect();
			if (cur != ix) {
				if (cur >= 0)
					SetSelect(cur, KLisztSelectOff);
				SetSelect(ix, KLisztSelectOn);
			}
		} else {
			SetSelect(ix, KLisztSelectOn);
			if (ix)
				SetSelect(0, ix - 1, KLisztSelectOff);
			SetSelect(ix + 1, 0x7FFFFFFF, KLisztSelectOff);
		}
	}
}

bool XGLisztView::Reveal (long ix, bool center)
{
	long start, xval, xfit, yfit;
	XGScrollView *v = dynamic_cast<XGScrollView *>(GetParent());

	if (ix < 0)
		ix = 0;
	if (ix >= fList.Length())
		ix = fList.Length() - 1;

	v->GetScrollValue(&xval, &yfit);
	start = yfit;
	v->GetPageSize(&xfit, &yfit);
	if (ix >= start && ix < start + yfit)
		return(false);

	if (center) {
		start = ix - (yfit >> 1);
	} else if (ix <= start) {
		start = ix;
	} else {
		start = ix - yfit + 1;
	}
	v->SetScrollValue(xval, start);
	return(true);
}

long XGLisztView::ListCount (void)
{
	return(fList.Length());
}

void XGLisztView::ListExpand (long newSize)
{
	XGLisztRec lr;

	newSize -= fList.Length();
	if (newSize < 0) {
		while (++newSize <= 0)
			fList.Delete(fList.Length() - 1);
		Sort(true);
	} else {
		lr.selected = false;
		lr.shown = false;
		lr.index = fList.Length();
		lr.data = NULL;
		while (--newSize >= 0) {
			fList += lr;
			lr.index++;
		}
		Sort(false);
	}
	if (fDrawing == 0) {
		InvalView();
		RecalcScroll();
	}
}

long XGLisztView::ListInsert (void *data, long before)
{
	XGLisztRec lr;

	if (before < 0 || before >= fList.Length())
		before = fList.Length();
	lr.selected = false;
	lr.shown = false;
	lr.data = data;
	try {
		fList.Insert(before, lr);
		Sort(true);
		if (fDrawing == 0) {
			InvalView();
			RecalcScroll();
		}
	} catch (...) {
		before = -1;
	}
	return(before);
}

void XGLisztView::ListDelete (long ix)
{
	if (ix >= 0 && ix < fList.Length()) {
		fList.Delete(ix);
		Sort(true);
		if (fDrawing == 0) {
			InvalView();
			RecalcScroll();
		}
	}
}

void *XGLisztView::ListGetData (long ix)
{
	if (ix >= 0 && ix < fList.Length())
		return(fList[ix].data);
	return(NULL);
}

void XGLisztView::ListSetData (void *data, long ix)
{
	if (ix >= 0 && ix < fList.Length()) {
		fList[ix].data = data;
		Sort(false);
	}
}

long XGLisztView::ListGetIndex (long ix)
{
	if (ix >= 0 && ix < fList.Length())
		return(fList[ix].index);
	return(-1);
}

XRect XGLisztView::GetCellRect (long ix, long count)
{
	XRect r;
	long x, y, h;
	XGScrollView *v;

	r = GetContentRect();
	r.bottom = r.top;
	if (ix >= 0 && ix < fList.Length()) {
		v = dynamic_cast<XGScrollView *>(GetParent());
		v->GetScrollValue(&x, &y);
		h = GetCellHeight();
		r.top -= (y - ix) * h;
		r.bottom = r.top + (count * h);
	}
	return(r);
}

void XGLisztView::AttachHeader (XGHeader *header)
{
	fHeader = header;
}

void XGLisztView::DoSorting (bool sortOn)
{
	if (!sortOn) {
		fSorting++;
	} else {
		fSorting--;
		if (fSorting < 0)
			fSorting = 0;
	}
}

void XGLisztView::DoDrawing (bool drawOn)
{
	if (!drawOn) {
		fDrawing++;
	} else {
		fDrawing--;
		if (fDrawing < 0)
			fDrawing = 0;
	}
}

/*$	XGLisztView::DoDrawSelect
 *
 *		Draw the selection background
 */

void XGLisztView::DoDrawHilite (XGDraw &draw, XRect &r, bool selected)
{
	if (selected) {
		draw.FillRect(r, KXGColorHilite);
		draw.SetForeColor(KXGColorHiliteText);
	} else {
		draw.EraseRect(r);
	}
}

/*$	XGLisztView::DoDrawView
 *
 *		Draw me
 */

void XGLisztView::DoDrawView (XRect dr)
{
	XGScrollView *v;
	long x, y, h, i;
	XRect r, vr, sr;
	XGDraw draw(this);
	
	vr = GetContentRect();
	v = dynamic_cast<XGScrollView *>(GetParent());
	h = GetCellHeight();
	v->GetScrollValue(&x, &y);

//	draw.EraseRect(vr);
	r.top = vr.top;
	r.bottom = r.top + h;
	r.left = vr.left - x * h;
	r.right = vr.right;
	for (i = PointToCell(vr.top); i < fList.Length(); i++) {	
		if (::SectRect(&dr, &r, &sr)) {
			draw.ClipRect(&sr);

			DoDrawHilite(draw, r, fList[i].selected);
			DrawItem(draw, dr, r, fList[i].index, fList[i].data, fList[i].selected);
			draw.SetForeColor(KXGColorBlack);
		
			draw.ClipRect();
		}
		OffsetRect(&r, 0, h);
		if (r.top > vr.bottom)
			break;
	}
	r.bottom = vr.bottom;
	if (r.bottom >= r.top)
		draw.EraseRect(r);
}

/*$	XGLisztView::DoSizeView
 *
 *		Resize view
 */

void XGLisztView::DoSizeView (void)
{
	InvalView();
	RecalcScroll();
}

long XGLisztView::PointToCell (long vpos, long)
{
	long x, y, h;
	XGScrollView *v;

	v = dynamic_cast<XGScrollView *>(GetParent());
	v->GetScrollValue(&x, &y);
	h = GetCellHeight();
	vpos += h << 8;
	return(y + (vpos / h) - 256);
}

bool XGLisztView::DoMouseDown (XPoint where, short flags)
{
	long cell;
	bool seld;
	
	SetFocus();
	fDouble = false;
	cell = PointToCell(where);
	if (cell < 0)
		return(false);

	fLastCell = cell;
	seld = GetSelect(cell);

	/* check for double-click in same cell as before */
	if ((flags & KDoubleClick) && (cell == fAnchor) && seld) {
		fDouble = true;
		return(true);
	}

	/* check for selection extension */
	if (fMultiSel
		&& (flags & KKeyShift)
		&& (fAnchor >= 0))
	{
		SetSelect(fAnchor, cell, KLisztSelectOn);
		return(true);
	}
#ifdef KKeyCommand
	if ((flags & KKeyCommand)
#else
	if ((flags & KKeyControl)
#endif
		&& (cell < fList.Length()))
	{
		fAnchor = cell;
		if (fMultiSel) {
			SetSelect(cell, KLisztSelectChange);
			return(true);
		}
		if (cell != GetSelect()) {
			SelectOne(cell);
			return(true);
		}

		SetSelect(KLisztSelectOff);
		fAnchor = -1;
		return(false);
	}

	if (cell < fList.Length()) {
		fAnchor = cell;
		if (!fMultiSel)
			SelectOne(cell);
		else {
			SetSelect(cell, KLisztSelectOn);
			if (!seld) {
				if (cell)
					SetSelect(0, cell - 1, KLisztSelectOff);
				SetSelect(cell + 1, 0x7FFFFFFF, KLisztSelectOff);
			}
		}

		if (DoDragStart(where, flags))
			return(false);

		if (fMultiSel && !seld) {
			if (cell)
				SetSelect(0, cell - 1, KLisztSelectOff);
			SetSelect(cell + 1, 0x7FFFFFFF, KLisztSelectOff);
		}
		return(true);
	}

	SetSelect(KLisztSelectOff);
	fAnchor = -1;
	return(false);
}

void XGLisztView::DoMouseMove (XPoint where, short flags)
{
	long cell;

	if (!(flags & KCapturedMouse)) {
		XGView::DoMouseMove(where,flags);
	} else {
		cell = PointToCell(where);
		if (cell < 0)
			cell = 0;

		/* check to see if anything has changed */
		if (cell == fLastCell)
			return;

		fDouble = false;
		/* check for double-click in same cell as before
		if ((flags & KDoubleClick) && (cell == fAnchor) && GetSelect(cell))
			return; */

		/* make sure this item is in view */
		Reveal(cell, false);

		/* check for selection extension */
		if (fMultiSel
			&& (flags & KKeyShift)
			&& (fAnchor >= 0))
		{
			if (fLastCell < cell && cell <= fAnchor)
				SetSelect(fLastCell, cell - 1, KLisztSelectOff);
			else if (fLastCell > cell && cell >= fAnchor)
				SetSelect(fLastCell, cell + 1, KLisztSelectOff);
			else
				SetSelect(fLastCell, cell, KLisztSelectOn);
		} else if (fMultiSel
#ifdef KKeyCommand
			&& (flags & KKeyCommand)
#else
			&& (flags & KKeyControl)
#endif
			&& (fAnchor >= 0))
		{
			if (fLastCell < cell && cell <= fAnchor)
				SetSelect(fLastCell, cell - 1, KLisztSelectChange);
			else if (fLastCell > cell && cell >= fAnchor)
				SetSelect(fLastCell, cell + 1, KLisztSelectChange);
			else if (cell < fLastCell && fLastCell <= fAnchor)
				SetSelect(fLastCell - 1, cell, KLisztSelectChange);
			else if (cell > fLastCell && fLastCell >= fAnchor)
				SetSelect(fLastCell + 1, cell, KLisztSelectChange);
			else
				SetSelect(fLastCell, cell, KLisztSelectChange);
		} else {
			SetSelect(fLastCell, KLisztSelectOff);
			if (cell >= fList.Length()) {
				fAnchor = -1;
			} else {
				fAnchor = cell;
				SetSelect(cell, KLisztSelectOn);
			}
		}

		fLastCell = cell;
	}
}

void
XGLisztView::DoMouseUp (XPoint where, short flags)
{
	long cell;

	if (!(flags & KCapturedMouse)) {
		XGView::DoMouseUp(where, flags);
	} else if (flags & KDoubleClick) {
		cell = PointToCell(where);
		if (fDouble && (cell >= 0) && (fAnchor == cell) && GetSelect(cell))
			DoDispatch(KLisztDoubleClick, GetViewID(), &fAnchor);
	}
}

bool
XGLisztView::DoDragStart (XPoint, short)
{
	return(false);
}

long
XGLisztView::DoTypeAhead (char *, long)
{
	return(-1);
}

void
XGLisztView::Sort (bool resort)
{
	long i, j, k, m, count;
	XGLisztRec temp;
	bool redraw;

	if (fSorting != 0)
		return;

	redraw = resort;
	count = fList.Length();
	if (resort) {
		for (i = 0; i < count; i++) {
			fList[i].index = i;
			fList[i].selected = false;
		}
	}

	for (i = 1; i < count; i++) {
		if (CompareItems(fList[i].index, fList[i - 1].index, fList[i].data, fList[i - 1].data) > 0)
			continue;
		j = 0;
		k = nice_number(i);
		if ((m = i - k) > 0)
			goto _compare;
		do {
			k >>= 1;
			m = j + (k ? k : 1);
_compare:
			if (CompareItems(fList[i].index, fList[m - 1].index, fList[i].data, fList[m - 1].data) > 0)
				j = m;
		} while (k);
		if (i == j)
			continue;
			
		
		memcpy(&temp, &fList[i], sizeof(XGLisztRec));
		memmove(&fList[j + 1], &fList[j], (i - j) * sizeof(XGLisztRec));
		memcpy(&fList[j], &temp, sizeof(XGLisztRec));
		redraw = true;
	}

	if (redraw && (fDrawing == 0))
		InvalView();
}

long XGLisztView::CompareItems (long ix1, long ix2, void *, void *)
{
	if (ix1 > ix2)
		return(1);
	if (ix1 < ix2)
		return(-1);
	return(0);
}

BEGINDISPATCH(XGLisztView,XGView)
	DISPATCHTABLE(KXGKeyEvent,XGLisztView::DoKey)
ENDDISPATCH

/*	TRectEditView::DoKey
 *
 *		Handle keyboard event. This handles the arrow commands to
 *	handle nudging this thing.
 */

long
XGLisztView::DoKey (long arg, void *)
{
	short msg = (arg >> 16) & 0x0FFFF;
	short key = arg & 0x0FFFF;
	long x, y, xfit, yfit, cell;
	XGScrollView *v;
	
	if (!(msg & KSpecialKey)) {
		if (fTypeAheadTimer.Expired())
			fTypeAheadLen = 0;
		fTypeAheadTimer.Reset(2);
		if (fTypeAheadLen < 31) {
			fTypeAhead[fTypeAheadLen++] = key;
			fTypeAhead[fTypeAheadLen] = 0;
			cell = DoTypeAhead(fTypeAhead, fTypeAheadLen);
			SelectOne(cell);
			if (cell >= 0) {
				fAnchor = cell;
				Reveal(fAnchor);
			}
		}
		return 0;

	} else {
		fTypeAheadLen = 0;
		switch (key) {
		case KKeyUpCursor:
		case KKeyLeftCursor:
			if (fAnchor < 0)
				fAnchor = GetSelect();
			if (fAnchor > 0) {
				fAnchor--;
				SetSelect(KLisztSelectOff);
				Reveal(fAnchor);
				SetSelect(fAnchor, KLisztSelectOn);
			}
			return 0;

		case KKeyDownCursor:
		case KKeyRightCursor:
			if (fAnchor < 0)
				fAnchor = GetSelect();
			if (fAnchor < fList.Length() - 1) {
				fAnchor++;
				SetSelect(KLisztSelectOff);
				Reveal(fAnchor);
				SetSelect(fAnchor, KLisztSelectOn);
			}
			return 0;

		case KKeyEscape:
			SetSelect(KLisztSelectOff);
			fAnchor = -1;
			return 0;

		case KKeyHome:
			Reveal(0, false);
			return 0;

		case KKeyEnd:
			Reveal(0x7FFFFFFF, false);
			return 0;

		case KKeyPageUp:
		case KKeyPageDown:
			v = dynamic_cast<XGScrollView *>(GetParent());
			v->GetScrollValue(&x, &y);
			v->GetPageSize(&xfit, &yfit);
			if (key == KKeyPageUp)
				y -= yfit;
			else
				y += yfit;
			v->SetScrollValue(x, y);
			return 0;

		default:
			break;
		}
	}
	
	return -1;
}

XRect XGLisztView::GetColumn (long ix, XRect *r)
{
	XRect col;

	if (!fHeader) {
		if (r)
			col = *r;
	} else {
		fHeader->GetColumnBox(ix, &col);
		if (r) {
			col.left += r->left;
			col.right += r->left;
			col.top = r->top;
			col.bottom = r->bottom;
		}
	}
	return col;
}

void XGLisztView::DrawItem (XGDraw &, XRect, XRect, long, void *, bool)
{

}

/*$	XGLisztView::RecalcScroll
 *
 *		Recalculate the scrollbar parameters
 */

void XGLisztView::RecalcScroll (void)
{
	XGScrollView *v;
	long x, y, h;
	XRect r;

	h = GetCellHeight();
	v = dynamic_cast<XGScrollView *>(GetParent());
	v->SetPixelStep(h);
	
	r = GetContentRect();
	x = (r.right - r.left) / h;
	y = (r.bottom - r.top) / h;
	if (x < 1) x = 1;
	if (y < 1) y = 1;
	v->SetPageSize(x, y);

	y = fList.Length() - y;
	if (y < 0)
		y = 0;
	v->SetMaxValue(1000, y);
}

static unsigned int
nice_number (unsigned int ceiling)
{
	unsigned int power;

	if (!ceiling) return(0);

	for (power = 1; power <= ceiling; power<<=1) ;
	return(power>>1);
}

