/*
Copyright 1990-2003 Sun Microsystems, Inc. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions: The above copyright notice and this
permission notice shall be included in all copies or substantial
portions of the Software.


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 OPEN GROUP OR SUN MICROSYSTEMS, INC. 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 EVEN IF
ADVISED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.


Except as contained in this notice, the names of The Open Group and/or
Sun Microsystems, Inc. shall not be used in advertising or otherwise to
promote the sale, use or other dealings in this Software without prior
written authorization from The Open Group and/or Sun Microsystems,
Inc., as applicable.


X Window System is a trademark of The Open Group

OSF/1, OSF/Motif and Motif are registered trademarks, and OSF, the OSF
logo, LBX, X Window System, and Xinerama are trademarks of the Open
Group. All other trademarks and registered trademarks mentioned herein
are the property of their respective owners. No right, title or
interest in or to any trademark, service mark, logo or trade name of
Sun Microsystems, Inc. or its licensors is granted.

*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <Xm/Xm.h>
#include <Xm/PushB.h>
#include <X11/cursorfont.h>
#include "xpm.h"
#include "CmnFunction.h"

AuxCommonData	gCommonData;

void SetRectangle(XRectangle* pRect, int nXPos, int nYPos, 
		  int nWidth, int nHeight)
{
	pRect->x = nXPos;
	pRect->y = nYPos;
	pRect->width = nWidth;
	pRect->height = nHeight;
}

void SetPoint(XPoint* pPoint, int nXPos, int nYPos) 
{
	pPoint->x = nXPos;
	pPoint->y = nYPos;
}

Boolean PointInRectangle(XRectangle* pRect, XPoint* pPoint) 
{
	return((pRect->x <= pPoint->x) && (pPoint->x <= (pRect->x + pRect->width)) &&
	       (pRect->y <= pPoint->y) && (pPoint->y <= (pRect->y + pRect->height)));
}

Pixel CreateColorPixel(Display* pDisplay, int nScreenNo,
		       unsigned short nRed, unsigned short nGreen,
		       unsigned short nBlue)
{
  	XColor RetColor;
  	RetColor.red = nRed;
  	RetColor.green = nGreen;
  	RetColor.blue = nBlue;
  	if (XAllocColor(pDisplay, DefaultColormap(pDisplay, nScreenNo), &RetColor))
  		return RetColor.pixel;
  	else
  		return BlackPixel(pDisplay, nScreenNo);
}

void GetScreenPointer(Display* pDisplay, int* pnXPos, int* pnYPos)
{
  	Window RetRootWin, RetChildWin;
  	int nChildXPos, nChildYPos;
  	unsigned int nMask;
  	XQueryPointer(pDisplay, RootWindow(pDisplay, DefaultScreen(pDisplay)),
		      &RetRootWin, &RetChildWin, pnXPos, pnYPos,
		      &nChildXPos, &nChildYPos, &nMask);
}

Boolean GetClientPointer(Widget widget, int* pnXPos, int* pnYPos)
{
  	Window RetRootWin, RetChildWin;
  	int nRootXPos, nRootYPos;
  	unsigned int nMask;
  	return XQueryPointer(XtDisplay(widget), XtWindow(widget),
			     &RetRootWin, &RetChildWin, &nRootXPos, &nRootYPos,
			     pnXPos, pnYPos, &nMask);
}

char* GetTextOfXmString(XmString xmstring)
{
	static char* lpszLabel;
	XmStringGetLtoR(xmstring, XmFONTLIST_DEFAULT_TAG, &lpszLabel);
	return lpszLabel;
}

Pixmap CreateTransparentPixmap(Widget parent, char** ppData, Boolean bArm)
{
	Display* pDisplay = XtDisplay(parent);
	Pixmap pixmap, mask;
	XpmAttributes attributes;
	XpmColorSymbol symbols[1];
	Pixel bgcolor;
	int nStatus;
	
	if (bArm && !XmIsPushButton(parent))
		bArm = FALSE;
	
 	XtVaGetValues(parent, 
 		      XmNdepth, &attributes.depth,
 		      XmNcolormap, &attributes.colormap,
 		      bArm ? XmNarmColor:XmNbackground, &bgcolor, 
 		      NULL);
 		      
 	symbols[0].name = "background";
 	symbols[0].value = NULL;
 	symbols[0].pixel = bgcolor;
 	
 	attributes.colorsymbols = symbols;
 	attributes.numsymbols = 1;
 	attributes.visual = DefaultVisual(pDisplay, DefaultScreen(pDisplay));
 	attributes.valuemask = XpmColorSymbols | XpmDepth | XpmColormap | XpmVisual;
 	
 	nStatus = XpmCreatePixmapFromData(pDisplay, DefaultRootWindow(pDisplay),
 					  ppData, &pixmap, &mask, &attributes);
 	if (mask)
 		XFreePixmap(pDisplay, mask);
 	
 	return (nStatus == XpmSuccess) ? pixmap : 0;				
}

#if 0
#define BUFSIZE (sizeof(long)*8 + 1)
char* ltoa(long lValue, char* lpszString, int nBase)
{
	register int i = 2;
	long lArg;
	char* lpszTail;
	char* lpszHead = lpszString;
	char  szBuffer[BUFSIZE];

	if (36 < nBase || 2 > nBase)
		nBase = 10;
		                   
	lpszTail = &szBuffer[BUFSIZE - 1];           
      	*lpszTail-- = '\0';

	if (10 == nBase && lValue < 0L) {
		*lpszHead++ = '-';
		lArg = -lValue;
      	} else {
		lArg = lValue;
	}

	if (lArg)
	{
		for (i = 1; lArg; ++i) {
			register ldiv_t r;
			r = ldiv(lArg, nBase);
                  	*lpszTail-- = (char)(r.rem + ((9L < r.rem) ? ('A' - 10L) : '0'));
                  	lArg = r.quot;
            	}
      	} else {
		*lpszTail-- = '0';
	}

	memcpy(lpszHead, ++lpszTail, i);
	
	return lpszString;
}
#endif

/**************************************************************************************/
/*            common functions for Auxiliary windows                                  */
/**************************************************************************************/
void DrawButtonFrame(Widget widget, XRectangle* pRect, Boolean bPushed, int nBorderWidth)
{
	Display* pDisplay = XtDisplay(widget);
	int nScreenNo = DefaultScreen(pDisplay);
	GC defGC = DefaultGC(pDisplay, nScreenNo);
	Pixel bottomShadowPixel, topShadowPixel;
	XPoint arrPt[3];
	int nXPosStart = pRect->x;
	int nYPosStart = pRect->y;
	int nXPosEnd   = pRect->x + pRect->width - 1;
	int nYPosEnd   = pRect->y + pRect->height - 1;
	int i;

	XtVaGetValues(widget, XmNbottomShadowColor, &bottomShadowPixel, XmNtopShadowColor, &topShadowPixel, NULL);
	
	XSetForeground(pDisplay, defGC, bPushed ? bottomShadowPixel : topShadowPixel);
	for (i = 0; i < nBorderWidth; i++) {
		arrPt[0].x = nXPosStart + i; arrPt[0].y = nYPosEnd - i;
		arrPt[1].x = nXPosStart + i; arrPt[1].y = nYPosStart + i;
		arrPt[2].x = nXPosEnd;   arrPt[2].y = nYPosStart + i;
		XDrawLines(pDisplay, XtWindow(widget), defGC, arrPt, 3, CoordModeOrigin);
	}

	XSetForeground(pDisplay, defGC, bPushed ? topShadowPixel : bottomShadowPixel);
	for (i = 0; i < nBorderWidth; i++) {
		arrPt[0].x = nXPosEnd - i;   arrPt[0].y = nYPosStart + i;
		arrPt[1].x = nXPosEnd - i;   arrPt[1].y = nYPosEnd - i;
		arrPt[2].x = nXPosStart + i; arrPt[2].y = nYPosEnd - i;
		XDrawLines(pDisplay, XtWindow(widget), defGC, arrPt, 3, CoordModeOrigin);
	}
}

void DrawMovingBoxFrame(XRectangle* pRect)
{
	Display* pDisplay = gCommonData.pDisplay;
	GC	gc = gCommonData.rootGC;
	Window	window = RootWindow(pDisplay, DefaultScreen(pDisplay));

	XSetForeground(pDisplay, gc, gCommonData.darkGrayPixel);
	XSetSubwindowMode(pDisplay, gc, IncludeInferiors);
	XSetFunction(pDisplay, gc, GXxor);
	XDrawRectangle(pDisplay, window, gc, pRect->x, pRect->y, pRect->width-1, pRect->height-1);
}

void SetMovingBoxFrame(XEvent* pEvent, XRectangle* pRect)
{
	int nX_root, nY_root, nX, nY;

	nX_root = pEvent->xbutton.x_root;
	nY_root = pEvent->xbutton.y_root;
	nX = pEvent->xbutton.x;
	nY = pEvent->xbutton.y;

	SetRectangle(&gCommonData.rcMovingFrame,
		nX_root - nX, nY_root - nY,
		pRect->width, pRect->height);

	DrawMovingBoxFrame(&gCommonData.rcMovingFrame);
	SetPoint(&gCommonData.ptStartMovingPoint, nX, nY);
}

void DrawMovingBoxFrameAtPoint(XEvent* pEvent, XRectangle* pRect)
{
	XRectangle rcBox;

	SetRectangle(&rcBox, 
		pEvent->xmotion.x_root-gCommonData.ptStartMovingPoint.x,
		pEvent->xmotion.y_root-gCommonData.ptStartMovingPoint.y,
		pRect->width, pRect->height);

	DrawMovingBoxFrame(&gCommonData.rcMovingFrame);
	DrawMovingBoxFrame(&rcBox);
	gCommonData.rcMovingFrame = rcBox;
}

void MoveWidgetToPoint(Widget widget, XEvent* pEvent, XRectangle* pRect)
{
	Display* pDisplay = XtDisplay(widget);
	int nScreenNo = DefaultScreen(pDisplay);
	XPoint ptButton;
	int nXPos, nYPos, nBoxWidth, nBoxHeight, nDispWidth, nDispHeight;
	int nXStart, nYStart;

	nXPos = gCommonData.rcMovingFrame.x;
	nYPos = gCommonData.rcMovingFrame.y;
	nXStart = gCommonData.ptStartMovingPoint.x;
	nYStart = gCommonData.ptStartMovingPoint.y;
	nBoxWidth = pRect->width;
	nBoxHeight = pRect->height;
	nDispWidth  = XDisplayWidth(pDisplay, nScreenNo);
	nDispHeight = XDisplayHeight(pDisplay, nScreenNo);

	SetPoint(&ptButton, pEvent->xbutton.x, pEvent->xbutton.y);

	DrawMovingBoxFrame(&gCommonData.rcMovingFrame);
	if (ptButton.x != nXStart || ptButton.y != nYStart) {
		if (nXPos + nBoxWidth >= nDispWidth)
			nXPos = nDispWidth - nBoxWidth;
		if (nXPos < 0)
			nXPos = 0;

		if (nYPos + nBoxHeight >= nDispHeight)
			nYPos = nDispHeight - nBoxHeight;
		if (nYPos < 0)
			nYPos = 0;

		XtVaSetValues(widget, XmNx, nXPos, XmNy, nYPos, NULL);
		XFlush(pDisplay);
		
		SetRectangle(&gCommonData.rcMovingFrame, 0, 0, 0, 0);
		SetPoint(&gCommonData.ptStartMovingPoint, 0, 0);
	}
}

void SetMenuPosition(Widget wdtMenu, XButtonEvent* pEvent, XRectangle* pRect, int nXRoot, int nYRoot)
{
	Display* pDisplay = XtDisplay(wdtMenu);
	int nScreenNo = DefaultScreen(pDisplay);
	int nDispWidth  = XDisplayWidth(pDisplay, nScreenNo);
	int nDispHeight = XDisplayHeight(pDisplay, nScreenNo);
	int nWidth, nHeight;
	Dimension dnWidth, dnHeight;
  
	XtVaGetValues(wdtMenu, XmNwidth,  &dnWidth, XmNheight, &dnHeight, NULL);
	nWidth = (int)dnWidth;
	nHeight = (int)dnHeight;	      
		      
	if (nXRoot + pRect->x + nWidth <= nDispWidth) {
      		pEvent->x_root = nXRoot + pRect->x;
    	} else {
      		pEvent->x_root = nDispWidth - nWidth;
    	}
    	if (nYRoot - nHeight < 0) {
      		pEvent->y_root = nYRoot + pRect->height + 4;
    	} else {
      		pEvent->y_root = nYRoot - nHeight;
    	}
/*
    	if (nYRoot + pRect->height + nHeight + 4 <= nDispHeight) {
      		pEvent->y_root = nYRoot + pRect->height + 4;
    	} else {
      		pEvent->y_root = nYRoot - nHeight;
    	}
*/
}

void OpenMenuAtBox(Widget parent, Widget wdtMenu, XButtonEvent* pEvent, XRectangle* pRect)
{
	Display* pDisplay = XtDisplay(parent);
	int nScreenNo = DefaultScreen(pDisplay);
	Window child;
	int nXRoot, nYRoot;
	
	if (wdtMenu) {
  		XTranslateCoordinates(pDisplay, XtWindow(parent), RootWindow(pDisplay, nScreenNo),
			      0, 0, &nXRoot, &nYRoot, &child);

		SetMenuPosition(wdtMenu, pEvent, pRect, nXRoot, nYRoot);
		XmMenuPosition(wdtMenu, (XButtonPressedEvent*)pEvent);
		XtManageChild(wdtMenu);
	}
}

void CommonData_Init(Display* pDisplay)
{
	int nScreenNo = DefaultScreen(pDisplay);
	Window RootWin = RootWindow(pDisplay, nScreenNo);
	char *locale_name;
	int i;

	gCommonData.pDisplay = pDisplay;
	gCommonData.rootGC = XCreateGC(pDisplay, RootWin, 0, NULL);
	gCommonData.darkGrayPixel = CreateColorPixel(pDisplay, nScreenNo, 0x79e7, 0x79e7, 0x79e7);

	for (i = 0; i < CURSOR_NUM; i++) 
		gCommonData.arrCursor[i] = None;

	gCommonData.arrCursor[CURSOR_NONE] = None;
	gCommonData.arrCursor[CURSOR_MOVE] = XCreateFontCursor(pDisplay, XC_fleur);

	gCommonData.locale_id = 0;
	gCommonData.locale_name = NULL;
	locale_name = setlocale(LC_CTYPE, NULL);
	if (locale_name != NULL) {
		gCommonData.locale_name = strdup(locale_name);
		gCommonData.locale_id = get_encodeid_from_locale(locale_name);
	}
}

void CommonData_Free()
{
	Display* pDisplay = gCommonData.pDisplay;
	int i;

	XFreeGC(pDisplay, gCommonData.rootGC);
	
	for (i = 0; i < CURSOR_NUM; i++) {
		if (None != gCommonData.arrCursor[i])
			XFreeCursor(pDisplay, gCommonData.arrCursor[i]);
	}

	if (gCommonData.locale_name != NULL)
		free(gCommonData.locale_name);
}

void SetCursorShape(Display *pDisplay, Window window, int nCursorID)
{
	if (nCursorID < 0 || nCursorID >= CURSOR_NUM)
		nCursorID = CURSOR_NONE;

	XDefineCursor(pDisplay, window, gCommonData.arrCursor[nCursorID]);
}

