/*
Copyright 1990-2001 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 "gbk_unicode.h"        /* GBK to Unicode mapping table */
#include "Converter.h"

#define False 0
#define True 1
/*
#define DEBUG
*/

typedef unsigned char *MString;
typedef unsigned char *XPointer;

static int isgb(unsigned char s1, unsigned s2)
{
    /* consider the first byte */
    if(s1 >= 0xA0 && s1 <= 0xf7 ){
      if(s2 < 0xA1 ||  s2 > 0xfe)
        return False;
      else
        return True;
    }else{
        return False;
    }
}

static int isgbk(unsigned char s1, unsigned s2)
{
    /* consider the first byte */
    if(s1 >= 0x81 && s1 <= 0xfe ){
      if(s2 < 0x40 || s2 == 0x7f || s2 > 0xfe)
        return False;
      else
        return True;
    }else{
        return False;
    }
}

zh_CN_euctoUTF_16(MString *from, int *from_len, MString *to, int *to_len)
{
    XPointer from_str=*from,  to_str=*to;
    int from_left, to_left, ret;
    int i,j;
    int n= *from_len;
    int count=0;
    int hanzi_num = 0;
    unsigned long   gb_val;        /* GB2312 value */
    int             unidx;          /* Unicode index */
    unsigned long   uni_val;        /* Unicode */

    from_left= *from_len;
    to_left = *to_len;

#ifdef DEBUG
    printf("Calling the  zh_CN_euctoUTF_16_built_in, from_len = %d,to_len=%d\n",*from_len,*to_len);
#endif

    j = 0;
    for(i = 0; i < *from_len; i ++) {
        if ((unsigned char)from_str[i] <= 0x7f) {
            to_str[j++] = from_str[i] >> 8;
            to_str[j++] = from_str[i] & 0xff;
            count = count +2;
        }
        else if (isgb((unsigned char)from_str[i],(unsigned char)from_str[i+1])) {
	    gb_val = ( ( (unsigned char)from_str[i] & 0xff ) << 8 ) 
		+ ( (unsigned char)from_str[i+1] & 0xff);
	    unidx = search_unicode(gb_val, gbk_unicode_tab, GBKMAX);
	    if (unidx >= 0) uni_val = gbk_unicode_tab[unidx].unicode;
	    else uni_val = -1;
            to_str[j++] = uni_val >> 8;
            to_str[j++] = uni_val & 0xff;
            i++;
            count = count +2;
	    hanzi_num ++;
        }
    }
    *to_len = to_left - count;

#ifdef DEBUG
    printf("MBSTOWCSfrom=%s,from_left=%d,wstr=%x,to_lef=%d\n",from_str,from_left,to_str[0],to_left);
    for(i=0;i<*from_len;i++) printf(" %x ", from_str[i]);
    printf("\n");
    for(i=0;i<j;i++) printf(" %0x",to_str[i]);
    printf("\n");
#endif

    return hanzi_num;
}

zh_CN_gbktoUTF_16(MString *from, int *from_len, MString *to, int *to_len)
{
    XPointer from_str=*from,  to_str=*to;
    int from_left, to_left, ret;
    int i,j;
    int n= *from_len;
    int count=0;
    int hanzi_num = 0;
    unsigned long   gbk_val;        /* GBK value */
    int             unidx;          /* Unicode index */
    unsigned long   uni_val;        /* Unicode */

    from_left= *from_len;
    to_left = *to_len;

#ifdef DEBUG
    printf("Calling the  zh_CN_gbktoUTF_16_built_in, from_len = %d,to_len=%d\n",*from_len,*to_len);
#endif

    j = 0;
    for(i = 0; i < *from_len; i ++) {
        if ((unsigned char)from_str[i] <= 0x7f) {
            to_str[j++] = from_str[i] >> 8;
            to_str[j++] = from_str[i] & 0xff;
	    count = count +2;
        }
        else if (isgbk((unsigned char)from_str[i],(unsigned char)from_str[i+1])) {
	    gbk_val = ( ( (unsigned char)from_str[i] & 0xff ) << 8 ) 
		+ ( (unsigned char)from_str[i+1] & 0xff);
	    unidx = search_unicode(gbk_val, gbk_unicode_tab, GBKMAX);
	    if (unidx >= 0) uni_val = gbk_unicode_tab[unidx].unicode;
	    else uni_val = -1;
            to_str[j++] = uni_val >> 8;
            to_str[j++] = uni_val & 0xff;
            i++;
            count = count +2;
	    hanzi_num ++;
        }
    }
    *to_len = to_left - count;

#ifdef DEBUG
    printf("MBSTOWCSfrom=%s,from_left=%d,wstr=%x,to_lef=%d\n",from_str,from_left,to_str[0],to_left);
    for(i=0;i<j;i++) printf(" %0x",to_str[i]);
    printf("\n");
#endif

    return hanzi_num;
}

void zh_str_to_utf16 (unsigned char* src, unsigned short* dst, int * caret) {

    unsigned char from_str[1024];
    unsigned char to_str[1024];
    unsigned char *from =from_str;
    unsigned char *to=to_str;
    int from_len,to_len =1024;
    unsigned short high, low;
    int i, j;
    int hanzi_num;

    from = from_str, to=to_str;
    strcpy(from, src);
    from_len = strlen(from);
    to_len = 1024;
    hanzi_num = zh_CN_gbktoUTF_16(&from, &from_len, &to, &to_len);
    *caret -= hanzi_num;

    if(to_len == 1024) dst[0] = 0; 
    else {
        for(i = 0, j = 0; i < 1024 - to_len;) {
            high = (unsigned short)to_str[i];
            low  = (unsigned short)to_str[i+1];
            dst[j] = high * 256 + low;
            j ++; i += 2;
        }
        dst[j] = 0;
    }
}

static KeySym getX11KeySym(long awtKey)
{
    int i;
    for (i = 0; keymapTable[i].awtKey != 0; i++) {
        if (keymapTable[i].awtKey == awtKey) {
            return keymapTable[i].x11Key;
        }
    }
    return 0;
}

modifyEvent(long *keyCode, unsigned short *keyChar, long *State)
{
    KeySym keysym = 0;
    long state = 0;

    switch(*keyCode) {
      case java_awt_event_KeyEvent_VK_ENTER:
      case java_awt_event_KeyEvent_VK_BACK_SPACE:
      case java_awt_event_KeyEvent_VK_TAB:
      case java_awt_event_KeyEvent_VK_ESCAPE:
      case java_awt_event_KeyEvent_VK_DELETE:
          keysym = getX11KeySym(*keyCode);
          break;
      default:
          if (*keyChar != 0 && *keyChar < 256) {
              keysym = *keyChar;
          } else {
              keysym = getX11KeySym(*keyCode);
          }
          break;
    }
    if (keysym >= 'A' && keysym <= 'Z') {
        state |= ShiftMask;
    }
    if (*State & java_awt_event_InputEvent_SHIFT_MASK) {
        state |= ShiftMask;
    }
    if (*State & java_awt_event_InputEvent_CTRL_MASK) {
        state |= ControlMask;
    }
    if (*State & java_awt_event_InputEvent_META_MASK) {
        state |= awt_MetaMask;
    }
    if (*State & java_awt_event_InputEvent_ALT_MASK) {
        state |= awt_AltMask;
    }

    *keyCode = keysym;
    if((*keyChar < 0x20) || (*keyChar > 0x7E))
	*keyChar = 0xFF;
    if(state != 0) *State = state;

#ifdef DEBUG
    printf("After convert code: %x, char %x, state %x\n", *keyCode, *keyChar, *State);
#endif
}

int search_unicode(unsigned long x, gbk_unicode v[], int n)
{
    int low, high, mid;

    low = 0;
    high = n - 1;
    while (low <= high) {
        mid = (low + high) / 2;
        if (x < v[mid].gbkcode) high = mid - 1;
        else if (x > v[mid].gbkcode) low = mid + 1;
        else return mid; /* found match */ 
    }
    return (-1);    /* no match */
}

