Example #1
0
/***
*BOOL __get_qualified_locale - return fully qualified locale
*
*Purpose:
*  get default locale, qualify partially complete locales
*
*Entry:
*       dwType - indicates type of lpInput, either QF_STRINGS or QF_LCID
*       lpInput - input string/id to be qualified
*       lpOutId - pointer to output id, may be NULL if lpOutStr is !NULL
*       lpOutStr - pointer to output string, may be NULL if lpOutId is !NULL
*
*Exit:
*       TRUE if success, qualified locale is valid
*       FALSE if failure
*
*Exceptions:
*
*******************************************************************************/
BOOL __cdecl __get_qualified_locale(
        const LPLC_STRINGS lpInStr,
        LPLC_ID lpOutId,
        LPLC_STRINGS lpOutStr
        )
{
        LC_ID Id;
        LCID cpLCID;
        BOOL fOCP = FALSE;
        WCHAR wcsTemp[MAX_TEMP_STR_LEN];

        if (!lpOutId && !lpOutStr)
            return FALSE;

        Id.wLanguage = (WORD)0;
        Id.wCountry = (WORD)0;
        Id.wCodePage = (WORD)0;

        /* -----------------------------------------------------------------------
        stage 1: convert input to internal LC_ID.
        -----------------------------------------------------------------------*/

        if (lpInStr->szLanguage
        && *(lpInStr->szLanguage)
        && (!(Id.wLanguage =
        trans_lang_lang((const PSZ)lpInStr->szLanguage))))
            return FALSE;

        if (lpInStr->szCountry
        && *(lpInStr->szCountry)
        && (!(Id.wCountry =
        trans_ctry_ctry((const PSZ)lpInStr->szCountry))))
            return FALSE;

        if (lpInStr->szCodePage
        && *(lpInStr->szCodePage))
        {
            /* ACP is the default anyway */
            if (!strcmp(lpInStr->szCodePage, "ACP"))
                /* do nothing */ ;

            /* if OCP, set flag */
            else if (!strcmp(lpInStr->szCodePage, "OCP"))
                fOCP = TRUE;

            /* user supplied a code page */
            else if (!(Id.wCodePage =
                atoi((const char *)lpInStr->szCodePage)))
                return FALSE;
        }

        /* -----------------------------------------------------------------------
        stage 2: qualify internal LC_ID
        -----------------------------------------------------------------------*/

        if (!Id.wLanguage)
        {
            /* language undefined*/
            if (!Id.wCountry)
            {
                /* language undefined, country undefined*/
                Id.wLanguage = Id.wCountry = LANGIDFROMLCID(GetUserDefaultLCID());

                if (!Id.wCodePage)
                    cpLCID = GetUserDefaultLCID();
            }
            else {
                /* language undefined, country defined*/
                Id.wCountry = Id.wLanguage = trans_ctry_lang(Id.wCountry);

                if (!Id.wCodePage)
                    cpLCID = MAKELCID(Id.wCountry, SORT_DEFAULT);
            }
        }
        else {
            /* language defined*/
            if (!Id.wCountry)
            {
                /* language defined, country undefined*/
                Id.wCountry = Id.wLanguage;

                if (!Id.wCodePage)
                    cpLCID = MAKELCID(Id.wCountry, SORT_DEFAULT);
            }
            else {
                /* language defined, country defined*/

                /* match and set country and language*/
                if (!match_ctry_lang((WORD *)&Id.wCountry, (WORD *)&Id.wLanguage))
                    return FALSE;

                if (!Id.wCodePage)
                    cpLCID = MAKELCID(Id.wCountry, SORT_DEFAULT);
            }
        }

        if (!Id.wCodePage)
        {
            if (__crtGetLocaleInfoW(cpLCID,
                                (fOCP) ? LOCALE_IDEFAULTCODEPAGE :
                                         LOCALE_IDEFAULTANSICODEPAGE,
                                wcsTemp,
                                MAX_TEMP_STR_LEN,
                                0)
                            == 0)
                return FALSE;

            Id.wCodePage = (WORD)wcstol(wcsTemp, NULL, 10);
        }

        /*
         * Must verify ALL code pages - even those coming from OS.
         */

        if (!IsValidCodePage(Id.wCodePage))
            return FALSE;

        /*
         * Must verify locale is installed.
         */

        if (!IsValidLocale(MAKELCID(Id.wLanguage, SORT_DEFAULT), LCID_INSTALLED))
            return FALSE;

        /* -----------------------------------------------------------------------
        stage 3: convert to proper output format
        -----------------------------------------------------------------------*/

        if (lpOutId)
        {
            *lpOutId = Id;
        }

        if (lpOutStr)
        {
            if (__crtGetLocaleInfoA(MAKELCID(Id.wLanguage, SORT_DEFAULT), LOCALE_SENGLANGUAGE, lpOutStr->szLanguage, MAX_LANG_LEN, 0)
                == 0)
                return FALSE;

            if (__crtGetLocaleInfoA(MAKELCID(Id.wCountry, SORT_DEFAULT), LOCALE_SENGCOUNTRY, lpOutStr->szCountry, MAX_CTRY_LEN, 0)
                == 0)
                return FALSE;

            _itoa((int)Id.wCodePage, (char *)lpOutStr->szCodePage, 10);
        }
        return TRUE;
}
Example #2
0
void CPreferences::InitThreadLocale()
{
	ASSERT( m_wLanguageID != 0 );

	// NOTE: This function is for testing multi language support only.
	// NOTE: This function is *NOT* to be enabled in release builds nor to be offered by any Mod!
	if (theApp.GetProfileInt(_T("eMule"), _T("SetLanguageACP"), 0) != 0)
	{
		//LCID lcidUser = GetUserDefaultLCID();		// Installation, or altered by user in control panel (WinXP)

		// get the ANSI codepage which is to be used for all non-Unicode conversions.
		LANGID lidSystem = m_wLanguageID;

		// get user's sorting preferences
		//UINT uSortIdUser = SORTIDFROMLCID(lcidUser);
		//UINT uSortVerUser = SORTVERSIONFROMLCID(lcidUser);
		// we can't use the same sorting paramters for 2 different Languages..
		UINT uSortIdUser = SORT_DEFAULT;
		UINT uSortVerUser = 0;

		// set thread locale, this is used for:
		//	- MBCS->Unicode conversions (e.g. search results).
		//	- Unicode->MBCS conversions (e.g. publishing local files (names) in network, or savint text files on local disk)...
		LCID lcid = MAKESORTLCID(lidSystem, uSortIdUser, uSortVerUser);
		SetThreadLocale(lcid);

		// if we set the thread locale (see comments above) we also have to specify the proper
		// codepage for the C-RTL, otherwise we may not be able to store some strings as MBCS
		// (Unicode->MBCS conversion may fail)
		SetRtlLocale(lcid);
	}
	else if (theApp.GetProfileInt(_T("eMule"), _T("SetSystemACP"), 0) != 0)
	{
		LCID lcidSystem = GetSystemDefaultLCID();	// Installation, or altered by user in control panel (WinXP)
		//LCID lcidUser = GetUserDefaultLCID();		// Installation, or altered by user in control panel (WinXP)

		// get the ANSI codepage which is to be used for all non-Unicode conversions.
		LANGID lidSystem = LANGIDFROMLCID(lcidSystem);

		// get user's sorting preferences
		//UINT uSortIdUser = SORTIDFROMLCID(lcidUser);
		//UINT uSortVerUser = SORTVERSIONFROMLCID(lcidUser);
		// we can't use the same sorting paramters for 2 different Languages..
		UINT uSortIdUser = SORT_DEFAULT;
		UINT uSortVerUser = 0;

		// create a thread locale which gives full backward compability for users which had run ANSI emule on 
		// a system where the system's code page did not match the user's language..
		LCID lcid = MAKESORTLCID(lidSystem, uSortIdUser, uSortVerUser);
		LCID lcidThread = GetThreadLocale();
		if (lcidThread != lcid)
		{
			TRACE("+++ Setting thread locale: 0x%08x\n", lcid);
			SetThreadLocale(lcid);

			// if we set the thread locale (see comments above) we also have to specify the proper
			// codepage for the C-RTL, otherwise we may not be able to store some strings as MBCS
			// (Unicode->MBCS conversion may fail)
			SetRtlLocale(lcid);
		}
	}
}
Example #3
0
static char *
win32_getlocale (void)
{
	LCID lcid;
	LANGID langid;
	char *ev;
	int primary, sub;
	char bfr[64];
	char iso639[10];
	char iso3166[10];
	const char *script = NULL;

	/* Let the user override the system settings through environment
	 * variables, as on POSIX systems. Note that in GTK+ applications
	 * since GTK+ 2.10.7 setting either LC_ALL or LANG also sets the
	 * Win32 locale and C library locale through code in gtkmain.c.
	 */
	if (((ev = getenv ("LC_ALL")) != NULL && ev[0] != '\0')
	 || ((ev = getenv ("LC_MESSAGES")) != NULL && ev[0] != '\0')
	 || ((ev = getenv ("LANG")) != NULL && ev[0] != '\0'))
		return safe_strdup (ev);

	lcid = GetThreadLocale ();

	if (!GetLocaleInfo (lcid, LOCALE_SISO639LANGNAME, iso639, sizeof (iso639)) ||
	    !GetLocaleInfo (lcid, LOCALE_SISO3166CTRYNAME, iso3166, sizeof (iso3166)))
		return safe_strdup ("C");

	/* Strip off the sorting rules, keep only the language part.	*/
	langid = LANGIDFROMLCID (lcid);

	/* Split into language and territory part.	*/
	primary = PRIMARYLANGID (langid);
	sub = SUBLANGID (langid);

	/* Handle special cases */
	switch (primary)
	{
		case LANG_AZERI:
			switch (sub)
			{
				case SUBLANG_AZERI_LATIN:
					script = "@Latn";
					break;
				case SUBLANG_AZERI_CYRILLIC:
					script = "@Cyrl";
					break;
			}
			break;
		case LANG_SERBIAN:								/* LANG_CROATIAN == LANG_SERBIAN */
			switch (sub)
			{
				case SUBLANG_SERBIAN_LATIN:
				case 0x06: /* Serbian (Latin) - Bosnia and Herzegovina */
					script = "@Latn";
					break;
			}
			break;
		case LANG_UZBEK:
			switch (sub)
			{
				case SUBLANG_UZBEK_LATIN:
					script = "@Latn";
					break;
				case SUBLANG_UZBEK_CYRILLIC:
					script = "@Cyrl";
					break;
			}
			break;
	}

	strcat (bfr, iso639);
	strcat (bfr, "_");
	strcat (bfr, iso3166);

	if (script)
		strcat (bfr, script);

	return safe_strdup (bfr);
}
Example #4
0
/*static*/ int wxLocale::GetSystemLanguage()
{
    CreateLanguagesDB();

    // init i to avoid compiler warning
    size_t i = 0,
        count = ms_languagesDB->GetCount();

#if defined(__UNIX__)
    // first get the string identifying the language from the environment
    wxString langFull;
#ifdef __WXMAC__
    wxCFRef<CFLocaleRef> userLocaleRef(CFLocaleCopyCurrent());

    // because the locale identifier (kCFLocaleIdentifier) is formatted a little bit differently, eg
    // az_Cyrl_AZ@calendar=buddhist;currency=JPY we just recreate the base info as expected by wx here

    wxCFStringRef str(wxCFRetain((CFStringRef)CFLocaleGetValue(userLocaleRef, kCFLocaleLanguageCode)));
    langFull = str.AsString()+"_";
    str.reset(wxCFRetain((CFStringRef)CFLocaleGetValue(userLocaleRef, kCFLocaleCountryCode)));
    langFull += str.AsString();
#else
    if (!wxGetEnv(wxS("LC_ALL"), &langFull) &&
        !wxGetEnv(wxS("LC_MESSAGES"), &langFull) &&
        !wxGetEnv(wxS("LANG"), &langFull))
    {
        // no language specified, treat it as English
        return wxLANGUAGE_ENGLISH_US;
    }

    if ( langFull == wxS("C") || langFull == wxS("POSIX") )
    {
        // default C locale is English too
        return wxLANGUAGE_ENGLISH_US;
    }
#endif

    // the language string has the following form
    //
    //      lang[_LANG][.encoding][@modifier]
    //
    // (see environ(5) in the Open Unix specification)
    //
    // where lang is the primary language, LANG is a sublang/territory,
    // encoding is the charset to use and modifier "allows the user to select
    // a specific instance of localization data within a single category"
    //
    // for example, the following strings are valid:
    //      fr
    //      fr_FR
    //      de_DE.iso88591
    //      de_DE@euro
    //      de_DE.iso88591@euro

    // for now we don't use the encoding, although we probably should (doing
    // translations of the msg catalogs on the fly as required) (TODO)
    //
    // we need the modified for languages like Valencian: ca_ES@valencia
    // though, remember it
    wxString modifier;
    size_t posModifier = langFull.find_first_of(wxS("@"));
    if ( posModifier != wxString::npos )
        modifier = langFull.Mid(posModifier);

    size_t posEndLang = langFull.find_first_of(wxS("@."));
    if ( posEndLang != wxString::npos )
    {
        langFull.Truncate(posEndLang);
    }

    // do we have just the language (or sublang too)?
    const bool justLang = langFull.find('_') == wxString::npos;

    // 0. Make sure the lang is according to latest ISO 639
    //    (this is necessary because glibc uses iw and in instead
    //    of he and id respectively).

    // the language itself (second part is the dialect/sublang)
    wxString langOrig = ExtractLang(langFull);

    wxString lang;
    if ( langOrig == wxS("iw"))
        lang = wxS("he");
    else if (langOrig == wxS("in"))
        lang = wxS("id");
    else if (langOrig == wxS("ji"))
        lang = wxS("yi");
    else if (langOrig == wxS("no_NO"))
        lang = wxS("nb_NO");
    else if (langOrig == wxS("no_NY"))
        lang = wxS("nn_NO");
    else if (langOrig == wxS("no"))
        lang = wxS("nb_NO");
    else
        lang = langOrig;

    // did we change it?
    if ( lang != langOrig )
    {
        langFull = lang + ExtractNotLang(langFull);
    }

    // 1. Try to find the language either as is:
    // a) With modifier if set
    if ( !modifier.empty() )
    {
        wxString langFullWithModifier = langFull + modifier;
        for ( i = 0; i < count; i++ )
        {
            if ( ms_languagesDB->Item(i).CanonicalName == langFullWithModifier )
                break;
        }
    }

    // b) Without modifier
    if ( modifier.empty() || i == count )
    {
        for ( i = 0; i < count; i++ )
        {
            if ( ms_languagesDB->Item(i).CanonicalName == langFull )
                break;
        }
    }

    // 2. If langFull is of the form xx_YY, try to find xx:
    if ( i == count && !justLang )
    {
        for ( i = 0; i < count; i++ )
        {
            if ( ms_languagesDB->Item(i).CanonicalName == lang )
            {
                break;
            }
        }
    }

    // 3. If langFull is of the form xx, try to find any xx_YY record:
    if ( i == count && justLang )
    {
        for ( i = 0; i < count; i++ )
        {
            if ( ExtractLang(ms_languagesDB->Item(i).CanonicalName)
                    == langFull )
            {
                break;
            }
        }
    }


    if ( i == count )
    {
        // In addition to the format above, we also can have full language
        // names in LANG env var - for example, SuSE is known to use
        // LANG="german" - so check for use of non-standard format and try to
        // find the name in verbose description.
        for ( i = 0; i < count; i++ )
        {
            if (ms_languagesDB->Item(i).Description.CmpNoCase(langFull) == 0)
            {
                break;
            }
        }
    }
#elif defined(__WIN32__)
    LCID lcid = GetUserDefaultLCID();
    if ( lcid != 0 )
    {
        wxUint32 lang = PRIMARYLANGID(LANGIDFROMLCID(lcid));
        wxUint32 sublang = SUBLANGID(LANGIDFROMLCID(lcid));

        for ( i = 0; i < count; i++ )
        {
            if (ms_languagesDB->Item(i).WinLang == lang &&
                ms_languagesDB->Item(i).WinSublang == sublang)
            {
                break;
            }
        }
    }
    //else: leave wxlang == wxLANGUAGE_UNKNOWN
#endif // Unix/Win32

    if ( i < count )
    {
        // we did find a matching entry, use it
        return ms_languagesDB->Item(i).Language;
    }

    // no info about this language in the database
    return wxLANGUAGE_UNKNOWN;
}
Example #5
0
/**********************************************************************
 *  find_entry
 *
 * Find a resource entry
 */
static NTSTATUS find_entry( HMODULE hmod, const LDR_RESOURCE_INFO *info,
                            ULONG level, const void **ret, int want_dir )
{
    ULONG size;
    const void *root;
    const IMAGE_RESOURCE_DIRECTORY *resdirptr;
    WORD list[9];  /* list of languages to try */
    int i, pos = 0;

    root = RtlImageDirectoryEntryToData( hmod, TRUE, IMAGE_DIRECTORY_ENTRY_RESOURCE, &size );
    if (!root) return STATUS_RESOURCE_DATA_NOT_FOUND;
    if (size < sizeof(*resdirptr)) return STATUS_RESOURCE_DATA_NOT_FOUND;
    resdirptr = root;

    if (!level--) goto done;
    if (!(*ret = find_entry_by_name( resdirptr, (LPCWSTR)info->Type, root, want_dir || level )))
        return STATUS_RESOURCE_TYPE_NOT_FOUND;
    if (!level--) return STATUS_SUCCESS;

    resdirptr = *ret;
    if (!(*ret = find_entry_by_name( resdirptr, (LPCWSTR)info->Name, root, want_dir || level )))
        return STATUS_RESOURCE_NAME_NOT_FOUND;
    if (!level--) return STATUS_SUCCESS;
    if (level) return STATUS_INVALID_PARAMETER;  /* level > 3 */

    /* 1. specified language */
    pos = push_language( list, pos, info->Language );

    /* 2. specified language with neutral sublanguage */
    pos = push_language( list, pos, MAKELANGID( PRIMARYLANGID(info->Language), SUBLANG_NEUTRAL ) );

    /* 3. neutral language with neutral sublanguage */
    pos = push_language( list, pos, MAKELANGID( LANG_NEUTRAL, SUBLANG_NEUTRAL ) );

    /* if no explicitly specified language, try some defaults */
    if (PRIMARYLANGID(info->Language) == LANG_NEUTRAL)
    {
        /* user defaults, unless SYS_DEFAULT sublanguage specified  */
        if (SUBLANGID(info->Language) != SUBLANG_SYS_DEFAULT)
        {
            /* 4. current thread locale language */
            pos = push_language( list, pos, LANGIDFROMLCID(NtCurrentTeb()->CurrentLocale) );

            /* 5. user locale language */
            pos = push_language( list, pos, LANGIDFROMLCID(user_lcid) );

            /* 6. user locale language with neutral sublanguage  */
            pos = push_language( list, pos, MAKELANGID( PRIMARYLANGID(user_lcid), SUBLANG_NEUTRAL ) );
        }

        /* now system defaults */

        /* 7. system locale language */
        pos = push_language( list, pos, LANGIDFROMLCID( system_lcid ) );

        /* 8. system locale language with neutral sublanguage */
        pos = push_language( list, pos, MAKELANGID( PRIMARYLANGID(system_lcid), SUBLANG_NEUTRAL ) );

        /* 9. English */
        pos = push_language( list, pos, MAKELANGID( LANG_ENGLISH, SUBLANG_DEFAULT ) );
    }

    resdirptr = *ret;
    for (i = 0; i < pos; i++)
        if ((*ret = find_entry_by_id( resdirptr, list[i], root, want_dir ))) return STATUS_SUCCESS;

    /* if no explicitly specified language, return the first entry */
    if (PRIMARYLANGID(info->Language) == LANG_NEUTRAL)
    {
        if ((*ret = find_first_entry( resdirptr, root, want_dir ))) return STATUS_SUCCESS;
    }
    return STATUS_RESOURCE_LANG_NOT_FOUND;

done:
    *ret = resdirptr;
    return STATUS_SUCCESS;
}
Example #6
0
DWORD
GetToken(
    IN  LPTSTR  pszBegin,
    OUT LPTSTR* ppszEnd,
    OUT LPDWORD pflTokenType,
    IN  DWORD   flFlags
)

/*++

Routine Description:

    GetToken attempts to locate and type the next token.  It takes the
    beginning of the token and determines the end of the token (i.e.
    the beginning of the next token, so that it can be called again).
    It also sets the TOKEN_TYPE_* bits for all of the token types which
    are appropriate to the specified type.

Arguments:

    pszBegin    - A pointer to the first character in the token.

    ppszEnd     - A pointer to the location in which to store the end of
                  the current token (actually, the first character of the
                  next token).

    pflTokenType- The place to store the token type.  Token types are
                  defined in TOKEN.H.

    flFlags     - Flags to determine operation.  Currently MBZ.

Return Value:

    DWORD
        Success - 0
        Failure - ERROR_INVALID_PARAMETER
                  ERROR_INVALID_NAME
                  ERROR_FILENAME_EXCED_RANGE

--*/

{
    register    TCHAR   chFirstChar;
    register    DWORD   cbTokenLen;
    BOOL    fComputernameOnly = FALSE;
    DWORD   usNameError = 0;
    DWORD   cbTrailingDotSpace;
    DWORD   iLow, iHigh, iMid;
    LONG    iCmpVal;
    LCID    lcid  = GetThreadLocale();
    BOOL    bDBCS = (PRIMARYLANGID( LANGIDFROMLCID(lcid)) == LANG_JAPANESE) ||
                    (PRIMARYLANGID(LANGIDFROMLCID(lcid)) == LANG_KOREAN) ||
                    (PRIMARYLANGID(LANGIDFROMLCID(lcid)) == LANG_CHINESE);

    extern      DWORD   cbMaxPathCompLen;

    //
    // This macro is used to make sure that the error value is set only
    // once in the computername-only case.
    //

#define SET_COMPUTERNAMEONLY(err)   if (! fComputernameOnly)            \
                                    {                                   \
                                        fComputernameOnly = TRUE;       \
                                        usNameError = err;              \
                                    }

    if (flFlags & GTF_RESERVED) {
        return ERROR_INVALID_PARAMETER;
    }

    //
    // Initialize the token type to 0
    //

    *pflTokenType = 0;

    //
    // Store the first character
    //

    chFirstChar = *pszBegin;

    //
    // Return immediately if the string is a null string
    //

    if (chFirstChar == TCHAR_EOS) {
        *ppszEnd = pszBegin;
        *pflTokenType = TOKEN_TYPE_EOS;
#ifdef DEVDEBUG
        DbgPrint("GetToken - returning TOKEN_TYPE_EOS\n");
#endif
        return 0;
    }

    //
    // Handle single-character, non-component tokens
    //

    if ((chFirstChar == TCHAR_BACKSLASH) || (chFirstChar == TCHAR_FWDSLASH)) {
        *pflTokenType = TOKEN_TYPE_SLASH;
    } else if (chFirstChar == TCHAR_COLON) {
        *pflTokenType = TOKEN_TYPE_COLON;
    }

    //
    // If we get here and the token type is non-zero, we have a single
    // character token.  We set <ppszEnd> and return 0.
    //

    if (*pflTokenType) {
        *ppszEnd = pszBegin + 1;
#ifdef DEVDEBUG
        DbgPrint("GetToken - *pflTokenType=%x\n", *pflTokenType);
#endif
        return 0;
    }

    //
    // If we get here, the token is a component, find the end of the
    // component by looking for the first character in the string which
    // isn't a valid component character.
    //
    // IMPORTANT:  There are certain names which are not valid component
    //             names but which may be valid computernames.  If we hit
    //             such a name, we set the <fComputernameOnly> flag.  Later
    //             on, we check to see if the name is a valid computername.
    //             If it is, we allow it; otherwise, we return an error.
    //

    cbTokenLen = STRCSPN(pszBegin, szNonComponentChars);

    //
    // We return an error if the first character is not a valid component
    // character, if the component is too long, or if the first
    // non-component character in the string is an illegal character.
    //

    if (cbTokenLen == 0) {
#ifdef DEVDEBUG
        DbgPrint("GetToken - returning ERROR_INVALID_NAME (token len = 0)\n");
#endif
        return ERROR_INVALID_NAME;
    }

    if (cbTokenLen > cbMaxPathCompLen) {
        SET_COMPUTERNAMEONLY(ERROR_FILENAME_EXCED_RANGE);
    }

    if (IsIllegalCharacter(pszBegin + cbTokenLen)) {
#ifdef DEVDEBUG
        DbgPrint("GetToken - returning ERROR_INVALID_NAME (illegal char)\n");
#endif
        return ERROR_INVALID_NAME;
    }

    //
    // Now we need to determine where the trailing dots and spaces begin,
    // and make sure that the component name contains something other
    // than dots and spaces, unless it's "." or ".."
    //
    // NOTE: If there are not trailing dots or spaces, <cbTrailingDotSpace>
    //       is set to <cbTokenLen>.
    //

    cbTrailingDotSpace = TrailingDotsAndSpaces(pszBegin, cbTokenLen );

    //
    // See if the token has only trailing dots and spaces
    //

    if (cbTrailingDotSpace == 0) {

        //
        // Return an error if the length of the token is greater than 2.
        //

        if (cbTokenLen > 2) {
            SET_COMPUTERNAMEONLY(ERROR_INVALID_NAME);
        }

        //
        // Return an error if the first character is not a dot or if the
        // token length is 2 and the second character is not a dot.
        //

        if ((chFirstChar != TCHAR_DOT) || ((cbTokenLen == 2) && (pszBegin[1] != TCHAR_DOT))) {
            SET_COMPUTERNAMEONLY(ERROR_INVALID_NAME);
        }

        //
        // Now we're OK, since the token is either "." or ".."
        //
    }

    //
    // WE HAVE A VALID COMPONENT
    //

    *pflTokenType = TOKEN_TYPE_COMPONENT;

    //
    // Now we determine if this token matches any of the component-based
    // types.
    //


    //
    // Is it a drive?
    //

    if (IS_DRIVE(chFirstChar) && (cbTokenLen == 1)) {
        *pflTokenType |= TOKEN_TYPE_DRIVE;
    }

    //
    // Is it "." or ".." ?
    //
    // Since we've already validated this string, we know that if it
    // contains nothing but dots and spaces it must be one of these
    // two.
    //

    if (cbTrailingDotSpace == 0) {
        *pflTokenType |= cbTokenLen == 1 ? TOKEN_TYPE_DOT : TOKEN_TYPE_DOTDOT;
    }

    //
    // If the 8.3 flag is specified, we also have to check that the
    // component is in 8.3 format.  We determine this as follows:
    //
    // Find the first dot in the token (or the end of the token).
    // Verify that at least 1 and at most 8 characters precede it.
    // Verify that at most 3 characters follow it.
    // Verify that none of the characters which follow it are dots.
    //
    // The exceptions to this are "." and "..".  Therefore, we don't check
    // this until after we've already determined that this component is
    // neither of those.
    //

    if ((cbTrailingDotSpace != 0) && (flFlags & GTF_8_DOT_3)) {
        DWORD   cbFirstDot;
        BOOL    fNoDot;

        cbFirstDot = STRCSPN(pszBegin, _text_SingleDot);

        if (fNoDot = cbFirstDot >= cbTokenLen) {
            cbFirstDot = cbTokenLen;
        }

        if (cbFirstDot == 0
                || cbFirstDot > 8
                || cbTokenLen - cbFirstDot > 4
                || (! fNoDot && STRCSPN(pszBegin + cbFirstDot + 1, _text_SingleDot)
                    < cbTokenLen - (cbFirstDot + 1))) {
            SET_COMPUTERNAMEONLY(ERROR_INVALID_NAME);
        }

        if( bDBCS ) {
            //
            // In case of MBCS, We also need to check the string is valid in MBCS
            // because Unicode character count is not eqaul MBCS byte count

            CHAR szCharToken[13]; // 8 + 3 + dot + null
            int  cbConverted = 0;
            BOOL bDefaultUsed = FALSE;

            // Convert Unicode string to Mbcs.
            cbConverted = WideCharToMultiByte( CP_OEMCP,  0,
                                               pszBegin, -1,
                                               szCharToken, sizeof(szCharToken),
                                               NULL, &bDefaultUsed );

            // If the converted langth is larger than the buffer, or the WideChar string
            // contains some character that is can not be repesented by MultiByte code page,
            // set error.

            if( cbConverted == FALSE || bDefaultUsed == TRUE ) {
                SET_COMPUTERNAMEONLY(ERROR_INVALID_NAME);
            } else {
                cbConverted -= 1; // Remove NULL;

                cbFirstDot = strcspn(szCharToken, ".");

                if (fNoDot = cbFirstDot >= (DWORD)cbConverted) {
                    cbFirstDot = cbConverted;
                }

                if (cbFirstDot == 0
                        || cbFirstDot > 8
                        || cbConverted - cbFirstDot > 4
                        || (! fNoDot && strcspn(szCharToken + cbFirstDot + 1, ".")
                            < cbConverted - (cbFirstDot + 1))) {
                    SET_COMPUTERNAMEONLY(ERROR_INVALID_NAME);
                }
            }
        }
    }

    //
    // Does it contain wildcards?
    //
    // If so, set the appropriate flag(s).
    //
    // If not, it may be a valid computername.
    //

    if (STRCSPN(pszBegin, szWildcards) < cbTokenLen) {

        *pflTokenType |= TOKEN_TYPE_WILDCARD;

        //
        // Special case the single '*' token
        //

        if (cbTokenLen == 1 && chFirstChar == TCHAR_STAR) {
            *pflTokenType |= TOKEN_TYPE_WILDONE;
        }
    } else {
        if( cbTokenLen <= MAX_PATH ) {
            *pflTokenType |= TOKEN_TYPE_COMPUTERNAME;
        }
    }

    //
    // IMPORTANT:  Now we've determined if the token is a valid computername.
    //             If the <fComputernameOnly> flag is set and it's a valid
    //             computername, then we turn off all other bits.  If it's
    //             not a valid computername, we return the stored error.
    //             If the flag isn't set, we continue with the component name
    //             processing.
    //

    if (fComputernameOnly) {
        if (*pflTokenType & TOKEN_TYPE_COMPUTERNAME) {
            *pflTokenType = TOKEN_TYPE_COMPUTERNAME;
        } else {
#ifdef DEVDEBUG
            DbgPrint("GetToken - returning usNameError (%u)\n", usNameError);
#endif
            return usNameError;
        }
    } else {

        //
        // Is this an LPT[1-9] token?
        //

        if (STRNICMP(pszBegin, szLPTName, LPT_TOKEN_LEN) == 0
                && IS_NON_ZERO_DIGIT(pszBegin[LPT_TOKEN_LEN])
                && cbTrailingDotSpace == LPT_TOKEN_LEN + 1) {
            *pflTokenType |= TOKEN_TYPE_LPT;
        }

        //
        // Is this an COM[1-9] token?
        //

        if (STRNICMP(pszBegin, szCOMName, COM_TOKEN_LEN) == 0
                && IS_NON_ZERO_DIGIT(pszBegin[COM_TOKEN_LEN])
                && cbTrailingDotSpace == COM_TOKEN_LEN + 1) {
            *pflTokenType |= TOKEN_TYPE_COM;
        }

        //
        // The remainder of the component-based token types are determined
        // by string comparisons.  In order to speed things up, we store
        // these strings in sorted order and do a binary search on them,
        // which reduces the worst-case number of comparisons from N to
        // log N (where N is the number of strings).
        //

        iLow = (ULONG)-1;
        iHigh = NUM_STRING_TOKENS;

        while (iHigh - iLow > 1) {
            iMid = (iLow + iHigh) / 2;

            //
            // We do the comparison up to the length of the longer of the
            // two strings.  This guarantees us a valid non-zero value for
            // iCmpVal if they don't match.  It also means that they won't
            // match unless they're the same length.
            //

            iCmpVal = STRNICMP(pszBegin,
                               StringTokenTable[iMid].pszTokenName,
                               max(StringTokenTable[iMid].cbTokenLen,
                                   cbTrailingDotSpace) );

            if (iCmpVal < 0) {
                iHigh = iMid;
            } else if (iCmpVal > 0) {
                iLow = iMid;
            } else {

                //
                // We have a match!
                //

                *pflTokenType |= StringTokenTable[iMid].flTokenType;

                //
                // We can only match one, so don't bother continuing
                //

                break;
            }
        }
    }

    //
    // We're done; set the end pointer and return with success
    //

    *ppszEnd = pszBegin + cbTokenLen;
#ifdef DEVDEBUG
    DbgPrint("GetToken - returning success\n");
#endif
    return 0;
}
Example #7
0
XIC X11DRV_CreateIC(XIM xim, struct x11drv_win_data *data)
{
    XPoint spot = {0};
    XVaNestedList preedit = NULL;
    XVaNestedList status = NULL;
    XIC xic;
    XICCallback destroy = {(XPointer)data, (XICProc)X11DRV_DestroyIC};
    XICCallback P_StartCB, P_DoneCB, P_DrawCB, P_CaretCB;
    LANGID langid = PRIMARYLANGID(LANGIDFROMLCID(GetThreadLocale()));
    Window win = data->whole_window;

    TRACE("xim = %p\n", xim);

    wine_tsx11_lock();

    /* use complex and slow XIC initialization method only for CJK */
    if (langid != LANG_CHINESE &&
        langid != LANG_JAPANESE &&
        langid != LANG_KOREAN)
    {
        xic = XCreateIC(xim,
                        XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
                        XNClientWindow, win,
                        XNFocusWindow, win,
                        XNDestroyCallback, &destroy,
                        NULL);
        wine_tsx11_unlock();
        data->xic = xic;
        return xic;
    }

    /* create callbacks */
    P_StartCB.client_data = NULL;
    P_DoneCB.client_data = NULL;
    P_DrawCB.client_data = NULL;
    P_CaretCB.client_data = NULL;
    P_StartCB.callback = (XICProc)XIMPreEditStartCallback;
    P_DoneCB.callback = (XICProc)XIMPreEditDoneCallback;
    P_DrawCB.callback = (XICProc)XIMPreEditDrawCallback;
    P_CaretCB.callback = (XICProc)XIMPreEditCaretCallback;

    if ((ximStyle & (XIMPreeditNothing | XIMPreeditNone)) == 0)
    {
        preedit = XVaCreateNestedList(0,
                        XNSpotLocation, &spot,
                        XNPreeditStartCallback, &P_StartCB,
                        XNPreeditDoneCallback, &P_DoneCB,
                        XNPreeditDrawCallback, &P_DrawCB,
                        XNPreeditCaretCallback, &P_CaretCB,
                        NULL);
        TRACE("preedit = %p\n", preedit);
    }
    else
    {
        preedit = XVaCreateNestedList(0,
                        XNPreeditStartCallback, &P_StartCB,
                        XNPreeditDoneCallback, &P_DoneCB,
                        XNPreeditDrawCallback, &P_DrawCB,
                        XNPreeditCaretCallback, &P_CaretCB,
                        NULL);

        TRACE("preedit = %p\n", preedit);
    }

    if ((ximStyle & (XIMStatusNothing | XIMStatusNone)) == 0)
    {
        status = XVaCreateNestedList(0,
            NULL);
        TRACE("status = %p\n", status);
     }

    if (preedit != NULL && status != NULL)
    {
        xic = XCreateIC(xim,
              XNInputStyle, ximStyle,
              XNPreeditAttributes, preedit,
              XNStatusAttributes, status,
              XNClientWindow, win,
              XNFocusWindow, win,
              XNDestroyCallback, &destroy,
              NULL);
     }
    else if (preedit != NULL)
    {
        xic = XCreateIC(xim,
              XNInputStyle, ximStyle,
              XNPreeditAttributes, preedit,
              XNClientWindow, win,
              XNFocusWindow, win,
              XNDestroyCallback, &destroy,
              NULL);
    }
    else if (status != NULL)
    {
        xic = XCreateIC(xim,
              XNInputStyle, ximStyle,
              XNStatusAttributes, status,
              XNClientWindow, win,
              XNFocusWindow, win,
              XNDestroyCallback, &destroy,
              NULL);
    }
    else
    {
        xic = XCreateIC(xim,
              XNInputStyle, ximStyle,
              XNClientWindow, win,
              XNFocusWindow, win,
              XNDestroyCallback, &destroy,
              NULL);
    }

    TRACE("xic = %p\n", xic);
    data->xic = xic;

    if (preedit != NULL)
        XFree(preedit);
    if (status != NULL)
        XFree(status);

    wine_tsx11_unlock();

    return xic;
}
/***
*BOOL __get_qualified_locale - return fully qualified locale
*
*Purpose:
*       get default locale, qualify partially complete locales
*
*Entry:
*       lpInStr - input strings to be qualified
*       lpOutId - pointer to numeric LCIDs and codepage output
*       lpOutStr - pointer to string LCIDs and codepage output
*
*Exit:
*       TRUE if success, qualified locale is valid
*       FALSE if failure
*
*Exceptions:
*
*******************************************************************************/
BOOL __cdecl __get_qualified_locale(const LPLC_STRINGS lpInStr, LPLC_ID lpOutId,
                                    LPLC_STRINGS lpOutStr)
{
    int     iCodePage;

    //  initialize pointer to call locale info routine based on operating system

    if (!pfnGetLocaleInfoA)
    {
        pfnGetLocaleInfoA = IsThisWindowsNT() ? GetLocaleInfoA : crtGetLocaleInfoA;
    }

    if (!lpInStr)
    {
        //  if no input defined, just use default LCID
        GetLcidFromDefault();
    }
    else
    {
        //  convert non-NLS language strings to three-letter abbreviations
        pchLanguage = lpInStr->szLanguage;
        if (pchLanguage && *pchLanguage)
            TranslateName(__rg_language,
                          sizeof(__rg_language) / sizeof(LOCALETAB) - 1,
                          &pchLanguage);

        //  convert non-NLS country strings to three-letter abbreviations
        pchCountry = lpInStr->szCountry;
        if (pchCountry && *pchCountry)
            TranslateName(__rg_country,
                          sizeof(__rg_country) / sizeof(LOCALETAB) - 1,
                          &pchCountry);

        iLcidState = 0;

        if (pchLanguage && *pchLanguage)
        {
            if (pchCountry && *pchCountry)
            {
                //  both language and country strings defined
                GetLcidFromLangCountry();
            }
            else
            {
                //  language string defined, but country string undefined
                GetLcidFromLanguage();
            }
        }
        else
        {
            if (pchCountry && *pchCountry)
            {
                //  country string defined, but language string undefined
                GetLcidFromCountry();
            }
            else
            {
                //  both language and country strings undefined
                GetLcidFromDefault();
            }
        }
    }

    //  test for error in LCID processing
    if (!iLcidState)
        return FALSE;

    //  process codepage value
    iCodePage = ProcessCodePage(lpInStr->szCodePage);

    //  verify codepage validity
    if (!iCodePage || !IsValidCodePage((WORD)iCodePage))
        return FALSE;

    //  verify locale is installed
    if (!IsValidLocale(lcidLanguage, LCID_INSTALLED))
        return FALSE;

    //  set numeric LCID and codepage results
    if (lpOutId)
    {
        lpOutId->wLanguage = LANGIDFROMLCID(lcidLanguage);
        lpOutId->wCountry = LANGIDFROMLCID(lcidCountry);
        lpOutId->wCodePage = (WORD)iCodePage;
    }

    //  set string language, country, and codepage results
    if (lpOutStr)
    {
        if ((*pfnGetLocaleInfoA)(lcidLanguage, LOCALE_SENGLANGUAGE,
                                 lpOutStr->szLanguage, MAX_LANG_LEN) == 0)
            return FALSE;
        if ((*pfnGetLocaleInfoA)(lcidCountry, LOCALE_SENGCOUNTRY,
                                 lpOutStr->szCountry, MAX_CTRY_LEN) == 0)
            return FALSE;
        _itoa((int)iCodePage, (char *)lpOutStr->szCodePage, 10);
    }
    return TRUE;
}
Example #9
0
int
TkSelGetSelection(
    Tcl_Interp *interp,		/* Interpreter to use for reporting errors. */
    Tk_Window tkwin,		/* Window on whose behalf to retrieve the
				 * selection (determines display from which to
				 * retrieve). */
    Atom selection,		/* Selection to retrieve. */
    Atom target,		/* Desired form in which selection is to be
				 * returned. */
    Tk_GetSelProc *proc,	/* Procedure to call to process the selection,
				 * once it has been retrieved. */
    ClientData clientData)	/* Arbitrary value to pass to proc. */
{
    char *data, *destPtr;
    Tcl_DString ds;
    HGLOBAL handle;
    Tcl_Encoding encoding;
    int result, locale;

    if ((selection != Tk_InternAtom(tkwin, "CLIPBOARD"))
	    || (target != XA_STRING)
	    || !OpenClipboard(NULL)) {
	goto error;
    }

    /*
     * Attempt to get the data in Unicode form if available as this is less
     * work that CF_TEXT.
     */

    result = TCL_ERROR;
    if (IsClipboardFormatAvailable(CF_UNICODETEXT)) {
	handle = GetClipboardData(CF_UNICODETEXT);
	if (!handle) {
	    CloseClipboard();
	    goto error;
	}
	data = GlobalLock(handle);
	Tcl_DStringInit(&ds);
	Tcl_UniCharToUtfDString((Tcl_UniChar *)data,
		Tcl_UniCharLen((Tcl_UniChar *)data), &ds);
	GlobalUnlock(handle);
    } else if (IsClipboardFormatAvailable(CF_TEXT)) {
	/*
	 * Determine the encoding to use to convert this text.
	 */

	if (IsClipboardFormatAvailable(CF_LOCALE)) {
	    handle = GetClipboardData(CF_LOCALE);
	    if (!handle) {
		CloseClipboard();
		goto error;
	    }

	    /*
	     * Get the locale identifier, determine the proper code page to
	     * use, and find the corresponding encoding.
	     */

	    Tcl_DStringInit(&ds);
	    Tcl_DStringAppend(&ds, "cp######", -1);
	    data = GlobalLock(handle);

	    /*
	     * Even though the documentation claims that GetLocaleInfo expects
	     * an LCID, on Windows 9x it really seems to expect a LanguageID.
	     */

	    locale = LANGIDFROMLCID(*((int*)data));
	    GetLocaleInfoA(locale, LOCALE_IDEFAULTANSICODEPAGE,
		    Tcl_DStringValue(&ds)+2, Tcl_DStringLength(&ds)-2);
	    GlobalUnlock(handle);

	    encoding = Tcl_GetEncoding(NULL, Tcl_DStringValue(&ds));
	    Tcl_DStringFree(&ds);
	} else {
	    encoding = NULL;
	}

	/*
	 * Fetch the text and convert it to UTF.
	 */

	handle = GetClipboardData(CF_TEXT);
	if (!handle) {
	    if (encoding) {
		Tcl_FreeEncoding(encoding);
	    }
	    CloseClipboard();
	    goto error;
	}
	data = GlobalLock(handle);
	Tcl_ExternalToUtfDString(encoding, data, -1, &ds);
	GlobalUnlock(handle);
	if (encoding) {
	    Tcl_FreeEncoding(encoding);
	}

    } else {
	CloseClipboard();
	goto error;
    }

    /*
     * Translate CR/LF to LF.
     */

    data = destPtr = Tcl_DStringValue(&ds);
    while (*data) {
	if (data[0] == '\r' && data[1] == '\n') {
	    data++;
	} else {
	    *destPtr++ = *data++;
	}
    }
    *destPtr = '\0';

    /*
     * Pass the data off to the selection procedure.
     */

    result = proc(clientData, interp, Tcl_DStringValue(&ds));
    Tcl_DStringFree(&ds);
    CloseClipboard();
    return result;

  error:
    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
	    "%s selection doesn't exist or form \"%s\" not defined",
	    Tk_GetAtomName(tkwin, selection), Tk_GetAtomName(tkwin, target)));
    Tcl_SetErrorCode(interp, "TK", "SELECTION", "EXISTS", NULL);
    return TCL_ERROR;
}
Example #10
0
VOID
ImmPostMessages(
    HWND      hWnd,
    HIMC      hImc,
    INT       iNum,
    PTRANSMSG pTransMsg)
{
    INT i;
    BOOL fAnsiIME;
    PCLIENTIMC pClientImc;
    PTRANSMSG pTransMsgTemp, pTransMsgBuf = NULL;

    //
    // Check if the IME is unicode or not.
    // The message buffer contains unicode messages
    // if the IME is unicode.
    //
    pClientImc = ImmLockClientImc(hImc);
    if (pClientImc == NULL) {
        RIPMSG1(RIP_WARNING,
                "ImmPostMessages: Invalid hImc %lx.", hImc);
        return;
    }

    fAnsiIME = ! TestICF(pClientImc, IMCF_UNICODE);
    ImmUnlockClientImc(pClientImc);

    //
    // translate messages to 3.x format if the App's version is 3.x.
    //
    pTransMsgTemp = pTransMsg;
    if (GetClientInfo()->dwExpWinVer < VER40) {
        DWORD dwLangId = PRIMARYLANGID(
                                      LANGIDFROMLCID(
                                                    GetSystemDefaultLCID()));
        if ( (dwLangId == LANG_KOREAN && TransGetLevel(hWnd) == 3) ||
             dwLangId == LANG_JAPANESE ) {

            pTransMsgBuf = ImmLocalAlloc(0, iNum * sizeof(TRANSMSG));
            if (pTransMsgBuf != NULL) {
                RtlCopyMemory(pTransMsgBuf, pTransMsg, iNum * sizeof(TRANSMSG));
                iNum = WINNLSTranslateMessage(iNum,
                                              pTransMsgBuf,
                                              hImc,
                                              fAnsiIME,
                                              dwLangId );
                pTransMsgTemp = pTransMsgBuf;
            }
        }
    }

    for (i = 0; i < iNum; i++) {
        if (fAnsiIME) {
            PostMessageA(hWnd,
                    pTransMsgTemp->message,
                    pTransMsgTemp->wParam,
                    pTransMsgTemp->lParam);
        } else {
            PostMessageW(hWnd,
                    pTransMsgTemp->message,
                    pTransMsgTemp->wParam,
                    pTransMsgTemp->lParam);
        }
        pTransMsgTemp++;
    }

    if (pTransMsgBuf != NULL) {
        ImmLocalFree(pTransMsgBuf);
    }
}
Example #11
0
java_props_t *
GetJavaProperties(JNIEnv* env)
{
    static java_props_t sprops = {0};

    OSVERSIONINFOEX ver;

    if (sprops.user_dir) {
        return &sprops;
    }

    /* AWT properties */
    sprops.awt_toolkit = "sun.awt.windows.WToolkit";

    /* tmp dir */
    {
        WCHAR tmpdir[MAX_PATH + 1];
        /* we might want to check that this succeed */
        GetTempPathW(MAX_PATH + 1, tmpdir);
        sprops.tmp_dir = _wcsdup(tmpdir);
    }

    /* Printing properties */
    sprops.printerJob = "sun.awt.windows.WPrinterJob";

    /* Java2D properties */
    sprops.graphics_env = "sun.awt.Win32GraphicsEnvironment";

    {   /* This is used only for debugging of font problems. */
        WCHAR *path = _wgetenv(L"JAVA2D_FONTPATH");
        sprops.font_dir = (path != NULL) ? _wcsdup(path) : NULL;
    }

    /* OS properties */
    {
        char buf[100];
        SYSTEM_INFO si;
        PGNSI pGNSI;

        ver.dwOSVersionInfoSize = sizeof(ver);
        GetVersionEx((OSVERSIONINFO *) &ver);

        ZeroMemory(&si, sizeof(SYSTEM_INFO));
        // Call GetNativeSystemInfo if supported or GetSystemInfo otherwise.
        pGNSI = (PGNSI) GetProcAddress(
                    GetModuleHandle(TEXT("kernel32.dll")),
                    "GetNativeSystemInfo");
        if(NULL != pGNSI)
            pGNSI(&si);
        else
            GetSystemInfo(&si);

        /*
         * From msdn page on OSVERSIONINFOEX, current as of this
         * writing, decoding of dwMajorVersion and dwMinorVersion.
         *
         *  Operating system            dwMajorVersion  dwMinorVersion
         * ==================           ==============  ==============
         *
         * Windows 95                   4               0
         * Windows 98                   4               10
         * Windows ME                   4               90
         * Windows 3.51                 3               51
         * Windows NT 4.0               4               0
         * Windows 2000                 5               0
         * Windows XP 32 bit            5               1
         * Windows Server 2003 family   5               2
         * Windows XP 64 bit            5               2
         *       where ((&ver.wServicePackMinor) + 2) = 1
         *       and  si.wProcessorArchitecture = 9
         * Windows Vista family         6               0  (VER_NT_WORKSTATION)
         * Windows Server 2008          6               0  (!VER_NT_WORKSTATION)
         * Windows 7                    6               1  (VER_NT_WORKSTATION)
         * Windows Server 2008 R2       6               1  (!VER_NT_WORKSTATION)
         *
         * This mapping will presumably be augmented as new Windows
         * versions are released.
         */
        switch (ver.dwPlatformId) {
        case VER_PLATFORM_WIN32s:
            sprops.os_name = "Windows 3.1";
            break;
        case VER_PLATFORM_WIN32_WINDOWS:
            if (ver.dwMajorVersion == 4) {
                switch (ver.dwMinorVersion) {
                case  0:
                    sprops.os_name = "Windows 95";
                    break;
                case 10:
                    sprops.os_name = "Windows 98";
                    break;
                case 90:
                    sprops.os_name = "Windows Me";
                    break;
                default:
                    sprops.os_name = "Windows 9X (unknown)";
                    break;
                }
            } else {
                sprops.os_name = "Windows 9X (unknown)";
            }
            break;
        case VER_PLATFORM_WIN32_NT:
            if (ver.dwMajorVersion <= 4) {
                sprops.os_name = "Windows NT";
            } else if (ver.dwMajorVersion == 5) {
                switch (ver.dwMinorVersion) {
                case  0:
                    sprops.os_name = "Windows 2000";
                    break;
                case  1:
                    sprops.os_name = "Windows XP";
                    break;
                case  2:
                    /*
                     * From MSDN OSVERSIONINFOEX and SYSTEM_INFO documentation:
                     *
                     * "Because the version numbers for Windows Server 2003
                     * and Windows XP 6u4 bit are identical, you must also test
                     * whether the wProductType member is VER_NT_WORKSTATION.
                     * and si.wProcessorArchitecture is
                     * PROCESSOR_ARCHITECTURE_AMD64 (which is 9)
                     * If it is, the operating system is Windows XP 64 bit;
                     * otherwise, it is Windows Server 2003."
                     */
                    if(ver.wProductType == VER_NT_WORKSTATION &&
                            si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) {
                        sprops.os_name = "Windows XP"; /* 64 bit */
                    } else {
                        sprops.os_name = "Windows 2003";
                    }
                    break;
                default:
                    sprops.os_name = "Windows NT (unknown)";
                    break;
                }
            } else if (ver.dwMajorVersion == 6) {
                /*
                 * See table in MSDN OSVERSIONINFOEX documentation.
                 */
                if (ver.wProductType == VER_NT_WORKSTATION) {
                    switch (ver.dwMinorVersion) {
                    case  0:
                        sprops.os_name = "Windows Vista";
                        break;
                    case  1:
                        sprops.os_name = "Windows 7";
                        break;
                    default:
                        sprops.os_name = "Windows NT (unknown)";
                    }
                } else {
                    switch (ver.dwMinorVersion) {
                    case  0:
                        sprops.os_name = "Windows Server 2008";
                        break;
                    case  1:
                        sprops.os_name = "Windows Server 2008 R2";
                        break;
                    default:
                        sprops.os_name = "Windows NT (unknown)";
                    }
                }
            } else {
                sprops.os_name = "Windows NT (unknown)";
            }
            break;
        default:
            sprops.os_name = "Windows (unknown)";
            break;
        }
        sprintf(buf, "%d.%d", ver.dwMajorVersion, ver.dwMinorVersion);
        sprops.os_version = _strdup(buf);
#if _M_IA64
        sprops.os_arch = "ia64";
#elif _M_AMD64
        sprops.os_arch = "amd64";
#elif _X86_
        sprops.os_arch = "x86";
#else
        sprops.os_arch = "unknown";
#endif

        sprops.patch_level = _strdup(ver.szCSDVersion);

        sprops.desktop = "windows";
    }

    /* Endianness of platform */
    {
        unsigned int endianTest = 0xff000000;
        if (((char*)(&endianTest))[0] != 0) {
            sprops.cpu_endian = "big";
        } else {
            sprops.cpu_endian = "little";
        }
    }

    /* CPU ISA list */
    sprops.cpu_isalist = cpu_isalist();

    /*
     * User name
     * We try to avoid calling GetUserName as it turns out to
     * be surprisingly expensive on NT.  It pulls in an extra
     * 100 K of footprint.
     */
    {
        WCHAR *uname = _wgetenv(L"USERNAME");
        if (uname != NULL && wcslen(uname) > 0) {
            sprops.user_name = _wcsdup(uname);
        } else {
            DWORD buflen = 0;
            if (GetUserNameW(NULL, &buflen) == 0 &&
                    GetLastError() == ERROR_INSUFFICIENT_BUFFER)
            {
                uname = (WCHAR*)malloc(buflen * sizeof(WCHAR));
                if (uname != NULL && GetUserNameW(uname, &buflen) == 0) {
                    free(uname);
                    uname = NULL;
                }
            } else {
                uname = NULL;
            }
            sprops.user_name = (uname != NULL) ? uname : L"unknown";
        }
    }

    /*
     * Home directory/
     *
     * We first look under a standard registry key.  If that fails we
     * fall back on using a SHELL32.DLL API.  If that fails we use a
     * default value.
     *
     * Note: To save space we want to avoid loading SHELL32.DLL
     * unless really necessary.  However if we do load it, we leave it
     * in memory, as it may be needed again later.
     *
     * The normal result is that for a given user name XXX:
     *     On multi-user NT, user.home gets set to c:\winnt\profiles\XXX.
     *     On multi-user Win95, user.home gets set to c:\windows\profiles\XXX.
     *     On single-user Win95, user.home gets set to c:\windows.
     */
    {
        WCHAR *homep = getHomeFromRegistry();
        if (homep == NULL) {
            homep = getHomeFromShell32();
            if (homep == NULL)
                homep = L"C:\\";
        }
        sprops.user_home = _wcsdup(homep);
    }

    /*
     *  user.language
     *  user.script, user.country, user.variant (if user's environment specifies them)
     *  file.encoding
     *  file.encoding.pkg
     */
    {
        /*
         * query the system for the current system default locale
         * (which is a Windows LCID value),
         */
        LCID userDefaultLCID = GetUserDefaultLCID();
        LCID systemDefaultLCID = GetSystemDefaultLCID();
        LCID userDefaultUILang = GetUserDefaultUILanguage();

        {
            char * display_encoding;

            // Windows UI Language selection list only cares "language"
            // information of the UI Language. For example, the list
            // just lists "English" but it actually means "en_US", and
            // the user cannot select "en_GB" (if exists) in the list.
            // So, this hack is to use the user LCID region information
            // for the UI Language, if the "language" portion of those
            // two locales are the same.
            if (PRIMARYLANGID(LANGIDFROMLCID(userDefaultLCID)) ==
                    PRIMARYLANGID(LANGIDFROMLCID(userDefaultUILang))) {
                userDefaultUILang = userDefaultLCID;
            }

            SetupI18nProps(userDefaultUILang,
                           &sprops.language,
                           &sprops.script,
                           &sprops.country,
                           &sprops.variant,
                           &display_encoding);
            SetupI18nProps(userDefaultLCID,
                           &sprops.format_language,
                           &sprops.format_script,
                           &sprops.format_country,
                           &sprops.format_variant,
                           &sprops.encoding);
            SetupI18nProps(userDefaultUILang,
                           &sprops.display_language,
                           &sprops.display_script,
                           &sprops.display_country,
                           &sprops.display_variant,
                           &display_encoding);

            sprops.sun_jnu_encoding = getEncodingInternal(systemDefaultLCID);
            if (LANGIDFROMLCID(userDefaultLCID) == 0x0c04 && ver.dwMajorVersion == 6) {
                // MS claims "Vista has built-in support for HKSCS-2004.
                // All of the HKSCS-2004 characters have Unicode 4.1.
                // PUA code point assignments". But what it really means
                // is that the HKSCS-2004 is ONLY supported in Unicode.
                // Test indicates the MS950 in its zh_HK locale is a
                // "regular" MS950 which does not handle HKSCS-2004 at
                // all. Set encoding to MS950_HKSCS.
                sprops.encoding = "MS950_HKSCS";
                sprops.sun_jnu_encoding = "MS950_HKSCS";
            }
        }
    }

    sprops.unicode_encoding = "UnicodeLittle";
    /* User TIMEZONE */
    {
        /*
         * We defer setting up timezone until it's actually necessary.
         * Refer to TimeZone.getDefault(). However, the system
         * property is necessary to be able to be set by the command
         * line interface -D. Here temporarily set a null string to
         * timezone.
         */
        sprops.timezone = "";
    }

    /* Current directory */
    {
        WCHAR buf[MAX_PATH];
        if (GetCurrentDirectoryW(sizeof(buf)/sizeof(WCHAR), buf) != 0)
            sprops.user_dir = _wcsdup(buf);
    }

    sprops.file_separator = "\\";
    sprops.path_separator = ";";
    sprops.line_separator = "\r\n";

    return &sprops;
}
Example #12
0
DWORD WINAPI ImmProcessKey(
    HWND    hWnd,
    HKL     hkl,
    UINT    uVKey,
    LPARAM  lParam,
    DWORD   dwHotKeyID)
{
    HIMC hIMC = ImmGetContext(hWnd);
    PIMEDPI pImeDpi = ImmLockImeDpi(hkl);
    DWORD dwReturn = 0;
#if DBG
    if (dwHotKeyID >= IME_KHOTKEY_FIRST && dwHotKeyID <= IME_KHOTKEY_LAST) {
        TAGMSG2(DBGTAG_IMM, "ImmProcessKey: Kor IME Hotkeys should not come here: dwHotKeyID=%x, uVKey=%x", dwHotKeyID, uVKey);
    }
#endif

    ImmAssert(dwHotKeyID != IME_KHOTKEY_ENGLISH &&
              dwHotKeyID != IME_KHOTKEY_SHAPE_TOGGLE &&
              dwHotKeyID != IME_KHOTKEY_HANJACONVERT);

    //
    // call ImeProcessKey
    //
    if (pImeDpi != NULL) {
        PINPUTCONTEXT pInputContext = ImmLockIMC(hIMC);

        if (pInputContext != NULL) {
            BOOLEAN fTruncateWideVK = FALSE;
            BOOLEAN fCallIme = TRUE;
            BOOLEAN fSkipThisKey = FALSE;

#ifdef LATER

            //
            // if the current imc is not open and IME doesn't need
            // keys when being closed, we don't pass any keyboard
            // input to ime except hotkey and keys that change
            // the keyboard status.
            //
            if ((pImeDpi->fdwProperty & IME_PROP_NO_KEYS_ON_CLOSE) &&
                    !pInputContext->fOpen &&
                    uVKey != VK_SHIFT &&
                    uVKey != VK_CONTROL &&
                    uVKey != VK_CAPITAL &&
                    uVKey != VK_KANA &&
                    uVKey != VK_NUMLOCK &&
                    uVKey != VK_SCROLL) {
                // Check if Korea Hanja conversion mode
                if(!(pimc->fdwConvMode & IME_CMODE_HANJACONVERT)) {
                    fCallIme = FALSE;
                }
            }
            else
#endif
            //
            // Protect IMEs which are unaware of wide virtual keys.
            //
            if ((BYTE)uVKey == VK_PACKET &&
                    (pImeDpi->ImeInfo.fdwProperty & IME_PROP_ACCEPT_WIDE_VKEY) == 0) {

                if (pImeDpi->ImeInfo.fdwProperty & IME_PROP_UNICODE) {
                    //
                    // Since this IME is not ready to accept wide VKey, we should
                    // truncate it.
                    //
                    fTruncateWideVK = TRUE;
                }
                else {
                    //
                    // Hmm, this guy is ANSI IME, and does not declare Wide Vkey awareness.
                    // Let's guess this one is not ready to accept Wide Vkey, so let's not
                    // pass it to this guy.
                    // And if it is opened, we'd better skip this key for safety.
                    //
                    fCallIme = FALSE;
                    if (pInputContext->fOpen) {
                        fSkipThisKey = TRUE;
                    }
                }
            }

            if (fCallIme) {
                PBYTE pbKeyState = (PBYTE)ImmLocalAlloc(0, 256);

                ImmAssert(fSkipThisKey == FALSE);

                if (pbKeyState != NULL) {
                    if (GetKeyboardState(pbKeyState)) {
                        UINT uVKeyIme = uVKey;
                        if (fTruncateWideVK) {
                            uVKeyIme &= 0xffff;
                        }
                        if ( (*pImeDpi->pfn.ImeProcessKey)(hIMC, uVKeyIme, lParam, pbKeyState) ) {
                            //
                            // if the return value of ImeProcessKey is TRUE,
                            // it means the key is the one that the ime is
                            // waiting for.
                            //
                            pInputContext->fChgMsg = TRUE;
                            pInputContext->uSavedVKey = uVKey;
                            dwReturn |= IPHK_PROCESSBYIME;
                        }
                    }
                    ImmLocalFree(pbKeyState);
                }
            }
            else if (fSkipThisKey) {
                dwReturn |= IPHK_SKIPTHISKEY;
                ImmAssert((dwReturn & (IPHK_PROCESSBYIME | IPHK_HOTKEY)) == 0);
            }
            ImmUnlockIMC(hIMC);
        }
        ImmUnlockImeDpi(pImeDpi);
    }

    //
    // call hotkey handler
    //
    if (dwHotKeyID != IME_INVALID_HOTKEY && HotKeyIDDispatcher(hWnd, hIMC, hkl, dwHotKeyID)) {
        // Backward compat:
        // On Japanese system, some applications may want VK_KANJI.
        if ((uVKey != VK_KANJI) ||
                (dwHotKeyID != IME_JHOTKEY_CLOSE_OPEN)) {
            dwReturn |= IPHK_HOTKEY;
        }
    }

    //
    // some 3.x application doesn't like to see
    // VK_PROCESSKEY.
    //
    if (dwReturn & IPHK_PROCESSBYIME) {

        DWORD dwImeCompat = ImmGetAppCompatFlags(hIMC);

        if (dwImeCompat & IMECOMPAT_NOVKPROCESSKEY) {

            // Korea 3.x application doesn't like to see dummy finalize VK_PROCESSKEY
            // and IME hot key.

            if ( PRIMARYLANGID(LANGIDFROMLCID(GetSystemDefaultLCID())) == LANG_KOREAN &&
                 ( (uVKey == VK_PROCESSKEY) || (dwReturn & IPHK_HOTKEY) ) ) {
                ImmReleaseContext(hWnd, hIMC);
                return dwReturn;
            }

            ImmTranslateMessage(hWnd, WM_KEYDOWN, VK_PROCESSKEY, lParam);
            dwReturn &= ~IPHK_PROCESSBYIME;
            dwReturn |= IPHK_SKIPTHISKEY;
        }
    }
    ImmReleaseContext(hWnd, hIMC);

    return dwReturn;
}
Example #13
0
void
msg_init(char * const *argv)
{
   char *p;
   SVX_ASSERT(argv);

   /* Point to argv[0] itself so we report a more helpful error if the
    * code to work out the clean appname generates a signal */
   appname_copy = argv[0];
#if OS_UNIX
   /* use name as-is on Unix - programs run from path get name as supplied */
   appname_copy = osstrdup(argv[0]);
#else
   /* use the lower-cased leafname on other platforms */
   p = leaf_from_fnm(argv[0]);
   appname_copy = p;
   while (*p) {
      *p = tolower(*p);
      ++p;
   }
#endif

   /* shortcut --version so you can check the version number even when the
    * correct message file can't be found... */
   if (argv[1] && strcmp(argv[1], "--version") == 0) {
      cmdline_version();
      exit(0);
   }
   if (argv[0]) {
      exe_pth = path_from_fnm(argv[0]);
#ifdef MACOSX_BUNDLE
      /* If we're being built into a bundle, always look relative to
       * the path to the binary. */
#ifdef AVEN
      /* Aven is packaged as an application, so we must look inside there. */
      pth_cfg_files = use_path(exe_pth, "../Resources");
#else
      pth_cfg_files = use_path(exe_pth, "share/survex");
#endif
#elif OS_UNIX && defined DATADIR && defined PACKAGE
      bool free_pth = fFalse;
      char *pth = getenv("srcdir");
      if (!pth || !pth[0]) {
	 pth = path_from_fnm(argv[0]);
	 free_pth = fTrue;
      }
      if (pth[0]) {
	 struct stat buf;
#if OS_UNIX_MACOSX
	 /* On MacOS X the programs may be installed anywhere, with the
	  * share directory and the binaries in the same directory. */
	 p = use_path(pth, "share/survex/en.msg");
	 if (lstat(p, &buf) == 0 && S_ISREG(buf.st_mode)) {
	    pth_cfg_files = use_path(pth, "share/survex");
	    goto macosx_got_msg;
	 }
	 osfree(p);
	 /* The cavern which aven runs is a hardlinked copy alongside
	  * the aven binary.
	  */
	 p = use_path(pth, "../Resources/en.msg");
	 if (lstat(p, &buf) == 0 && S_ISREG(buf.st_mode)) {
	    pth_cfg_files = use_path(pth, "../Resources");
	    goto macosx_got_msg;
	 }
	 osfree(p);
#endif
	 /* If we're run with an explicit path, check if "../lib/en.msg"
	  * from the program's path exists, and if so look there for
	  * support files - this allows us to test binaries in the build
	  * tree easily. */
	 p = use_path(pth, "../lib/en.msg");
	 if (lstat(p, &buf) == 0) {
#ifdef S_ISREG
	    /* POSIX way */
	    if (S_ISREG(buf.st_mode)) {
	       pth_cfg_files = use_path(pth, "../lib");
	    }
#else
	    /* BSD way */
	    if ((buf.st_mode & S_IFMT) == S_IFREG) {
	       pth_cfg_files = use_path(pth, "../lib");
	    }
#endif
	 }
#if defined(__GNUC__) && defined(__APPLE_CC__)
macosx_got_msg:
#endif
	 osfree(p);
      }

      if (free_pth) osfree(pth);
#elif OS_WIN32
      DWORD len = 256;
      char *buf = NULL, *modname;
      while (1) {
	  DWORD got;
	  buf = osrealloc(buf, len);
	  got = GetModuleFileName(NULL, buf, len);
	  if (got < len) break;
	  len += len;
      }
      modname = buf;
      /* Strange Win32 nastiness - strip prefix "\\?\" if present */
      if (strncmp(modname, "\\\\?\\", 4) == 0) modname += 4;
      pth_cfg_files = path_from_fnm(modname);
      osfree(buf);
#else
      /* Get the path to the support files from argv[0] */
      pth_cfg_files = path_from_fnm(argv[0]);
#endif
   }

   msg_lang = getenv("SURVEXLANG");
#ifdef DEBUG
   fprintf(stderr, "msg_lang = %p (= \"%s\")\n", msg_lang, msg_lang?msg_lang:"(null)");
#endif

   msg_lang_explicit = fTrue;
   if (!msg_lang || !*msg_lang) {
      msg_lang_explicit = fFalse;
      msg_lang = getenv("LC_ALL");
   }
   if (!msg_lang || !*msg_lang) {
      msg_lang = getenv("LC_MESSAGES");
      if (!msg_lang || !*msg_lang) {
	 msg_lang = getenv("LANG");
	 /* Something (AutoCAD?) on Microsoft Windows sets LANG to a number. */
	 if (msg_lang && !isalpha(msg_lang[0])) msg_lang = NULL;
      }
      if (!msg_lang || !*msg_lang) {
#if OS_WIN32
	 LCID locid;
#endif
#ifdef DEFAULTLANG
	 msg_lang = STRING(DEFAULTLANG);
#else
	 msg_lang = "en";
#endif
#if OS_WIN32
	 /* GetUserDefaultUILanguage() requires Microsoft Windows 2000 or
	  * newer.  For older versions, we use GetUserDefaultLCID().
	  */
	 {
	    HMODULE win32 = GetModuleHandle(TEXT("kernel32.dll"));
	    FARPROC f = GetProcAddress(win32, "GetUserDefaultUILanguage");
	    if (f) {
	       typedef LANGID (WINAPI *func_GetUserDefaultUILanguage)(void);
	       func_GetUserDefaultUILanguage g;
	       g = (func_GetUserDefaultUILanguage)f;
	       locid = g();
	    } else {
	       locid = GetUserDefaultLCID();
	    }
	 }
	 if (locid) {
	    WORD langid = LANGIDFROMLCID(locid);
	    switch (PRIMARYLANGID(langid)) {
	     case LANG_BULGARIAN:
	       msg_lang = "bg";
	       break;
/* older mingw compilers don't seem to supply this value */
#ifndef LANG_CATALAN
# define LANG_CATALAN 0x03
#endif
	     case LANG_CATALAN:
	       msg_lang = "ca";
	       break;
	     case LANG_CHINESE:
	       msg_lang = "zh_CN";
	       break;
	     case LANG_ENGLISH:
	       if (SUBLANGID(langid) == SUBLANG_ENGLISH_US)
		  msg_lang = "en_US";
	       else
		  msg_lang = "en";
	       break;
	     case LANG_FRENCH:
	       msg_lang = "fr";
	       break;
	     case LANG_GERMAN:
	       switch (SUBLANGID(langid)) {
		case SUBLANG_GERMAN_SWISS:
		  msg_lang = "de_CH";
		  break;
		default:
		  msg_lang = "de";
	       }
	       break;
	     case LANG_GREEK:
	       msg_lang = "el";
	       break;
	     case LANG_HUNGARIAN:
	       msg_lang = "hu";
	       break;
	     case LANG_INDONESIAN:
	       msg_lang = "id";
	       break;
	     case LANG_ITALIAN:
	       msg_lang = "it";
	       break;
	     case LANG_POLISH:
	       msg_lang = "pl";
	       break;
	     case LANG_PORTUGUESE:
	       if (SUBLANGID(langid) == SUBLANG_PORTUGUESE_BRAZILIAN)
		  msg_lang = "pt_BR";
	       else
		  msg_lang = "pt";
	       break;
	     case LANG_ROMANIAN:
	       msg_lang = "ro";
	       break;
	     case LANG_RUSSIAN:
	       msg_lang = "ru";
	       break;
	     case LANG_SLOVAK:
	       msg_lang = "sk";
	       break;
	     case LANG_SPANISH:
	       msg_lang = "es";
	       break;
	    }
	 }
#endif
      }
   }
#ifdef DEBUG
   fprintf(stderr, "msg_lang = %p (= \"%s\")\n", msg_lang, msg_lang?msg_lang:"(null)");
#endif

   /* On Mandrake LANG defaults to C */
   if (strcmp(msg_lang, "C") == 0) msg_lang = "en";

   { /* If msg_lang has a country code, snip it out to give msg_lang2. */
      size_t b = 0;
      while (isalpha((unsigned char)msg_lang[b])) {
	 ++b;
      }
      if (msg_lang[b] == '_') {
	 char * tmp;
	 size_t e = b + 1;
	 while (isalpha((unsigned char)msg_lang[e])) {
	    ++e;
	 }
	 tmp = osstrdup(msg_lang);
	 memmove(tmp + b, tmp + e, strlen(tmp + e) + 1);
	 msg_lang2 = tmp;
      }
   }

#ifdef LC_MESSAGES
   /* try to setlocale() appropriately too */
   if (!setlocale(LC_MESSAGES, msg_lang)) {
      if (msg_lang2) {
	 (void)setlocale(LC_MESSAGES, msg_lang2);
      }
   }
#endif

   select_charset(default_charset());
}
Example #14
0
VOID
CmGetSystemControlValues(
    __in PVOID                   SystemHiveBuffer,
    __inout PCM_SYSTEM_CONTROL_VECTOR  ControlVector
    )
/*++

Routine Description:

    Look for registry values in current control set, as specified
    by entries in ControlVector.  Report data for value entries
    (if any) to variables ControlVector points to.

Arguments:

    SystemHiveBuffer - pointer to flat image of the system hive

    ControlVector - pointer to structure that describes what values
                    to pull out and store

Return Value:

    NONE.

--*/
{
    NTSTATUS        status;
    PHHIVE          SystemHive;
    HCELL_INDEX     RootCell;
    HCELL_INDEX     BaseCell;
    UNICODE_STRING  Name;
    HCELL_INDEX     KeyCell;
    HCELL_INDEX     ValueCell;
    PCM_KEY_VALUE   ValueBody;
    ULONG           Length;
    BOOLEAN         AutoSelect;
    BOOLEAN         small;
    ULONG           tmplength;
    PCM_KEY_NODE    Node;

    //
    // set up to read flat system hive image loader passes us
    //
    RtlZeroMemory((PVOID)&CmControlHive, sizeof(CmControlHive));
    SystemHive = &(CmControlHive.Hive);
    CmpInitHiveViewList((PCMHIVE)SystemHive);
    CmpInitSecurityCache((PCMHIVE)SystemHive);
    status = HvInitializeHive(
                SystemHive,
                HINIT_FLAT,
                HIVE_VOLATILE,
                HFILE_TYPE_PRIMARY,
                SystemHiveBuffer,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                NULL,
                1,
                NULL
                );
    if (!NT_SUCCESS(status)) {
         CM_BUGCHECK(BAD_SYSTEM_CONFIG_INFO,BAD_SYSTEM_CONTROL_VALUES,1,SystemHive,status);
    }

    //
    // don't bother locking/releasing cells
    //
    ASSERT( SystemHive->ReleaseCellRoutine == NULL );
    //
    // get hive.cell of root of current control set
    //
    RootCell = ((PHBASE_BLOCK)SystemHiveBuffer)->RootCell;
    RtlInitUnicodeString(&Name, L"current");
    BaseCell = CmpFindControlSet(
                    SystemHive,
                    RootCell,
                    &Name,
                    &AutoSelect
                    );
    if (BaseCell == HCELL_NIL) {
        CM_BUGCHECK(BAD_SYSTEM_CONFIG_INFO,BAD_SYSTEM_CONTROL_VALUES,2,SystemHive,&Name);
    }

    Node = (PCM_KEY_NODE)HvGetCell(SystemHive,BaseCell);
    if( Node == NULL ) {
        //
        // we couldn't map a view for the bin containing this cell
        //
        return;
    }
    RtlInitUnicodeString(&Name, L"control");
    BaseCell = CmpFindSubKeyByName(SystemHive,
                                   Node,
                                   &Name);
    if (BaseCell == HCELL_NIL) {
        CM_BUGCHECK(BAD_SYSTEM_CONFIG_INFO,BAD_SYSTEM_CONTROL_VALUES,3,Node,&Name);
    }

    //
    // SystemHive.BaseCell = \registry\machine\system\currentcontrolset\control
    //

    //
    // step through vector, trying to fetch each value
    //
    while (ControlVector->KeyPath != NULL) {

        //
        //  Assume we will fail to find the key or value.
        //
        
        Length = (ULONG)-1;

        KeyCell = CmpWalkPath(SystemHive, BaseCell, ControlVector->KeyPath);

        if (KeyCell != HCELL_NIL) {

            //
            // found the key, look for the value entry
            //
            Node = (PCM_KEY_NODE)HvGetCell(SystemHive,KeyCell);
            if( Node == NULL ) {
                //
                // we couldn't map a view for the bin containing this cell
                //
                return;
            }
            RtlInitUnicodeString(&Name, ControlVector->ValueName);
            ValueCell = CmpFindValueByName(SystemHive,
                                           Node,
                                           &Name);
            if (ValueCell != HCELL_NIL) {

                //
                // SystemHive.ValueCell is value entry body
                //

                if (ControlVector->BufferLength == NULL) {
                    tmplength = sizeof(ULONG);
                } else {
                    tmplength = *(ControlVector->BufferLength);
                }

                ValueBody = (PCM_KEY_VALUE)HvGetCell(SystemHive, ValueCell);
                if( ValueBody == NULL ) {
                    //
                    // we couldn't map a view for the bin containing this cell
                    //
                    return;
                }

                small = CmpIsHKeyValueSmall(Length, ValueBody->DataLength);

                if (tmplength < Length) {
                    Length = tmplength;
                }

                if (Length > 0) {

                    PCELL_DATA  Buffer;
                    BOOLEAN     BufferAllocated;
                    ULONG       realsize;
                    HCELL_INDEX CellToRelease;

                    ASSERT((small ? (Length <= CM_KEY_VALUE_SMALL) : TRUE));
                    //
                    // get the data from source, regardless of the size
                    //
                    if( CmpGetValueData(SystemHive,ValueBody,&realsize,&Buffer,&BufferAllocated,&CellToRelease) == FALSE ) {
                        //
                        // insufficient resources; return NULL
                        //
                        ASSERT( BufferAllocated == FALSE );
                        ASSERT( Buffer == NULL );
                        return;
                    }

                    RtlCopyMemory(
                        ControlVector->Buffer,
                        Buffer,
                        Length
                        );

                    //
                    // cleanup the temporary buffer
                    //
                    if( BufferAllocated == TRUE ) {
                        ExFreePool( Buffer );
                    }
                    if( CellToRelease != HCELL_NIL ) {
                        HvReleaseCell(SystemHive,CellToRelease);
                    }
                }

                if (ControlVector->Type != NULL) {
                    *(ControlVector->Type) = ValueBody->Type;
                }
            }
        }

        //
        // Stash the length of result (-1 if nothing was found)
        //
        
        if (ControlVector->BufferLength != NULL) {
            *(ControlVector->BufferLength) = Length;
        }

        ControlVector++;
    }

    //
    // Get the default locale ID for the system from the registry.
    //

    if (CmDefaultLanguageIdType == REG_SZ) {
        PsDefaultSystemLocaleId = (LCID) CmpConvertLangId( 
                                                CmDefaultLanguageId,
                                                CmDefaultLanguageIdLength);
    } else {
        PsDefaultSystemLocaleId = 0x00000409;
    }

    //
    // Get the install (native UI) language ID for the system from the registry.
    //

    if (CmInstallUILanguageIdType == REG_SZ) {
        PsInstallUILanguageId =  CmpConvertLangId( 
                                                CmInstallUILanguageId,
                                                CmInstallUILanguageIdLength);
    } else {
        PsInstallUILanguageId = LANGIDFROMLCID(PsDefaultSystemLocaleId);
    }

    //
    // Set the default thread locale to the default system locale
    // for now.  This will get changed as soon as somebody logs in.
    // Use the install (native) language id as our default UI language id. 
    // This also will get changed as soon as somebody logs in.
    //

    PsDefaultThreadLocaleId = PsDefaultSystemLocaleId;
    PsDefaultUILanguageId = PsInstallUILanguageId;
}
/*
	static
*/
DialectCode	VComponentManager::GetLocalizationLanguage(VFolder * inLocalizationResourcesFolder,bool inGotoResourceFolder)
{
	DialectCode sResult = XBOX::DC_NONE;	// sc 19/05/2008 was XBOX::DC_ENGLISH_US
	VFolder * localizationResourcesFolder = NULL;
	
	if(testAssert(inLocalizationResourcesFolder != NULL && inLocalizationResourcesFolder->Exists()))
	{
		if (inGotoResourceFolder)
		{
			XBOX::VFilePath componentOrPluginFolderPath = inLocalizationResourcesFolder->GetPath();
			componentOrPluginFolderPath.ToSubFolder(CVSTR("Contents")).ToSubFolder(CVSTR("Resources"));
			localizationResourcesFolder = new XBOX::VFolder(componentOrPluginFolderPath);
		}
		else
		{
			localizationResourcesFolder = inLocalizationResourcesFolder;
			localizationResourcesFolder->Retain();
		}

		bool englishFolderDetected = false;
		XBOX::DialectCode dialectCode = XBOX::DC_NONE;
		
		//Detect what is the favorite language of the OS/App
#if VERSIONWIN
		LCID lcid = ::GetUserDefaultLCID();
		XBOX::DialectCode currentDialectCode = (XBOX::DialectCode)LANGIDFROMLCID(lcid);

#elif VERSION_LINUX

		//jmo - Be coherent with code in VIntlMgr.cpp
		XBOX::DialectCode currentDialectCode=XBOX::DC_ENGLISH_US;   // Postponed Linux Implementation !
		
#else

		CFBundleRef	bundle = ::CFBundleGetMainBundle();
		XBOX::DialectCode currentDialectCode = XBOX::DC_ENGLISH_US;
		if ( bundle != nil ){
			CFArrayRef array_ref = ::CFBundleCopyBundleLocalizations(bundle);			
			if (array_ref != nil){
				CFArrayRef usedLanguages = ::CFBundleCopyPreferredLocalizationsFromArray(array_ref);
				CFStringRef cfPrimaryLanguage = (CFStringRef)CFArrayGetValueAtIndex(usedLanguages, 0);
				XBOX::VString xboxPrimaryLanguage;
				xboxPrimaryLanguage.MAC_FromCFString(cfPrimaryLanguage);
				::CFRelease(usedLanguages);
				if(!XBOX::VIntlMgr::GetDialectCodeWithISOLanguageName(xboxPrimaryLanguage, currentDialectCode))
					if(!XBOX::VIntlMgr::GetDialectCodeWithRFC3066BisLanguageCode(xboxPrimaryLanguage, currentDialectCode))
						currentDialectCode = XBOX::DC_ENGLISH_US;
				CFRelease(array_ref);
			}
		}
#endif
		//Try to see if we have this language. If not, take english
		for ( XBOX::VFolderIterator folderIter( localizationResourcesFolder ); folderIter.IsValid() && currentDialectCode != dialectCode ; ++folderIter )
		{
			XBOX::VString folderName;
			folderIter->GetName(folderName);
			uLONG posStr = folderName.Find(CVSTR(".lproj"), 1, false);
			if ( posStr > 0 )
			{
				folderName.Remove(posStr, folderName.GetLength() - posStr + 1);
				if( XBOX::VIntlMgr::GetDialectCodeWithRFC3066BisLanguageCode(folderName, dialectCode ) || XBOX::VIntlMgr::GetDialectCodeWithISOLanguageName(folderName, dialectCode)){
					if(dialectCode == XBOX::DC_ENGLISH_US)
						englishFolderDetected = true;
					
					if(currentDialectCode == dialectCode)
						sResult = dialectCode;
				}
			}
		}
		
		if ( sResult == XBOX::DC_NONE ){
			if ( englishFolderDetected ) 
				sResult = XBOX::DC_ENGLISH_US;
			else 
				sResult = dialectCode;
		}
		
		ReleaseRefCountable(&localizationResourcesFolder);
	}
	
	return sResult;
}
Example #16
0
BOOL CTMonitorApp::InitInstance()
{

	CWinApp::InitInstance();

	AfxEnableControlContainer();

	// Create the shell manager, in case the dialog contains
	// any shell tree view or shell list view controls.
	CShellManager *pShellManager = new CShellManager;

	// Standard initialization
	// If you are not using these features and wish to reduce the size
	// of your final executable, you should remove from the following
	// the specific initialization routines you do not need
	// Change the registry key under which our settings are stored
	// TODO: You should modify this string to be something appropriate
	// such as the name of your company or organization
	SetRegistryKey(_T("Local AppWizard-Generated Applications"));

	CString strPath = CUtils::GetAppPath();
	CString strConfigName = CUtils::GetFilePathWithoutName(strPath) + CONFIG_FILE;

	CIni ini(strConfigName);

	int language = ini.GetInt(_T("Language"),_T("Language"),-1);
	LCID lcid = GetThreadLocale();
	if (language == 0)
	{
		if (LANG_CHINESE == PRIMARYLANGID(LANGIDFROMLCID(lcid)))
		{
			SetThreadUILanguage(MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US));
		}
		
	}
	else if (language == 1)
	{
		if (LANG_ENGLISH == PRIMARYLANGID(LANGIDFROMLCID(lcid)))
		{
			SetThreadUILanguage(MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED));
		}
		
	}

	CTMonitorDlg dlg;
	m_pMainWnd = &dlg;
	INT_PTR nResponse = dlg.DoModal();
	if (nResponse == IDOK)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with OK
	}
	else if (nResponse == IDCANCEL)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with Cancel
	}

	// Delete the shell manager created above.
	if (pShellManager != NULL)
	{
		delete pShellManager;
	}

	// Since the dialog has been closed, return FALSE so that we exit the
	//  application, rather than start the application's message pump.
	return FALSE;
}
Example #17
0
BOOL OdbcMsg::GetOdbcMessage (DWORD dwLangId, DWORD ErrCode, ODBCMXMSG_Def *MsgStruc, ...)
//************************************************************************
//*
//*   Function:  GetOdbcMessage
//*
//*   Input Params: ErrCode - the Message ID to look for in the message file
//*
//*   Output Params: MsgStruc - The Message text components
//*
//*   Description:  It will look for the message in the messages file (if loaded).
//*					Valid values for the language are generated through the MAKELANGID 
//*					macro and the provided LANG_*, SUBLANG_* literals; 
//*					to use the pre-defined value the user can retrieve it using the 
//*					GetLanguageId function in this class.
//************************************************************************
{
	UINT	actual_len;
	DWORD	error_code;
	LPTSTR	lpMsgBuf;
	va_list	Arguments;

	va_start( Arguments, MsgStruc);
	lpMsgBuf = NULL;

	// clean up message structure
	CleanUpMsgStructure(MsgStruc);
	if (bMsgDLLLoaded)
	{
		// Load string from the DLL
		// if the function cannot find a message for the LANGID specified,
		// it returns ERROR_RESOURCE_LANG_NOT_FOUND; if we pass 0, it will look for
		// a message in te following order:
		//	1) Language Neutral
		//  2) Thread LANGID
		//  3) user default LANGID, based on user locale (be aware that it could be the server)
		//  4) system default LANGID
		//  5) US English

		actual_len = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
			FORMAT_MESSAGE_FROM_HMODULE,
			hMsgDll,
			ErrCode,
			LANGIDFROMLCID(dwLangId),
			(LPTSTR) &lpMsgBuf,
			0,
			&Arguments	// va_list
			);
		error_code = GetLastError();
		if ((actual_len == 0) && (error_code == ERROR_RESOURCE_LANG_NOT_FOUND))
		{
			// deallocate previously allocated buffer
			if (lpMsgBuf)
				LocalFree( lpMsgBuf );

			// if the specified language is not there, try english as default
			actual_len = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
				FORMAT_MESSAGE_FROM_HMODULE,
				hMsgDll,
				ErrCode,
				MAKELANGID (LANG_ENGLISH, SUBLANG_NEUTRAL),
				(LPTSTR) &lpMsgBuf,
				0,
				&Arguments	// va_list
				);
			error_code = GetLastError();
			if ((actual_len == 0) && 
				(error_code == ERROR_RESOURCE_LANG_NOT_FOUND) &&
				(dwLangId != 0)) // lang id = 0 already tested before
			{
				// deallocate previously allocated buffer
				if (lpMsgBuf)
					LocalFree( lpMsgBuf );

				// try the default option for FormatMessage
				actual_len = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
					FORMAT_MESSAGE_FROM_HMODULE,
					hMsgDll,
					ErrCode,
					0,	// to go through all default four options again
					(LPTSTR) &lpMsgBuf,
					0,
					&Arguments	// va_list
					);
				if (actual_len == 0) // cannot get the message, maybe is not there
				{
					ReportError (MsgStruc, ErrCode, GetLastError());
				}
				else
				{
					// we got the message finally
					FillMsgStructure(ErrCode, (LPSTR)lpMsgBuf, MsgStruc, actual_len);
				}
			}
			else if (actual_len > 0)
			{
				// we got something, let's return it
				FillMsgStructure(ErrCode, (LPSTR)lpMsgBuf, MsgStruc, actual_len);
			}
			else
			{
				// this is an error
				ReportError (MsgStruc, ErrCode, GetLastError());
			}
		}
		else if (actual_len > 0)
		{
			// we got a message, return it
			FillMsgStructure(ErrCode, (LPSTR)lpMsgBuf, MsgStruc, actual_len);
		}
		else
		{
			// it is trully and error
			ReportError (MsgStruc, ErrCode, GetLastError());
		}
		// deallocate previously allocated buffer
		if (lpMsgBuf)
			LocalFree( lpMsgBuf );
	}
	else // Message DLL is not loaded
	{
		ReportError (MsgStruc, ErrCode, 0) ;
		return FALSE;
	}
	// if successfull, return TRUE
	return TRUE;
}
JavascriptString*
DateImplementation::GetDateLocaleString(DateTime::YMD *pymd, TZD *ptzd, DateTimeFlag noDateTime,ScriptContext* scriptContext)
{
    SYSTEMTIME st;
    int cch;
    int count = 0;
    const int kcchMax = 256;
    WCHAR wszBuf[kcchMax];
    WCHAR *pwszBuf, *pToBeFreed = NULL, *p;
    JavascriptString *bs = nullptr;

    // the caller of this function should ensure that the range of pymd->year is such that the following conversion works.
    st.wYear = (WORD)pymd->year;
    st.wMonth = (WORD)pymd->mon + 1;
    st.wDayOfWeek = (WORD)pymd->wday;
    st.wDay = (WORD)pymd->mday + 1;
    st.wHour = (WORD)(pymd->time / 3600000);
    st.wMinute = (WORD)((pymd->time / 60000) % 60);
    st.wSecond = (WORD)((pymd->time / 1000) % 60);
    st.wMilliseconds = (WORD)(pymd->time % 60);

    cch = 0;

    LCID lcid = GetUserDefaultLCID();
    if( !(noDateTime & DateTimeFlag::NoDate))
    {
        DWORD dwFormat = DATE_LONGDATE;

        if ((PRIMARYLANGID(LANGIDFROMLCID(lcid)) == LANG_ARABIC) ||
                (PRIMARYLANGID(LANGIDFROMLCID(lcid)) == LANG_HEBREW))
        {
            dwFormat |= DATE_RTLREADING;
        }
        int c = GetDateFormatW( lcid, dwFormat, &st, NULL, NULL, 0 );

        if( c <= 0 )
        {
            if (PRIMARYLANGID(LANGIDFROMLCID(lcid)) == LANG_HEBREW)
            {
                // Can't support some Hebrew dates - current limit is 1 Jan AD 2240
                Js::JavascriptError::ThrowRangeError(scriptContext, VBSERR_CantDisplayDate);
            }

            AssertMsg(false, "GetDateFormat failed");
            goto Error;
        }
        cch += c;
    }

    if( !(noDateTime & DateTimeFlag::NoTime))
    {
        int c = GetTimeFormatW( lcid, 0, &st, NULL, NULL, 0 );
        if( c <= 0 )
        {
            AssertMsg(false, "GetTimeFormat failed");
            goto Error;
        }
        cch += c;
    }
    cch++; // For the space between the date and the time.

    if( cch > kcchMax )
    {
        pwszBuf = pToBeFreed = (WCHAR *)malloc( cch * sizeof(WCHAR) );
        if(!pwszBuf)
        {
            Js::JavascriptError::ThrowOutOfMemoryError(scriptContext);
        }
    }
    else
    {
        wszBuf[0] = '\0';
        pwszBuf = wszBuf;
    }

    count = cch;
    p = pwszBuf;

    if( !(noDateTime & DateTimeFlag::NoDate))
    {
        DWORD dwFormat = DATE_LONGDATE;

        if ((PRIMARYLANGID(LANGIDFROMLCID(lcid)) == LANG_ARABIC) ||
                (PRIMARYLANGID(LANGIDFROMLCID(lcid)) == LANG_HEBREW))
        {
            dwFormat |= DATE_RTLREADING;
        }
        int c = GetDateFormatW( lcid, dwFormat, &st, NULL, p, cch );

        if( c <= 0 || c > cch)
        {
            if (PRIMARYLANGID(LANGIDFROMLCID(lcid)) == LANG_HEBREW)
            {
                // Can't support some Hebrew dates - current limit is 1 Jan AD 2240
                Js::JavascriptError::ThrowRangeError(scriptContext, VBSERR_CantDisplayDate);
            }

            AssertMsg(false, "GetDateFormat failed");
            goto Error;
        }

        p += (c-1);
        cch -= (c-1);
        if( !(noDateTime & DateTimeFlag::NoTime))
        {
            *p++ = _u(' ');
            cch--;
        }

    }

    if( !(noDateTime & DateTimeFlag::NoTime))
    {
        int c = GetTimeFormatW( lcid, 0, &st, NULL, p, cch );
        Assert( c > 0 );
        if( c <= 0 )
        {
            AssertMsg(false, "GetTimeFormat failed");
            goto Error;
        }
        cch -= (c-1);
    }

    bs = JavascriptString::NewCopyBuffer(pwszBuf, count-cch, scriptContext);

Error:
    if( pToBeFreed )
        free(pToBeFreed);

    return bs;
}
// Get the list of keyboard layouts available in the system
// Set mLTRKeyboard to the first LTR keyboard in the list and mRTLKeyboard to the first RTL keyboard in the list
// These defaults will be used unless the user explicitly sets something else.
nsresult nsBidiKeyboard::SetupBidiKeyboards()
{
  if (mInitialized)
    return mHaveBidiKeyboards ? NS_OK : NS_ERROR_FAILURE;

  int keyboards;
  HKL far* buf;
  HKL locale;
  PRUnichar localeName[KL_NAMELENGTH];
  bool isLTRKeyboardSet = false;
  bool isRTLKeyboardSet = false;
  
  // GetKeyboardLayoutList with 0 as first parameter returns the number of keyboard layouts available
  keyboards = ::GetKeyboardLayoutList(0, nsnull);
  if (!keyboards)
    return NS_ERROR_FAILURE;

  // allocate a buffer to hold the list
  buf = (HKL far*) PR_Malloc(keyboards * sizeof(HKL));
  if (!buf)
    return NS_ERROR_OUT_OF_MEMORY;

  // Call again to fill the buffer
  if (::GetKeyboardLayoutList(keyboards, buf) != keyboards) {
    PR_Free(buf);
    return NS_ERROR_UNEXPECTED;
  }

  // Go through the list and pick a default LTR and RTL keyboard layout
  while (keyboards--) {
    locale = buf[keyboards];
    if (IsRTLLanguage(locale)) {
      _snwprintf(mRTLKeyboard, KL_NAMELENGTH, L"%.*x", KL_NAMELENGTH - 1,
                 LANGIDFROMLCID((DWORD_PTR)locale));
      isRTLKeyboardSet = true;
    }
    else {
      _snwprintf(mLTRKeyboard, KL_NAMELENGTH, L"%.*x", KL_NAMELENGTH - 1,
                 LANGIDFROMLCID((DWORD_PTR)locale));
      isLTRKeyboardSet = true;
    }
  }
  PR_Free(buf);
  mInitialized = true;

  // If there is not at least one keyboard of each directionality, Bidi
  // keyboard functionality will be disabled.
  mHaveBidiKeyboards = (isRTLKeyboardSet && isLTRKeyboardSet);
  if (!mHaveBidiKeyboards)
    return NS_ERROR_FAILURE;

  // Get the current keyboard layout and use it for either mRTLKeyboard or
  // mLTRKeyboard as appropriate. If the user has many keyboard layouts
  // installed this prevents us from arbitrarily resetting the current
  // layout (bug 80274)
  locale = ::GetKeyboardLayout(0);
  if (!::GetKeyboardLayoutNameW(localeName))
    return NS_ERROR_FAILURE;

  NS_ASSERTION(*localeName, 
    "GetKeyboardLayoutName return string length == 0");
  NS_ASSERTION((wcslen(localeName) < KL_NAMELENGTH), 
    "GetKeyboardLayout return string length >= KL_NAMELENGTH");

  if (IsRTLLanguage(locale)) {
    wcsncpy(mRTLKeyboard, localeName, KL_NAMELENGTH);
    mRTLKeyboard[KL_NAMELENGTH-1] = '\0'; // null terminate
  }
  else {
    wcsncpy(mLTRKeyboard, localeName, KL_NAMELENGTH);
    mLTRKeyboard[KL_NAMELENGTH-1] = '\0'; // null terminate
  }

  NS_ASSERTION(*mRTLKeyboard, 
    "mLTRKeyboard has string length == 0");
  NS_ASSERTION(*mLTRKeyboard, 
    "mLTRKeyboard has string length == 0");

  return NS_OK;
}
Example #20
0
/*----------------------------------------------------------------------------------------------
	Set the keyboard through TSF
----------------------------------------------------------------------------------------------*/
bool SetKeyboard_TSF(bool fDoingKeyman, int lcid, int * pnActiveLangId)
{
#ifdef Tracing_KeybdSelection
	StrAnsi sta;
	sta.Format("LgTextServices::SetKeyboard(%d) [making TSF calls]%n", lcid);
	::OutputDebugStringA(sta.Chars());
	sta.Format("LgTextServices::SetKeyboard(%d) - ::GetKeyboardLayout() = %x%n",
		lcid, ::GetKeyboardLayout(0));
	::OutputDebugStringA(sta.Chars());
#endif
	HRESULT hr = S_OK;
	ITfInputProcessorProfilesPtr qtfipp;
	int nLangId = LANGIDFROMLCID(lcid);
	bool fSetInputLang = false;
	// Don't check the HR or use CreateInstance; I (JohnT) think this may fail if TSF is not
	// fully active.
	::CoCreateInstance(CLSID_TF_InputProcessorProfiles, NULL, CLSCTX_ALL,
		IID_ITfInputProcessorProfiles, (void **)&qtfipp);
	if (!qtfipp)
	{
		Warn("Could not get ITfInputProcessorProfiles to set Keyman text service\n");
	}
	else
	{
		// Have to make the language active before we can set the profile;
		// and want to set the language even if we aren't doing Keyman.
		if (*pnActiveLangId != (LANGID)nLangId)
		{
			// Do NOT do this if the right langID is already current. In some bizarre cases
			// during WM_INPUTLANGCHANGED it can lead to a new input-lang-changed in a
			// DIFFERENT language and an infinite loop.
			*pnActiveLangId = (LANGID)nLangId;
			IgnoreHr(hr = qtfipp->ChangeCurrentLanguage((LANGID)nLangId));
		}
#ifdef Tracing_KeybdSelection
		sta.Format(
			"LgTextServices::SetKeyboard(%d) [qtfipp->ChangeCL(%d) => hr = %x]%n",
			lcid, nLangId, hr);
		::OutputDebugStringA(sta.Chars());
#endif
		if (FAILED(hr))
		{
			Warn("failed to change language\n");
		}
		else if (fDoingKeyman)
		{
			// Make sure the Keyman text service is turned on. For some bizarre reason there is
			// no API to just ask for the service to turn on for the langid, we have to do our
			// own search for the profile that corresponds to this langid and text service.
			IEnumTfLanguageProfilesPtr qenum;
	#ifdef Tracing_KeybdSelection
			sta.Format("LgTextServices::SetKeyboard(%d) [qtfipp->EnumLP(%d)]%n",
				lcid, nLangId);
			::OutputDebugStringA(sta.Chars());
			sta.Format("LgTextServices::SetKeyboard(%d) - ::GetKeyboardLayout() = %x%n",
				lcid, ::GetKeyboardLayout(0));
			::OutputDebugStringA(sta.Chars());
	#endif
			IgnoreHr(hr = qtfipp->EnumLanguageProfiles((LANGID)nLangId, &qenum));
			if (FAILED(hr))
			{
				Warn("Could not get enumerator for language profiles\n");
			}
			else
			{
				// If doing keyman try to turn on Keyman text service.
				TF_LANGUAGEPROFILE profile;
				for ( ; ; )
				{
					ULONG cprofile;
					IgnoreHr(hr = qenum->Next(1, &profile, &cprofile));
					if (FAILED(hr) || cprofile != 1)
					{
						Warn("failed to find language profiled for Keyman\n");
						break;
					}
					if (kclsidKMTipTextService == profile.clsid)
					{
						// got it at last!
#ifdef Tracing_KeybdSelection
						StrAnsi sta;
						sta.Format("LgTextServices::SetKeyboard(%d) - "
							"qtfipp->ActivateLanguageProfile(nLangId = %d)\n",
							lcid, nLangId);
						::OutputDebugStringA(sta.Chars());
#endif
						IgnoreHr(hr = qtfipp->ActivateLanguageProfile(
							kclsidKMTipTextService, (LANGID)nLangId, profile.guidProfile));
						if (FAILED(hr))
						{
							Warn("failed to activate language profile\n");
						}
						else
						{
							fSetInputLang = true;
						}
						break;
					}
				}
			}
#ifdef Tracing_KeybdSelection
			sta.Format("LgTextServices::SetKeyboard(%d) [after qtfipp->ChangeCL(%d)]%n",
				lcid, nLangId);
			::OutputDebugStringA(sta.Chars());
			sta.Format("LgTextServices::SetKeyboard(%d) - ::GetKeyboardLayout() = %x%n",
				lcid, ::GetKeyboardLayout(0));
			::OutputDebugStringA(sta.Chars());
#endif
		}
		else
		{
			// We're not doing keyman, but we already set the input language.
			fSetInputLang = true;
		}
	}
	return fSetInputLang;
}
Example #21
0
File: lsa.c Project: bilboed/wine
static void test_LsaLookupNames2(void)
{
    static const WCHAR n1[] = {'L','O','C','A','L',' ','S','E','R','V','I','C','E'};
    static const WCHAR n2[] = {'N','T',' ','A','U','T','H','O','R','I','T','Y','\\','L','o','c','a','l','S','e','r','v','i','c','e'};

    NTSTATUS status;
    LSA_HANDLE handle;
    LSA_OBJECT_ATTRIBUTES attrs;
    PLSA_REFERENCED_DOMAIN_LIST domains;
    PLSA_TRANSLATED_SID2 sids;
    LSA_UNICODE_STRING name[3];
    LPSTR account, sid_dom;

    if (!pLsaLookupNames2)
    {
        win_skip("LsaLookupNames2 not avaliable\n");
        return;
    }

    if (PRIMARYLANGID(LANGIDFROMLCID(GetThreadLocale())) != LANG_ENGLISH)
    {
        skip("Non-english locale (skipping LsaLookupNames2 tests)\n");
        return;
    }

    memset(&attrs, 0, sizeof(attrs));
    attrs.Length = sizeof(attrs);

    status = pLsaOpenPolicy(NULL, &attrs, POLICY_ALL_ACCESS, &handle);
    ok(status == STATUS_SUCCESS || status == STATUS_ACCESS_DENIED,
       "LsaOpenPolicy(POLICY_ALL_ACCESS) returned 0x%08x\n", status);

    /* try a more restricted access mask if necessary */
    if (status == STATUS_ACCESS_DENIED)
    {
        trace("LsaOpenPolicy(POLICY_ALL_ACCESS) failed, trying POLICY_VIEW_LOCAL_INFORMATION\n");
        status = pLsaOpenPolicy(NULL, &attrs, POLICY_LOOKUP_NAMES, &handle);
        ok(status == STATUS_SUCCESS, "LsaOpenPolicy(POLICY_VIEW_LOCAL_INFORMATION) returned 0x%08x\n", status);
    }
    if (status != STATUS_SUCCESS)
    {
        skip("Cannot acquire policy handle\n");
        return;
    }

    name[0].Buffer = HeapAlloc(GetProcessHeap(), 0, sizeof(n1));
    name[0].Length = name[0].MaximumLength = sizeof(n1);
    memcpy(name[0].Buffer, n1, sizeof(n1));

    name[1].Buffer = HeapAlloc(GetProcessHeap(), 0, sizeof(n1));
    name[1].Length = name[1].MaximumLength = sizeof(n1) - sizeof(WCHAR);
    memcpy(name[1].Buffer, n1, sizeof(n1) - sizeof(WCHAR));

    name[2].Buffer = HeapAlloc(GetProcessHeap(), 0, sizeof(n2));
    name[2].Length = name[2].MaximumLength = sizeof(n2);
    memcpy(name[2].Buffer, n2, sizeof(n2));

    /* account name only */
    sids = NULL;
    domains = NULL;
    status = pLsaLookupNames2(handle, 0, 1, &name[0], &domains, &sids);
    ok(status == STATUS_SUCCESS, "expected STATUS_SUCCESS, got %x)\n", status);
    ok(sids[0].Use == SidTypeWellKnownGroup, "expected SidTypeWellKnownGroup, got %u\n", sids[0].Use);
    ok(sids[0].Flags == 0, "expected 0, got 0x%08x\n", sids[0].Flags);
    ok(domains->Entries == 1, "expected 1, got %u\n", domains->Entries);
    get_sid_info(sids[0].Sid, &account, &sid_dom);
    ok(!strcmp(account, "LOCAL SERVICE"), "expected \"LOCAL SERVICE\", got \"%s\"\n", account);
    ok(!strcmp(sid_dom, "NT AUTHORITY"), "expected \"NT AUTHORITY\", got \"%s\"\n", sid_dom);
    pLsaFreeMemory(sids);
    pLsaFreeMemory(domains);

    /* unknown account name */
    sids = NULL;
    domains = NULL;
    status = pLsaLookupNames2(handle, 0, 1, &name[1], &domains, &sids);
    ok(status == STATUS_NONE_MAPPED, "expected STATUS_NONE_MAPPED, got %x)\n", status);
    ok(sids[0].Use == SidTypeUnknown, "expected SidTypeUnknown, got %u\n", sids[0].Use);
    ok(sids[0].Flags == 0, "expected 0, got 0x%08x\n", sids[0].Flags);
    ok(domains->Entries == 0, "expected 0, got %u\n", domains->Entries);
    pLsaFreeMemory(sids);
    pLsaFreeMemory(domains);

    /* account + domain */
    sids = NULL;
    domains = NULL;
    status = pLsaLookupNames2(handle, 0, 1, &name[2], &domains, &sids);
    ok(status == STATUS_SUCCESS, "expected STATUS_SUCCESS, got %x)\n", status);
    ok(sids[0].Use == SidTypeWellKnownGroup, "expected SidTypeWellKnownGroup, got %u\n", sids[0].Use);
    ok(sids[0].Flags == 0, "expected 0, got 0x%08x\n", sids[0].Flags);
    ok(domains->Entries == 1, "expected 1, got %u\n", domains->Entries);
    get_sid_info(sids[0].Sid, &account, &sid_dom);
    ok(!strcmp(account, "LOCAL SERVICE"), "expected \"LOCAL SERVICE\", got \"%s\"\n", account);
    ok(!strcmp(sid_dom, "NT AUTHORITY"), "expected \"NT AUTHORITY\", got \"%s\"\n", sid_dom);
    pLsaFreeMemory(sids);
    pLsaFreeMemory(domains);

    /* all three */
    sids = NULL;
    domains = NULL;
    status = pLsaLookupNames2(handle, 0, 3, name, &domains, &sids);
    ok(status == STATUS_SOME_NOT_MAPPED, "expected STATUS_SOME_NOT_MAPPED, got %x)\n", status);
    ok(sids[0].Use == SidTypeWellKnownGroup, "expected SidTypeWellKnownGroup, got %u\n", sids[0].Use);
    ok(sids[1].Use == SidTypeUnknown, "expected SidTypeUnknown, got %u\n", sids[0].Use);
    ok(sids[2].Use == SidTypeWellKnownGroup, "expected SidTypeWellKnownGroup, got %u\n", sids[0].Use);
    ok(sids[0].DomainIndex == 0, "expected 0, got %u\n", sids[0].DomainIndex);
    ok(domains->Entries == 1, "expected 1, got %u\n", domains->Entries);
    pLsaFreeMemory(sids);
    pLsaFreeMemory(domains);

    HeapFree(GetProcessHeap(), 0, name[0].Buffer);
    HeapFree(GetProcessHeap(), 0, name[1].Buffer);
    HeapFree(GetProcessHeap(), 0, name[2].Buffer);

    status = pLsaClose(handle);
    ok(status == STATUS_SUCCESS, "LsaClose() failed, returned 0x%08x\n", status);
}
Example #22
0
/*----------------------------------------------------------------------------------------------
	Set a keyman keyboard
----------------------------------------------------------------------------------------------*/
HRESULT SetKeyboard_Keyman(int lcid, BSTR bstrKeymanKbd, BSTR * pbstrActiveKeymanKbd,
	ComBool * pfSelectLangPending)
{
#ifdef Tracing_KeybdSelection
	StrAnsi sta;
	sta.Format("LgTextServices::SetKeyboard(%d) [setting Keyman kbd]%n", lcid);
	::OutputDebugStringA(sta.Chars());
#endif
	int nLangId = LANGIDFROMLCID(lcid);
	HRESULT hr = S_OK;
	ILgKeymanHandlerPtr qkh;
	qkh.CreateInstance(CLSID_LgKeymanHandler);
	// Tell Keyman about the particular keyboard (but only if it changed).
	if (IsKeyboardDifferent(bstrKeymanKbd, *pbstrActiveKeymanKbd))
	{
		// Activate the particular layout we want.
		// John Durdin says this next step is necessary.
		//::ActivateKeyboardLayout(::GetKeyboardLayout(0), 0);
		// JohnT: discovered that if we've never set a keyboard before, the current one
		// won't be right, but forcing the right langid into the low word seems to help.
		// Keyman always uses the US English keyboard, which is the magic number we're
		// stuffing into the high word.
		HKL hklDesired = (HKL)(0x04090000 | (nLangId & 0xffff));
#ifdef Tracing_KeybdSelection
		StrAnsi sta;
		sta.Format("LgTextServices::SetKeyboard(%d) - "
			"::ActivateKeyboardLayout(%d [%x], 0) for keyman setup\n",
			lcid, hklDesired, hklDesired);
		::OutputDebugStringA(sta.Chars());
#endif
		::ActivateKeyboardLayout(hklDesired, 0);

		try
		{
			CheckHr(qkh->put_ActiveKeyboardName(bstrKeymanKbd));
#ifdef TRACING_KEYMAN
			StrUni stuMsg;
			stuMsg.Format(L"%b is now the active Keyman keyboard.\n",
				bstrKeymanKbd);
			::OutputDebugStringW(stuMsg.Chars());
#endif
			if (*pbstrActiveKeymanKbd)
				::SysFreeString(*pbstrActiveKeymanKbd);
			CopyBstr(pbstrActiveKeymanKbd, bstrKeymanKbd);
			*pfSelectLangPending = true;
		}
		catch (Throwable& thr)
		{
			hr = thr.Result();
#ifdef TRACING_KEYMAN
			StrAnsi staMsg;
			staMsg.Format("Cannot make %B the active Keyman keyboard!?\n",
				bstrKeymanKbd);
			::OutputDebugStringA(staMsg.Chars());
#endif
			if (BstrLen(*pbstrActiveKeymanKbd))
			{
				// We failed, so ensure it's turned off.
				TurnOffKeymanKbd(pbstrActiveKeymanKbd);
				*pfSelectLangPending = true;
			}
		}
	}
	return hr;
}
Example #23
0
static void test_VarFormat(void)
{
  static const WCHAR szTesting[] = { 't','e','s','t','i','n','g','\0' };
  static const WCHAR szNum[] = { '3','9','6','9','7','.','1','1','\0' };
  size_t i;
  WCHAR buffW[256];
  char buff[256];
  VARIANT in;
  VARIANT_BOOL bTrue = VARIANT_TRUE, bFalse = VARIANT_FALSE;
  int fd = 0, fw = 0;
  ULONG flags = 0;
  BSTR bstrin, out = NULL;
  HRESULT hres;

  CHECKPTR(VarFormat);

  if (PRIMARYLANGID(LANGIDFROMLCID(GetUserDefaultLCID())) != LANG_ENGLISH)
  {
    skip("Skipping VarFormat tests for non English language\n");
    return;
  }
  GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, buff, sizeof(buff)/sizeof(char));
  if (buff[0] != '.' || buff[1])
  {
    skip("Skipping VarFormat tests as decimal separator is '%s'\n", buff);
    return;
  }
  GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_IDIGITS, buff, sizeof(buff)/sizeof(char));
  if (buff[0] != '2' || buff[1])
  {
    skip("Skipping VarFormat tests as decimal places is '%s'\n", buff);
    return;
  }

  VARFMT(VT_BOOL,V_BOOL,VARIANT_TRUE,"True/False",S_OK,"True");
  VARFMT(VT_BOOL,V_BOOL,VARIANT_FALSE,"True/False",S_OK,"False");

  VNUMFMT(VT_I1,V_I1);
  VNUMFMT(VT_I2,V_I2);
  VNUMFMT(VT_I4,V_I4);
  if (has_i8)
  {
    VNUMFMT(VT_I8,V_I8);
  }
  VNUMFMT(VT_INT,V_INT);
  VNUMFMT(VT_UI1,V_UI1);
  VNUMFMT(VT_UI2,V_UI2);
  VNUMFMT(VT_UI4,V_UI4);
  if (has_i8)
  {
    VNUMFMT(VT_UI8,V_UI8);
  }
  VNUMFMT(VT_UINT,V_UINT);
  VNUMFMT(VT_R4,V_R4);
  VNUMFMT(VT_R8,V_R8);

  /* Reference types are dereferenced */
  VARFMT(VT_BOOL|VT_BYREF,V_BOOLREF,&bTrue,"True/False",S_OK,"True");
  VARFMT(VT_BOOL|VT_BYREF,V_BOOLREF,&bFalse,"True/False",S_OK,"False");

  /* Dates */
  for (i = 0; i < sizeof(VarFormat_date_results)/sizeof(FMTDATERES); i++)
  {
    if (i < 7)
      fd = i + 1; /* Test first day */
    else
      fd = 0;
    VARFMT(VT_DATE,V_DATE,VarFormat_date_results[i].val,
           VarFormat_date_results[i].fmt,S_OK,
           VarFormat_date_results[i].res);
  }

  /* Named time formats */
  GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_STIMEFORMAT, buff, sizeof(buff)/sizeof(char));
  if (strcmp(buff, "h:mm:ss tt"))
  {
    skip("Skipping named time tests as time format is '%s'\n", buff);
  }
  else
  {
    for (i = 0; i < sizeof(VarFormat_namedtime_results)/sizeof(FMTDATERES); i++)
    {
      fd = 0;
      VARFMT(VT_DATE,V_DATE,VarFormat_namedtime_results[i].val,
             VarFormat_namedtime_results[i].fmt,S_OK,
             VarFormat_namedtime_results[i].res);
    }
  }

  /* Strings */
  bstrin = SysAllocString(szTesting);
  VARFMT(VT_BSTR,V_BSTR,bstrin,"",S_OK,"testing");
  VARFMT(VT_BSTR,V_BSTR,bstrin,"@",S_OK,"testing");
  VARFMT(VT_BSTR,V_BSTR,bstrin,"&",S_OK,"testing");
  VARFMT(VT_BSTR,V_BSTR,bstrin,"\\x@\\x@",S_OK,"xtxesting");
  VARFMT(VT_BSTR,V_BSTR,bstrin,"\\x&\\x&",S_OK,"xtxesting");
  VARFMT(VT_BSTR,V_BSTR,bstrin,"@\\x",S_OK,"txesting");
  VARFMT(VT_BSTR,V_BSTR,bstrin,"@@@@@@@@",S_OK," testing");
  VARFMT(VT_BSTR,V_BSTR,bstrin,"@\\x@@@@@@@",S_OK," xtesting");
  VARFMT(VT_BSTR,V_BSTR,bstrin,"&&&&&&&&",S_OK,"testing");
  VARFMT(VT_BSTR,V_BSTR,bstrin,"!&&&&&&&",S_OK,"testing");
  VARFMT(VT_BSTR,V_BSTR,bstrin,"&&&&&&&!",S_OK,"testing");
  VARFMT(VT_BSTR,V_BSTR,bstrin,">&&",S_OK,"TESTING");
  VARFMT(VT_BSTR,V_BSTR,bstrin,"<&&",S_OK,"testing");
  VARFMT(VT_BSTR,V_BSTR,bstrin,"<&>&",S_OK,"testing");
  SysFreeString(bstrin);
  bstrin = SysAllocString(szNum);
  todo_wine VARFMT(VT_BSTR,V_BSTR,bstrin,"hh:mm",S_OK,"02:38");
  todo_wine VARFMT(VT_BSTR,V_BSTR,bstrin,"mm-dd-yy",S_OK,"09-06-08");
  SysFreeString(bstrin);
  /* Numeric values are converted to strings then output */
  VARFMT(VT_I1,V_I1,1,"<&>&",S_OK,"1");

  /* Number formats */
  VARFMT(VT_I4,V_I4,1,"#00000000",S_OK,"00000001");
  VARFMT(VT_I4,V_I4,1,"000###",S_OK,"000001");
  VARFMT(VT_I4,V_I4,1,"#00##00#0",S_OK,"00000001");
  VARFMT(VT_I4,V_I4,1,"1#####0000",S_OK,"10001");
  VARFMT(VT_I4,V_I4,1,"##abcdefghijklmnopqrstuvwxyz",S_OK,"1abcdefghijklmnopqrstuvwxyz");
  VARFMT(VT_I4,V_I4,100000,"#,###,###,###",S_OK,"100,000");
  VARFMT(VT_I4,V_I4,1,"0,000,000,000",S_OK,"0,000,000,001");
  VARFMT(VT_I4,V_I4,123456789,"#,#.#",S_OK,"123,456,789.");
  VARFMT(VT_I4,V_I4,123456789,"###, ###, ###",S_OK,"123, 456, 789");
  VARFMT(VT_I4,V_I4,1,"#;-#",S_OK,"1");
  VARFMT(VT_I4,V_I4,-1,"#;-#",S_OK,"-1");
  VARFMT(VT_R8,V_R8,1.23456789,"0#.0#0#0#0#0",S_OK,"01.234567890");
  VARFMT(VT_R8,V_R8,1.2,"0#.0#0#0#0#0",S_OK,"01.200000000");
  VARFMT(VT_R8,V_R8,9.87654321,"#0.#0#0#0#0#",S_OK,"9.87654321");
  VARFMT(VT_R8,V_R8,9.8,"#0.#0#0#0#0#",S_OK,"9.80000000");
  VARFMT(VT_R8,V_R8,0.00000008,"#0.#0#0#0#0#0",S_OK,"0.0000000800");
  VARFMT(VT_R8,V_R8,0.00010705,"#0.##########",S_OK,"0.00010705");
  VARFMT(VT_I4,V_I4,17,"#0",S_OK,"17");
  VARFMT(VT_I4,V_I4,4711,"#0",S_OK,"4711");
  VARFMT(VT_I4,V_I4,17,"#00",S_OK,"17");
  VARFMT(VT_I4,V_I4,100,"0##",S_OK,"100");
  VARFMT(VT_I4,V_I4,17,"#000",S_OK,"017");
  VARFMT(VT_I4,V_I4,17,"#0.00",S_OK,"17.00");
  VARFMT(VT_I4,V_I4,17,"#0000.00",S_OK,"0017.00");
  VARFMT(VT_I4,V_I4,17,"#.00",S_OK,"17.00");
  VARFMT(VT_R8,V_R8,1.7,"#.00",S_OK,"1.70");
  VARFMT(VT_R8,V_R8,.17,"#.00",S_OK,".17");
  VARFMT(VT_I4,V_I4,17,"#3",S_OK,"173");
  VARFMT(VT_I4,V_I4,17,"#33",S_OK,"1733");
  VARFMT(VT_I4,V_I4,17,"#3.33",S_OK,"173.33");
  VARFMT(VT_I4,V_I4,17,"#3333.33",S_OK,"173333.33");
  VARFMT(VT_I4,V_I4,17,"#.33",S_OK,"17.33");
  VARFMT(VT_R8,V_R8,.17,"#.33",S_OK,".33");
  VARFMT(VT_R8,V_R8,1.7,"0.0000E-000",S_OK,"1.7000E000");
  VARFMT(VT_R8,V_R8,1.7,"0.0000e-1",S_OK,"1.7000e01");
  VARFMT(VT_R8,V_R8,86.936849,"#0.000000000000e-000",S_OK,"86.936849000000e000");
  VARFMT(VT_R8,V_R8,1.7,"#0",S_OK,"2");
  VARFMT(VT_R8,V_R8,1.7,"#.33",S_OK,"2.33");
  VARFMT(VT_R8,V_R8,1.7,"#3",S_OK,"23");
  VARFMT(VT_R8,V_R8,1.73245,"0.0000E+000",S_OK,"1.7325E+000");
  VARFMT(VT_R8,V_R8,9.9999999,"#0.000000",S_OK,"10.000000");
  VARFMT(VT_R8,V_R8,1.7,"0.0000e+0#",S_OK,"1.7000e+0");
  VARFMT(VT_R8,V_R8,100.0001e+0,"0.0000E+0",S_OK,"1.0000E+2");
  VARFMT(VT_R8,V_R8,1000001,"0.0000e+1",S_OK,"1.0000e+61");
  VARFMT(VT_R8,V_R8,100.0001e+25,"0.0000e+0",S_OK,"1.0000e+27");
  VARFMT(VT_R8,V_R8,450.0001e+43,"#000.0000e+0",S_OK,"4500.0010e+42");
  VARFMT(VT_R8,V_R8,0.0001e-11,"##00.0000e-0",S_OK,"1000.0000e-18");
  VARFMT(VT_R8,V_R8,0.0317e-11,"0000.0000e-0",S_OK,"3170.0000e-16");
  VARFMT(VT_R8,V_R8,0.0021e-11,"00##.0000e-0",S_OK,"2100.0000e-17");
  VARFMT(VT_R8,V_R8,1.0001e-27,"##00.0000e-0",S_OK,"1000.1000e-30");
  VARFMT(VT_R8,V_R8,47.11,".0000E+0",S_OK,".4711E+2");
  VARFMT(VT_R8,V_R8,3.0401e-13,"#####.####e-0%",S_OK,"30401.e-15%");
  VARFMT(VT_R8,V_R8,1.57,"0.00",S_OK,"1.57");
  VARFMT(VT_R8,V_R8,-1.57,"0.00",S_OK,"-1.57");
  VARFMT(VT_R8,V_R8,-1.57,"#.##",S_OK,"-1.57");
  VARFMT(VT_R8,V_R8,-0.1,".#",S_OK,"-.1");
  VARFMT(VT_R8,V_R8,0.099,"#.#",S_OK,".1");
  VARFMT(VT_R8,V_R8,0.0999,"#.##",S_OK,".1");
  VARFMT(VT_R8,V_R8,0.099,"#.##",S_OK,".1");
  VARFMT(VT_R8,V_R8,0.0099,"#.##",S_OK,".01");
  VARFMT(VT_R8,V_R8,0.0049,"#.##",S_OK,".");
  VARFMT(VT_R8,V_R8,0.0094,"#.##",S_OK,".01");
  VARFMT(VT_R8,V_R8,0.00099,"#.##",S_OK,".");
  VARFMT(VT_R8,V_R8,0.0995,"#.##",S_OK,".1");
  VARFMT(VT_R8,V_R8,8.0995,"#.##",S_OK,"8.1");
  VARFMT(VT_R8,V_R8,0.0994,"#.##",S_OK,".1");
  VARFMT(VT_R8,V_R8,1.00,"#,##0.00",S_OK,"1.00");
  VARFMT(VT_R8,V_R8,0.0995,"#.###",S_OK,".1");


  /* 'out' is not cleared */
  out = (BSTR)0x1;
  hres = pVarFormat(&in,NULL,fd,fw,flags,&out); /* Would crash if out is cleared */
  ok(hres == S_OK, "got %08x\n", hres);
  SysFreeString(out);
  out = NULL;

  /* VT_NULL */
  V_VT(&in) = VT_NULL;
  hres = pVarFormat(&in,NULL,fd,fw,0,&out);
  ok(hres == S_OK, "VarFormat failed with 0x%08x\n", hres);
  ok(out == NULL, "expected NULL formatted string\n");

  /* Invalid args */
  hres = pVarFormat(&in,NULL,fd,fw,flags,NULL);
  ok(hres == E_INVALIDARG, "Null out: expected E_INVALIDARG, got 0x%08x\n", hres);
  hres = pVarFormat(NULL,NULL,fd,fw,flags,&out);
  ok(hres == E_INVALIDARG, "Null in: expected E_INVALIDARG, got 0x%08x\n", hres);
  fd = -1;
  VARFMT(VT_BOOL,V_BOOL,VARIANT_TRUE,"",E_INVALIDARG,"");
  fd = 8;
  VARFMT(VT_BOOL,V_BOOL,VARIANT_TRUE,"",E_INVALIDARG,"");
  fd = 0; fw = -1;
  VARFMT(VT_BOOL,V_BOOL,VARIANT_TRUE,"",E_INVALIDARG,"");
  fw = 4;
  VARFMT(VT_BOOL,V_BOOL,VARIANT_TRUE,"",E_INVALIDARG,"");
}
Example #24
0
File: hash.c Project: GYGit/reactos
/***********************************************************************
 *		lhash_val_of_name_sys
 *
 * Copy of oleaut32.LHashValOfNameSysA
 * Produce a string hash value.
 *
 * PARAMS
 *  skind [I] Type of the system.
 *  lcid  [I] Locale id for the hash.
 *  lpStr [I] String to hash.
 *
 * RETURNS
 *  Success: The hash value of the string.
 *  Failure: 0, if lpStr is NULL.
 *
 * NOTES
 *  This function produces a two part hash: The high word is based on
 *  skind and lcid, while the low word is based on a repeated string
 *  hash of skind/str.
 */
unsigned int lhash_val_of_name_sys( syskind_t skind, LCID lcid, LPCSTR lpStr)
{
  ULONG nOffset, nMask = skind == SYS_MAC ? 1 : 0;
  ULONG nHiWord, nLoWord = 0x0deadbee;
  const unsigned char *str = (const unsigned char *)lpStr, *pnLookup = NULL;

  if (!str)
    return 0;

  switch (PRIMARYLANGID(LANGIDFROMLCID(lcid)))
  {
  default:
    fprintf(stderr, "Unknown lcid %x, treating as latin-based, please report\n", lcid);
    /* .. Fall Through .. */
  case LANG_AFRIKAANS:  case LANG_ALBANIAN:   case LANG_ARMENIAN:
  case LANG_ASSAMESE:   case LANG_AZERI:      case LANG_BASQUE:
  case LANG_BELARUSIAN: case LANG_BENGALI:    case LANG_BULGARIAN:
  case LANG_CATALAN:    case LANG_DANISH:     case LANG_DIVEHI:
  case LANG_DUTCH:      case LANG_ENGLISH:    case LANG_ESTONIAN:
  case LANG_FAEROESE:   case LANG_FINNISH:    case LANG_FRENCH:
  case LANG_GALICIAN:   case LANG_GEORGIAN:   case LANG_GERMAN:
  case LANG_GUJARATI:   case LANG_HINDI:      case LANG_INDONESIAN:
  case LANG_ITALIAN:    case LANG_KANNADA:    case LANG_KASHMIRI:
  case LANG_KAZAK:      case LANG_KONKANI:    case LANG_KYRGYZ:
  case LANG_LATVIAN:    case LANG_LITHUANIAN: case LANG_MACEDONIAN:
  case LANG_MALAY:      case LANG_MALAYALAM:  case LANG_MANIPURI:
  case LANG_MARATHI:    case LANG_MONGOLIAN:  case LANG_NEPALI:
  case LANG_ORIYA:      case LANG_PORTUGUESE: case LANG_PUNJABI:
  case LANG_ROMANIAN:   case LANG_SANSKRIT:   case LANG_SERBIAN:
  case LANG_SINDHI:     case LANG_SLOVENIAN:  case LANG_SWAHILI:
  case LANG_SWEDISH:    case LANG_SYRIAC:     case LANG_TAMIL:
  case LANG_TATAR:      case LANG_TELUGU:     case LANG_THAI:
  case LANG_UKRAINIAN:  case LANG_URDU:       case LANG_UZBEK:
  case LANG_VIETNAMESE: case LANG_MALTESE:    case LANG_IRISH:
  case LANG_SAMI:       case LANG_UPPER_SORBIAN: case LANG_TSWANA:
  case LANG_XHOSA:      case LANG_ZULU:       case LANG_WELSH:
  case LANG_BRETON:     case LANG_NEUTRAL:
/* some languages not in all windows versions or ReactOS */
#ifdef LANG_GAELIC
  case LANG_GAELIC:
#endif
#ifdef LANG_TAJIK
  case LANG_TAJIK:
#endif
#ifdef LANG_ROMANSH
  case LANG_ROMANSH:
#endif
#ifdef LANG_SUTU
  case LANG_SUTU:
#endif
#ifdef LANG_TSONGA
  case LANG_TSONGA:
#endif
#ifdef LANG_VENDA
  case LANG_VENDA:
#endif
#ifdef LANG_ESPERANTO
  case LANG_ESPERANTO:
#endif
#ifdef LANG_WALON
  case LANG_WALON:
#endif
#ifdef LANG_CORNISH
  case LANG_CORNISH:
#endif
    nOffset = 16;
    pnLookup = Lookup_16;
    break;
  case LANG_CZECH:  case LANG_HUNGARIAN:  case LANG_POLISH:
  case LANG_SLOVAK: case LANG_SPANISH:
    nOffset = 32;
    pnLookup = Lookup_32;
    break;
  case LANG_HEBREW:
    nOffset = 48;
    pnLookup = Lookup_48;
    break;
  case LANG_JAPANESE:
    nOffset = 64;
    pnLookup = Lookup_64;
    break;
  case LANG_KOREAN:
    nOffset = 80;
    pnLookup = Lookup_80;
    break;
  case LANG_CHINESE:
    nOffset = 112;
    pnLookup = Lookup_112;
    break;
  case LANG_GREEK:
    nOffset = 128;
    pnLookup = Lookup_128;
    break;
  case LANG_ICELANDIC:
    nOffset = 144;
    pnLookup = Lookup_144;
    break;
  case LANG_TURKISH:
    nOffset = 160;
    pnLookup = Lookup_160;
    break;
  case LANG_NORWEGIAN:
    if (SUBLANGID(LANGIDFROMLCID(lcid)) == SUBLANG_NORWEGIAN_NYNORSK)
    {
      nOffset = 176;
      pnLookup = Lookup_176;
    }
    else
    {
      nOffset = 16;
      pnLookup = Lookup_16;
    }
    break;
  case LANG_ARABIC:
  case LANG_FARSI:
    nOffset = 208;
    pnLookup = Lookup_208;
    break;
  case LANG_RUSSIAN:
    nOffset = 224;
    pnLookup = Lookup_224;
    break;
  }

  nHiWord = (nOffset | nMask) << 16;

  while (*str)
  {
    nLoWord = 37 * nLoWord + pnLookup[*str > 0x7f && nMask ? *str + 0x80 : *str];
    str++;
  }
  /* Constrain to a prime modulo and sizeof(WORD) */
  nLoWord = (nLoWord % 65599) & 0xffff;

  return nHiWord | nLoWord;
}
Example #25
0
 * PROGRAMMERS:     Alex Ionescu ([email protected])
 *                  Eric Kohl
 *                  Thomas Weidenmueller ([email protected]
 */

/* INCLUDES ******************************************************************/

#include <ntoskrnl.h>
#define NDEBUG
#include <debug.h>

/* GLOBALS *******************************************************************/

/* System IDs: EN_US */
LCID PsDefaultSystemLocaleId = 0x00000409;
LANGID PsInstallUILanguageId = LANGIDFROMLCID(0x00000409);

/* UI/Thread IDs: Same as system */
LANGID PsDefaultUILanguageId = 0x00000409;
LCID PsDefaultThreadLocaleId = LANGIDFROMLCID(0x00000409);

/* PRIVATE FUNCTIONS *********************************************************/

NTSTATUS
NTAPI
ExpGetCurrentUserUILanguage(IN PWSTR MuiName,
                            OUT LANGID* LanguageId)
{
    UCHAR ValueBuffer[256];
    PKEY_VALUE_PARTIAL_INFORMATION ValueInfo;
    OBJECT_ATTRIBUTES ObjectAttributes;
Example #26
0
//  Based on the code from C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\atlmfc\src\mfc\appcore.cpp
//      with modification for our multiple lanugage support in VC6.
LANGID CMultiLanguage::DetectUILanguage()
{
    LANGID langid = 0;
    int nPrimaryLang = 0;
    int nSubLang = 0;
    LCID lcid = 0;
    PFNGETUSERDEFAULTUILANGUAGE pfnGetUserDefaultUILanguage;
    PFNGETSYSTEMDEFAULTUILANGUAGE pfnGetSystemDefaultUILanguage;
    HINSTANCE hKernel32;

    hKernel32 = ::GetModuleHandle(_T("kernel32.dll"));
    ASSERT(hKernel32 != NULL);
    pfnGetUserDefaultUILanguage = (PFNGETUSERDEFAULTUILANGUAGE)::GetProcAddress(
                                      hKernel32, "GetUserDefaultUILanguage");
    if(pfnGetUserDefaultUILanguage != NULL)
    {
        // First, try the user's UI language
        langid = pfnGetUserDefaultUILanguage();
        AddLangId( langid );
        TRACE(_T("CMultiLanguage::DetectUILanguage() 1st/2nd = %04X\n"), langid );

        // Then, try the system's default UI language
        pfnGetSystemDefaultUILanguage = (PFNGETSYSTEMDEFAULTUILANGUAGE)::GetProcAddress(
                                            hKernel32, "GetSystemDefaultUILanguage");
        ASSERT( pfnGetSystemDefaultUILanguage != NULL );

        langid = pfnGetSystemDefaultUILanguage();
        AddLangId( langid );
        TRACE(_T("CMultiLanguage::DetectUILanguage() 3rd/4th = %04X\n"), langid );
    }
    else
    {
        // We're not on an MUI-capable system.
        if (::GetVersion()&0x80000000)
        {
            // We're on Windows 9x, so look in the registry for the UI language
            HKEY hKey = NULL;
            LONG nResult = ::RegOpenKeyEx(HKEY_CURRENT_USER,
                                          _T( "Control Panel\\Desktop\\ResourceLocale" ), 0, KEY_READ, &hKey);
            if (nResult == ERROR_SUCCESS)
            {
                DWORD dwType;
                TCHAR szValue[16];
                ULONG nBytes = sizeof( szValue );
                nResult = ::RegQueryValueEx(hKey, NULL, NULL, &dwType,
                                            LPBYTE( szValue ), &nBytes );
                if ((nResult == ERROR_SUCCESS) && (dwType == REG_SZ))
                {
                    DWORD dwLangID;
                    int nFields = _stscanf( szValue, _T( "%x" ), &dwLangID );
                    if( nFields == 1 )
                    {
                        langid = LANGID( dwLangID );
                        AddLangId( langid );
                        TRACE(_T("CMultiLanguage::DetectUILanguage() 9X1st/2nd = %04X\n"),
                              langid );
                    }
                }
                ::RegCloseKey(hKey);
            }
        }
        else
        {
            // We're on NT 4.  The UI language is the same as the language of the
            // version resource in ntdll.dll
            HMODULE hNTDLL = ::GetModuleHandle( _T( "ntdll.dll" ) );
            if (hNTDLL != NULL)
            {
                langid = 0;
                ::EnumResourceLanguages( hNTDLL, RT_VERSION, MAKEINTRESOURCE( 1 ),
                                         _AfxEnumResLangProc, reinterpret_cast< LONG_PTR >( &langid ) );
                if (langid != 0)
                {
                    AddLangId( langid );
                    TRACE(_T("CMultiLanguage::DetectUILanguage() NT1st/2nd = %04X\n"),
                          langid );
                }
            }
        }
    }

    if ( m_nLocales < MAX_NUM_LCID )
    {
        m_alcidSearch[m_nLocales] = LOCALE_SYSTEM_DEFAULT;
        m_nLocales++;
    }
    else
    {
        m_alcidSearch[MAX_NUM_LCID-1] = LOCALE_SYSTEM_DEFAULT;
        m_nLocales = MAX_NUM_LCID;
    }

    return LANGIDFROMLCID(m_alcidSearch[0]);
}
Example #27
0
File: hash.c Project: GYGit/reactos
/***********************************************************************
 *		LHashValOfNameSysA (OLEAUT32.166)
 *
 * Produce a string hash value.
 *
 * PARAMS
 *  skind [I] Type of the system.
 *  lcid  [I] Locale id for the hash.
 *  lpStr [I] String to hash.
 *
 * RETURNS
 *  Success: The hash value of the string.
 *  Failure: 0, if lpStr is NULL.
 *
 * NOTES
 *  This function produces a two part hash: The high word is based on
 *  skind and lcid, while the low word is based on a repeated string
 *  hash of skind/str.
 */
ULONG WINAPI LHashValOfNameSysA( SYSKIND skind, LCID lcid, LPCSTR lpStr)
{
  ULONG nOffset, nMask = skind == SYS_MAC ? 1 : 0;
  ULONG nHiWord, nLoWord = 0x0deadbee;
  const unsigned char *str = (const unsigned char *)lpStr, *pnLookup = NULL;

  TRACE("(%d, 0x%x, %s) %s\n", skind, lcid, debugstr_a(lpStr),
    (skind == SYS_WIN16) ? "SYS_WIN16" : (skind == SYS_WIN32) ? "SYS_WIN32" : "");

  if (!str)
    return 0;

  lcid = ConvertDefaultLocale(lcid);

  switch (PRIMARYLANGID(LANGIDFROMLCID(lcid)))
  {
  default:
    ERR("Unknown lcid %x, treating as latin-based, please report\n", lcid);
    /* .. Fall Through .. */
  case LANG_AFRIKAANS:  case LANG_ALBANIAN:   case LANG_ARMENIAN:
  case LANG_ASSAMESE:   case LANG_AZERI:      case LANG_BASQUE:
  case LANG_BELARUSIAN: case LANG_BENGALI:    case LANG_BULGARIAN:
  case LANG_CATALAN:    case LANG_DANISH:     case LANG_DIVEHI:
  case LANG_DUTCH:      case LANG_ENGLISH:    case LANG_ESTONIAN:
  case LANG_FAEROESE:   case LANG_FINNISH:    case LANG_FRENCH:
  case LANG_GALICIAN:   case LANG_GEORGIAN:   case LANG_GERMAN:
  case LANG_GUJARATI:   case LANG_HINDI:      case LANG_INDONESIAN:
  case LANG_ITALIAN:    case LANG_KANNADA:    case LANG_KASHMIRI:
  case LANG_KAZAK:      case LANG_KONKANI:    case LANG_KYRGYZ:
  case LANG_LATVIAN:    case LANG_LITHUANIAN: case LANG_MACEDONIAN:
  case LANG_MALAY:      case LANG_MALAYALAM:  case LANG_MANIPURI:
  case LANG_MARATHI:    case LANG_MONGOLIAN:  case LANG_NEPALI:
  case LANG_ORIYA:      case LANG_PORTUGUESE: case LANG_PUNJABI:
  case LANG_ROMANIAN:   case LANG_SANSKRIT:   case LANG_SERBIAN:
  case LANG_SINDHI:     case LANG_SLOVENIAN:  case LANG_SWAHILI:
  case LANG_SWEDISH:    case LANG_SYRIAC:     case LANG_TAMIL:
  case LANG_TATAR:      case LANG_TELUGU:     case LANG_THAI:
  case LANG_UKRAINIAN:  case LANG_URDU:       case LANG_UZBEK:
  case LANG_VIETNAMESE: case LANG_SCOTTISH_GAELIC: case LANG_MALTESE:
  case LANG_MAORI:      case LANG_ROMANSH:    case LANG_IRISH:
  case LANG_SAMI:       case LANG_UPPER_SORBIAN: case LANG_SUTU:
  case LANG_TSONGA:     case LANG_TSWANA:     case LANG_VENDA:
  case LANG_XHOSA:      case LANG_ZULU:       case LANG_ESPERANTO:
  case LANG_WALON:      case LANG_CORNISH:    case LANG_WELSH:
  case LANG_BRETON:     case LANG_MANX_GAELIC:
    nOffset = 16;
    pnLookup = Lookup_16;
    break;
  case LANG_CZECH:  case LANG_HUNGARIAN:  case LANG_POLISH:
  case LANG_SLOVAK: case LANG_SPANISH:
    nOffset = 32;
    pnLookup = Lookup_32;
    break;
  case LANG_HEBREW:
    nOffset = 48;
    pnLookup = Lookup_48;
    break;
  case LANG_JAPANESE:
    nOffset = 64;
    pnLookup = Lookup_64;
    break;
  case LANG_KOREAN:
    nOffset = 80;
    pnLookup = Lookup_80;
    break;
  case LANG_CHINESE:
    nOffset = 112;
    pnLookup = Lookup_112;
    break;
  case LANG_GREEK:
    nOffset = 128;
    pnLookup = Lookup_128;
    break;
  case LANG_ICELANDIC:
    nOffset = 144;
    pnLookup = Lookup_144;
    break;
  case LANG_TURKISH:
    nOffset = 160;
    pnLookup = Lookup_160;
    break;
  case LANG_NORWEGIAN:
    if (SUBLANGID(LANGIDFROMLCID(lcid)) == SUBLANG_NORWEGIAN_NYNORSK)
    {
      nOffset = 176;
      pnLookup = Lookup_176;
    }
    else
    {
      nOffset = 16;
      pnLookup = Lookup_16;
    }
    break;
  case LANG_ARABIC:
  case LANG_FARSI:
    nOffset = 208;
    pnLookup = Lookup_208;
    break;
  case LANG_RUSSIAN:
    nOffset = 224;
    pnLookup = Lookup_224;
    break;
  }

  nHiWord = (nOffset | nMask) << 16;

  while (*str)
  {
    nLoWord = 37 * nLoWord + pnLookup[*str > 0x7f && nMask ? *str + 0x80 : *str];
    str++;
  }
  /* Constrain to a prime modulo and sizeof(WORD) */
  nLoWord = (nLoWord % 65599) & 0xffff;

  return nHiWord | nLoWord;
}
Example #28
0
void
__kmp_i18n_do_catopen(
) {

    LCID          locale_id = GetThreadLocale();
    WORD 	  lang_id = LANGIDFROMLCID( locale_id );
    WORD          primary_lang_id = PRIMARYLANGID( lang_id );
    kmp_str_buf_t path;

    KMP_DEBUG_ASSERT( status == KMP_I18N_CLOSED );
    KMP_DEBUG_ASSERT( cat    == KMP_I18N_NULLCAT );

    __kmp_str_buf_init( & path );

    // Do not try to open English catalog because internal messages are
    // exact copy of messages in English catalog.
    if ( primary_lang_id == LANG_ENGLISH ) {
	status = KMP_I18N_ABSENT;  // mark catalog as absent so it will not be re-opened.
	goto end;
    }; // if

    // Construct resource DLL name.
    /*
        Simple
            LoadLibrary( name )
        is not suitable due to security issue (see
        http://www.microsoft.com/technet/security/advisory/2269637.mspx). We have to specify full
        path to the message catalog.
    */
    {

        // Get handle of our DLL first.
        HMODULE handle;
        BOOL brc =
            GetModuleHandleEx(
                GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
                reinterpret_cast< LPCSTR >( & __kmp_i18n_do_catopen ),
                & handle
            );
        if ( ! brc ) {    // Error occurred.
            status = KMP_I18N_ABSENT;  // mark catalog as absent so it will not be re-opened.
            goto end;
            // TODO: Enable multiple messages (KMP_MSG) to be passed to __kmp_msg; and print
            // a proper warning.
        }; // if

        // Now get path to the our DLL.
        for ( ; ; ) {
            DWORD drc = GetModuleFileName( handle, path.str, path.size );
            if ( drc == 0 ) {    // Error occurred.
                status = KMP_I18N_ABSENT;
                goto end;
            }; // if
            if ( drc < path.size ) {
                path.used = drc;
                break;
            }; // if
            __kmp_str_buf_reserve( & path, path.size * 2 );
        }; // forever

        // Now construct the name of message catalog.
        kmp_str_fname fname;
        __kmp_str_fname_init( & fname, path.str );
        __kmp_str_buf_clear( & path );
        __kmp_str_buf_print( & path, "%s%lu/%s", fname.dir, (unsigned long)( locale_id ), name );
        __kmp_str_fname_free( & fname );

    }

    // For security reasons, use LoadLibraryEx() and load message catalog as a data file.
    cat = LoadLibraryEx( path.str, NULL, LOAD_LIBRARY_AS_DATAFILE );
    status = ( cat == KMP_I18N_NULLCAT ? KMP_I18N_ABSENT : KMP_I18N_OPENED );

    if ( status == KMP_I18N_ABSENT ) {
      if (__kmp_generate_warnings > kmp_warnings_low) { // AC: only issue warning in case explicitly asked to
	DWORD error = GetLastError();
	// Infinite recursion will not occur -- status is KMP_I18N_ABSENT now, so
	// __kmp_i18n_catgets() will not try to open catalog but will return default message.
        /*
         If message catalog for another architecture found (e.g. OpenMP RTL
	 for IA-32 architecture opens libompui.dll for Intel(R) 64)
	 Windows* OS returns error 193 (ERROR_BAD_EXE_FORMAT). However,
         FormatMessage fails to return a message for this error, so user
	 will see:

         OMP: Warning #2: Cannot open message catalog "1041\libompui.dll":
         OMP: System error #193: (No system error message available)
         OMP: Info #3: Default messages will be used.

         Issue a hint in this case to let cause of trouble more understandable.
        */
	__kmp_msg(
	    kmp_ms_warning,
	    KMP_MSG( CantOpenMessageCatalog, path.str ),
	    KMP_SYSERRCODE( error ),
            ( error == ERROR_BAD_EXE_FORMAT ? KMP_HNT( BadExeFormat, path.str, KMP_ARCH_STR ) : __kmp_msg_null ),
	    __kmp_msg_null
	);
	KMP_INFORM( WillUseDefaultMessages );
      }
    } else { // status == KMP_I18N_OPENED

        int section = get_section( kmp_i18n_prp_Version );
        int number  = get_number( kmp_i18n_prp_Version );
        char const * expected = __kmp_i18n_default_table.sect[ section ].str[ number ];
        kmp_str_buf_t version;   // Actual version of the catalog.
        __kmp_str_buf_init( & version );
        __kmp_str_buf_print( & version, "%s", ___catgets( kmp_i18n_prp_Version ) );
            // String returned by catgets is invalid after closing the catalog, so copy it.
        if ( strcmp( version.str, expected ) != 0 ) {
            // Close bad catalog.
            __kmp_i18n_catclose();
            status = KMP_I18N_ABSENT;  // And mark it as absent.
            if (__kmp_generate_warnings > kmp_warnings_low) {
                // And now print a warning using default messages.
                __kmp_msg(
                    kmp_ms_warning,
                    KMP_MSG( WrongMessageCatalog, path.str, version.str, expected ),
                    __kmp_msg_null
                );
                KMP_INFORM( WillUseDefaultMessages );
            } // __kmp_generate_warnings
        }; // if
        __kmp_str_buf_free( & version );

    }; // if
    code_page = get_code_page();

    end:
        __kmp_str_buf_free( & path );
        return;

} // func __kmp_i18n_do_catopen
Example #29
0
static void LoaderThread(void *arg)
{
	LoaderThreadStartParams *dtsp = (LoaderThreadStartParams *)arg;

	FILE *fp;
	char line[4096];
	char *pszLine, *pszColon, *pszBuf;
	int startOfLine = 0;

	WIN32_FIND_DATA wfd;
	HANDLE hFind;
	TCHAR szDir[MAX_PATH];
	TCHAR szSearch[MAX_PATH];
	TCHAR *p;
	int success = 0;

	struct DialogData dialog;
	struct DlgControlData *control;
	void *buf;
	ZeroMemory(&dialog, sizeof(dialog));

	if (GetModuleFileName(NULL, szDir, _countof(szDir))) {
		p = _tcsrchr(szDir, _T('\\'));
		if (p)
			*p = _T('\0');
		mir_sntprintf(szSearch, _T("%s\\helppack_*.txt"), szDir);

		hFind = FindFirstFile(szSearch, &wfd);
		if (hFind != INVALID_HANDLE_VALUE) {
			do {
				if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
					continue;
				if (lstrlen(wfd.cFileName) < 4 || wfd.cFileName[lstrlen(wfd.cFileName) - 4] != _T('.'))
					continue;
				mir_sntprintf(szSearch, _T("%s\\%s"), szDir, wfd.cFileName);
				success = 1;
				break;
			} while (FindNextFile(hFind, &wfd));
			FindClose(hFind);
		}
	}
	if (!success) {
		if (!Miranda_Terminated() && IsWindow(hwndHelpDlg))
			PostMessage(hwndHelpDlg, M_HELPLOADFAILED, 0, (LPARAM)dtsp->hwndCtl);
		return;
	}

	fp = _tfopen(szSearch, _T("rt"));
	if (fp == NULL) {
		if (!Miranda_Terminated() && IsWindow(hwndHelpDlg))
			PostMessage(hwndHelpDlg, M_HELPLOADFAILED, 0, (LPARAM)dtsp->hwndCtl);
		return;
	}
	fgets(line, _countof(line), fp);
	TrimString(line);
	if (lstrcmpA(line, "Miranda Help Pack Version 1")) {
		fclose(fp);
		if (!Miranda_Terminated() && IsWindow(hwndHelpDlg))
			PostMessage(hwndHelpDlg, M_HELPLOADFAILED, 0, (LPARAM)dtsp->hwndCtl);
		return;
	}

	// headers
	dialog.locale = LOCALE_USER_DEFAULT;
	dialog.defaultCodePage = CP_ACP;
	while (!feof(fp)) {
		startOfLine = ftell(fp);
		if (fgets(line, _countof(line), fp) == NULL)
			break;
		TrimString(line);
		if (IsEmpty(line) || line[0] == ';' || line[0] == '\0')
			continue;
		if (line[0] == '[')
			break;
		pszColon = strchr(line, ':');
		if (pszColon == NULL) {
			fclose(fp);
			if (!Miranda_Terminated() && IsWindow(hwndHelpDlg))
				PostMessage(hwndHelpDlg, M_HELPLOADFAILED, 0, (LPARAM)dtsp->hwndCtl);
			return;
		}
		*pszColon = '\0';

		// locale
		if (!lstrcmpA(line, "Locale")) {
			char szCP[6];
			TrimString(pszColon + 1);
			dialog.locale = MAKELCID((USHORT)strtol(pszColon + 1, NULL, 16), SORT_DEFAULT);
			// codepage
			if (GetLocaleInfoA(dialog.locale, LOCALE_IDEFAULTANSICODEPAGE, szCP, sizeof(szCP))) {
				szCP[5] = '\0'; // codepages have 5 digits at max
				dialog.defaultCodePage = atoi(szCP);
			}
		}
	}

	// RTL flag
	// see also: http://blogs.msdn.com/michkap/archive/2006/03/03/542963.aspx
	{
		LOCALESIGNATURE sig;
		dialog.isLocaleRTL = 0;
		if (GetLocaleInfo(dialog.locale, LOCALE_FONTSIGNATURE, (LPTSTR)&sig, sizeof(sig) / sizeof(TCHAR)))
			dialog.isLocaleRTL = (sig.lsUsb[3] & 0x8000000); // Win2000+: testing for 'Layout progress: horizontal from right to left' bit
		switch (PRIMARYLANGID(LANGIDFROMLCID(dialog.locale))) { // prior to Win2000
		case LANG_ARABIC:
		case LANG_HEBREW:
		case LANG_FARSI:
			dialog.isLocaleRTL = 1;
		}
	}

	// body
	fseek(fp, startOfLine, SEEK_SET);
	success = 1;
	control = NULL;
	while (!feof(fp)) {
		if (fgets(line, _countof(line), fp) == NULL)
			break;
		if (IsEmpty(line) || line[0] == ';' || line[0] == '\0')
			continue;
		TrimStringSimple(line);

		if (line[0] == '[' && line[lstrlenA(line) - 1] == ']') {
			pszLine = line + 1;
			line[lstrlenA(line) - 1] = '\0';

			// module
			pszColon = strrchr(pszLine, ':');
			if (pszColon == NULL)
				continue;
			*pszColon = '\0';
			pszColon++;
			TrimString(pszLine);
			if (lstrcmpiA(dtsp->szModule, pszLine))
				continue;
			pszBuf = pszLine;

			// dlgid
			pszLine = pszColon;
			pszColon = strrchr(pszLine, '@');
			if (pszColon == NULL)
				continue;
			*pszColon = '\0';
			pszColon++;
			TrimString(pszColon);
			if (lstrcmpA(dtsp->szDlgId, pszColon))
				continue;

			if (dialog.szModule == NULL && dialog.szId == NULL) {
				dialog.szModule = mir_strdup(pszBuf);
				dialog.szId = mir_strdup(pszColon);
				if (dialog.szId == NULL || dialog.szModule == NULL) {
					success = 0;
					break;
				}
			}
			buf = (struct DlgControlData*)mir_realloc(dialog.control, sizeof(struct DlgControlData)*(dialog.controlCount + 1));
			if (buf == NULL) {
				success = 0;
				break;
			}
			dialog.controlCount++;
			dialog.control = (struct DlgControlData*)buf;
			control = &dialog.control[dialog.controlCount - 1];
			ZeroMemory(control, sizeof(*control));

			// ctlid
			TrimString(pszLine);
			control->id = atoi(pszLine);
		}
		else if (control != NULL) {
			pszLine = line;

			// ctltext
			pszColon = strchr(pszLine, '=');
			if (pszColon == NULL)
				continue;
			*pszColon = '\0';
			pszColon++;
			TrimString(pszColon);
			TrimString(pszLine);
			if (*pszColon == '\0' || *pszLine == '\0')
				continue;
			int size = lstrlenA(pszLine) + 1;
			control->szTitle = (WCHAR*)mir_alloc(size*sizeof(WCHAR));
			if (control->szTitle != NULL) {
				*control->szTitle = _T('\0');
				MultiByteToWideChar(dialog.defaultCodePage, 0, pszLine, -1, control->szTitle, size);
			}

			// text
			control->szText = mir_utf8encodecp(pszColon, dialog.defaultCodePage);
			control = NULL; // control done
		}
	}
	fclose(fp);

	if (success) {
		int i, dialogInserted = 0;

		dialog.timeLoaded = dialog.timeLastUsed = GetTickCount();
		EnterCriticalSection(&csDialogCache);
		for (i = 0; i < dialogCacheCount; i++) {
			if (dialogCache[i].timeLastUsed && dialogCache[i].timeLastUsed<(dialog.timeLoaded - DIALOGCACHEEXPIRY)) {
				FreeDialogCacheEntry(&dialogCache[i]);
				if (dialogInserted || !dialog.controlCount) {
					MoveMemory(dialogCache + i, dialogCache + i + 1, sizeof(struct DialogData)*(dialogCacheCount - i - 1));
					dialogCacheCount--;
					buf = (struct DialogData*)mir_realloc(dialogCache, sizeof(struct DialogData)*dialogCacheCount);
					if (buf != NULL)
						dialogCache = (struct DialogData*)buf;
					else if (!dialogCacheCount)
						dialogCache = NULL;
				}
				else {
					dialogInserted = 1;
					dialogCache[i] = dialog;
				}
			}
		}
		if (dialog.controlCount && !dialogInserted) {
			buf = (struct DialogData*)mir_realloc(dialogCache, sizeof(struct DialogData)*(dialogCacheCount + 1));
			if (buf != NULL) {
				dialogCacheCount++;
				dialogCache = (struct DialogData*)buf;
				dialogCache[dialogCacheCount - 1] = dialog;
				dialogInserted = 1;
			}
		}
		LeaveCriticalSection(&csDialogCache);

		if (!dialogInserted) {
			mir_free(dialog.szId); // does NULL check
			mir_free(dialog.szModule); // does NULL check
			mir_free(dialog.control); // does NULL check
		}
		if (!Miranda_Terminated() && IsWindow(hwndHelpDlg))
			PostMessage(hwndHelpDlg, M_HELPLOADED, 0, (LPARAM)dtsp->hwndCtl);
	}
	if (!success) {
		mir_free(dialog.szId); // does NULL check
		mir_free(dialog.szModule); // does NULL check
		mir_free(dialog.control); // does NULL check
		if (!Miranda_Terminated() && IsWindow(hwndHelpDlg))
			PostMessage(hwndHelpDlg, M_HELPLOADFAILED, 0, (LPARAM)dtsp->hwndCtl);
	}

	mir_free(dtsp->szDlgId);
	mir_free(dtsp->szModule);
	mir_free(dtsp);
}
LRESULT CALLBACK WndProc (HWND hwnd, UINT uimessage, WPARAM wParam, LPARAM lParam) 
{
    switch (uimessage)
    {          
        //check to see if a refresh is required
    case WM_TODAYCUSTOM_QUERYREFRESHCACHE: 
        {   
            
            TODAYLISTITEM *ptliItem;
            INT iItemHeight;
            
            BOOL    bReturn = FALSE;
            
            // get the pointer to the item from the Today screen
            ptliItem = (TODAYLISTITEM*)wParam;

            if ((NULL == ptliItem) || (WaitForSingleObject(SHELL_API_READY_EVENT, 0) == WAIT_TIMEOUT))
            {
                return FALSE;
            }

            iItemHeight = DRA::SCALEY(36);

            if (0 == ptliItem->cyp)
            {
                ptliItem->cyp = iItemHeight;
                bReturn = TRUE;
            }


            return bReturn;
        }        
        
    case WM_CREATE:         
        break;
        
    case WM_LBUTTONUP: 
        Call_Manilla2D_DevTools_EnableM2D_App();
        break;          
        
    case WM_PAINT: 
        PAINTSTRUCT     ps;
        RECT            rcWindBounds; 
        RECT            rcMyBounds;
        HDC             hDC;
        HFONT            hFontOld;
        COLORREF        crText;

        GetWindowRect( hwnd, &rcWindBounds); 
        
        hDC = BeginPaint(hwnd, &ps);
        
        // create a custom rectangle relative to the client area
        rcMyBounds.left = 0;
        rcMyBounds.top = DRA::SCALEY(2);
        rcMyBounds.right = rcWindBounds.right - rcWindBounds.left;
        rcMyBounds.bottom = rcWindBounds.bottom - rcWindBounds.top;          
        
        // draw the icon on the screen
        SetBkMode(hDC, TRANSPARENT);
        DrawIcon(hDC, 2, 0, g_hIcon);
        
        BOOL bIsFarEast;
        LOGFONT lf;
        HFONT hSysFont;
        HFONT hFont;

        //determine if this is a Far East platform
        switch (PRIMARYLANGID(LANGIDFROMLCID(GetSystemDefaultLCID())))
        {
        case LANG_CHINESE:
        case LANG_KOREAN:
        case LANG_JAPANESE:
            bIsFarEast = TRUE;
            break;
            
        default:
            bIsFarEast = FALSE;
            break;
        }

        hSysFont = (HFONT) GetStockObject(SYSTEM_FONT);
        GetObject(hSysFont, sizeof(LOGFONT), &lf);
        // If it is far east, use a normal font at 9 points,
        //  otherwise use a bold font as 8 points
        if (bIsFarEast)
        {
            lf.lfWeight = FW_NORMAL;
            // Calculate the font size, making sure to round the result to the nearest integer
            lf.lfHeight = (long) -((9.0 * (double)GetDeviceCaps(hDC, LOGPIXELSY) / 72.0)+.5);
        }
        else
        {
            lf.lfWeight = FW_BOLD;
            // Calculate the font size, making sure to round the result to the nearest integer
            lf.lfHeight = (long) -((8.0 * (double)GetDeviceCaps(hDC, LOGPIXELSY) / 72.0)+.5);
        }

        // create the font
        hFont = CreateFontIndirect(&lf);
    
        // Select the system font into the device context
        hFontOld = (HFONT) SelectObject(hDC, hFont);

        // determine the theme's current text color
        //  this color will change when the user picks a new theme,
        //  so get it each time the display needs to be painted
        crText = SendMessage(GetParent(hwnd), TODAYM_GETCOLOR, (WPARAM) TODAYCOLOR_TEXT, NULL);

        // set that color
        SetTextColor(hDC, crText);

        rcMyBounds.left = rcMyBounds.left + DRA::SCALEX(35);
        DrawText(hDC, TEXT("*** Tap To Enable TouchFlo ***"), -1, &rcMyBounds, DT_LEFT);
        
        // Select the previous font back into the device context
        SelectObject(hDC, hFontOld);

        DeleteObject(hFont);

        EndPaint(hwnd, &ps);
        return 0;
        
    case WM_DESTROY :          
        return 0 ;
        
    // this fills in the background with the today screen image
    case WM_ERASEBKGND:
        TODAYDRAWWATERMARKINFO dwi;
        dwi.hdc = (HDC)wParam;
        GetClientRect(hwnd, &dwi.rc);
        
        dwi.hwnd = hwnd;
        SendMessage(GetParent(hwnd), TODAYM_DRAWWATERMARK, 0,(LPARAM)&dwi);
        return TRUE;
    }

    return DefWindowProc (hwnd, uimessage, wParam, lParam) ;
}