/*	XGInlinePopup.cpp
 *
 *		This provides the ability to pop up a list, including mouse
 *	and arrow navigation
 */

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

  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>			// must be first to optimize compile on MSVC++
#include <string.h>
#include <XDataUtil.h>
#include <XInline.h>
#include <XMessages.h>
#include <XMisc.h>
#include <XWindow.h>
#include <XPopup.h>

/************************************************************************/
/*																		*/
/*	Standard Classes													*/
/*																		*/
/************************************************************************/

/*$	XGInlinePopup::XGInlinePopup
 *
 *		Inline editing support
 */

XGInlinePopup::XGInlinePopup(XGView *parent, XGSViewInitRecord &init) :
	XGView(parent,init)
{
	fPopTime = XGGetTime() + XGGetDoubleClick();
	fPopQuick = true;
	
	fTypePos = 0;
	
	fLastPos.h = -1;
	fLastPos.v = -1;
}

/*$	XGInlinePopup::~XGInlinePopup
 *
 *		Delete me
 */

XGInlinePopup::~XGInlinePopup()
{
	if (fPopWindow) delete fPopWindow;
}

/************************************************************************/
/*																		*/
/*	Standard Classes													*/
/*																		*/
/************************************************************************/

/*$	XGInlinePopup::Create
 *
 *		Create one of me. This creates the view in the parent's window, 
 *	not in the parent view. This has the advantage of making this thing
 *	appear regardless of the clipping boundaries of the parent, which is
 *	exactly what I want...
 */

XGInlinePopup *XGInlinePopup::Create(XGView *parent, 
								   XRect &where,
								   short font,
								   XGStringList *list,
								   short value)
{
	XGSViewInitRecord einit;
	XGInlinePopup *iedit;
	XRect r;
	XPoint size;
	short len;
	
	/*
	 *	Build the view
	 */
	
	r = where;
	parent->ViewToGlobal(&r);
	parent->GetWindow()->GlobalToView(&r);
	
	einit.fViewType = 'ipop';
	einit.fViewID = 0;
	einit.fRefNum = -1;
	einit.fLockLeft = true;
	einit.fLockTop = true;
	einit.fLockRight = false;
	einit.fLockBottom = false;
	einit.fVisible = true;
	einit.fEnabled = true;
	einit.fTabStop = false;
	einit.fAutoLeft = r.left;
	einit.fAutoTop = r.top;
	einit.fAutoRight = r.right;
	einit.fAutoBottom = r.bottom;
		
	iedit = new XGInlinePopup(parent->GetWindow(),einit);
	iedit->fParentEvent = parent;
	iedit->SetFocus();
	
	/*
	 *	Create popup
	 */
	
	XGDraw draw(iedit);
	draw.SetFont(XGFont::LoadFont(font));
	
	len = list->GetNumStrings();
	if (value >= len) value = len-1;
	if (value < 0) value = 0;
	
	iedit->fPopView = new XGPopMenuView(list,font,value);
	size = iedit->fPopView->GetPopSize(draw);
	
	r = iedit->AutoPosWindow(draw,size);	
	iedit->fPopWindow = new XGPopWindow(iedit,r,iedit->fPopView);
	
	return iedit;
}

/*	XGInlinePopup::DeleteSelf
 *
 *		Self-destruction support; this invalidates the area around me to
 *	make sure things get drawn correctly.
 */

void XGInlinePopup::DeleteSelf(bool adjfocus)
{
	XRect r;
	XGView *v;
	
	r = GetContentRect();
	ViewToGlobal(&r);
	v = GetWindow();
	v->GlobalToView(&r);
	v->InvalView(&r);
	
	/*
	 *	Make sure the focus is changed to my parent if I had it
	 *	before.
	 */
	
	if (HasFocus() && adjfocus) {
		v = fParentEvent;
		delete this;
		v->SetFocus();
	} else {
		delete this;
	}
}

/*	XGInlinePopup::GetParentDispatch
 *
 *		Get the dispatch parent. This is different from the view parent
 *	for this view; that enables me to host my editor display in the
 *	root window, yet send events to the "container view"
 */

XGDispatch *XGInlinePopup::GetParentDispatch()
{
	if (fParentEvent) return fParentEvent;
	return XGView::GetParentDispatch();
}

/************************************************************************/
/*																		*/
/*	Autodestruction														*/
/*																		*/
/************************************************************************/

/*$	XGInlinePopup::DoDrawView
 *
 *		Handle drawing by doing nothing...
 */

void XGInlinePopup::DoDrawView(XRect)
{
}

/*$	XGInlinePopup::DoActivate
 *
 *		Handle activation/deactivation by sending up a message. If on
 *	deactivation I can go away, then I do.
 */

void XGInlinePopup::DoActivate(bool a)
{
	XGSPopupInline i;
	
	if (a) return;
	
	if (!a) {
		i.popup = this;
		i.value = fPopView->GetLocation();
		if (1 != DoDispatch(KXGPopupInlineClose,GetRefNum(),&i)) {
			DeleteSelf();
		}
	}
}

/*$	XGInlinePopup::DoLoseFocus
 *
 *		Lose focus.
 */

void XGInlinePopup::DoLoseFocus()
{
	XGSPopupInline i;
	
	i.popup = this;
	i.value = fPopView->GetLocation();
	DoDispatch(KXGPopupInlineClose,GetRefNum(),&i);
	DeleteSelf(false);
}

/*$	XGInlinePopup::DoMouseDown
 *
 *		Handle mouse down event.
 */

bool XGInlinePopup::DoMouseDown(XPoint where, short flag)
{
	DoMouseMove(where,flag);
	return true;
}

/*$	XGInlinePopup::DoMouseUp
 *
 *		Handle mouse up event
 */

void XGInlinePopup::DoMouseUp(XPoint where, short flag)
{
	DoMouseMove(where,flag);
	if (fPopQuick && (XGGetTime() < fPopTime)) {
		/*
		 *	Brief click
		 */
		
//		HoldCapture();
	} else {
		Close();
	}
}

/*$	XGInlinePopup::DoMouseMove
 *
 *		Handle mouse move event
 */

void XGInlinePopup::DoMouseMove(XPoint where, short flags)
{
	XRect r;
	
	if (fPopWindow) {
		r = fPopWindow->GetLocation();
		if (PtInRect(where,&r)) {
			fPopQuick = false;
			where.h -= r.left;
			where.v -= r.top;
			if ((fLastPos.h != where.h) || (fLastPos.v != where.v)) {
				fPopView->DoMouseMove(where,flags);
			}
			fLastPos = where;
		} else {
			// point not in popup menu; force popup to be clear
			where.h = -1;
			where.v = -1;
			fPopView->DoMouseMove(where,flags);
		}
	}
}

/*$	XGInlinePopup::DoMouseLeave
 *
 *		Handle mouse leave event
 */

void XGInlinePopup::DoMouseLeave()
{
	XPoint where;
	
	where.h = -1;
	where.v = -1;
	fPopView->DoMouseMove(where,0);
}

/************************************************************************/
/*																		*/
/*	Events																*/
/*																		*/
/************************************************************************/

BEGINDISPATCH(XGInlinePopup,XGView)
	DISPATCHTABLE(KXGAppPeriodic,XGInlinePopup::DoPeriodic)
	DISPATCHTABLE(KXGKeyEvent,XGInlinePopup::DoKey)
ENDDISPATCH

/*	XGInlinePopup::DoPeriodic
 *
 *		Handle periodic events
 */

long XGInlinePopup::DoPeriodic(long, void *)
{
	if ((fTypePos > 0) && (fTypeTime < XGGetTime())) {
		fTypePos = 0;
	}
	return -1;
}

/*	XGInlinePopup::DoKey
 *
 *		If the enter key is pressed, this sets the focus to my parent.
 *	This also traps up and down arrows for selection, and traps
 *	regular keys for immediate selection stuff.
 */

long XGInlinePopup::DoKey(long arg, void *parg)
{
	short c;
	short mods;
	
	mods = GETHIWORD(arg);
	c = GETLOWORD(arg);
	
	if (mods & KSpecialKey) {
		if (c == KKeyUpCursor) {
			if (fPopView) fPopView->MoveUp();
			return 0;
		} else if (c == KKeyDownCursor) {
			if (fPopView) fPopView->MoveDown();
			return 0;
		}
	} else {
		if (c == 0x0D) {
			fParentEvent->SetFocus();
			return 0;
		} else if (c == 0x09) {
			/* Tab control? Close up shop and pass to my parent. */
			/* Note that I dispatch this directly to the parent */
			/* as after the SetFocus() event, I no longer exist. */
			fParentEvent->SetFocus();
			fParentEvent->DoDispatch(KXGKeyEvent,arg,parg);
			return 0;
		} else {
			if (c == 0x08) {
				if (fTypePos > 0) fTypePos--;
			} else {
				if (fTypePos < sizeof(fTypeChar)) {
					fTypeChar[fTypePos++] = c;
				}
			}
			fTypeTime = XGGetTime() + XGGetSecond()/2;
			fPopView->MoveTo(fTypePos,fTypeChar);
			return 0;
		}
	}
	return -1;
}

/************************************************************************/
/*																		*/
/*	Internals															*/
/*																		*/
/************************************************************************/

/*	XGInlinePopup::AutoPosWindow
 *
 *		Automatic position of window
 */

XRect XGInlinePopup::AutoPosWindow(XGDraw &draw, XPoint size)
{
	XRect r;
	XRect s;
	XRect t;
	short lines,h;
	
	/*
	 *	Get my size and the screen size in view-local coordinates
	 */
	
	r = GetContentRect();
#if OPT_WINOS
	/* Windows: GetScreenSize doesn't quite return the right thing. */
	s.left   = 0;
	s.top    = 0;
	s.right  = ::GetSystemMetrics(SM_CXFULLSCREEN);
	s.bottom = ::GetSystemMetrics(SM_CYFULLSCREEN);
#else
	XGWindow::GetScreenSize(&s);
#endif
	ScreenToView(&s);

	/*
	 *	Get where I think this should go
	 */
	
	t.top = r.bottom;
	t.bottom = t.top + size.v;
	t.left = 0;
	t.right = size.h;
	
	/*
	 *	Is this below the bottom of the screen?
	 */
	
	if (t.bottom > s.bottom) {
		/*
		 *	find height in number of lines; if it's less than 6,
		 *	try to put this above the popup area instead.
		 */
		
		h = draw.GetFontHeight();
		lines = (s.bottom - t.top - 6) / h;
		if (lines > 6) {
			t.bottom = t.top + 6 + lines * h;
		} else {
			t.bottom = r.top;
			t.top = t.bottom - size.v;
			
			if (t.top < s.top) {
				lines = (t.bottom - s.top - 6) / h;
				if (lines > 6) {
					t.top = t.bottom - 6 - lines * h;
				} else {
					/*
					 *	If we get here, we've got a problem.
					 *	The popup doesn't fit. In that case,
					 *	just do it from the top to the bottom
					 *	as many lines that will fit
					 */
					
					t.top = s.top;
					lines = (s.bottom - s.top - 6) / h;
					t.bottom = t.top + lines * h;
				}
			}
		}
	}
	
	/*
	 *	Fit horizontally
	 */
	
	if (t.right > s.right) {
		t.right = s.right;
		t.left = t.right - size.h;
	}
	if (t.left < s.left) {
		t.left = s.left;
		t.right = t.left + size.h;
	}
	
	/*
	 *	Done. Return it
	 */
	
	return t;
}