/*
** Nostalgia OS Watcom C keyboard handling
** (C) 1996-1997, Jason A. Leigh
**
** Most code is taken from Pascal sources I developed in June 1996.
**
** Room for improvement:
** - KBD_CapsAffected checks for hardcoded range of scancodes. This only works for
**   english keyboard mapping. Should be adjustable (e.g. a per scancode affected map).
** - Most foreign keyboard have a AltGr-key to allow for an extra (or two extra, in
**   combination with Shift) key-combination. We only allow one extra key-combination,
**   Shift + key. This should be extended to include AltGr + key.
*/

// most work 21/22/23-08-97

#include "nos_keyb.h"                               // key definitions
#include "nos_keyb.ph"
#include "nos_keys.h"                               // keyboard definitions
/*
#include "nos_int.h"                                // interrupt defines
*/

uint8_t ReadIoByte(uint16_t Port);
void WriteIoByte(uint16_t Port, uint8_t Value);

#define TRUE	1
#define FALSE	0

// some variables

static uint16_t wKeybFlags;                             // keyboard flags
static KBD_KEYMAP *pas_KeyMap = as_KeyMapUS;        // current keyboard map
static KBD_KEYINBUF as_KeyBuf[KBD_BUFSIZE];         // circular keyboard buffer
static int iKeyBufNextRead = 0;                     // index of next key to read
static volatile int iKeyBufNextStore = 0;           // index of next key to store
static volatile int afKeyPressed[256];             // array of keys pressed yes/no 1)
//static int fInstalled = FALSE;                     // handle installed or not

/*
** 1) the first 128 positions map to key scan codes, the second 128 to keys that are
**    extended (prepended by scancode 224)
*/


/***( help functions )********************************************************/


// These functions are not static, since they are also used in nos_mous for
// PS/2 mouse support.

/*
** 26-08-97 - waits for input from keyboard input port, returns FALSE if
** timeout, TRUE otherwise, returns uint8_t read in *pbVal.
** 28-08-97 - _waitval, extra parameter
*/
int _waitval (uint8_t *pbVal, int iMask)
{       
    int i;


    //for (i = 0; i < 100000; i++)
    for (i = 0; i < 1000000; i++)
    {
        if ((ReadIoByte (0x64) & iMask) == iMask)
        {
            i = ReadIoByte (0x60);             // 28-08-97, always read port
            if (pbVal) *pbVal = i;
            return TRUE;
        }
    }

    return FALSE;
}


// 28-08-97
int waitval (uint8_t *pbVal)
{
    return _waitval (pbVal, 1);
}


/*
** 27-08-97 - waits for output bit to clear so we can send the next command
*/
int waitsend (void)
{
    int i;


    for (i = 0; i < 100; i++)       // smaller time-out, shouldn't take too long
    {
        if (!(ReadIoByte(0x64) & 2))
        {
            return TRUE;
        }
    }

    return FALSE;
}


int deactsecunit (void)
{
    int i;

    uint8_t bVal;


    WriteIoByte (0x64, 0xd4);
    waitsend ();

    WriteIoByte (0x60, 0xf5);
    for (i = 0; i < 100; i++)
    {
        waitval (&bVal);
        if (bVal == 0xfa) break;
    }

    return bVal == 0xfa;
}


/***( lowlevel hardware functions )*******************************************/


/*
** toggles keyboard lights
*/
static void KBD_ToggleKeybLock (int iMask)
{
    uint16_t bMask;


    // toggle flag (first mask out, then toggle)

    wKeybFlags = (wKeybFlags & ~(uint16_t)iMask) | (wKeybFlags ^ (uint16_t)iMask);

    // sync lights

    bMask = 0;
    if (wKeybFlags & KF_CAPSL) bMask |= 4;
    if (wKeybFlags & KF_NUML) bMask |= 2;
    if (wKeybFlags & KF_SCROLLL) bMask |= 1;

    WriteIoByte (0x60, 0xed);
    waitval (NULL);
    WriteIoByte (0x60, bMask);
    waitval (NULL);
}


/*
** sets keyboard flags (global wKeybFlags)
*/
static void KBD_SetKeybFlags (int iMask, int fSet)
{
    if (fSet)
    {
        wKeybFlags |= (uint16_t)iMask;
    }
    else
        wKeybFlags &= ~(uint16_t)iMask;
}


/*
** sets keyboard flags, looks at status of extended key (global wKeybFlags)
*/
static void KBD_SetKeybFlagsExt (int iMask1, int iMask2, int fSet)
{
    if (wKeybFlags & KF_EXTENDED)
    {
        KBD_SetKeybFlags (iMask2, fSet);
    }
    else
        KBD_SetKeybFlags (iMask1, fSet);
}


/*
** put key in buffer
*/
static void KBD_PutKeyInBuf (int iScanCode, uint32_t KeyCode, uint16_t wKeybFlags)
{
    int iIdx;
    KBD_KEYINBUF *p;


    iIdx = (iKeyBufNextStore + 1) % KBD_BUFSIZE;    // calculate next position
    if (iIdx == iKeyBufNextRead) return;            // full!

    p = &as_KeyBuf[iKeyBufNextStore];

    p->bScanCode = (uint8_t)iScanCode;
    //p->cKeyCode = (char)iKeyCode;
    p->cKeyCode = KeyCode;
    p->wKeybFlags = wKeybFlags;

    iKeyBufNextStore = iIdx;
}


/*
** some key tricks (I'll explain some day...)
*/
static int KBD_CapsAffected (int iScanCode)
{
    return
        (iScanCode >= 16 && iScanCode <= 25) ||       // q..p
        (iScanCode >= 30 && iScanCode <= 38) ||       // a..l
        (iScanCode >= 44 && iScanCode <= 50);         // z..m
}

static int KBD_NumAffected (int iScanCode)
{
    // 23-08-97: include del/.
    return
        (iScanCode >= 71 && iScanCode <= 73) ||       // num 7..9
        (iScanCode >= 75 && iScanCode <= 77) ||       // num 4..6
        (iScanCode >= 79 && iScanCode <= 83);         // num 1..3, 0, .
}

static int KBD_NotAffected (int iScanCode)
{
    return !KBD_CapsAffected(iScanCode) && !KBD_NumAffected(iScanCode);
}

/*
** some more tricks...
*/
static int KBD_ShiftStatus (uint16_t wMask)
{
    return (int)(wMask & (KF_LSHIFT | KF_RSHIFT));
}

static int KBD_CapsStatus (uint16_t wMask)
{
    int fA = KBD_ShiftStatus(wMask);
    int fB = (wMask & KF_CAPSL) > 0;

    return (fA && !fB) || (fB && !fA);      // unfortunately there's no logical xor in C...
}

static int KBD_NumStatus (uint16_t wMask)
{
    int fA = KBD_ShiftStatus(wMask);
    int fB = (wMask & KF_NUML) > 0;

    return (fA && !fB) || (fB && !fA);      // unfortunately there's no logical xor in C...
}


/*
** finds key in specified table
*/
static int KBD_FindKeyInDef (int iScanCode, KBD_KEYMAP *pas_KeyMap)
{
    int iKey = 0;
    int n;


    for (n = 0; pas_KeyMap[n].bScanCode; n++)
    {
        if (pas_KeyMap[n].bScanCode == iScanCode)
        {
            if ((KBD_CapsAffected(iScanCode) && KBD_CapsStatus(wKeybFlags)) ||
                (KBD_NumAffected(iScanCode) && KBD_NumStatus(wKeybFlags)) ||
                (KBD_NotAffected(iScanCode) && KBD_ShiftStatus(wKeybFlags)))
            {
                iKey = pas_KeyMap[n].cShiftCode;
            }
            else
                iKey = pas_KeyMap[n].cKeyCode;
        }
    }

    return iKey;
}

static int KBD_FindVirtKey(int ScanCode, KBD_VIRTMAP* paVirtMap)
{
	int i;

	for (i = 0; paVirtMap[i].bScanCode != 0; i++)
	{
		if (paVirtMap[i].bScanCode == ScanCode)
		{
			return paVirtMap[i].iVirtKey;
		}
	}

	return 0;
}

/*
** returns mapped key
*/
static int KBD_MapKey (int iScanCode)
{
    int iKey;


    iKey = KBD_FindKeyInDef(iScanCode, pas_KeyMap);
    if (!iKey) iKey = KBD_FindKeyInDef(iScanCode, as_KeyMapStd);
	if (!iKey) iKey = KBD_FindVirtKey(iScanCode, VirtKeyMap);

    return iKey;
}


/*
** reverse of KBD_FindKeyInDef, finds scancode in specified table
*/
static int KBD_FindScanInDef (int iKey, KBD_KEYMAP *pas_KeyMap)
{
    int iScanCode = 0;
    int n;       

    for (n = 0; pas_KeyMap[n].bScanCode; n++)
    {
        if (pas_KeyMap[n].cKeyCode == iKey || pas_KeyMap[n].cShiftCode == iKey)
        {
            iScanCode = pas_KeyMap[n].bScanCode;
        }
    }

    return iScanCode;
}


/*
** reverse of KBD_MapKey, gets key from scancode
*/
static int KBD_GetMappedKey (int iKey)
{
    int iScanCode;


    iScanCode = KBD_FindScanInDef(iKey, pas_KeyMap);
    if (!iScanCode) iScanCode = KBD_FindScanInDef(iKey, as_KeyMapStd);

    return iScanCode;
}


/*
** actual handling of the key
*/
/*static*/
void KBD_HandleKey (int iScanCode)
{
    int fPressed;


    if (iScanCode >= KBD_ACK) return;       // 27-08-97, ignore ACKs etc.

    if (iScanCode == EXT_KEY1 || iScanCode == EXT_KEY2)
    {
        KBD_SetKeybFlags ((iScanCode == EXT_KEY1) ? KF_EXTENDED : KF_EXTENDED2, TRUE);
        return;
    }

    fPressed = !(iScanCode & 0x80);         // release sets high-bit
    iScanCode &= ~0x80;                     // strip release bit

    switch (iScanCode)
    {
        case 29:            // ctrl
            if (wKeybFlags & KF_EXTENDED2) return;  // not control but pause

            KBD_SetKeybFlagsExt (KF_LCTRL, KF_RCTRL, fPressed);
            break;

        case 42:            // left shift
            if (wKeybFlags & KF_EXTENDED)       // not lshift but prtscr
            {
                KBD_SetKeybFlags (KF_EXTENDED, FALSE);
                KBD_SetKeybFlags (KF_EXTENDED2, TRUE);
                return;
            }
            else
                KBD_SetKeybFlags (KF_LSHIFT, fPressed);
            break;

        case 54:            // right shift
            KBD_SetKeybFlags (KF_RSHIFT, fPressed);
            break;

        case 56:            // alt
            KBD_SetKeybFlagsExt (KF_LALT, KF_RALT, fPressed);
            break;

        case 58:            // caps lock
            if (fPressed && !(wKeybFlags & KF_CAPSLP))
            {
                KBD_ToggleKeybLock (KF_CAPSL);
            }

            KBD_SetKeybFlags (KF_CAPSLP, fPressed);
            break;

        case 69:            // num lock            
            if (wKeybFlags & KF_EXTENDED2)      // part of pause sequence
            {
                if (fPressed)
                {
                    KBD_PutKeyInBuf (VIRTKEY_PAUSE, 0, wKeybFlags);
                }
                else
                    KBD_SetKeybFlags (KF_EXTENDED2, FALSE);
            }
            else
            {
                if (fPressed && !(wKeybFlags & KF_NUMLP))
                {
                    KBD_ToggleKeybLock (KF_NUML);
                }

                KBD_SetKeybFlags (KF_NUMLP, fPressed);
            }
            break;

        case 70:            // scroll lock
            if (wKeybFlags & KF_EXTENDED)       // break
            {
                if (fPressed) KBD_PutKeyInBuf (VIRTKEY_BREAK, 0, wKeybFlags);
            }
            else
            {
                if (fPressed && !(wKeybFlags & KF_SCROLLLP))
                {
                    KBD_ToggleKeybLock (KF_SCROLLL);
                }

                KBD_SetKeybFlags (KF_SCROLLLP, fPressed);
            }
            break;

        default:            // some other key
            if (iScanCode == 55 && (wKeybFlags & KF_EXTENDED2))     // print screen
            {
                iScanCode = VIRTKEY_PRTSCR;
                if (!fPressed) KBD_SetKeybFlags (KF_EXTENDED2, FALSE);
            }

            if (fPressed)                   // only record key presses
            {
                KBD_PutKeyInBuf (iScanCode, KBD_MapKey(iScanCode), wKeybFlags);
            }
            break;
    }

    if (wKeybFlags & KF_EXTENDED)
    {
        afKeyPressed[iScanCode & KEY_EXTENDED] = fPressed;
    }
    else
        afKeyPressed[iScanCode] = fPressed;

    KBD_SetKeybFlags (KF_EXTENDED, FALSE);
}


/*
** interrupt routine for keyboard handling
*/
#if (0)
static void __interrupt __far KBD_KeyboardHandler (void)
{
    /* this was necessary for XT-keyboards
    WriteIoByte (0x61, ReadIoByte(0x61) | 0x80);              // satisfy keyboard controller
    */

    KBD_HandleKey (ReadIoByte(0x60));                  // handle key

    resetpic (1);                               // satisfy interrupt controller
}
#endif


static void _memset(void* pMem, uint8_t Value, size_t Size)
{
	int i;
	for (i = 0; i < Size; i++)
	{
		((uint8_t*)pMem)[i] = Value;
	}
}


/*
** 23-08-97 - keyboard reset, returns FALSE on hardware failure, TRUE otherwise
*/
//static
int KBD_Reset (void)
{
    int i;

    uint8_t bRes;


    /*
    ** 28-08-97 - first try to deactivate the 2nd unit (PS/2 mouse), so we
    ** don't get values from it when we are waiting for an ACK
    */
    deactsecunit ();

    /*
    ** controller calls
    */

    // controller selftest (64/aa), returns 0x55 if successful
    /* For some mysterious reason unbeknownst to me, after a successful
    ** selftest (result is 0x55), the keyboard locks, returning ab 83
    ** instead of ab 41 with keyboard identification. I haven't been
    ** able to determine the cause. So far for the controller selftest...
    **
    ** KH_140899 - according to Ralph Brown's portlist, ab 41 = translation
    ** ab 83 = pass through
    */
    /*
    WriteIoByte (0x64, 0xaa);
    if (!waitval(&bRes) || bRes != 0x55) return FALSE;
    */

//#define DEBUG_MESS

#ifdef DEBUG_MESS
nprintf ("check\n");
#endif
    // check interface (64/ab)
    WriteIoByte (0x64, 0xab);
    if (!waitval(&bRes) || bRes != 0x00) return FALSE;

    // activate keyboard  (64/ae)
    /* Another mysterious thing: the activating/deactivation calls are
    ** supposed to return an ACK, but do not do so.
    **
    ** KH_140899 - RB's portlist does not specify an ACK
    */
    /*
    WriteIoByte (0x64, 0xae);
    if (!waitval(&bRes) || bRes != 0xfa) return FALSE;
    */
      
    /*
    ** keyboard calls
    */               

#ifdef DEBUG_MESS
nprintf ("reset\n");
#endif
    // reset keyboard (60/ff)
    WriteIoByte (0x60, 0xff);
    if (!waitval(&bRes) || bRes != 0xfa) return FALSE;
    // wait for BAT result (aa)
    // this may take some time, so allow max. 4 time outs
    for (i = 0; i < 5; i++)
    {
        if (waitval(&bRes)) break;
    }
    if (i >= 5 || bRes != 0xaa) return FALSE;

#ifdef DEBUG_MESS
nprintf ("echo\n");
#endif
    // echo test (60/ee)
    WriteIoByte (0x60, 0xee);
    if (!waitval(&bRes) || bRes != 0xee) return FALSE;

#ifdef DEBUG_MESS
nprintf ("get id\n");
#endif
    // keyboard identification (60/f2)
    WriteIoByte (0x60, 0xf2);
    if (!waitval(&bRes) || bRes != 0xfa) return FALSE;
    if (!waitval(&bRes) || bRes != 0xab) return FALSE;
    if (!waitval(&bRes) || bRes != 0x41) return FALSE;

#ifdef DEBUG_MESS
nprintf ("set speed\n");
#endif
    // set maximum keyboard speed / minimum delay (60/f3 -> 0)
    WriteIoByte (0x60, 0xf3);
    if (!waitval(&bRes) || bRes != 0xfa) return FALSE;
    WriteIoByte (0x60, 0x03);
    // I'm not sure whether this should always ACK
    if (waitval(&bRes) && bRes != 0xfa) return FALSE;

#ifdef DEBUG_MESS
nprintf ("activate\n");
#endif
    // activate keyboard (60/f4)
    /* This seems to be necessary to keep it from hanging after any
    ** 0x64 call, I've got no clue why...
    */
    WriteIoByte (0x60, 0xf4);
    if (!waitval(&bRes) || bRes != 0xfa) return FALSE;

    /*
    ** software part, reset keyboard flags etc.
    */

#ifdef DEBUG_MESS
nprintf ("done\n");
#endif
    iKeyBufNextRead = 0;
    iKeyBufNextStore = 0;
    _memset ((void*)afKeyPressed, 0, sizeof(afKeyPressed));

    wKeybFlags = 0;

    return TRUE;
}


#if (0)
// called when stopping our service, so BIOS can safely take over
static void KBD_Leave (void)
{
    // reset BIOS keyboard status

    *(uint16_t *)0x417 = 0;

    // reset keyboard lights

    WriteIoByte (0x60, 0xed);
    waitval (NULL);
    WriteIoByte (0x60, 0);
    waitval (NULL);

    // enable keyboard (in case we stopped during init)

    WriteIoByte (0x60, 0xf4);
    waitval (NULL);
}
#endif


/***( interface functions )***************************************************/


/*
** check whether key available or not
*/
int KBD_KeyReady (void)
{   
    //return fInstalled ? iKeyBufNextRead != iKeyBufNextStore : FALSE;
    return iKeyBufNextRead != iKeyBufNextStore;
}


/*
** wait for key and process
*/
int KBD_GetKey (uint32_t *pKey, uint8_t *pbScanCode, uint16_t *pwKeybFlags)
{
    KBD_KEYINBUF *p;


    //if (!fInstalled) return FALSE;

    while (!KBD_KeyReady()) ;           // wait until key in buffer

    p = &as_KeyBuf[iKeyBufNextRead];

    if (pKey) *pKey = p->cKeyCode;
    if (pbScanCode) *pbScanCode = p->bScanCode;
    if (pwKeybFlags) *pwKeybFlags = p->wKeybFlags;

    iKeyBufNextRead = (iKeyBufNextRead + 1) % KBD_BUFSIZE;

    return TRUE;
}


/*
** check for key and process if available
*/
int KBD_CheckKey (uint32_t *pcKey, uint8_t *pbScanCode, uint16_t *pwKeybFlags)
{
    if (KBD_KeyReady())                 // if key ready then process
    {
        KBD_GetKey (pcKey, pbScanCode, pwKeybFlags);
        return TRUE;
    }
    else
        return FALSE;
}


/*
** check whether key iKeyCode is pressed or not
*/
int KBD_KeyPressed (int iKeyCode)
{
    //if (!fInstalled) return FALSE;

    if (iKeyCode & KEY_VIRTKEY)         // virtual key, find directly with scan code
    {
        /*
        ** Some keys have both an extended and a non-extended version (Ctrl, Alt). If the
        ** extended or noextend flag is set, use the specific code, otherwise use either
        ** of the values (i.e. if KEY_ALT is requested, a press of KEY_RALT or KEY_LALT is
        ** both valid).
        */
        if ((iKeyCode & KEY_EXTENDED) || (iKeyCode & KEY_NOEXTEND))
        {
            return afKeyPressed[iKeyCode & KEY_SCANCODE];
        }
        else                                                // either extended or not
        {
            iKeyCode &= KEY_SCANCODE;
            return afKeyPressed[iKeyCode] || afKeyPressed[iKeyCode | KEY_EXTENDED];
        }
    }
    else                                // redefinable key, find in key map
    {
        return afKeyPressed[KBD_GetMappedKey(iKeyCode & KEY_NORMAL)];
    }
}


/*
** clear keyboard buffer
*/
void KBD_ClearBuffer (void)
{
    iKeyBufNextRead = iKeyBufNextStore;     // clear buffer
}


/*
** wait until first keystroke after empty buffer
*/
void KBD_Pause (void)
{
    KBD_ClearBuffer ();
    KBD_GetKey (NULL, NULL, NULL);
}


/***( init functions )********************************************************/

#if (0)
static (__interrupt __far *pOrgKeybHandler)();      // original keyboard handler


int KBD_InstallHandler (void)
{
    int iErr = ERR_NO_ERROR;


    if (!fInstalled)
    {
        pOrgKeybHandler = _dos_getvect(0x09);

        clrirq (1);

        if (!KBD_Reset())
        {
            KBD_Leave ();
            iErr = ERR_INT_HW_FAILURE;
        }
        else
        {
            _dos_setvect (0x09, KBD_KeyboardHandler);
            fInstalled = 1;
        }

        setirq (1);
    }
    else
        iErr = ERR_INT_INSTALLED;

    return iErr;
}


int KBD_DestallHandler (void)
{
    int iErr = ERR_NO_ERROR;


    if (fInstalled)
    {
        clrirq (1);

        _dos_setvect (0x09, pOrgKeybHandler);

        KBD_Leave ();

        setirq (1);

        fInstalled = 0;
    }
    else
        iErr = ERR_INT_NOT_INSTALLED;

    return iErr;
}
#endif


/*
static void waitack (void)
{       
    int i;
    int j;
    int n;


    n = 0;
    for (i = 0; i < 100000; i++)
    {
        j = ReadIoByte(0x64);
        if (j != n)
        {
            nprintf ("%4d: %08b\n", i, j);
            n = j;

            if (j & 1) break;
        }
    }

    if (j & 1) nprintf ("ack: %x\n", ReadIoByte(0x60));
}
*/

