/***********************************************************
Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts,
and the Massachusetts Institute of Technology, Cambridge, Massachusetts.

                        All Rights Reserved

Permission to use, copy, modify, and distribute this software and its 
documentation for any purpose and without fee is hereby granted, 
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in 
supporting documentation, and that the names of Digital or MIT not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.  

DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.

******************************************************************/
/* $XConsortium: scrinit.c,v 1.57 88/10/02 15:08:27 rws Exp $ */

#include "X.h"
#include "Xproto.h"	/* for xColorItem */
#include "Xmd.h"
#include "scrnintstr.h"
#include "pixmapstr.h"
#include "resource.h"
#include "colormap.h"
#include "cursor.h"
#include "../common/ibmmouse.h"
#include "../../mi/mistruct.h"
#include "dix.h"
#include <dos.h>
#include <string.h>
#include "validate.h"
#include "svga.h"

#include "servermd.h"
#include "funcs.h"
#include "svgafuncs.h"
#include "mxfuncs.h"

extern int monitorResolution;

static VisualRec visual = {
/* vid  class       bpRGB cmpE nplan rMask gMask bMask oRed oGreen oBlue */
   0,   PseudoColor, 6,   256,   8,    0,    0,    0,    0,   0,     0
};

static VisualID VID;

static DepthRec depth = {
/* depth	numVid		vids */
    8,		1,		&VID,
#ifdef notdef
    1,		0,		0
#endif
};

#ifdef BACKING_STORE
miBSFuncRec svgaBSfuncs = {
	mxSaveAreas,
	mxRestoreAreas,
	mxSetClipmaskRgn,
	mxGetImagePixmap,
	mxGetSpansPixmap,
};
#endif

#ifdef ERGO
const __segment	svga_base;
#endif
int	svga_width;	/* width of screen in bytes */
u_char	svga_curpage;
u_char	svga_page_shift;	/* for VESA support */

int svgaGeneration = 0;
int svgaGCPrivateIndex;
/* int svgaWinPrivateIndex; */

struct resolution {
	int width, height;
};

static struct resolution vga_res[] = {
    { 0,	0},
    { 640,	480},
    { 800,	600},
    { 1024,	768},
    { 1280,	1024}
};

static int svgaIsOpen = 0;

Bool
mxinit(iScreen, pScreen, argc, argv)
int iScreen;
ScreenPtr pScreen;
int argc;
char **argv;
{
    ColormapPtr pColormap;
    int		mode = 1;
    int		i;
    CARD16	zero = 0, ones = ~0;

    iScreen = iScreen;
    while (argc > 0) {
	if (strcmp(*argv, "-mode") == 0) {
		argv++; argc--;
		if (!argc) {
			printf("bad -mode argument\n");
			break;
		}
		mode = atoi(*argv);
	}
	argv++; argc--;
    }

    if (svgaGeneration != serverGeneration)
    {
	svgaGCPrivateIndex = AllocateGCPrivateIndex();
/*	svgaScrPrivateIndex = AllocateScreenPrivateIndex(); */
/*	svgaWinPrivateIndex = AllocateWindowPrivateIndex(); */
	visual.vid = FakeClientID(0);
	VID = visual.vid;
	svgaGeneration = serverGeneration;
    }
    if (!AllocateGCPrivate(pScreen, svgaGCPrivateIndex, sizeof(svgaPrivGC)))
	return FALSE;

/*
    if (!AllocateWindowPrivate(pScreen, svgaWinPrivateIndex, 0))
	return FALSE;
*/

    if (VGAOpen(mode)) {
	return FALSE;
    }
    svgaIsOpen++;
    svga_curpage = 0;
    SetPage();

#ifdef ERGO
    if (svga_base == 0) {
	/* Get a 64k window to screen memory */
	*(__segment *)&svga_base = get_real_window(0xa0000, 0x10000);
	if (*(__segment *)&svga_base == 0) {
	    printf("Can't get window, error %d\n", errno);
	    (void)mxClose(0, 0);
	    return FALSE;
	}
    }
#endif

    if (!svga_width)
	svga_width = vga_res[mode].width;
    if (!scr_width)
	scr_width = vga_res[mode].width;
    pScreen->width = scr_width;
    if (!scr_height)
	scr_height = vga_res[mode].height;
    pScreen->height = scr_height;
/*
printf("svga: mode=%d, columns=%d, height=%d\n", regs.h.al, regs.h.ah, pScreen->height);
*/

    if (monitorResolution) {
	pScreen->mmWidth = pScreen->width * 25 / monitorResolution;
	pScreen->mmHeight = pScreen->height * 25 / monitorResolution;
    } else {
	pScreen->mmWidth = 250;
	pScreen->mmHeight = 180;
    }

    pScreen->numDepths = 1;
    pScreen->allowedDepths = &depth;

    pScreen->rootDepth = 8;
    pScreen->rootVisual = VID;
#ifdef BACKING_STORE
    pScreen->backingStoreSupport = WhenMapped;
#else
    pScreen->backingStoreSupport = NotUseful;
#endif
    pScreen->saveUnderSupport = NotUseful;

    pScreen->numVisuals = 1;
    pScreen->visuals = &visual;

    pScreen->CreateWindow = mxCreateWindow;
    pScreen->DestroyWindow = mxDestroyWindow;
    pScreen->PositionWindow = mxPositionWindow;
    pScreen->RealizeWindow = mxMapWindow;
    pScreen->UnrealizeWindow = mxUnmapWindow;
    pScreen->ChangeWindowAttributes = mxChangeWindowAttributes;
    pScreen->ValidateTree = miValidateTree;
    pScreen->WindowExposures = miWindowExposures;

    pScreen->ClearToBackground = miClearToBackground;
    pScreen->PaintWindowBackground = mxPaintWindow;
    pScreen->PaintWindowBorder = mxPaintWindow;
    pScreen->CopyWindow = mxCopyWindow;

    pScreen->RealizeFont = mxRealizeFont;
    pScreen->UnrealizeFont = mxUnrealizeFont;
    pScreen->GetImage = mxGetImage;
    pScreen->GetSpans = mxGetSpans;
    pScreen->CreatePixmap = mxCreatePixmap;
    pScreen->DestroyPixmap = mxDestroyPixmap;

    pScreen->CreateColormap = mxCreateColormap;
    pScreen->DestroyColormap = mxDestroyColormap;
    pScreen->InstallColormap = mxInstallColormap;
    pScreen->UninstallColormap = mxUninstallColormap;
    pScreen->ListInstalledColormaps = mxListInstalledColormaps;
    pScreen->StoreColors = mxStoreColors;
    pScreen->ResolveColor = mxResolveColor;

    pScreen->CreateGC = mxCreateGC;

    pScreen->RegionCreate = miRegionCreate;
    pScreen->RegionInit = miRegionInit;
    pScreen->RegionCopy = miRegionCopy;
    pScreen->RegionDestroy = miRegionDestroy;
    pScreen->RegionUninit = miRegionUninit;
    pScreen->Intersect = miIntersect;
    pScreen->Inverse = miInverse;
    pScreen->Union = miUnion;
    pScreen->Subtract = miSubtract;
    pScreen->RegionReset = miRegionReset;
    pScreen->TranslateRegion = miTranslateRegion;
    pScreen->RectIn = miRectIn;
    pScreen->PointInRegion = miPointInRegion;
    pScreen->RegionNotEmpty = miRegionNotEmpty;
    pScreen->RegionEmpty = miRegionEmpty;
    pScreen->RegionExtents = miRegionExtents;
    pScreen->RegionAppend = miRegionAppend;
    pScreen->RegionValidate = miRegionValidate;
#ifdef SHAPE
    pScreen->BitmapToRegion = mfbPixmapToRegion;
    pScreen->RectsToRegion = miRectsToRegion;
#endif
    pScreen->SendGraphicsExpose = miSendGraphicsExpose;

    pScreen->CloseScreen = mxClose;
    pScreen->SaveScreen = mxSaveScreen;

    /*
     * Cursor functions
     */
    pScreen->PointerNonInterestBox = mousePointerNonInterestBox;
    pScreen->RealizeCursor = mouseRealizeCursor;
    pScreen->UnrealizeCursor = mouseUnrealizeCursor;
    pScreen->DisplayCursor = mouseDisplayCursor;
    pScreen->SetCursorPosition = mouseSetCursorPosition;
    pScreen->CursorLimits = mouseCursorLimits;
    pScreen->ConstrainCursor = mouseConstrainCursor;
    pScreen->RecolorCursor = mxRecolorCursor;

    pScreen->QueryBestSize = mxQueryBestSize;

#ifdef BACKING_STORE
    miInitializeBackingStore (pScreen, &svgaBSfuncs);
#endif

    /* os layer stuff */
#ifdef notused
    pScreen->BlockHandler = mxBlockHandler;
    pScreen->WakeupHandler = mxWakeupHandler;
    pScreen->wakeupData = (pointer)0;
    pScreen->blockData = (pointer)0;
#endif

    pScreen->defColormap = (Colormap) FakeClientID(0);
    pScreen->minInstalledCmaps = 1;
    pScreen->maxInstalledCmaps = 1;
    pScreen->whitePixel = 0xff;
    pScreen->blackPixel = 0;
    if ((i = CreateColormap(pScreen->defColormap, pScreen, &visual,
	&pColormap, AllocNone, 0)) != Success || pColormap == NULL) {
		ErrorF("svgainit: CreateColormap returned %d\n", i);
		return FALSE;
    }
    if (AllocColor(pColormap, &zero, &zero, &zero, (&pScreen->blackPixel), 0) ||
	AllocColor(pColormap, &ones, &ones, &ones, (&pScreen->whitePixel), 0))
		FatalError("svgaInit: Can't alloc black & white pixels\n");
    mxInstallColormap(pColormap);

    /* Initialize the mouse to black on white */
    svgaCursor.fore_color = pScreen->blackPixel;
    svgaCursor.back_color = pScreen->whitePixel;
    svgaCursor.depth = depth.depth;

    return TRUE;
}

/* Should this be a 8-bit array? */
int endtab[16] = 
	{
	0x0000,
	0x8000,
	0xC000,
	0xE000,
	0xF000,
	0xF800,
	0xFC00,
	0xFE00,
	0xFF00,
	0xFF80,
	0xFFC0,
	0xFFE0,
	0xFFF0,
	0xFFF8,
	0xFFFC,
	0xFFFE
	};

u_char masktab[8] = {
	0x80,
	0x40,
	0x20,
	0x10,
	0x08,
	0x04,
	0x02,
	0x01
};

void
screen_abort()
{
	if (svgaIsOpen)
		mxClose(0, (ScreenPtr)0);
}

Bool
mxClose(index, pScreen)
int index;
ScreenPtr pScreen;
{
    index = index;
    if (svgaIsOpen) {
	VGAClose();
	svgaIsOpen = 0;
    }
    if (pScreen == 0)
	return FALSE;
    pScreen->devPrivate = 0;
    return TRUE;
}

mxSaveScreen(pScr, on)
ScreenPtr pScr;
int on;
{
	union REGS regs;

	pScr = pScr;
	regs.h.bl = 0x36;
	if (on == SCREEN_SAVER_OFF)
		regs.w.ax = 0x1200;
	else
		regs.w.ax = 0x1201;
	int386(0x10, &regs, &regs);

#ifdef notdef
	outp(0x3c4, 1);
	if (on == SCREEN_SAVER_OFF)
		outp(0x3c5, inp(0x3c5) & ~0x20);
	else
		outp(0x3c5, inp(0x3c5) | 0x20);
#endif
	return TRUE;
}

void
mxQueryBestSize(kind, pWidth, pHeight)
int kind;
unsigned short *pWidth, *pHeight;
{
	unsigned width, test;

	pHeight = pHeight;
	switch (kind) {
	    case CursorShape:
#ifdef DIRECT_CURSOR
		*pWidth = 16;
		*pHeight = 16;
#endif
		break;
	    case TileShape:
	    case StippleShape:
		width = *pWidth;
		if (width > 0) {
			/* Find the smallest power of two greater than
			 * width. */
			test = 1;
			while (test < width)
				test <<= 1;
			*pWidth = test;
		}
		break;
	}
}
