Ejemplo n.º 1
0
/*++
Function:
  _mbslen

Determines the number of characters (code points) in a multibyte
character string.

Parameters

string  Points to a multibyte character string.

Return Values

The mbslen subroutine returns the number of multibyte characters in a
multibyte character string. It returns 0 if the string parameter
points to a null character or if a character cannot be formed from the
string pointed to by this parameter.

--*/
size_t 
__cdecl
_mbslen(
        const unsigned char *string)
{
    size_t ret = 0;
    CPINFO cpinfo;
    PERF_ENTRY(_mbslen);
    ENTRY("_mbslen (string=%p (%s))\n", string, string);

    if (string)
    {
        if (GetCPInfo(CP_ACP, &cpinfo) && cpinfo.MaxCharSize == 1)
        {
            ret = strlen((const char*)string);
        }
        else
        {
            while (*string)
            {
                if (IsDBCSLeadByteEx(CP_ACP, *string))
                {
                    ++string;
                }
                ++string;
                ++ret;
            }
        }
    }

    LOGEXIT("_mbslen returning size_t %u\n", ret);
    PERF_EXIT(_mbslen);
    return ret;
}
Ejemplo n.º 2
0
int __cdecl main(int argc, char *argv[])
{

    if (0 != PAL_Initialize(argc, argv))
    {
        return FAIL;
    }

    if (IsDBCSLeadByteEx(-1, 0))
    {
        Fail("IsDBCSLeadByteEx did not error on an invalid code page!\n");
    }

    /* Clear the last error. */
    SetLastError(0);


    DoTest(0);
    DoTest(CP_ACP);
    DoTest(0x4E4);

    PAL_Terminate();

    return PASS;
}
Ejemplo n.º 3
0
void DoTest(int codepage)
{
    int value;
    int ret;
    int i;


    for (i=0; i<256; i++)
    {
        value = IsDBCSLeadByteEx(codepage, i);

        ret = GetLastError();
        if (ret == ERROR_INVALID_PARAMETER)
        {
            Fail("IsDBCSLeadByteEx unexpectedly errored with ERROR_INVALID_PARAMETER!\n");
        }
        else if (ret != 0)
        {
            Fail("IsDBCSLeadByteEx had an unexpected error!\n");
        }
        else if (value)
        {
            Fail("IsDBCSLeadByteEx incorrectly found a lead byte in code "
                 "page %d\n", codepage);
        }

    }
}
Ejemplo n.º 4
0
__cdecl
_mbsinc(
        const unsigned char *string)
{
    unsigned char *ret;

    PERF_ENTRY(_mbsinc);
    ENTRY("_mbsinc (string=%p)\n", string);

    if (string == NULL)
    {
        ret = NULL;
    }
    else
    {
        ret = (unsigned char *) string;
        if (IsDBCSLeadByteEx(CP_ACP, *ret))
        {
            ++ret;
        }
        ++ret;
    }

    LOGEXIT("_mbsinc returning unsigned char* %p (%s)\n", ret, ret);
    PERF_EXIT(_mbsinc);
    return ret;
}
Ejemplo n.º 5
0
Archivo: text.c Proyecto: RPG-7/reactos
/*
 * @implemented
 */
LPSTR
WINAPI
CharNextExA(WORD codepage, LPCSTR ptr, DWORD flags)
{
    if (!*ptr) return (LPSTR)ptr;
    if (IsDBCSLeadByteEx(codepage, ptr[0]) && ptr[1]) return (LPSTR)(ptr + 2);
    return (LPSTR)(ptr + 1);
}
Ejemplo n.º 6
0
/* stdio functions - versions that translate to/from utf-8 */
static int GSDLLCALL
gsdll_stdin_utf8(void *instance, char *buf, int len)
{
    static WCHAR thiswchar = 0; /* wide character to convert to multiple bytes */
    static int nmore = 0;       /* number of additional encoding bytes to generate */
    UINT consolecp = 0;
    int nret = 0;               /* number of bytes returned to caller */
    int i;

    while (len) {
        while (len && nmore) {
            nmore--;
            *buf++ = 0x80 | ((thiswchar >> (6 * nmore)) & 0x3F), nret++;
            len--;
        }
        while (len) {
            if (0 >= _read(fileno(stdin), buf, 1))
                return nret;
            nret++, buf++, len--;
            if (buf[-1] == '\n')
                /* return at end of line (note: no traslation needed) */
                return nret;
            else if ((unsigned char)buf[-1] <= 0x7F)
                /* no translation needed for 7-bit ASCII codes */
                continue;
            else {
                /* extended character, may be double */
                BYTE dbcsstr[2];

                dbcsstr[0] = buf[-1];
                if (!consolecp)
                    consolecp = GetConsoleCP();
                thiswchar = L'?'; /* initialize in case the conversion below fails */
                if (IsDBCSLeadByteEx(consolecp, dbcsstr[0])) {
                    /* double-byte character code, fetch the trail byte */
                    _read(fileno(stdin), &dbcsstr[1], 1);
                    MultiByteToWideChar(consolecp, 0, dbcsstr, 2, &thiswchar, 1);
                }
                else {
                    MultiByteToWideChar(consolecp, 0, dbcsstr, 1, &thiswchar, 1);
                }
                /* convert thiswchar to utf-8 */
                if (thiswchar <= 0x007F) {          /* encoded as single byte */
                    buf[-1] = (char)thiswchar;
                } else if (thiswchar <= 0x07FF) {   /* encoded as 2 bytes */
                    buf[-1] = 0xC0 | ((thiswchar >> 6) & 0x1F);
                    nmore = 1;
                    break;
                } else if (thiswchar <= 0xFFFF) {   /* encoded as 3 bytes */
                    buf[-1] = 0xE0 | ((thiswchar >> 12) & 0xF);
                    nmore = 2;
                    break;
                } else
Ejemplo n.º 7
0
LPCSTR CMainApp::UnFormat(CString strTmp)
{
    m_strBuffer2 = strTmp;

    int i = m_strBuffer2.GetLength();
    char * pStr = m_strBuffer2.GetBuffer(0);
    char * pNext;
    

    while(*pStr)
    {
        if(*pStr=='\\' && !IsDBCSLeadByteEx(m_uiCodePage, *pStr))
        {           
            pNext = CharNextExA(m_uiCodePage, pStr, 0);
            switch(*pNext)
            {
                case '\\':
                    *pStr = '\\';
                    break;
                case 't':
                    *pStr = '\t';
                    break;
                case 'n':
                    *pStr = '\n';
                    break;
                case 'r':
                    *pStr = '\r';
                    break;
                default:
                    break; 
            }

            pStr = pNext;
            pNext = CharNextExA(m_uiCodePage, pNext, 0);
            memmove(pStr, pNext, --i);
                    
        }
        else 
        {
            pStr = CharNextExA(m_uiCodePage, pStr, 0);
            i--;
        }
    }

    m_strBuffer2.ReleaseBuffer(-1);

    return m_strBuffer2;
}
Ejemplo n.º 8
0
LPCSTR CMainApp::Format(CString strTmp)
{
    char * pStr = strTmp.GetBuffer(0);
    char * pDest = m_strBuffer2.GetBuffer(MAX_STR_SIZE);
    char * pNext;
    

    while(*pStr)
    {
        if(!IsDBCSLeadByteEx(m_uiCodePage, *pStr))
        {
            switch(*pStr)
            {
                case '\\':
                    *pDest++ = '\\';
                    *pDest++ = '\\';
                    break;
                case '\t':
                    *pDest++ = '\\';
                    *pDest++ = 't';
                    break;
                case '\r':
                    *pDest++ = '\\';
                    *pDest++ = 'r';
                    break;
                case '\n':
                    *pDest++ = '\\';
                    *pDest++ = 'n';
                    break;
                default:
                    *pDest++ = *pStr;
                    break;
            }
        }
        else {
            memcpy( pDest, pStr, 2 );
            pDest += 2;
        }

        pStr = CharNextExA(m_uiCodePage, pStr, 0);
    }

    *pDest = '\0';

    m_strBuffer2.ReleaseBuffer(-1);

    return m_strBuffer2;
}
Ejemplo n.º 9
0
bool
ArbI18N::JIScheck(CString s)
{ 
	int ctl = s.GetLength();
	int cursor = 0;
	while (cursor < ctl)
	{
		TCHAR c = s[cursor];
		if (IsDBCSLeadByteEx(932, c))
		{
			cursor++; //skip trail byte if in a double byte char
		}
		cursor++;
	}
	return true;
}
Ejemplo n.º 10
0
int mblen(const char *mbstr, size_t count)
{
	const char *p = mbstr;
	size_t i;
	int    n=0;

	for( i=0; i<count; i++ )
	{
		if( *p=='\0' ) break;
		if( IsDBCSLeadByteEx( CP_UTF8, *p ) )
			n+=2, p+=2;
		else
			n+=1, p+=1;
	}

	return n;
}
Ejemplo n.º 11
0
int KCharset::to_uchar(const char* src, int len, unsigned int* uchar) const
{
	*uchar = 0;
#if defined(WIN32)
	int bytes = IsDBCSLeadByteEx(m_codepage,src[0]) ? 2:1;
	if(len < bytes) return -1;
	int n = MultiByteToWideChar(m_codepage, 0, src, bytes, (wchar_16*)uchar, 1);
	if(!n) return -1;
	return bytes;
#else
	char* src2 = (char*)src; size_t srclen = len;
	char* dst2 = (char*)uchar; size_t dstlen = sizeof(int);
	size_t n = iconv(m_iconv_utf32, &src2, &srclen, &dst2, &dstlen);
	if(n == -1 && errno != E2BIG) return -1;
	return (int)(src2 - src);
#endif
}
Ejemplo n.º 12
0
__cdecl
_mbsdec(
        const unsigned char *start, 
        const unsigned char *current)
{
    unsigned char *ret;
    unsigned char *strPtr;
    CPINFO cpinfo;

    PERF_ENTRY(_mbsdec);
    ENTRY("_mbsdec (start=%p, current=%p)\n", start, current);

    if (current <= start)
    {
        ret = NULL;
    }
    else if (GetCPInfo(CP_ACP, &cpinfo) && cpinfo.MaxCharSize == 1)
    {
        ret = (unsigned char *) current - 1;
    }
    else
    {
        ret = strPtr = (unsigned char *) start;
        while (strPtr < current)
        {
            ret = strPtr;
            if (IsDBCSLeadByteEx(CP_ACP, *strPtr))
            {
                ++strPtr;
            }
            ++strPtr;
        }
    }
    LOGEXIT("_mbsdec returning unsigned int %p (%s)\n", ret, ret);
    PERF_EXIT(_mbsdec);
    return ret;
}
Ejemplo n.º 13
0
__cdecl
_mbsninc(
         const unsigned char *string, size_t count)
{
    unsigned char *ret;
    CPINFO cpinfo;

    PERF_ENTRY(_mbsninc);
    ENTRY("_mbsninc (string=%p, count=%lu)\n", string, count);
    if (string == NULL)
    {
        ret = NULL;
    }
    else
    {
        ret = (unsigned char *) string;
        if (GetCPInfo(CP_ACP, &cpinfo) && cpinfo.MaxCharSize == 1)
        {
            ret += std::min(count, strlen((const char*)string));
        }
        else
        {
            while (count-- && (*ret != 0))
            {
                if (IsDBCSLeadByteEx(CP_ACP, *ret))
                {
                    ++ret;
                }
                ++ret;
            }
        }
    }
    LOGEXIT("_mbsninc returning unsigned char* %p (%s)\n", ret, ret);
    PERF_EXIT(_mbsninc);
    return ret;
}
Ejemplo n.º 14
0
Archivo: rc.c Proyecto: mingpen/OpenNT
BOOL RC_PreProcess(PCHAR szname)
{
    PFILE fhout;        /* fhout: is temp file with rcincluded stuff */
    PFILE fhin;
    CHAR nm[_MAX_PATH*2];
    PCHAR pch;
    PWCHAR pwch;
    PWCHAR pfilename;
    WCHAR readszbuf[READ_MAX];
    WCHAR szT[ MAXSTR ];
    UINT iLine = 0;
    int fBlanks = TRUE;
    INT fFileType;

    /* Open the .RC source file. */
    MultiByteToWideChar(uiCodePage, MB_PRECOMPOSED, szname, -1, Filename, MED_BUFFER+1);
    fhin = fopen(szname, "rb");
    if (!fhin) {
        SET_MSG(Msg_Text, sizeof(Msg_Text), GET_MSG(1110), szname);
        return(FALSE);
    }

    /* Open the temporary output file. */
    fhout = fopen(szTempFileName, "w+b");
    if (!fhout) {
        strcpy(Msg_Text, GET_MSG(2180));
        return(FALSE);
    }

    /* output the current filename for RCPP messages */
    for (pch=nm ; *szname ; szname = CharNextA(szname)) {
        *pch++ = *szname;
        if (IsDBCSLeadByteEx(uiCodePage, *szname))
            *pch++ = *(szname + 1);
        /* Hack to fix bug #8786: makes '\' to "\\" */
        else if (*szname == '\\')
            *pch++ = '\\';
    }
    *pch++ = '\000';

    /* Output the current filename for RCPP messages */
    wcscpy(szT, L"#line 1\"");
    // hack - strlen("#line 1\"") is 8.
    MultiByteToWideChar(uiCodePage, MB_PRECOMPOSED, nm, -1, szT+8, MAXSTR+1-8);
    wcscat(szT, L"\"\r\n");
    MyWrite(fhout, szT, wcslen(szT) * sizeof(WCHAR));

    /* Determine if the input file is Unicode */
    fFileType = DetermineFileType (fhin);

    /* Process each line of the input file. */
    while (fgetl(readszbuf, READ_MAX, fFileType == DFT_FILE_IS_16_BIT, fhin)) {

        /* keep track of the number of lines read */
        Linenumber = iLine++;

        if ((iLine & RC_PREPROCESS_UPDATE) == 0)
            UpdateStatus(1, iLine);

        /* Skip the Byte Order Mark and the leading bytes. */
        pwch = readszbuf;
        while (*pwch && (iswspace(*pwch) || *pwch == 0xFEFF))
            pwch++;

        /* if the line is a rcinclude line... */
        if (strpre(L"rcinclude", pwch)) {
            /* Get the name of the rcincluded file. */
            pfilename = skipblanks(pwch + 9, TRUE);

            MyWrite(fhout, L"#include \"", 10 * sizeof(WCHAR));
            MyWrite(fhout, pfilename, wcslen(pfilename) * sizeof(WCHAR));
            MyWrite(fhout, L"\"\r\n", 3 * sizeof(WCHAR));

        }
        else if (strpre(L"#pragma", pwch)) {
            WCHAR cSave;

            pfilename = skipblanks(pwch + 7, FALSE);
            if (strpre(L"code_page", pfilename)) {
                pfilename = skipblanks(pfilename + 9, FALSE);
                if (*pfilename == L'(') {
                    ULONG cp = 0;

                    pfilename = skipblanks(pfilename + 1, FALSE);
                    // BUGBUG really should allow hex/octal, but ...
                    if (iswdigit(*pfilename)) {
                        while (iswdigit(*pfilename)) {
                            cp = cp * 10 + (*pfilename++ - L'0');
                        }
                        pfilename = skipblanks(pfilename, FALSE);
                    }
                    else if (strpre(L"default", pfilename)) {
                        cp = uiDefaultCodePage;
                        pfilename = skipblanks(pfilename + 7, FALSE);
                    }

                    if (cp == 0) {
                        wsprintfA(Msg_Text, "%s%ws", GET_MSG(4212), pfilename);
                        error(4212);
                    }
                    else if (*pfilename != L')') {
                        strcpy (Msg_Text, GET_MSG (4211));
                        error(4211);
                    }
                    else if (cp == CP_WINUNICODE) {
                        strcpy (Msg_Text, GET_MSG (4213));
                        warning(4213);
                    }
                    else if (!IsValidCodePage(cp)) {
                        strcpy (Msg_Text, GET_MSG (4214));
                        warning(4214);
                    }
                    else {
                        uiCodePage = cp;
                        /* Copy the #pragma line to the temp file. */
                        MyWrite(fhout, pwch, wcslen(pwch) * sizeof(WCHAR));
                        MyWrite(fhout, L"\r\n", 2 * sizeof(WCHAR));
                    }
                }
                else {
                    strcpy (Msg_Text, GET_MSG (4210));
                    error(4210);
                }
            }
        }
        else if (!*pwch)
            fBlanks = TRUE;
        else {
            if (fBlanks) {
                swprintf(szT, L"#line %d\r\n", iLine);
                MyWrite(fhout, szT, wcslen(szT) * sizeof(WCHAR));
                fBlanks = FALSE;
            }
            /* Copy the .RC line to the temp file. */
            MyWrite(fhout, pwch, wcslen(pwch) * sizeof(WCHAR));
            MyWrite(fhout, L"\r\n", 2 * sizeof(WCHAR));
        }
    }

    lCPPTotalLinenumber = iLine;
    Linenumber = 0;

    uiCodePage = uiDefaultCodePage;

    fclose(fhout);
    fclose(fhin);

    return(TRUE);
}
Ejemplo n.º 15
0
/* return code -1 means that event_queue_ptr won't be incremented.
   In other word, this event makes two key codes.   (by himi)       */
static int
key_event (KEY_EVENT_RECORD *event, struct input_event *emacs_ev, int *isdead)
{
  static int mod_key_state = 0;
  int wParam;

  *isdead = 0;

  /* Skip key-up events.  */
  if (!event->bKeyDown)
    {
      switch (event->wVirtualKeyCode)
	{
	case VK_LWIN:
	  mod_key_state &= ~LEFT_WIN_PRESSED;
	  break;
	case VK_RWIN:
	  mod_key_state &= ~RIGHT_WIN_PRESSED;
	  break;
	case VK_APPS:
	  mod_key_state &= ~APPS_PRESSED;
	  break;
	}
      return 0;
    }

  /* Ignore keystrokes we fake ourself; see below.  */
  if (faked_key == event->wVirtualKeyCode)
    {
      faked_key = 0;
      return 0;
    }

  /* To make it easier to debug this code, ignore modifier keys!  */
  switch (event->wVirtualKeyCode)
    {
    case VK_LWIN:
      if (NILP (Vw32_pass_lwindow_to_system))
	{
	  /* Prevent system from acting on keyup (which opens the Start
	     menu if no other key was pressed) by simulating a press of
	     Space which we will ignore.  */
	  if ((mod_key_state & LEFT_WIN_PRESSED) == 0)
	    {
	      if (NUMBERP (Vw32_phantom_key_code))
		faked_key = XUINT (Vw32_phantom_key_code) & 255;
	      else
		faked_key = VK_SPACE;
	      keybd_event (faked_key, (BYTE) MapVirtualKey (faked_key, 0), 0, 0);
	    }
	}
      mod_key_state |= LEFT_WIN_PRESSED;
      if (!NILP (Vw32_lwindow_modifier))
	return 0;
      break;
    case VK_RWIN:
      if (NILP (Vw32_pass_rwindow_to_system))
	{
	  if ((mod_key_state & RIGHT_WIN_PRESSED) == 0)
	    {
	      if (NUMBERP (Vw32_phantom_key_code))
		faked_key = XUINT (Vw32_phantom_key_code) & 255;
	      else
		faked_key = VK_SPACE;
	      keybd_event (faked_key, (BYTE) MapVirtualKey (faked_key, 0), 0, 0);
	    }
	}
      mod_key_state |= RIGHT_WIN_PRESSED;
      if (!NILP (Vw32_rwindow_modifier))
	return 0;
      break;
    case VK_APPS:
      mod_key_state |= APPS_PRESSED;
      if (!NILP (Vw32_apps_modifier))
	return 0;
      break;
    case VK_CAPITAL:
      /* Decide whether to treat as modifier or function key.  */
      if (NILP (Vw32_enable_caps_lock))
	goto disable_lock_key;
      return 0;
    case VK_NUMLOCK:
      /* Decide whether to treat as modifier or function key.  */
      if (NILP (Vw32_enable_num_lock))
	goto disable_lock_key;
      return 0;
    case VK_SCROLL:
      /* Decide whether to treat as modifier or function key.  */
      if (NILP (Vw32_scroll_lock_modifier))
	goto disable_lock_key;
      return 0;
    disable_lock_key:
      /* Ensure the appropriate lock key state is off (and the
	 indicator light as well).  */
      wParam = event->wVirtualKeyCode;
      if (GetAsyncKeyState (wParam) & 0x8000)
	{
	  /* Fake another press of the relevant key.  Apparently, this
	     really is the only way to turn off the indicator.  */
	  faked_key = wParam;
	  keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
		       KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
	  keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
		       KEYEVENTF_EXTENDEDKEY | 0, 0);
	  keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
		       KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
	}
      break;
    case VK_MENU:
    case VK_CONTROL:
    case VK_SHIFT:
      return 0;
    case VK_CANCEL:
      /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
	 which is confusing for purposes of key binding; convert
	 VK_CANCEL events into VK_PAUSE events.  */
      event->wVirtualKeyCode = VK_PAUSE;
      break;
    case VK_PAUSE:
      /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
	 for purposes of key binding; convert these back into
	 VK_NUMLOCK events, at least when we want to see NumLock key
	 presses.  (Note that there is never any possibility that
	 VK_PAUSE with Ctrl really is C-Pause as per above.)  */
      if (NILP (Vw32_enable_num_lock)
	  && (event->dwControlKeyState
	      & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0)
	event->wVirtualKeyCode = VK_NUMLOCK;
      break;
    }

  /* Recognize state of Windows and Apps keys.  */
  event->dwControlKeyState |= mod_key_state;

  /* Distinguish numeric keypad keys from extended keys.  */
  event->wVirtualKeyCode =
    map_keypad_keys (event->wVirtualKeyCode,
		     (event->dwControlKeyState & ENHANCED_KEY));

  if (lispy_function_keys[event->wVirtualKeyCode] == 0)
    {
      if (!NILP (Vw32_recognize_altgr)
	  && (event->dwControlKeyState & LEFT_CTRL_PRESSED)
	  && (event->dwControlKeyState & RIGHT_ALT_PRESSED))
	{
	  /* Don't try to interpret AltGr key chords; ToAscii seems not
	     to process them correctly.  */
	}
      /* Handle key chords including any modifiers other than shift
         directly, in order to preserve as much modifier information as
         possible.  */
      else if (event->dwControlKeyState
	       & (  RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED
		  | RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED
		  | (!NILP (Vw32_lwindow_modifier) ? LEFT_WIN_PRESSED : 0)
		  | (!NILP (Vw32_rwindow_modifier) ? RIGHT_WIN_PRESSED : 0)
		  | (!NILP (Vw32_apps_modifier) ? APPS_PRESSED : 0)
		  | (!NILP (Vw32_scroll_lock_modifier) ? SCROLLLOCK_ON : 0)))
	{
	  /* Don't translate modified alphabetic keystrokes, so the user
	     doesn't need to constantly switch layout to type control or
	     meta keystrokes when the normal layout translates
	     alphabetic characters to non-ascii characters.  */
	  if ('A' <= event->wVirtualKeyCode && event->wVirtualKeyCode <= 'Z')
	    {
	      event->uChar.AsciiChar = event->wVirtualKeyCode;
	      if ((event->dwControlKeyState & SHIFT_PRESSED) == 0)
		event->uChar.AsciiChar += ('a' - 'A');
	    }
	  /* Try to handle unrecognized keystrokes by determining the
             base character (ie. translating the base key plus shift
             modifier).  */
	  else if (event->uChar.AsciiChar == 0)
	    w32_kbd_patch_key (event, -1);
	}

      if (event->uChar.AsciiChar == 0)
	{
	  emacs_ev->kind = NO_EVENT;
	  return 0;
	}
      else if (event->uChar.AsciiChar > 0)
	{
	  /* Pure ASCII characters < 128.  */
	  emacs_ev->kind = ASCII_KEYSTROKE_EVENT;
	  emacs_ev->code = event->uChar.AsciiChar;
	}
      else if (event->uChar.UnicodeChar > 0
	       && w32_console_unicode_input)
	{
	  /* Unicode codepoint; only valid if we are using Unicode
	     console input mode.  */
	  emacs_ev->kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
	  emacs_ev->code = event->uChar.UnicodeChar;
	}
      else
	{
	  /* Fallback handling of non-ASCII characters for non-Unicode
	     versions of Windows, and for non-Unicode input on NT
	     family of Windows.  Only characters in the current
	     console codepage are supported by this fallback.  */
	  wchar_t code;
	  char dbcs[2];
          int cpId;

	  /* Get the current console input codepage to interpret this
	     key with.  Note that the system defaults for the OEM
	     codepage could have been changed by calling SetConsoleCP
	     or w32-set-console-codepage, so using GetLocaleInfo to
	     get LOCALE_IDEFAULTCODEPAGE is not TRT here.  */
          cpId = GetConsoleCP ();

	  dbcs[0] = dbcs_lead;
	  dbcs[1] = event->uChar.AsciiChar;
	  if (dbcs_lead)
	    {
	      dbcs_lead = 0;
	      if (!MultiByteToWideChar (cpId, 0, dbcs, 2, &code, 1))
		{
		  /* Garbage  */
		  DebPrint (("Invalid DBCS sequence: %d %d\n",
			     dbcs[0], dbcs[1]));
		  emacs_ev->kind = NO_EVENT;
		}
	    }
	  else if (IsDBCSLeadByteEx (cpId, dbcs[1]))
	    {
	      dbcs_lead = dbcs[1];
	      emacs_ev->kind = NO_EVENT;
	    }
	  else
	    {
	      if (!MultiByteToWideChar (cpId, 0, &dbcs[1], 1, &code, 1))
		{
		  /* Garbage  */
		  DebPrint (("Invalid character: %d\n", dbcs[1]));
		  emacs_ev->kind = NO_EVENT;
		}
	    }
	  emacs_ev->kind = MULTIBYTE_CHAR_KEYSTROKE_EVENT;
	  emacs_ev->code = code;
	}
    }
  else
    {
      /* Function keys and other non-character keys.  */
      emacs_ev->kind = NON_ASCII_KEYSTROKE_EVENT;
      emacs_ev->code = event->wVirtualKeyCode;
    }

  XSETFRAME (emacs_ev->frame_or_window, get_frame ());
  emacs_ev->modifiers = w32_kbd_mods_to_emacs (event->dwControlKeyState,
					       event->wVirtualKeyCode);
  emacs_ev->timestamp = GetTickCount ();
  return 1;
}
Ejemplo n.º 16
0
// Obtain the reading string upon WM_IME_NOTIFY/INM_PRIVATE notification.
void CIME::GetPrivateReadingString()
{
	DWORD dwId = GetImeId();
	if(!dwId)
	{
		s_bShowReadingWindow = false;
		return;
	}

	HIMC hImc;
	hImc = ImmGetContext(UIGetHWND());
	if(!hImc)
	{
		s_bShowReadingWindow = false;
		return;
	}

	DWORD dwReadingStrLen = 0;
	DWORD dwErr = 0;
	WCHAR *pwszReadingStringBuffer = NULL;  // Buffer for when the IME supports GetReadingString()
	WCHAR *wstr = 0;
	bool bUnicodeIme = false;  // Whether the IME context component is Unicode.
	INPUTCONTEXT *lpIC = NULL;

	if(_GetReadingString)
	{
		UINT uMaxUiLen;
		BOOL bVertical;
		// Obtain the reading string size
		dwReadingStrLen = _GetReadingString(hImc, 0, NULL, (PINT)&dwErr, &bVertical, &uMaxUiLen);
		if(dwReadingStrLen)
		{
			wstr = pwszReadingStringBuffer = (LPWSTR)HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * dwReadingStrLen);
			if(!pwszReadingStringBuffer)
			{
				// Out of memory. Exit.
				_ImmReleaseContext(UIGetHWND(), hImc);
				return;
			}

			// Obtain the reading string
			dwReadingStrLen = _GetReadingString(hImc, dwReadingStrLen, wstr, (PINT)&dwErr, &bVertical, &uMaxUiLen);
		}

		s_bHorizontalReading = !bVertical;
		bUnicodeIme = true;
	}
	else
	{
		// IMEs that doesn't implement Reading String API

		lpIC = _ImmLockIMC(hImc);

		LPBYTE p = 0;
		switch(dwId)
		{
		case IMEID_CHT_VER42: // New(Phonetic/ChanJie)IME98  : 4.2.x.x // Win98
		case IMEID_CHT_VER43: // New(Phonetic/ChanJie)IME98a : 4.3.x.x // WinMe, Win2k
		case IMEID_CHT_VER44: // New ChanJie IME98b          : 4.4.x.x // WinXP
			p = *(LPBYTE *)((LPBYTE)_ImmLockIMCC(lpIC->hPrivate) + 24);
			if(!p) break;
			dwReadingStrLen = *(DWORD *)(p + 7 * 4 + 32 * 4);
			dwErr = *(DWORD *)(p + 8 * 4 + 32 * 4);
			wstr = (WCHAR *)(p + 56);
			bUnicodeIme = true;
			break;

		case IMEID_CHT_VER50: // 5.0.x.x // WinME
			p = *(LPBYTE *)((LPBYTE)_ImmLockIMCC(lpIC->hPrivate) + 3 * 4);
			if(!p) break;
			p = *(LPBYTE *)((LPBYTE)p + 1*4 + 5*4 + 4*2);
			if(!p) break;
			dwReadingStrLen = *(DWORD *)(p + 1*4 + (16*2+2*4) + 5*4 + 16);
			dwErr = *(DWORD *)(p + 1*4 + (16*2+2*4) + 5*4 + 16 + 1*4);
			wstr = (WCHAR *)(p + 1*4 + (16*2+2*4) + 5*4);
			bUnicodeIme = false;
			break;

		case IMEID_CHT_VER51: // 5.1.x.x // IME2002(w/OfficeXP)
		case IMEID_CHT_VER52: // 5.2.x.x // (w/whistler)
		case IMEID_CHS_VER53: // 5.3.x.x // SCIME2k or MSPY3 (w/OfficeXP and Whistler)
			p = *(LPBYTE *)((LPBYTE)_ImmLockIMCC(lpIC->hPrivate) + 4);
			if(!p) break;
			p = *(LPBYTE *)((LPBYTE)p + 1*4 + 5*4);
			if(!p) break;
			dwReadingStrLen = *(DWORD *)(p + 1*4 + (16*2+2*4) + 5*4 + 16 * 2);
			dwErr = *(DWORD *)(p + 1*4 + (16*2+2*4) + 5*4 + 16 * 2 + 1*4);
			wstr  = (WCHAR *) (p + 1*4 + (16*2+2*4) + 5*4);
			bUnicodeIme = true;
			break;

			// the code tested only with Win 98 SE (MSPY 1.5/ ver 4.1.0.21)
		case IMEID_CHS_VER41:
			{
				int nOffset;
				nOffset = (GetImeId(1) >= 0x00000002) ? 8 : 7;

				p = *(LPBYTE *)((LPBYTE)_ImmLockIMCC(lpIC->hPrivate) + nOffset * 4);
				if(!p) break;
				dwReadingStrLen = *(DWORD *)(p + 7*4 + 16*2*4);
				dwErr = *(DWORD *)(p + 8*4 + 16*2*4);
				dwErr = __min(dwErr, dwReadingStrLen);
				wstr = (WCHAR *)(p + 6*4 + 16*2*1);
				bUnicodeIme = true;
				break;
			}

		case IMEID_CHS_VER42: // 4.2.x.x // SCIME98 or MSPY2 (w/Office2k, Win2k, WinME, etc)
			{
				OSVERSIONINFOW osi;
				osi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
				GetVersionExW(&osi);

				int nTcharSize = (osi.dwPlatformId == VER_PLATFORM_WIN32_NT) ? sizeof(WCHAR) : sizeof(char);
				p = *(LPBYTE *)((LPBYTE)_ImmLockIMCC(lpIC->hPrivate) + 1*4 + 1*4 + 6*4);
				if(!p) break;
				dwReadingStrLen = *(DWORD *)(p + 1*4 + (16*2+2*4) + 5*4 + 16 * nTcharSize);
				dwErr = *(DWORD *)(p + 1*4 + (16*2+2*4) + 5*4 + 16 * nTcharSize + 1*4);
				wstr  = (WCHAR *) (p + 1*4 + (16*2+2*4) + 5*4);
				bUnicodeIme = (osi.dwPlatformId == VER_PLATFORM_WIN32_NT) ? true : false;
			}
		}   // switch
	}

	// Copy the reading string to the candidate list first
	s_CandList.awszCandidate[0][0] = 0;
	s_CandList.awszCandidate[1][0] = 0;
	s_CandList.awszCandidate[2][0] = 0;
	s_CandList.awszCandidate[3][0] = 0;
	s_CandList.dwCount = dwReadingStrLen;
	s_CandList.dwSelection = (DWORD)-1; // do not select any char
	if(bUnicodeIme)
	{
		UINT i;
		for(i = 0; i < dwReadingStrLen; ++i) // dwlen > 0, if known IME
		{
			if(dwErr <= i && s_CandList.dwSelection == (DWORD)-1)
			{
				// select error char
				s_CandList.dwSelection = i;
			}

			s_CandList.awszCandidate[i][0] = wstr[i];
			s_CandList.awszCandidate[i][1] = 0;
		}
		s_CandList.awszCandidate[i][0] = 0;
	}
	else
	{
		char *p = (char *)wstr;
		DWORD i, j;
		for(i = 0, j = 0; i < dwReadingStrLen; ++i, ++j) // dwlen > 0, if known IME
		{
			if(dwErr <= i && s_CandList.dwSelection == (DWORD)-1)
			{
				s_CandList.dwSelection = j;
			}
			// Obtain the current code page
			WCHAR wszCodePage[8];
			UINT uCodePage = CP_ACP;  // Default code page
			if(GetLocaleInfoW(MAKELCID(GetLanguage(), SORT_DEFAULT),
				LOCALE_IDEFAULTANSICODEPAGE,
				wszCodePage,
				sizeof(wszCodePage)/sizeof(wszCodePage[0])))
			{
				uCodePage = wcstoul(wszCodePage, NULL, 0);
			}
			MultiByteToWideChar(uCodePage, 0, p + i, IsDBCSLeadByteEx(uCodePage, p[i]) ? 2 : 1,
				s_CandList.awszCandidate[j], 1);
			if(IsDBCSLeadByteEx(uCodePage, p[i]))
				++i;
		}
		s_CandList.awszCandidate[j][0] = 0;
		s_CandList.dwCount = j;
	}
	if(!_GetReadingString)
	{
		_ImmUnlockIMCC(lpIC->hPrivate);
		_ImmUnlockIMC(hImc);
		GetReadingWindowOrientation(dwId);
	}
	_ImmReleaseContext(UIGetHWND(), hImc);

	if(pwszReadingStringBuffer)
		HeapFree(GetProcessHeap(), 0, pwszReadingStringBuffer);

	// Copy the string to the reading string buffer
	if(s_CandList.dwCount > 0)
		s_bShowReadingWindow = true;
	else
		s_bShowReadingWindow = false;
	if(s_bHorizontalReading)
	{
		s_CandList.nReadingError = -1;
		s_wstrReadingString.clear();
		for(UINT i = 0; i < s_CandList.dwCount; ++i)
		{
			if(s_CandList.dwSelection == i)
				s_CandList.nReadingError = s_wstrReadingString.length();
			s_wstrReadingString+=s_CandList.awszCandidate[i];
		}
	}

	s_CandList.dwPageSize = MAX_CANDLIST;
}
Ejemplo n.º 17
0
BOOL CArborEdit::OnKillfocus() 
{
   // check to see if the control was modified at all....if so continue
   if( GetModify() )
   {
	   // check to see if any value has been entered into the control....
	   if( GetWindowTextLength() )
	   {
           //CAMqa72199 Wasabi - check for non-JIS chars in text field
           //Note that this code disallows extended Japanese characters
           //which are used in some proper names
           CString ControlText;
           if (ArbI18N::IsJapanese() || ArbI18N::IsBidi() ) 
           {
           	GetWindowText(ControlText);
	           int ctl = ControlText.GetLength();
	           int cursor = 0;
	           bool ok = true;
	           while ((cursor < ctl) && ok)
	           {
	               TCHAR c = ControlText[cursor];
	               if (IsDBCSLeadByteEx(932, c))
	               {
	                   cursor++; //skip trail byte if in a double byte char
					   //CAMqa77746 applying CAMqa70838 - delete the non-JIS character check
	               }
	               cursor++;
	           }
	           if (!ok)
	           {
	               AfxMessageBox(GetIntlString(IDS_GUI_MSG_INVALID_INPUT_CHAR), MB_ICONERROR);
	               SetSel( 0, -1 );
	               SetFocus();
	               AfxThrowUserException();
	           }
           } //CAMqa72199 End Japanese-only processing
		  if( EditStyleIs(EDIT_CURRENCY) || EditStyleIs(EDIT_FLOAT) ) 
			{
				double dTemp = GetDoubleValue();

				LPTSTR buff = new char[80];
				FloatToString( buff, dTemp) ;
				SetWindowText(buff);
				SetModify( TRUE ); 
				delete buff;
			}
			else 	if( EditStyleIs( EDIT_DATE	) )
			{
				CString ControlText;
				// Extract the text from the exit control and then 
				GetWindowText(ControlText);
															//we have to re-format Date on case if Date = "x/x/xx"
				//otherwise  ValidateDate()	function return FALSE
				COleDateTime oleDate;			
				//TCHAR year[5];
				
				if( !ParseDate( ControlText, oleDate ) ||						
				( oleDate.GetStatus() == COleDateTime::invalid ))  // invalid date
				{	 
					return FALSE;   // no message Boxes
				}


	         Arb_date CDate;
			char strdate[GAL_DATE_LEN];

        	CDate.year = oleDate.GetYear();
			CDate.month = oleDate.GetMonth();
			CDate.day = oleDate.GetDay();
			strcpy(strdate,(CString)Arbdate_to_string(&CDate,ArbI18N::GetSysDateFmt()));
			CString Text = CString(strdate);
			SetWindowText(Text);
			SetModify( TRUE ); 
				
			//SetWindowText(ControlText);
			SetModify( TRUE ); 
			}
		}
   }

   return FALSE;

}
Ejemplo n.º 18
0
static void test_threadcp(void)
{
    static const LCID ENGLISH  = MAKELCID(MAKELANGID(LANG_ENGLISH,  SUBLANG_ENGLISH_US),         SORT_DEFAULT);
    static const LCID HINDI    = MAKELCID(MAKELANGID(LANG_HINDI,    SUBLANG_HINDI_INDIA),        SORT_DEFAULT);
    static const LCID GEORGIAN = MAKELCID(MAKELANGID(LANG_GEORGIAN, SUBLANG_GEORGIAN_GEORGIA),   SORT_DEFAULT);
    static const LCID RUSSIAN  = MAKELCID(MAKELANGID(LANG_RUSSIAN,  SUBLANG_RUSSIAN_RUSSIA),     SORT_DEFAULT);
    static const LCID JAPANESE = MAKELCID(MAKELANGID(LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN),     SORT_DEFAULT);
    static const LCID CHINESE  = MAKELCID(MAKELANGID(LANG_CHINESE,  SUBLANG_CHINESE_SIMPLIFIED), SORT_DEFAULT);

    BOOL islead, islead_acp;
    CPINFOEXA cpi;
    UINT cp, acp;
    int  i, num;
    LCID last;
    BOOL ret;

    struct test {
        LCID lcid;
        UINT threadcp;
    } lcids[] = {
        { HINDI,    0    },
        { GEORGIAN, 0    },
        { ENGLISH,  1252 },
        { RUSSIAN,  1251 },
        { JAPANESE, 932  },
        { CHINESE,  936  }
    };

    struct test_islead_nocp {
        LCID lcid;
        BYTE testchar;
    } isleads_nocp[] = {
        { HINDI,    0x00 },
        { HINDI,    0x81 },
        { HINDI,    0xa0 },
        { HINDI,    0xe0 },

        { GEORGIAN, 0x00 },
        { GEORGIAN, 0x81 },
        { GEORGIAN, 0xa0 },
        { GEORGIAN, 0xe0 },
    };

    struct test_islead {
        LCID lcid;
        BYTE testchar;
        BOOL islead;
    } isleads[] = {
        { ENGLISH,  0x00, FALSE },
        { ENGLISH,  0x81, FALSE },
        { ENGLISH,  0xa0, FALSE },
        { ENGLISH,  0xe0, FALSE },

        { RUSSIAN,  0x00, FALSE },
        { RUSSIAN,  0x81, FALSE },
        { RUSSIAN,  0xa0, FALSE },
        { RUSSIAN,  0xe0, FALSE },

        { JAPANESE, 0x00, FALSE },
        { JAPANESE, 0x81,  TRUE },
        { JAPANESE, 0xa0, FALSE },
        { JAPANESE, 0xe0,  TRUE },

        { CHINESE,  0x00, FALSE },
        { CHINESE,  0x81,  TRUE },
        { CHINESE,  0xa0,  TRUE },
        { CHINESE,  0xe0,  TRUE },
    };

    last = GetThreadLocale();
    acp  = GetACP();

    for (i = 0; i < sizeof(lcids)/sizeof(lcids[0]); i++)
    {
        SetThreadLocale(lcids[i].lcid);

        cp = 0xdeadbeef;
        GetLocaleInfoA(lcids[i].lcid, LOCALE_IDEFAULTANSICODEPAGE|LOCALE_RETURN_NUMBER, (LPSTR)&cp, sizeof(cp));
        ok(cp == lcids[i].threadcp, "wrong codepage %u for lcid %04x, should be %u\n", cp, lcids[i].threadcp, cp);

        /* GetCPInfoEx/GetCPInfo - CP_ACP */
        SetLastError(0xdeadbeef);
        memset(&cpi, 0, sizeof(cpi));
        ret = GetCPInfoExA(CP_ACP, 0, &cpi);
        ok(ret, "GetCPInfoExA failed for lcid %04x, error %d\n", lcids[i].lcid, GetLastError());
        ok(cpi.CodePage == acp, "wrong codepage %u for lcid %04x, should be %u\n", cpi.CodePage, lcids[i].lcid, acp);

        /* WideCharToMultiByte - CP_ACP */
        num = WideCharToMultiByte(CP_ACP, 0, foobarW, -1, NULL, 0, NULL, NULL);
        ok(num == 7, "ret is %d (%04x)\n", num, lcids[i].lcid);

        /* MultiByteToWideChar - CP_ACP */
        num = MultiByteToWideChar(CP_ACP, 0, "foobar", -1, NULL, 0);
        ok(num == 7, "ret is %d (%04x)\n", num, lcids[i].lcid);

        /* GetCPInfoEx/GetCPInfo - CP_THREAD_ACP */
        SetLastError(0xdeadbeef);
        memset(&cpi, 0, sizeof(cpi));
        ret = GetCPInfoExA(CP_THREAD_ACP, 0, &cpi);
        ok(ret, "GetCPInfoExA failed for lcid %04x, error %d\n", lcids[i].lcid, GetLastError());
        if (lcids[i].threadcp)
            ok(cpi.CodePage == lcids[i].threadcp, "wrong codepage %u for lcid %04x, should be %u\n",
               cpi.CodePage, lcids[i].lcid, lcids[i].threadcp);
        else
            ok(cpi.CodePage == acp, "wrong codepage %u for lcid %04x, should be %u\n",
               cpi.CodePage, lcids[i].lcid, acp);

        /* WideCharToMultiByte - CP_THREAD_ACP */
        num = WideCharToMultiByte(CP_THREAD_ACP, 0, foobarW, -1, NULL, 0, NULL, NULL);
        ok(num == 7, "ret is %d (%04x)\n", num, lcids[i].lcid);

        /* MultiByteToWideChar - CP_THREAD_ACP */
        num = MultiByteToWideChar(CP_THREAD_ACP, 0, "foobar", -1, NULL, 0);
        ok(num == 7, "ret is %d (%04x)\n", num, lcids[i].lcid);
    }

    /* IsDBCSLeadByteEx - locales without codepage */
    for (i = 0; i < sizeof(isleads_nocp)/sizeof(isleads_nocp[0]); i++)
    {
        SetThreadLocale(isleads_nocp[i].lcid);

        islead_acp = IsDBCSLeadByteEx(CP_ACP,        isleads_nocp[i].testchar);
        islead     = IsDBCSLeadByteEx(CP_THREAD_ACP, isleads_nocp[i].testchar);

        ok(islead == islead_acp, "wrong islead %i for test char %x in lcid %04x.  should be %i\n",
            islead, isleads_nocp[i].testchar, isleads_nocp[i].lcid, islead_acp);
    }

    /* IsDBCSLeadByteEx - locales with codepage */
    for (i = 0; i < sizeof(isleads)/sizeof(isleads[0]); i++)
    {
        SetThreadLocale(isleads[i].lcid);

        islead = IsDBCSLeadByteEx(CP_THREAD_ACP, isleads[i].testchar);
        ok(islead == isleads[i].islead, "wrong islead %i for test char %x in lcid %04x.  should be %i\n",
            islead, isleads[i].testchar, isleads[i].lcid, isleads[i].islead);
    }

    SetThreadLocale(last);
}
Ejemplo n.º 19
0
errno_t __cdecl _cgetws_s (
        wchar_t *string,
        size_t sizeInWords,
        size_t * pSizeRead
        )
{
        ULONG oldstate;
        ULONG num_read;
        errno_t err = 0;

        _VALIDATE_CLEAR_OSSERR_RETURN_ERRCODE((string != NULL), EINVAL);
        _VALIDATE_CLEAR_OSSERR_RETURN_ERRCODE((sizeInWords > 0), EINVAL);
        _RESET_STRING(string, sizeInWords);

        _VALIDATE_CLEAR_OSSERR_RETURN_ERRCODE((pSizeRead != NULL), EINVAL);

        _mlock(_CONIO_LOCK);            /* lock the console */
        __TRY

            /*
             * We need to decrement sizeInWords because ReadConsole reads as
             * many characters as the parameter passed, doesn't null terminate
             */

            --sizeInWords;
            *pSizeRead = 0;

            /*
             * If the __console_whcar_buffer_used is set, then first fill the
             * buffered character and then proceed.
             */
            if (__console_wchar_buffer_used != 0 && sizeInWords > 0)
            {
                *string++ = __console_wchar_buffer;
                __console_wchar_buffer = 0;
                --sizeInWords;
                (*pSizeRead)++;
                if (__console_wchar_buffer == L'\0')
                    sizeInWords = 0;
            }

                        /* if the user only asked for one character, we have now filled their request
                        */
            if (sizeInWords != 0)
                        {
                                /*
                                * _coninpfh, the handle to the console input, is created the first
                                * time that either _getch() or _cgets() or _kbhit() is called.
                                */

                                if ( _coninpfh == -2 )
                                        __initconin();

                                if ( _coninpfh != -1 ) {

                                        GetConsoleMode( (HANDLE)_coninpfh, &oldstate );
                                        SetConsoleMode( (HANDLE)_coninpfh, ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT );
                                        // First try usual way just as _cgets
                                        if ( bUseW)
                                        {
                                                if ( !ReadConsoleW( (HANDLE)_coninpfh,
                                                                                        (LPVOID)string,
                                                                                        (DWORD)sizeInWords,
                                                                                        &num_read,
                                                                                        NULL )
                                                        )
                                                {
                                                        if ( bUseW == 2 )
                                                        {
                                                                if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
                                                                        bUseW = FALSE;
                                                                else
                                                                        bUseW = TRUE;
                                                        }
                                                }
                                                else
                                                {
                                                        bUseW = TRUE;

                                                        /* set length of string and null terminate it */

                                                        if (string[num_read - 2] == L'\r') {
                                                                (*pSizeRead) += num_read - 2;
                                                                string[num_read - 2] = L'\0';
                                                        } else if ( (num_read == sizeInWords) &&
                                                                                (string[num_read - 1] == L'\r') ) {
                                                        /* special case 1 - \r\n straddles the boundary */
                                                                (*pSizeRead) += num_read -1;
                                                                string[num_read - 1] = L'\0';
                                                        } else if ( (num_read == 1) && (string[0] == L'\n') ) {
                                                                /* special case 2 - read a single '\n'*/
                                                                string[0] = L'\0';
                                                                (*pSizeRead) += 0;
                                                        } else {
                                                                (*pSizeRead) += num_read;
                                                                string[num_read] = L'\0';
                                                        }
                                                }
                                        }
                                        // If ReadConsoleW is not present, use ReadConsoleA and then convert
                                        // to Wide Char.
                                        if ( !bUseW)
                                        {
                                                static char AStr[BUF_MAX_LEN +1];
                                                static int in_buff = 0, was_buff_full = 0;
                                                unsigned int Copy, Sz, consoleCP;
                                                unsigned int last_read = 0, i;
                                                consoleCP = GetConsoleCP();
                                                do {
                                                        if (!in_buff)
                                                        {
                                                                if ( ReadConsoleA( (HANDLE)_coninpfh,
                                                                                                        (LPVOID)AStr,
                                                                                                        BUF_MAX_LEN,
                                                                                                        &num_read,
                                                                                   NULL) &&
                                                                     num_read <= BUF_MAX_LEN
                                                                        ) {
                                                                        if (num_read >= 2 && AStr[num_read -2] == '\r')
                                                                        {
                                                                                AStr[num_read -2] = '\0';
                                                                        }
                                                                        else if (num_read == BUF_MAX_LEN &&
                                                                                        AStr[num_read -1] == '\r')
                                                                                AStr[num_read -1] = '\0';
                                                                        else if (num_read == 1 && AStr[0] == '\n')
                                                                                AStr[0] = '\0';
                                                                        else
                                                                                AStr[num_read] = '\0';
                                                                } else {
                                                                        _dosmaperr(GetLastError());
                                                                        err = errno;
                                                                }
                                                        }
                                                        for ( i = 0; AStr[i] != '\0' &&
                                                                                i < (BUF_MAX_LEN) &&
                                                                                last_read < sizeInWords; i += Sz)
                                                        {
                                                                // Check if this character is lead byte. If yes, the size
                                                                // of this character is 2. Else 1.
                                                                if ( IsDBCSLeadByteEx( GetConsoleCP(), AStr[i]))
                                                                        Sz = 2;
                                                                else
                                                                        Sz = 1;
                                                                if ( (Copy = MultiByteToWideChar( consoleCP,
                                                                                                                                MB_PRECOMPOSED | MB_ERR_INVALID_CHARS,
                                                                                                                                &AStr[i],
                                                                                                                                Sz,
                                                                                                                                &string[last_read],
                                                                                                                                (int)sizeInWords - last_read)))
                                                                {
                                                                        last_read += Copy;
                                                                }
                                                        }
                                                        // Check if this conversion was from buffer. If yes, was
                                                        // buffer fully filled when it was first read using
                                                        // ReadConsoleA. If the buffer not fully filled, we don't need
                                                        // to read more from buffer. This is necessary to make it
                                                        // behave same as if we are reading using ReadConsoleW.
                                                        if ( in_buff && i == strlen(AStr))
                                                        {
                                                                in_buff = 0;
                                                                if ( was_buff_full)
                                                                {
                                                                        was_buff_full = 0;
                                                                        continue;
                                                                }
                                                                else
                                                                {
                                                                        break;
                                                                }
                                                        }
                                                        else if ( i < (BUF_MAX_LEN))
                                                                break;
                                                } while (last_read < sizeInWords);
                                                // We save the buffer to be used again.
                                                if ( i < strlen(AStr))
                                                {
                                                        in_buff = 1;
                                                        if ( strlen(AStr) == (BUF_MAX_LEN))
                                                                was_buff_full = 1;
                                                        memmove(AStr, &AStr[i], BUF_MAX_LEN +1 - i);
                                                }
                                                string[last_read] = '\0';
                                                (*pSizeRead) += last_read;
                                        }

                                        SetConsoleMode( (HANDLE)_coninpfh, oldstate );
                                } else {
                                        _dosmaperr(GetLastError());
                                        err = errno;
                                }
                        }

        __FINALLY
            _munlock(_CONIO_LOCK);          /* unlock the console */
        __END_TRY_FINALLY

        if (err != 0)
        {
            errno = err;
        }
        return err;
}
Ejemplo n.º 20
0
Archivo: rc.c Proyecto: mingpen/OpenNT
void _CRTAPI1 _splitpath (
    register const char *path,
    char *drive,
    char *dir,
    char *fname,
    char *ext
    )
{
    register char *p;
    char *last_slash = NULL, *dot = NULL;
    unsigned len;

    /* we assume that the path argument has the following form, where any
     * or all of the components may be missing.
     *
     *  <drive><dir><fname><ext>
     *
     * and each of the components has the following expected form(s)
     *
     *  drive:
     *  0 to _MAX_DRIVE-1 characters, the last of which, if any, is a
     *  ':'
     *  dir:
     *  0 to _MAX_DIR-1 characters in the form of an absolute path
     *  (leading '/' or '\') or relative path, the last of which, if
     *  any, must be a '/' or '\'.  E.g -
     *  absolute path:
     *      \top\next\last\     ; or
     *      /top/next/last/
     *  relative path:
     *      top\next\last\  ; or
     *      top/next/last/
     *  Mixed use of '/' and '\' within a path is also tolerated
     *  fname:
     *  0 to _MAX_FNAME-1 characters not including the '.' character
     *  ext:
     *  0 to _MAX_EXT-1 characters where, if any, the first must be a
     *  '.'
     *
     */

    /* extract drive letter and :, if any */

    if (*(path + _MAX_DRIVE - 2) == ':') {
    if (drive) {
        strncpy(drive, path, _MAX_DRIVE - 1);
        *(drive + _MAX_DRIVE-1) = '\0';
    }
    path += _MAX_DRIVE - 1;
    }
    else if (drive) {
    *drive = '\0';
    }

    /* extract path string, if any.  Path now points to the first character
     * of the path, if any, or the filename or extension, if no path was
     * specified.  Scan ahead for the last occurence, if any, of a '/' or
     * '\' path separator character.  If none is found, there is no path.
     * We will also note the last '.' character found, if any, to aid in
     * handling the extension.
     */

    for (last_slash = NULL, p = (char *)path; *p; p++) {
        if (IsDBCSLeadByteEx(uiCodePage, *p))
        p++;
    else {
        if (*p == '/' || *p == '\\')
        /* point to one beyond for later copy */
        last_slash = p + 1;
        else if (*p == '.')
        dot = p;
    }
    }

    if (last_slash) {

    /* found a path - copy up through last_slash or max. characters
     * allowed, whichever is smaller
     */

    if (dir) {
        len = __min((last_slash - path), (_MAX_DIR - 1));
        strncpy(dir, path, len);
        *(dir + len) = '\0';
    }
    path = last_slash;
    }
    else if (dir) {

    /* no path found */

    *dir = '\0';
    }

    /* extract file name and extension, if any.  Path now points to the
     * first character of the file name, if any, or the extension if no
     * file name was given.  Dot points to the '.' beginning the extension,
     * if any.
     */

    if (dot && (dot >= path)) {
    /* found the marker for an extension - copy the file name up to
     * the '.'.
     */
    if (fname) {
        len = __min((dot - path), (_MAX_FNAME - 1));
        strncpy(fname, path, len);
        *(fname + len) = '\0';
    }
    /* now we can get the extension - remember that p still points
     * to the terminating nul character of path.
     */
    if (ext) {
        len = __min((p - dot), (_MAX_EXT - 1));
        strncpy(ext, dot, len);
        *(ext + len) = '\0';
    }
    }
    else {
    /* found no extension, give empty extension and copy rest of
     * string into fname.
     */
    if (fname) {
        len = __min((p - path), (_MAX_FNAME - 1));
        strncpy(fname, path, len);
        *(fname + len) = '\0';
    }
    if (ext) {
        *ext = '\0';
    }
    }
}