/* vi: set sw=4 ts=4: */
/*
 * CCE - Console Chinese Environment -
 * Copyright (C) 1998-2003 Rui He (rhe@3eti.com)
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE TERRENCE R. LAMBERT BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */

/* This software is subject to the terms of the Common Public License
   You must accept the terms of this license to use this software.

   Copyright (C) 2002, International Business Machines Corporation
   and others.  All Rights Reserved.

   Further information about Common Public License Version 0.5 is obtained
   from url http://oss.software.ibm.com/developer/opensource/license-cpl.html 
*/
#include "config.h"

#ifdef SUPPORT_X11FONT

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#include "fontxlfd.h"
#include "fontmisc.h"
#include "fontstruct.h"
#include "fntfil.h"
#include "bitmap.h"
#include "pcf.h"
#include "bdfint.h"

#include "defs.h"
#include "font.h"

#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif

extern FontRegs *dbFReg, *sbFReg, fSRegs[], fDRegs[];

typedef int (readfontfunc) __P ((FontPtr, FontFilePtr, int, int, int, int));

static char *GetX11FontEncoding(FontRec * fr)
{
	int i, encoding = -1;
	char *ename = NULL, *font = NULL, *dup, *p;

	for (i = 0; i < fr->info.nprops; i++)
    {
    	if (!strcmp (NameForAtom (fr->info.props[i].name), "CHARSET_REGISTRY"))
    		ename = NameForAtom (fr->info.props[i].value);
      	else
    	if (!strcmp (NameForAtom (fr->info.props[i].name), "CHARSET_ENCODING"))
    		encoding = atoi (NameForAtom (fr->info.props[i].value));
      	else if (!strcmp (NameForAtom (fr->info.props[i].name), "FONT"))
    		font = NameForAtom (fr->info.props[i].value);
	}

  	if (ename == NULL && font != NULL)
    {
    	dup = strdup (font);
      	p = strtok (dup, "-");

      	for (i = 0; i < 11; i++)
    	{

      		p = strtok (NULL, "-");
      		if (p == NULL)
        		return NULL;
    	}

      	ename = p;
      	free (dup);
      	if (encoding == -1)
    		encoding = atoi (strtok (NULL, "-"));
	}
  
	return (ename);
}

int LoadX11Font(char *pathName)
{
	FontRec *font = NULL;
	FontFilePtr input = NULL;
	readfontfunc *readfont = NULL;

	FontInfo fi;
	char *registry;
	FontRegs *FReg;
	int n, encoding, width, height, fw;

	if (!pathName || pathName[0] == '\0') return -1;

  	font = (FontRec *) malloc (sizeof (FontRec));
  	if (font == NULL) return -1;
  	memset (font, 0x0, sizeof (FontRec));

   	input = FontFileOpen (pathName);  /* We don't add CCELIB for X11 font ! */
   	if (input == NULL) return -1;

   	readfont = strstr (pathName, ".bdf") || strstr (pathName, ".BDF") ? 
		bdfReadFont : pcfReadFont;

  	if (!readfont) return -1;

   	if ((readfont) (font, input, MSBFirst, MSBFirst, 1, 1/*4, 4*/) != Successful ||
	    (registry = GetX11FontEncoding(font)) == NULL ||
		(encoding = CodingByRegistry(registry)) < 0)
   	{
   		warn("Failed to load font %s\n", pathName);
   		FontFileClose (input);
   		return -1;
   	}

  	width = font->info.maxbounds.characterWidth;
  	height = font->info.maxbounds.ascent + font->info.maxbounds.descent;

#ifdef DEBUG
  	fprintf (stderr, "Font %s: ascent=%d descent=%d Width=%d Height=%d Registry=%s\n"
			 " bit=%d byte=%d glyph=%d scan=%d\n",
        basename(pathName), font->info.maxbounds.ascent,
  		font->info.maxbounds.descent, width, height, registry,
		font->bit, font->byte, font->glyph, font->scan);
#endif

  	if (width > 32 || height > 32 || width < 4 || height < 4)
    {
    	warn("Invalid font size %dx%d: %s\n", width, height, pathName);
      	FontFileClose (input);
      	return -1;
    }

    if (encoding & CHR_DBC)  /* double-byte fonts */
    {
        n = encoding & ~CHR_DFLD;
        FReg = &(fDRegs[n]);    
    }
    else  /* single byte font */
    {
        n = encoding & ~CHR_SFLD;
		FReg = &(fSRegs[n]);
	}

	if (fontwidth == 0)
	{
		fontwidth = width / (encoding & CHR_DBC ? 2: 1);
        fontheight = height;
        fontbytes = FONTBYTES(fontwidth, fontheight);  /* 8x16 -> 16, 12x24, 48 bytes */
        fontbytes2 = FONTBYTES(2*fontwidth, fontheight);
    }
    else if (width != (encoding & CHR_DBC ? 2: 1)*fontwidth || height != fontheight)
	{
        warn("Double-byte font should have same height and twice width as single-byte font.\r\n");
        return -1;
    }

	FReg->height = height;
    FReg->width = width;
    FReg->size = 0; /*  not used  */
    FReg->bitmap = (char *)font; /* FontRec* pointer */
    FReg->fi = MAP_FAILED; /* not mapped yet */
    FReg->fd = 1024;  /* fake one, make it non -1 don't close!! FIXME! */
	FReg->stat = FR_X11FONT;  /* flag for X11font, don't mmap it */
    
	return 0;
}

u_char *GetX11FontBits(void *frec, int codepoint)
{
	int firstCol, lastCol, firstRow, lastRow;
	int col, row, numCols; 
	int can_num, n; 

	BitmapFontPtr bp = (BitmapFontPtr) (((FontRec *)frec)->fontPrivate);
	CharInfoPtr cp = (CharInfoPtr) (bp->metrics);
	CharInfoPtr dp = (CharInfoPtr) (bp->pDefault);
	CharInfoPtr **ep = (CharInfoPtr **) (bp->encoding);

	firstCol = ((FontRec *)frec)->info.firstCol;
	lastCol = ((FontRec *)frec)->info.lastCol;
	firstRow = ((FontRec *)frec)->info.firstRow;
	lastRow = ((FontRec *)frec)->info.lastRow;
	numCols = lastCol - firstCol + 1;

	row = ((codepoint >> 8) & 0xFF);
	col = codepoint & 0xFF;
	
	if (row > lastRow) row &= 0x7F;
	if (col > lastCol) col &= 0x7F;
	
	if (row >= firstRow && row <= lastRow && col >= firstCol && col <= lastCol)
    {
		can_num = (row - firstRow) * numCols + (col - firstCol);

   		n = ACCESSENCODING (ep, can_num) - cp;
   		if (n > 0) return cp[n].bits;
	}

	return dp->bits; /* default font char */
}

#endif
