Exemple #1
0
Language Language::TryGuessFromFilename(const wxString& filename)
{
    wxFileName fn(filename);
    fn.MakeAbsolute();

    // Try matching the filename first:
    //  - entire name
    //  - suffix (foo.cs_CZ.po, wordpressTheme-cs_CZ.po)
    //  - directory name (cs_CZ, cs.lproj, cs/LC_MESSAGES)
    wxString name = fn.GetName();
    Language lang = Language::TryParseWithValidation(name);
            if (lang.IsValid())
                return lang;

    size_t pos = name.find_first_of(".-_");
    while (pos != wxString::npos)
    {
        auto part = name.substr(pos+1);
        lang = Language::TryParseWithValidation(part);
        if (lang.IsValid())
            return lang;
         pos = name.find_first_of(".-_",  pos+1);
    }

    auto dirs = fn.GetDirs();
    if (!dirs.empty())
    {
        auto d = dirs.rbegin();
        if (d->IsSameAs("LC_MESSAGES", /*caseSensitive=*/false))
        {
            if (++d == dirs.rend())
                return Language(); // failed to match
        }
        wxString rest;
        if (d->EndsWith(".lproj", &rest))
            return Language::TryParseWithValidation(rest);
        else
            return Language::TryParseWithValidation(*d);
    }

    return Language(); // failed to match
}
Exemple #2
0
int main()
{
    using Language = derp::Language<char>;
    using GC = Language::GarbageCollector;
    using Factory = derp::Factory<Language>;

    GC gc;
    Factory F(gc);

    // Language = ("foo" | "bar")*
    Language l = *(F("foo") | "bar");

    std::cout << "grammar: " << l.toString() << std::endl;
    std::cout << "input: " << std::flush;

    std::string input;
    std::getline(std::cin, input);

    std::cout << "matches? " << derp::matches(input, l) << std::endl;
}
Exemple #3
0
void PoeditApp::SetupLanguage()
{
#if defined(__WXMSW__)
	wxLocale::AddCatalogLookupPathPrefix(wxStandardPaths::Get().GetResourcesDir() + "\\Translations");
#elif !defined(__WXMAC__)
    wxLocale::AddCatalogLookupPathPrefix(wxStandardPaths::Get().GetInstallPrefix() + "/share/locale");
#endif

    wxTranslations *trans = new wxTranslations();
    wxTranslations::Set(trans);
    #if NEED_CHOOSELANG_UI
    trans->SetLanguage(GetUILanguage());
    #endif
    trans->AddCatalog("poedit");
    trans->AddStdCatalog();

    Language uiLang = Language::TryParse(trans->GetBestTranslation("poedit"));
    UErrorCode err = U_ZERO_ERROR;
    icu::Locale::setDefault(uiLang.ToIcu(), err);
}
Exemple #4
0
int Locale::Load( MemBuffer &file ) {

  unsigned short langs = file.Read16();
  for ( int i = 0; i < langs; ++i ) {
    Language lang;
    int rc = lang.ReadCatalog( file );

    if ( rc >= 0 ) AddLanguage( lang );
    else return -1;
  }

  if ( lib.size() == 0 ) return -1;

  if ( !SetDefaultLanguage( CF_LANG_DEFAULT ) ) {
    // no english translation found, use something we have
    SetDefaultLanguage( lib.begin()->first );
  }

  return lib.size();
}
    Language* intersection(const Language& language1,
                           const Language& language2){
        if (!equalAlphabets(language1, language2)){
            throw std::invalid_argument("Languages Alphabets must match");
        }

        Language* intersectionLanguage = new Language(language1.getAlphabet());

        for(unsigned int i = 0; i < language1.size(); i++){
            Word* word1 = language1.getWord(i);
            for(unsigned int j = 0; j < language2.size(); j++){
                Word* word2 = language2.getWord(j);
                if(*word1 == *word2){
                    Word* intersectingWord = new Word(word1);
                    intersectionLanguage->addWord(intersectingWord);
                }
            }
        }

        return intersectionLanguage;
    }
    double similarity(const Language &language1, const Language &language2) {
        unsigned int size1 = language1.size();
        unsigned int size2 = language2.size();

        std::vector<double> wordSimilarities;
        double similarityLanguage = 0;
        for(unsigned int i = 0; i < size1; i++){
            wordSimilarities.clear();
            Word* word1 = language1.getWord(i);
            for(unsigned int j = 0; j < size2; j++){
                Word* word2 = language2.getWord(j);
                double similarity = word::similarity(*word1, *word2);
                wordSimilarities.push_back(similarity);
            }
            double maxSimilarity = math::max(wordSimilarities);
            similarityLanguage += maxSimilarity;
        }
        similarityLanguage /= size1;

        return similarityLanguage;
    }
Exemple #7
0
void Palette::realize(const ByteArray *text, Token *objectToken)
{
    scopeName_ = resourceContext()->top()->fileName();
    if (scopeName_ == "default") {
        scope_ = SyntaxDefinition::scope(scopeName_);
        for (int i = 0; i < children()->count(); ++i) {
            Style *style = cast<Style>(children()->at(i));
            style->rule_ = defaultRuleByName(style->ruleName());
            if (style->rule_ == Undefined) {
                Token *token = childToken(objectToken, i);
                token = valueToken(text, token, "name");
                throw SemanticError(
                    Format("Undefined default style '%%'") << style->ruleName(),
                    text, token->i1()
                );
            }
            styleByRule_->establish(style->rule_, style);
        }
        return;
    }

    Language *language = 0;
    if (!registry()->lookupLanguageByName(scopeName_, &language))
        throw SemanticError(Format("Undefined language '%%'") << scopeName_);

    const SyntaxDefinition *syntax = language->highlightingSyntax();
    scope_ = syntax->id();
    for (int i = 0; i < children()->count(); ++i) {
        Style *style = cast<Style>(children()->at(i));
        try {
            style->rule_ = syntax->ruleByName(style->ruleName());
            styleByRule_->insert(style->rule_, style);
        }
        catch (DebugError &ex) {
            Token *token = childToken(objectToken, i);
            token = valueToken(text, token, "name");
            throw SemanticError(ex.message(), text, token->i1());
        }
    }
}
Exemple #8
0
void PropertiesDialog::TransferFrom(Catalog *cat)
{
    cat->Header().Charset = GetCharsetFromCombobox(m_charset);
    cat->Header().SourceCodeCharset = GetCharsetFromCombobox(m_sourceCodeCharset);

    #define GET_VAL(what,what2) cat->Header().what = m_##what2->GetValue()
    GET_VAL(Team, team);
    GET_VAL(TeamEmail, teamEmail);
    GET_VAL(Project, project);
    GET_VAL(BasePath, basePath);
    #undef GET_VAL

    Language lang = m_language->GetLang();
    if (lang.IsValid())
        cat->Header().Lang = lang;

    GetStringsFromControl(m_keywords, cat->Header().Keywords);
    GetPathsFromControl(m_paths, cat->Header().SearchPaths);
    GetPathsFromControl(m_excludedPaths, cat->Header().SearchPathsExcluded);

    if (!cat->Header().SearchPaths.empty() && cat->Header().BasePath.empty())
        cat->Header().BasePath = ".";

    m_keywords->GetStrings(cat->Header().Keywords);

    wxString pluralForms;
    if (m_pluralFormsDefault->GetValue() && cat->Header().Lang.IsValid())
    {
        pluralForms = cat->Header().Lang.DefaultPluralFormsExpr();
    }

    if (pluralForms.empty())
    {
        pluralForms = m_pluralFormsExpr->GetValue().Strip(wxString::both);
        if ( !pluralForms.empty() && !pluralForms.EndsWith(";") )
            pluralForms += ";";
    }
    cat->Header().SetHeaderNotEmpty("Plural-Forms", pluralForms);
}
void main(void)
{
 Language l;

 try
  {
   l.selectLang().showDialog();
  }
 
 catch(OPMException ex)
  {
   ex.viewError();
  }

 catch(OVioException ex)
  {
   ex.description + "\n";
   ex.description + OMessage(ex.rc);
   OMsgs().error(ex.description);
  }

 _exit(0); 
}
Exemple #10
0
void CrowdinClient::DownloadFile(const std::string& project_id, const std::wstring& file, const Language& lang,
                                 const std::wstring& output_file,
                                 std::function<void()> onSuccess,
                                 error_func_t onError)
{
    // NB: "export_translated_only" means the translation is not filled with the source string
    //     if there's no translation, i.e. what Poedit wants.
    auto url = "/api/project/" + project_id + "/export-file"
                   "?json="
                   "&export_translated_only=1"
                   "&language=" + lang.LanguageTag() +
                   "&file=" + http_client::url_encode(file);
    m_api->download(url, output_file, onSuccess, onError);
}
Exemple #11
0
void TestLanguageFiles::checkIdUniqueness()
{
    ResourceManager manager;
    QStringList languageFiles = QStandardPaths::locateAll(QStandardPaths::DataLocation, QString("data/languages/*.xml"));
    foreach (const QString &file, languageFiles) {
        qDebug() << "File being parsed: " << file;
        QStringList idList;
        const QUrl &languageFile = QUrl::fromLocalFile(file);
        QVERIFY(languageFile.isLocalFile());

        QXmlSchema schema = loadXmlSchema("language");
        QVERIFY(schema.isValid());

        QDomDocument document = loadDomDocument(languageFile, schema);
        QVERIFY(!document.isNull());

        QDomElement root(document.documentElement());
        Language *language = new Language(this);
        language->setFile(languageFile);
        language->setId(root.firstChildElement("id").text());
        language->setTitle(root.firstChildElement("title").text());
        // create phoneme groups
        for (QDomElement groupNode = root.firstChildElement("phonemeGroups").firstChildElement();
                !groupNode.isNull();
                groupNode = groupNode.nextSiblingElement())
        {
            for (QDomElement phonemeNode = groupNode.firstChildElement("phonemes").firstChildElement();
                    !phonemeNode.isNull();
                    phonemeNode = phonemeNode.nextSiblingElement())
            {
                QString id = phonemeNode.firstChildElement("id").text();
                qDebug() << "ID: " << id;
                QVERIFY2(!idList.contains(id),"Phoneme ID used more than once in the tested file");
                idList.append(id);
            }
        }
    }
Exemple #12
0
int Program::main(const std::vector<CL_String> &args)
{
	try
	{
		// Initialize ClanLib base components
		CL_SetupCore setup_core;

		// Initialize the ClanLib display component
		CL_SetupDisplay setup_display;

		#ifdef USE_SOFTWARE_RENDERER
			CL_SetupSWRender setup_swrender;
		#endif

		#ifdef USE_OPENGL_1
			CL_SetupGL1 setup_gl1;
		#endif

		#ifdef USE_OPENGL_2
			CL_SetupGL setup_gl;
		#endif

		// Start the Application
		Language app;
		int retval = app.start(args);
		return retval;
	}
	catch(CL_Exception &exception)
	{
		// Create a console window for text-output if not available
		CL_ConsoleWindow console("Console", 80, 160);
		CL_Console::write_line("Exception caught: " + exception.get_message_and_stack_trace());
		console.display_close_message();

		return -1;
	}
}
Exemple #13
0
void CrowdinClient::UploadFile(const std::string& project_id, const std::wstring& file, const Language& lang,
                                 const std::string& file_content,
                                 std::function<void()> onSuccess,
                                 error_func_t onError)
{
    auto url = "/api/project/" + project_id + "/upload-translation";

    multipart_form_data data;
    data.add_value("json", "");
    data.add_value("language", lang.LanguageTag());
    data.add_value("import_duplicates", "0");
    data.add_value("import_eq_suggestions", "0");
    data.add_file("files[" + str::to_utf8(file) + "]", "upload.po", file_content);

    m_api->post(url, data, onSuccess, onError);
}
Exemple #14
0
KText::KText(Language lang)
{
	KText::lang = lang;

	sf::Image fontImg;
	fontImg.loadFromFile(VIDEO + L"Basic_Latin.png");

	basic_latin = sf::Texture();
	basic_latin.loadFromImage(fontImg);

	latinWidths = new int[256];
	for (int i = 0; i < 256; i++) { latinWidths[i] = FONT_SIZE; }

	KFile file(VIDEO + L"Latin_Widths.txt");
	bool comment = false;
	wstring w;
	for (bool b = true; b; )
	{
		file.readLine(w);

		if (w.length() == 0) continue;
		if (StringEditor::equals(w, L"endFile;")) {
			break;
		}
		else
		{
			int equals = StringEditor::findCharacter(w, L'=', 1);

			latinWidths[stoi(StringEditor::substring(w, 0, equals))] = stoi(StringEditor::substring(w, equals + 1, w.length()));
		}
	}
	file.close();

	//JAPANESE

	if (lang.getLanguageCode().toWideString().compare(L"ja-JP") == 0)
	{
		sf::Image japaneseImg;
		japaneseImg.loadFromFile(VIDEO + L"Japanese.png");

		japanese = sf::Texture();
		japanese.loadFromImage(japaneseImg);

		for (int i = 0; i < 256; i++) { latinWidths[i] = FONT_SIZE / 2; }
	}
}
void Trans_SetLanguage( const char* lang )
{
	Language requestLang = Language::from_env( std::string( lang ) );

	// default to english
	Language bestLang = Language::from_env( "en" );
	int bestScore = Language::match( requestLang, bestLang );

	std::set<Language> langs = trans_manager.get_languages();

	for( std::set<Language>::iterator i = langs.begin(); i != langs.end(); i++ )
	{
		int score = Language::match( requestLang, *i );

		if( score > bestScore )
		{
			bestScore = score;
			bestLang = *i;
		}
	}

	// language not found, display warning
	if( bestScore == 0 )
	{
		Com_Printf( S_WARNING "Language \"%s\" (%s) not found. Default to \"English\" (en)\n",
					requestLang.get_name().empty() ? "Unknown Language" : requestLang.get_name().c_str(),
					lang );
	}

	trans_manager.set_language( bestLang );
	trans_managergame.set_language( bestLang );

	Cvar_Set( "language", bestLang.str().c_str() );

	Com_Printf( "Set language to %s" , bestLang.get_name().c_str() );
}
Exemple #16
0
SuggestionsList TranslationMemoryImpl::Search(const Language& srclang,
                                              const Language& lang,
                                              const std::wstring& source)
{
    try
    {
        // TODO: query by srclang too!
        auto srclangQ = newLucene<TermQuery>(newLucene<Term>(L"srclang", srclang.WCode()));

        const Lucene::String fullLang = lang.WCode();
        const Lucene::String shortLang = StringUtils::toUnicode(lang.Lang());

        QueryPtr langPrimary = newLucene<TermQuery>(newLucene<Term>(L"lang", fullLang));
        QueryPtr langSecondary;
        if (fullLang == shortLang)
        {
            // for e.g. 'cs', search also 'cs_*' (e.g. 'cs_CZ')
            langSecondary = newLucene<PrefixQuery>(newLucene<Term>(L"lang", shortLang + L"_"));
        }
        else
        {
            // search short variants of the language too
            langSecondary = newLucene<TermQuery>(newLucene<Term>(L"lang", shortLang));
        }
        langSecondary->setBoost(0.85);
        auto langQ = newLucene<BooleanQuery>();
        langQ->add(langPrimary, BooleanClause::SHOULD);
        langQ->add(langSecondary, BooleanClause::SHOULD);

        SuggestionsList results;

        const Lucene::String sourceField(L"source");
        auto boolQ = newLucene<BooleanQuery>();
        auto phraseQ = newLucene<PhraseQuery>();

        auto stream = m_analyzer->tokenStream(sourceField, newLucene<StringReader>(source));
        int sourceTokensCount = 0;
        int sourceTokenPosition = -1;
        while (stream->incrementToken())
        {
            sourceTokensCount++;
            auto word = stream->getAttribute<TermAttribute>()->term();
            sourceTokenPosition += stream->getAttribute<PositionIncrementAttribute>()->getPositionIncrement();
            auto term = newLucene<Term>(sourceField, word);
            boolQ->add(newLucene<TermQuery>(term), BooleanClause::SHOULD);
            phraseQ->add(term, sourceTokenPosition);
        }

        auto searcher = m_mng->Searcher();

        // Try exact phrase first:
        PerformSearch(searcher.ptr(), srclangQ, langQ, source, phraseQ, results,
                      QUALITY_THRESHOLD, /*scoreScaling=*/1.0);
        if (!results.empty())
            return results;

        // Then, if no matches were found, permit being a bit sloppy:
        phraseQ->setSlop(1);
        PerformSearch(searcher.ptr(), srclangQ, langQ, source, phraseQ, results,
                      QUALITY_THRESHOLD, /*scoreScaling=*/0.9);

        if (!results.empty())
            return results;

        // As the last resort, try terms search. This will almost certainly
        // produce low-quality results, but hopefully better than nothing.
        boolQ->setMinimumNumberShouldMatch(std::max(1, boolQ->getClauses().size() - MAX_ALLOWED_LENGTH_DIFFERENCE));
        PerformSearchWithBlock
        (
            searcher.ptr(), srclangQ, langQ, source, boolQ,
            QUALITY_THRESHOLD, /*scoreScaling=*/0.8,
            [=,&results](DocumentPtr doc, double score)
            {
                auto s = get_text_field(doc, sourceField);
                auto t = get_text_field(doc, L"trans");
                auto stream2 = m_analyzer->tokenStream(sourceField, newLucene<StringReader>(s));
                int tokensCount2 = 0;
                while (stream2->incrementToken())
                    tokensCount2++;

                if (std::abs(tokensCount2 - sourceTokensCount) <= MAX_ALLOWED_LENGTH_DIFFERENCE &&
                    !ContainsResult(results, t))
                {
                    time_t ts = DateField::stringToTime(doc->get(L"created"));
                    Suggestion r {t, score, int(ts)};
                    r.id = StringUtils::toUTF8(doc->get(L"uuid"));
                    results.push_back(r);
                }
            }
        );

        std::stable_sort(results.begin(), results.end());
        return results;
    }
    catch (LuceneException&)
    {
        return SuggestionsList();
    }
}
Exemple #17
0
void Locale::AddLanguage( Language &lang ) {
  lib[lang.ID()] = lang;
  if ( this->lang == NULL ) this->lang = &lib[lang.ID()];
}
Exemple #18
0
void Locale::RemoveLanguage( Language &lang ) {
  if ( this->lang && (this->lang->ID() == lang.ID()) ) this->lang = NULL;
  lib.erase( lang.ID() );
}
Exemple #19
0
 PunctuationMismatch(Language lang) : m_lang(lang.Lang())
 {
 }
Exemple #20
0
		void CloseLang() { Lang.Close(); }
Exemple #21
0
		const wchar_t *GetMsg(int nID) { return Lang.GetMsg(nID); }
Exemple #22
0
		bool InitLang(const wchar_t *Path) { return Lang.Init(Path,true); }
Exemple #23
0
void ArchiveModule::ReloadLanguage(
		const TCHAR* lpLanguage
		)
{
	string strPath = m_strModuleName;
	CutToSlash (strPath);

	Language* pLanguage = nullptr;
	Language* pEnglishLanguage = nullptr;

	string strMask = strPath+_T("*.lng");
	
	WIN32_FIND_DATA FindData;
	bool bResult = false;

	HANDLE hSearch = FindFirstFile(
			strMask,
			(WIN32_FIND_DATA*)&FindData
			);

	if ( hSearch != INVALID_HANDLE_VALUE )
	{
		do {
			string strFileName = strPath+FindData.cFileName;

			pLanguage = new Language();

			if ( pLanguage->LoadFromFile(strFileName) )
			{
				string strLanguage = pLanguage->GetLanguage();

				if ( strLanguage == lpLanguage )
				{
					if ( m_pLanguage )
						delete m_pLanguage;

					m_pLanguage = pLanguage;

					bResult = true;
				}
				else
				{
					if ( strLanguage == _T("English") ) //case??
					{
						if ( !pEnglishLanguage ) //нам два не надо
							pEnglishLanguage = pLanguage;
						else
							delete pLanguage;
					}
					else
						delete pLanguage;
				}
			}
			else
				delete pLanguage;

		} while ( !bResult && FindNextFile(hSearch, (WIN32_FIND_DATA*)&FindData) );

		FindClose (hSearch);
	}

	if ( pEnglishLanguage )
	{
		if ( !bResult )
		{
			if ( m_pLanguage )
				delete m_pLanguage;

			m_pLanguage = pEnglishLanguage;
		}
		else
			delete pEnglishLanguage;
	}
}
// ----------------------------------------------------------------------------
Translations::Translations() //: m_dictionary_manager("UTF-16")
{
    m_dictionary_manager.add_directory(
                        file_manager->getAsset(FileManager::TRANSLATION,""));
                        
    if (g_language_list.size() == 0)
    {
        std::set<Language> languages = m_dictionary_manager.get_languages();      
        
        // English is always there but won't be found on file system
        g_language_list.push_back("en");
    
        std::set<Language>::iterator it;
        for (it = languages.begin(); it != languages.end(); it++)
        {
            g_language_list.push_back((*it).str());
        }
    }

    // LC_ALL does not work, sscanf will then not always be able
    // to scan for example: s=-1.1,-2.3,-3.3 correctly, which is
    // used in driveline files.
#if defined(WIN32) && !defined(__CYGWIN__)
    // Windows does not have LC_MESSAGES
    setlocale(LC_CTYPE,    "");
#else
    setlocale(LC_MESSAGES, "");
#endif


    /*
    bindtextdomain (PACKAGE, file_manager->getTranslationDir().c_str());

    if (sizeof(wchar_t) == 4)
    {
        if (IS_LITTLE_ENDIAN) bind_textdomain_codeset(PACKAGE, "UTF-32LE");
        else                  bind_textdomain_codeset(PACKAGE, "UTF-32BE");
    }
    else if (sizeof(wchar_t) == 2)
    {
        bind_textdomain_codeset(PACKAGE, "UTF-16LE");
    }
    else
    {
        fprintf(stderr, "Your wchar_t is neither 2 byte-long nor 4. What now??\n");
        exit(1);
    }

    textdomain (PACKAGE);
    */

    /*
    const std::set<Language>& languages = m_dictionary_manager.get_languages();
    Log::info("Translatings", "Number of languages: %d", languages.size());
    for (std::set<Language>::const_iterator i = languages.begin();
                                            i != languages.end(); ++i)
    {
        const Language& language = *i;
        Log::info("Translatings", "Env:       %s", language.str());
        Log::info("Translatings", "Name:      %s", language.get_name());
        Log::info("Translatings", "Language:  %s", language.get_language());
        Log::info("Translatings", "Country:   %s", language.get_country());
        Log::info("Translatings", "Modifier:  %s", language.get_modifier());
    }
    */

    const char *p_language = getenv("LANGUAGE");

    std::string language;

    if(p_language)
    {
        language=p_language;
    }
    else
    {
        const char *p_lang = getenv("LANG");

        if(p_lang)
            language = p_lang;
        else
        {
#ifdef WIN32
            // Thanks to the frogatto developer for this code snippet:
            char c[1024];
            GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_SISO639LANGNAME,
                           c, 1024);
            Log::verbose("translation", "GetLocaleInfo langname returns '%s'.",
                         c);
            if(c[0])
            {
                language = c;
                GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_SISO3166CTRYNAME,
                               c, 1024);
                Log::verbose("translation",
                             "GetLocaleInfo tryname returns '%s'.", c);
                if(c[0]) language += std::string("_")+c;
            }   // if c[0]
#endif
        }   // neither LANGUAGE nor LANG defined

    }

    if (language != "")
    {
        Log::verbose("translation", "Env var LANGUAGE = '%s'.",
                     language.c_str());

        if (language.find(":") != std::string::npos)
        {
            std::vector<std::string> langs = StringUtils::split(language, ':');
            Language l;

            for (unsigned int curr=0; curr<langs.size(); curr++)
            {
                l = Language::from_env(langs[curr]);
                if (l)
                {
                    Log::verbose("translation", "Language '%s'.",
                                 l.get_name().c_str());
                    m_dictionary = m_dictionary_manager.get_dictionary(l);
                    break;
                }
            }

            m_current_language_name = l.get_name();
            m_current_language_name_code = l.get_language();

            if (!l)
            {
                m_dictionary = m_dictionary_manager.get_dictionary();
            }
        }
        else
        {
            const Language& tgtLang = Language::from_env(language);
            if (!tgtLang)
            {
                Log::warn("Translation", "Unsupported langage '%s'", language.c_str());
                UserConfigParams::m_language = "system";
                m_current_language_name = "Default language";
                m_current_language_name_code = "en";
                m_dictionary = m_dictionary_manager.get_dictionary();
            }
            else
            {
                m_current_language_name = tgtLang.get_name();
                m_current_language_name_code = tgtLang.get_language();
                Log::verbose("translation", "Language '%s'.", m_current_language_name.c_str());
                m_dictionary = m_dictionary_manager.get_dictionary(tgtLang);
            }
        }
    }
    else
    {
        m_current_language_name = "Default language";
        m_current_language_name_code = "en";
        m_dictionary = m_dictionary_manager.get_dictionary();
    }

    // This is a silly but working hack I added to determine whether the
    // current language is RTL or not, since gettext doesn't seem to provide
    // this information

    // This one is just for the xgettext parser to pick up
#define ignore(X)

    //I18N: Do NOT literally translate this string!! Please enter Y as the
    //      translation if your language is a RTL (right-to-left) language,
    //      N (or nothing) otherwise
    ignore(_("   Is this a RTL language?"));

    const std::string isRtl =
        m_dictionary.translate("   Is this a RTL language?");

    m_rtl = false;

    for (unsigned int n=0; n < isRtl.size(); n++)
    {
        if (isRtl[n] == 'Y')
        {
            m_rtl = true;
            break;
        }
    }
#ifdef TEST_BIDI
    m_rtl = true;
#endif
}   // Translations
Exemple #25
0
// unit handler
int UnitHandler::ParseSection( ifstream &in, const string *opt, unsigned long &line ) {
  int rc = KeyValueSectionHandler::ParseSection( in, opt, line );

  if ( rc == 0 ) {
    bool named = false;

    EdUnitType t;
    t.SetTerrain( TT_ENTRANCE );
    t.SetImage( 0 );
    t.SetFlags( 0 );
    t.SetMoves( 0 );
    t.SetWeight( 0 );
    t.SetDefence( 0 );
    t.SetPowerGround( 0 );
    t.SetPowerShip( 0 );
    t.SetPowerAir( 0 );
    t.SetMinRangeGround( 1 );
    t.SetMaxRangeGround( 1 );
    t.SetMinRangeShip( 1 );
    t.SetMaxRangeShip( 1 );
    t.SetMinRangeAir( 1 );
    t.SetMaxRangeAir( 1 );
    t.SetCost( 0 );
    t.SetTransSlots( 0 );
    t.SetTransMinWeight( 0 );
    t.SetTransMaxWeight( 0 );
    t.SetPortrait( -1 );

    for ( vector<pair<string, string> >::iterator it = pairs.begin();
          it != pairs.end(); ++it ) {
      string key = (*it).first;
      string val = (*it).second;

      if ( key == "type" ) {
        if ( val == "ground" ) t.AddFlags( U_GROUND );
        else if ( val == "ship" ) t.AddFlags( U_SHIP );
        else if ( val == "aircraft" ) t.AddFlags( U_AIR );
        else if ( val == "trooper" ) t.AddFlags( U_CONQUER );
        else if ( val == "slow" ) t.AddFlags( U_SLOW );
        else if ( val == "mine" ) t.AddFlags( U_MINE );
        else if ( val == "medic" ) t.AddFlags( U_MEDIC );
        else if ( val == "sweeper" ) t.AddFlags( U_MINESWEEPER );
        else {
          rc = 1;
          cerr << "Error near line " << line << ": Invalid unit class '" << val << "'" << endl;
          break;
        }
      }
      else if ( key == "terrain" ) {
        if ( val == "road" ) t.AddTerrain( TT_ROAD );
        else if ( val == "plains" ) t.AddTerrain( TT_PLAINS );
        else if ( val == "forest" ) t.AddTerrain( TT_FOREST );
        else if ( val == "swamp" ) t.AddTerrain( TT_SWAMP );
        else if ( val == "mountains" ) t.AddTerrain( TT_MOUNTAINS );
        else if ( val == "shallowwater" ) t.AddTerrain( TT_WATER_SHALLOW );
        else if ( val == "deepwater" ) t.AddTerrain( TT_WATER_DEEP );
        else if ( val == "water" ) t.AddTerrain( TT_WATER );
        else if ( val == "rough" ) t.AddTerrain( TT_BARRICADES );
        else if ( val == "rails" ) t.AddTerrain( TT_RAILS );
        else if ( val == "restricted" ) t.AddTerrain( TT_RESTRICTED );
        else if ( val == "trenches" ) t.AddTerrain( TT_TRENCHES );
        else {
          rc = 1;
          cerr << "Error near line " << line << ": Invalid terrain '" << val << "'" << endl;
          break;
        }
      }
      else if ( key == "icon" ) t.SetImage( StrToNum( val ) );
      else if ( key == "armour" ) t.SetDefence( StrToNum( val ) );
      else if ( key == "speed" ) t.SetMoves( StrToNum( val ) );
      else if ( key == "price" ) t.SetCost( StrToNum( val ) );
      else if ( key == "weight" ) t.SetWeight( StrToNum( val ) );
      else if ( key == "transslots" ) t.SetTransSlots( StrToNum( val ) );
      else if ( key == "transminweight" ) t.SetTransMinWeight( StrToNum( val ) );
      else if ( key == "transmaxweight" ) t.SetTransMaxWeight( StrToNum( val ) );
      else if ( key == "portrait" ) {
        vector<string>::iterator it =
                find( info.portraits.begin(), info.portraits.end(), val );
        if ( it == info.portraits.end() ) {
          t.SetPortrait( info.portraits.size() );
          info.portraits.push_back( val );
        } else {
          t.SetPortrait( distance( info.portraits.begin(), it ) );
        }
      }
      else if ( key.substr( 0, 5 ) == "power" ) {
        string type = ParseOpt( key );

        if ( type == "" ) rc = 1;
        else rc = ParsePower( val, type, t );
      }
      else if ( key.substr( 0, 4 ) == "name" ) {
        string lang = ParseOpt( key );

        if ( lang == "" ) rc = 1;
        else if ( lang.size() != 2 ) {
          rc = 1;
          cerr << "Error near line " << line << ": '" << val << "' is not a valid language" << endl;
        } else {
          map <string, Language>::iterator it = names.find( lang );
          if ( it == names.end() ) {
            // only accept new languages for the first unit
            if ( units.size() == 0 ) {
              Language l;
              l.SetID( lang.c_str() );
              l.AddMsg( val );
              names[lang] = l;
              named = true;
            } else
              cerr << "Warning near line " << line << ": New language '" << lang << "' ignored" << endl;
          } else {
            it->second.AddMsg( val );
            named = true;
          }
        }
      } else {
        rc = 1;
        cerr << "Error near line " << line << ": Invalid keyword '" << key << "' in this context" << endl;
      }
    }

    if ( t.Firepower( U_GROUND ) == 0 ) {
      t.SetMinRangeGround( 0 );
      t.SetMaxRangeGround( 0 );
    }
    if ( t.Firepower( U_SHIP ) == 0 ) {
      t.SetMinRangeShip( 0 );
      t.SetMaxRangeShip( 0 );
    }
    if ( t.Firepower( U_AIR ) == 0 ) {
      t.SetMinRangeAir( 0 );
      t.SetMaxRangeAir( 0 );
    }
    if ( t.Slots() > 0 ) t.AddFlags( U_TRANSPORT );
    if ( t.Terrain() == 0 ) {
      rc = 1;
      cerr << "Error near line " << line << ": Unit does not specify terrain" << endl;
    }

    if ( !named ) {
      rc = 1;
      cerr << "Error near line " << line << ": Unit does not specify a name" << endl;
    } else {
      unsigned short msgs = names[CF_LANG_DEFAULT].Size();
      for ( map<string, Language>::iterator it = names.begin();
            it != names.end(); ++it ) {
        if ( it->second.Size() != msgs ) {
          const char *defname = names[CF_LANG_DEFAULT].GetMsg(msgs-1);
          if ( defname ) {
            cerr << "Warning near line " << line
                 << ": Unit does not specify name for language '" << it->first
                 << "', using '" << CF_LANG_DEFAULT << "' default ("
                 << defname << ')' << endl;
            it->second.AddMsg( defname );
          } else {
            rc = 1;
            cerr << "Error near line " << line
                 << ": Unit does not specify name for language '" << it->first << "'" << endl;
          }
        }
      }
    }

    units.push_back( t );
  }
  return rc;
}
int main(int argc, char** argv)
{
  try
  {
    if (argc == 3 && strcmp(argv[1], "language-dir") == 0)
    {
      DictionaryManager dictionary_manager;
      dictionary_manager.add_directory(argv[2]);
      const std::set<Language>& languages = dictionary_manager.get_languages();
      std::cout << "Number of languages: " << languages.size() << std::endl;
      for (std::set<Language>::const_iterator i = languages.begin(); i != languages.end(); ++i)
      {
        const Language& language = *i;
        std::cout << "Env:       " << language.str()           << std::endl
                  << "Name:      " << language.get_name()      << std::endl
                  << "Language:  " << language.get_language()  << std::endl
                  << "Country:   " << language.get_country()   << std::endl
                  << "Modifier:  " << language.get_modifier()  << std::endl
                  << std::endl;
      }
    }
    else if (argc == 3 && strcmp(argv[1], "language") == 0)
    {
      const char* language_cstr = argv[2];
      Language language = Language::from_name(language_cstr);

      if (language)
        std::cout << "Env:       " << language.str()           << std::endl
                  << "Name:      " << language.get_name()      << std::endl
                  << "Language:  " << language.get_language()  << std::endl
                  << "Country:   " << language.get_country()   << std::endl
                  << "Modifier:  " << language.get_modifier()  << std::endl;
      else
        std::cout << "not found" << std::endl;
    }
    else if (argc == 4 && strcmp(argv[1], "translate") == 0)
    {
      const char* filename = argv[2];
      const char* message  = argv[3];

      Dictionary dict;
      read_dictionary(filename, dict);
      std::cout << "TRANSLATION: \"\"\"" << dict.translate(message) << "\"\"\""<< std::endl;
    }
    else if (argc == 5 && strcmp(argv[1], "translate") == 0)
    {
      const char* filename = argv[2];
      const char* context  = argv[3];
      const char* message  = argv[4];

      Dictionary dict;
      read_dictionary(filename, dict);
      std::cout << dict.translate_ctxt(context, message) << std::endl;
    }
    else if (argc == 6 && strcmp(argv[1], "translate") == 0)
    {
      const char* filename = argv[2];
      const char* message_singular = argv[3];
      const char* message_plural   = argv[4];
      int num = atoi(argv[5]);

      Dictionary dict;
      read_dictionary(filename, dict);
      std::cout << dict.translate_plural(message_singular, message_plural, num) << std::endl;
    }
    else if (argc == 7 && strcmp(argv[1], "translate") == 0)
    {
      const char* filename = argv[2];
      const char* context  = argv[3];
      const char* message_singular = argv[4];
      const char* message_plural   = argv[5];
      int num = atoi(argv[6]);

      Dictionary dict;
      read_dictionary(filename, dict);
      std::cout << dict.translate_ctxt_plural(context, message_singular, message_plural, num) << std::endl;
    }
    else if ((argc == 4 || argc == 5) && strcmp(argv[1], "directory") == 0)
    {
      const char* directory = argv[2];
      const char* message   = argv[3];
      const char* language  = (argc == 5) ? argv[4] : NULL;

      DictionaryManager manager;
      manager.add_directory(directory);

      if (language)
      {
        Language lang = Language::from_name(language);
        if (lang)
        {
          manager.set_language(lang);
        }
        else
        {
          std::cout << "Unknown language: " << language << std::endl;
          exit(EXIT_FAILURE);
        }
      }

      std::cout << "Directory:   '" << directory << "'"  << std::endl;
      std::cout << "Message:     '" << message << "'" << std::endl;
      std::cout << "Language:    '" << manager.get_language().str() << "' (name: '"
                << manager.get_language().get_name() << "', language: '"
                << manager.get_language().get_language() << "', country: '"
                << manager.get_language().get_country() << "', modifier: '"
                << manager.get_language().get_modifier() << "')"
                << std::endl;
      std::cout << "Translation: '" << manager.get_dictionary().translate(message) << "'" << std::endl;
    }
    else if ((argc == 3) && strcmp(argv[1], "list-msgstrs") == 0)
    {
      const char* filename = argv[2];

      Dictionary dict;
      read_dictionary(filename, dict);
      dict.foreach(print_msg);
      dict.foreach_ctxt(print_msg_ctxt);
    }
    else
    {
      print_usage(argc, argv);
    }
  }
  catch(std::exception& err)
  {
    std::cout << "Exception: " << err.what() << std::endl;
  }

  return 0;
}
template<> XmlNode NodeCreator<Language>::createNodeFromObject(const Language& t) {
	XmlNode n("language");
	n.addChild(XmlNode("id", boost::lexical_cast<std::string>(t.getId())));
	n.addChild(XmlNode("nameID", boost::lexical_cast<std::string>(t.getName()->getId())));
	return n;
}
Exemple #28
0
 CaseMismatch(Language lang) : m_lang(lang.Lang())
 {
 }