Exemplo n.º 1
0
bool CSceneAmpCoder::DeCode_Ver_D( const CDataChunk& inData,OBJ_HANDLE handle )
{
	CSceneManagerClient* pScene = (CSceneManagerClient*)handle;
	CPkgFile& File = *((CPkgFile*)inData.GetBuffer());

	DeCoder_Com_B_D(File,handle);

	size_t size = 0, ajenctsize= 0;
	File.read(&size, sizeof(size_t));
	if( size == 0 )
		return true;
	else
	{
		locale loc = locale::global(locale(""));
		uint32 dwNameLen = 0;
		char szBuf[256];
		for( size_t i = 0; i < size; ++i )
		{
			RegionsInfo *pRgnInfo = new RegionsInfo;

			if( !pRgnInfo )
				return false;
			///scene
			File.read(&pRgnInfo->lightParam.globalAmbient.R, sizeof(uint8));
			File.read(&pRgnInfo->lightParam.globalAmbient.G, sizeof(uint8));
			File.read(&pRgnInfo->lightParam.globalAmbient.B, sizeof(uint8));

			File.read(&pRgnInfo->lightParam.globalDiffuse.R, sizeof(uint8));
			File.read(&pRgnInfo->lightParam.globalDiffuse.G, sizeof(uint8));
			File.read(&pRgnInfo->lightParam.globalDiffuse.B, sizeof(uint8));

#ifndef	AMBIENT_SHADOW_COLOR	
			File.read(&pRgnInfo->lightParam.globalShadow.R, sizeof(uint8));
			File.read(&pRgnInfo->lightParam.globalShadow.G, sizeof(uint8));
			File.read(&pRgnInfo->lightParam.globalShadow.B, sizeof(uint8));
#else
			uint8 dummy;
			File.read(&dummy, sizeof(uint8));
			File.read(&dummy, sizeof(uint8));
			File.read(&dummy, sizeof(uint8));
#endif

			File.read(&pRgnInfo->lightParam.fogColor.R, sizeof(uint8));
			File.read(&pRgnInfo->lightParam.fogColor.G, sizeof(uint8));
			File.read(&pRgnInfo->lightParam.fogColor.B, sizeof(uint8));

			///player
			File.read(&pRgnInfo->lightParam.playerAmbient.R, sizeof(uint8));
			File.read(&pRgnInfo->lightParam.playerAmbient.G, sizeof(uint8));
			File.read(&pRgnInfo->lightParam.playerAmbient.B, sizeof(uint8));

			File.read(&pRgnInfo->lightParam.playerDiffuse.R, sizeof(uint8));
			File.read(&pRgnInfo->lightParam.playerDiffuse.G, sizeof(uint8));
			File.read(&pRgnInfo->lightParam.playerDiffuse.B, sizeof(uint8));

			File.read(&pRgnInfo->uFogMode,	 sizeof(pRgnInfo->uFogMode));
			File.read(&pRgnInfo->lightParam.fogStart,	 sizeof(float));
			File.read(&pRgnInfo->lightParam.fogEnd,		 sizeof(float));
			File.read(&pRgnInfo->lightParam.fogDensity, sizeof(float));

			///music name
			File.Read(&dwNameLen,sizeof(dwNameLen));
			File.Read(szBuf, sizeof(char)*dwNameLen);
			pRgnInfo->strMusicName = szBuf;

			pScene->m_RgnsList.push_back(pRgnInfo);
		}

		locale::global(loc);//恢复全局locale	
	}

	return true;
}
int QWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        if (_id < 23)
            qt_static_metacall(this, _c, _id, _a);
        _id -= 23;
    }
#ifndef QT_NO_PROPERTIES
      else if (_c == QMetaObject::ReadProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: *reinterpret_cast< bool*>(_v) = isModal(); break;
        case 1: *reinterpret_cast< Qt::WindowModality*>(_v) = windowModality(); break;
        case 2: *reinterpret_cast< bool*>(_v) = isEnabled(); break;
        case 3: *reinterpret_cast< QRect*>(_v) = geometry(); break;
        case 4: *reinterpret_cast< QRect*>(_v) = frameGeometry(); break;
        case 5: *reinterpret_cast< QRect*>(_v) = normalGeometry(); break;
        case 6: *reinterpret_cast< int*>(_v) = x(); break;
        case 7: *reinterpret_cast< int*>(_v) = y(); break;
        case 8: *reinterpret_cast< QPoint*>(_v) = pos(); break;
        case 9: *reinterpret_cast< QSize*>(_v) = frameSize(); break;
        case 10: *reinterpret_cast< QSize*>(_v) = size(); break;
        case 11: *reinterpret_cast< int*>(_v) = width(); break;
        case 12: *reinterpret_cast< int*>(_v) = height(); break;
        case 13: *reinterpret_cast< QRect*>(_v) = rect(); break;
        case 14: *reinterpret_cast< QRect*>(_v) = childrenRect(); break;
        case 15: *reinterpret_cast< QRegion*>(_v) = childrenRegion(); break;
        case 16: *reinterpret_cast< QSizePolicy*>(_v) = sizePolicy(); break;
        case 17: *reinterpret_cast< QSize*>(_v) = minimumSize(); break;
        case 18: *reinterpret_cast< QSize*>(_v) = maximumSize(); break;
        case 19: *reinterpret_cast< int*>(_v) = minimumWidth(); break;
        case 20: *reinterpret_cast< int*>(_v) = minimumHeight(); break;
        case 21: *reinterpret_cast< int*>(_v) = maximumWidth(); break;
        case 22: *reinterpret_cast< int*>(_v) = maximumHeight(); break;
        case 23: *reinterpret_cast< QSize*>(_v) = sizeIncrement(); break;
        case 24: *reinterpret_cast< QSize*>(_v) = baseSize(); break;
        case 25: *reinterpret_cast< QPalette*>(_v) = palette(); break;
        case 26: *reinterpret_cast< QFont*>(_v) = font(); break;
        case 27: *reinterpret_cast< QCursor*>(_v) = cursor(); break;
        case 28: *reinterpret_cast< bool*>(_v) = hasMouseTracking(); break;
        case 29: *reinterpret_cast< bool*>(_v) = isActiveWindow(); break;
        case 30: *reinterpret_cast< Qt::FocusPolicy*>(_v) = focusPolicy(); break;
        case 31: *reinterpret_cast< bool*>(_v) = hasFocus(); break;
        case 32: *reinterpret_cast< Qt::ContextMenuPolicy*>(_v) = contextMenuPolicy(); break;
        case 33: *reinterpret_cast< bool*>(_v) = updatesEnabled(); break;
        case 34: *reinterpret_cast< bool*>(_v) = isVisible(); break;
        case 35: *reinterpret_cast< bool*>(_v) = isMinimized(); break;
        case 36: *reinterpret_cast< bool*>(_v) = isMaximized(); break;
        case 37: *reinterpret_cast< bool*>(_v) = isFullScreen(); break;
        case 38: *reinterpret_cast< QSize*>(_v) = sizeHint(); break;
        case 39: *reinterpret_cast< QSize*>(_v) = minimumSizeHint(); break;
        case 40: *reinterpret_cast< bool*>(_v) = acceptDrops(); break;
        case 41: *reinterpret_cast< QString*>(_v) = windowTitle(); break;
        case 42: *reinterpret_cast< QIcon*>(_v) = windowIcon(); break;
        case 43: *reinterpret_cast< QString*>(_v) = windowIconText(); break;
        case 44: *reinterpret_cast< double*>(_v) = windowOpacity(); break;
        case 45: *reinterpret_cast< bool*>(_v) = isWindowModified(); break;
        case 46: *reinterpret_cast< QString*>(_v) = toolTip(); break;
        case 47: *reinterpret_cast< QString*>(_v) = statusTip(); break;
        case 48: *reinterpret_cast< QString*>(_v) = whatsThis(); break;
        case 49: *reinterpret_cast< QString*>(_v) = accessibleName(); break;
        case 50: *reinterpret_cast< QString*>(_v) = accessibleDescription(); break;
        case 51: *reinterpret_cast< Qt::LayoutDirection*>(_v) = layoutDirection(); break;
        case 52: *reinterpret_cast< bool*>(_v) = autoFillBackground(); break;
        case 53: *reinterpret_cast< QString*>(_v) = styleSheet(); break;
        case 54: *reinterpret_cast< QLocale*>(_v) = locale(); break;
        case 55: *reinterpret_cast< QString*>(_v) = windowFilePath(); break;
        case 56: *reinterpret_cast< Qt::InputMethodHints*>(_v) = inputMethodHints(); break;
        }
        _id -= 57;
    } else if (_c == QMetaObject::WriteProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 1: setWindowModality(*reinterpret_cast< Qt::WindowModality*>(_v)); break;
        case 2: setEnabled(*reinterpret_cast< bool*>(_v)); break;
        case 3: setGeometry(*reinterpret_cast< QRect*>(_v)); break;
        case 8: move(*reinterpret_cast< QPoint*>(_v)); break;
        case 10: resize(*reinterpret_cast< QSize*>(_v)); break;
        case 16: setSizePolicy(*reinterpret_cast< QSizePolicy*>(_v)); break;
        case 17: setMinimumSize(*reinterpret_cast< QSize*>(_v)); break;
        case 18: setMaximumSize(*reinterpret_cast< QSize*>(_v)); break;
        case 19: setMinimumWidth(*reinterpret_cast< int*>(_v)); break;
        case 20: setMinimumHeight(*reinterpret_cast< int*>(_v)); break;
        case 21: setMaximumWidth(*reinterpret_cast< int*>(_v)); break;
        case 22: setMaximumHeight(*reinterpret_cast< int*>(_v)); break;
        case 23: setSizeIncrement(*reinterpret_cast< QSize*>(_v)); break;
        case 24: setBaseSize(*reinterpret_cast< QSize*>(_v)); break;
        case 25: setPalette(*reinterpret_cast< QPalette*>(_v)); break;
        case 26: setFont(*reinterpret_cast< QFont*>(_v)); break;
        case 27: setCursor(*reinterpret_cast< QCursor*>(_v)); break;
        case 28: setMouseTracking(*reinterpret_cast< bool*>(_v)); break;
        case 30: setFocusPolicy(*reinterpret_cast< Qt::FocusPolicy*>(_v)); break;
        case 32: setContextMenuPolicy(*reinterpret_cast< Qt::ContextMenuPolicy*>(_v)); break;
        case 33: setUpdatesEnabled(*reinterpret_cast< bool*>(_v)); break;
        case 34: setVisible(*reinterpret_cast< bool*>(_v)); break;
        case 40: setAcceptDrops(*reinterpret_cast< bool*>(_v)); break;
        case 41: setWindowTitle(*reinterpret_cast< QString*>(_v)); break;
        case 42: setWindowIcon(*reinterpret_cast< QIcon*>(_v)); break;
        case 43: setWindowIconText(*reinterpret_cast< QString*>(_v)); break;
        case 44: setWindowOpacity(*reinterpret_cast< double*>(_v)); break;
        case 45: setWindowModified(*reinterpret_cast< bool*>(_v)); break;
        case 46: setToolTip(*reinterpret_cast< QString*>(_v)); break;
        case 47: setStatusTip(*reinterpret_cast< QString*>(_v)); break;
        case 48: setWhatsThis(*reinterpret_cast< QString*>(_v)); break;
        case 49: setAccessibleName(*reinterpret_cast< QString*>(_v)); break;
        case 50: setAccessibleDescription(*reinterpret_cast< QString*>(_v)); break;
        case 51: setLayoutDirection(*reinterpret_cast< Qt::LayoutDirection*>(_v)); break;
        case 52: setAutoFillBackground(*reinterpret_cast< bool*>(_v)); break;
        case 53: setStyleSheet(*reinterpret_cast< QString*>(_v)); break;
        case 54: setLocale(*reinterpret_cast< QLocale*>(_v)); break;
        case 55: setWindowFilePath(*reinterpret_cast< QString*>(_v)); break;
        case 56: setInputMethodHints(*reinterpret_cast< Qt::InputMethodHints*>(_v)); break;
        }
        _id -= 57;
    } else if (_c == QMetaObject::ResetProperty) {
        switch (_id) {
        case 27: unsetCursor(); break;
        case 51: unsetLayoutDirection(); break;
        case 54: unsetLocale(); break;
        }
        _id -= 57;
    } else if (_c == QMetaObject::QueryPropertyDesignable) {
        bool *_b = reinterpret_cast<bool*>(_a[0]);
        switch (_id) {
        case 41: *_b = isWindow(); break;
        case 42: *_b = isWindow(); break;
        case 43: *_b = isWindow(); break;
        case 44: *_b = isWindow(); break;
        case 45: *_b = isWindow(); break;
        case 55: *_b = isWindow(); break;
        }
        _id -= 57;
    } else if (_c == QMetaObject::QueryPropertyScriptable) {
        _id -= 57;
    } else if (_c == QMetaObject::QueryPropertyStored) {
        _id -= 57;
    } else if (_c == QMetaObject::QueryPropertyEditable) {
        _id -= 57;
    } else if (_c == QMetaObject::QueryPropertyUser) {
        _id -= 57;
    }
#endif // QT_NO_PROPERTIES
    return _id;
}
Exemplo n.º 3
0
void pTranslationDialog::init( pTranslationManager* translationManager )
{
    if ( mTranslationManager == translationManager ) {
        return;
    }

    mTranslationManager = translationManager;
    mOriginalLocale = mTranslationManager ? mTranslationManager->currentLocale().name() : locale().name();

    if ( !ui ) {
        ui = new Ui::pTranslationDialog;
        ui->setupUi( this );
    }

    ui->tbReload->click();
    localeChanged();
}
Exemplo n.º 4
0
//! [10]
void Window::createGeneralOptionsGroupBox()
{
    generalOptionsGroupBox = new QGroupBox(tr("General Options"));

    localeCombo = new QComboBox;
    int curLocaleIndex = -1;
    int index = 0;
    for (int _lang = QLocale::C; _lang <= QLocale::LastLanguage; ++_lang) {
        QLocale::Language lang = static_cast<QLocale::Language>(_lang);
        QList<QLocale::Country> countries = QLocale::countriesForLanguage(lang);
        for (int i = 0; i < countries.count(); ++i) {
            QLocale::Country country = countries.at(i);
            QString label = QLocale::languageToString(lang);
            label += QLatin1Char('/');
            label += QLocale::countryToString(country);
            QLocale locale(lang, country);
            if (this->locale().language() == lang && this->locale().country() == country)
                curLocaleIndex = index;
            localeCombo->addItem(label, locale);
            ++index;
        }
    }
    if (curLocaleIndex != -1)
        localeCombo->setCurrentIndex(curLocaleIndex);
    localeLabel = new QLabel(tr("&Locale"));
    localeLabel->setBuddy(localeCombo);

    firstDayCombo = new QComboBox;
    firstDayCombo->addItem(tr("Sunday"), Qt::Sunday);
    firstDayCombo->addItem(tr("Monday"), Qt::Monday);
    firstDayCombo->addItem(tr("Tuesday"), Qt::Tuesday);
    firstDayCombo->addItem(tr("Wednesday"), Qt::Wednesday);
    firstDayCombo->addItem(tr("Thursday"), Qt::Thursday);
    firstDayCombo->addItem(tr("Friday"), Qt::Friday);
    firstDayCombo->addItem(tr("Saturday"), Qt::Saturday);

    firstDayLabel = new QLabel(tr("Wee&k starts on:"));
    firstDayLabel->setBuddy(firstDayCombo);
//! [10]

    selectionModeCombo = new QComboBox;
    selectionModeCombo->addItem(tr("Single selection"),
                                QCalendarWidget::SingleSelection);
    selectionModeCombo->addItem(tr("None"), QCalendarWidget::NoSelection);

    selectionModeLabel = new QLabel(tr("&Selection mode:"));
    selectionModeLabel->setBuddy(selectionModeCombo);

    gridCheckBox = new QCheckBox(tr("&Grid"));
    gridCheckBox->setChecked(calendar->isGridVisible());

    navigationCheckBox = new QCheckBox(tr("&Navigation bar"));
    navigationCheckBox->setChecked(true);

    horizontalHeaderCombo = new QComboBox;
    horizontalHeaderCombo->addItem(tr("Single letter day names"),
                                   QCalendarWidget::SingleLetterDayNames);
    horizontalHeaderCombo->addItem(tr("Short day names"),
                                   QCalendarWidget::ShortDayNames);
    horizontalHeaderCombo->addItem(tr("None"),
                                   QCalendarWidget::NoHorizontalHeader);
    horizontalHeaderCombo->setCurrentIndex(1);

    horizontalHeaderLabel = new QLabel(tr("&Horizontal header:"));
    horizontalHeaderLabel->setBuddy(horizontalHeaderCombo);

    verticalHeaderCombo = new QComboBox;
    verticalHeaderCombo->addItem(tr("ISO week numbers"),
                                 QCalendarWidget::ISOWeekNumbers);
    verticalHeaderCombo->addItem(tr("None"), QCalendarWidget::NoVerticalHeader);

    verticalHeaderLabel = new QLabel(tr("&Vertical header:"));
    verticalHeaderLabel->setBuddy(verticalHeaderCombo);

//! [11]
    connect(localeCombo, SIGNAL(currentIndexChanged(int)),
            this, SLOT(localeChanged(int)));
    connect(firstDayCombo, SIGNAL(currentIndexChanged(int)),
            this, SLOT(firstDayChanged(int)));
    connect(selectionModeCombo, SIGNAL(currentIndexChanged(int)),
            this, SLOT(selectionModeChanged(int)));
    connect(gridCheckBox, SIGNAL(toggled(bool)),
            calendar, SLOT(setGridVisible(bool)));
    connect(navigationCheckBox, SIGNAL(toggled(bool)),
            calendar, SLOT(setNavigationBarVisible(bool)));
    connect(horizontalHeaderCombo, SIGNAL(currentIndexChanged(int)),
            this, SLOT(horizontalHeaderChanged(int)));
    connect(verticalHeaderCombo, SIGNAL(currentIndexChanged(int)),
            this, SLOT(verticalHeaderChanged(int)));
//! [11]

    QHBoxLayout *checkBoxLayout = new QHBoxLayout;
    checkBoxLayout->addWidget(gridCheckBox);
    checkBoxLayout->addStretch();
    checkBoxLayout->addWidget(navigationCheckBox);

    QGridLayout *outerLayout = new QGridLayout;
    outerLayout->addWidget(localeLabel, 0, 0);
    outerLayout->addWidget(localeCombo, 0, 1);
    outerLayout->addWidget(firstDayLabel, 1, 0);
    outerLayout->addWidget(firstDayCombo, 1, 1);
    outerLayout->addWidget(selectionModeLabel, 2, 0);
    outerLayout->addWidget(selectionModeCombo, 2, 1);
    outerLayout->addLayout(checkBoxLayout, 3, 0, 1, 2);
    outerLayout->addWidget(horizontalHeaderLabel, 4, 0);
    outerLayout->addWidget(horizontalHeaderCombo, 4, 1);
    outerLayout->addWidget(verticalHeaderLabel, 5, 0);
    outerLayout->addWidget(verticalHeaderCombo, 5, 1);
    generalOptionsGroupBox->setLayout(outerLayout);

//! [12]
    firstDayChanged(firstDayCombo->currentIndex());
    selectionModeChanged(selectionModeCombo->currentIndex());
    horizontalHeaderChanged(horizontalHeaderCombo->currentIndex());
    verticalHeaderChanged(verticalHeaderCombo->currentIndex());
}
Exemplo n.º 5
0
void
StringCaseTest::TestCasingImpl(const UnicodeString &input,
                               const UnicodeString &output,
                               int32_t whichCase,
                               void *iter, const char *localeID, uint32_t options) {
    // UnicodeString
    UnicodeString result;
    const char *name;
    Locale locale(localeID);

    result=input;
    switch(whichCase) {
    case TEST_LOWER:
        name="toLower";
        result.toLower(locale);
        break;
    case TEST_UPPER:
        name="toUpper";
        result.toUpper(locale);
        break;
#if !UCONFIG_NO_BREAK_ITERATION
    case TEST_TITLE:
        name="toTitle";
        result.toTitle((BreakIterator *)iter, locale, options);
        break;
#endif
    case TEST_FOLD:
        name="foldCase";
        result.foldCase(options);
        break;
    default:
        name="";
        break; // won't happen
    }
    if(result!=output) {
        dataerrln("error: UnicodeString.%s() got a wrong result for a test case from casing.res", name);
    }
#if !UCONFIG_NO_BREAK_ITERATION
    if(whichCase==TEST_TITLE && options==0) {
        result=input;
        result.toTitle((BreakIterator *)iter, locale);
        if(result!=output) {
            dataerrln("error: UnicodeString.toTitle(options=0) got a wrong result for a test case from casing.res");
        }
    }
#endif

    // UTF-8
    char utf8In[100], utf8Out[100];
    int32_t utf8InLength, utf8OutLength, resultLength;
    UChar *buffer;

    IcuTestErrorCode errorCode(*this, "TestCasingImpl");
    LocalUCaseMapPointer csm(ucasemap_open(localeID, options, errorCode));
#if !UCONFIG_NO_BREAK_ITERATION
    if(iter!=NULL) {
        // Clone the break iterator so that the UCaseMap can safely adopt it.
        UBreakIterator *clone=ubrk_safeClone((UBreakIterator *)iter, NULL, NULL, errorCode);
        ucasemap_setBreakIterator(csm.getAlias(), clone, errorCode);
    }
#endif

    u_strToUTF8(utf8In, (int32_t)sizeof(utf8In), &utf8InLength, input.getBuffer(), input.length(), errorCode);
    switch(whichCase) {
    case TEST_LOWER:
        name="ucasemap_utf8ToLower";
        utf8OutLength=ucasemap_utf8ToLower(csm.getAlias(),
                    utf8Out, (int32_t)sizeof(utf8Out),
                    utf8In, utf8InLength, errorCode);
        break;
    case TEST_UPPER:
        name="ucasemap_utf8ToUpper";
        utf8OutLength=ucasemap_utf8ToUpper(csm.getAlias(),
                    utf8Out, (int32_t)sizeof(utf8Out),
                    utf8In, utf8InLength, errorCode);
        break;
#if !UCONFIG_NO_BREAK_ITERATION
    case TEST_TITLE:
        name="ucasemap_utf8ToTitle";
        utf8OutLength=ucasemap_utf8ToTitle(csm.getAlias(),
                    utf8Out, (int32_t)sizeof(utf8Out),
                    utf8In, utf8InLength, errorCode);
        break;
#endif
    case TEST_FOLD:
        name="ucasemap_utf8FoldCase";
        utf8OutLength=ucasemap_utf8FoldCase(csm.getAlias(),
                    utf8Out, (int32_t)sizeof(utf8Out),
                    utf8In, utf8InLength, errorCode);
        break;
    default:
        name="";
        utf8OutLength=0;
        break; // won't happen
    }
    buffer=result.getBuffer(utf8OutLength);
    u_strFromUTF8(buffer, result.getCapacity(), &resultLength, utf8Out, utf8OutLength, errorCode);
    result.releaseBuffer(errorCode.isSuccess() ? resultLength : 0);

    if(errorCode.isFailure()) {
        errcheckln(errorCode, "error: %s() got an error for a test case from casing.res - %s", name, u_errorName(errorCode));
        errorCode.reset();
    } else if(result!=output) {
        errln("error: %s() got a wrong result for a test case from casing.res", name);
        errln("expected \"" + output + "\" got \"" + result + "\"" );
    }
}
Exemplo n.º 6
0
// This method sets the requested language, based on wxLanguage id and an optional 'confirmation'
// canonical code.  If the canonical code is provided, it is used to confirm that the ID matches
// the intended language/dialect.  If the ID and canonical do not match, this method will use
// wx's FindLAnguageInfo to provide a "best guess" canonical match (usually relying on the user's
// operating system default).
//
// Rationale: wxWidgets language IDs are just simple enums, and not especially unique.  Future
// versions of PCSX2 may have language ID changes if built against new/different versions of wx.
// To prevent PCSX2 from selecting a completely wrong language when upgraded, we double-check
// the wxLanguage code against the canonical name.  We can't simply use canonical names either
// because those are not unique (dialects of chinese, for example), and wx returns the generic
// form over a specific dialect, when given a choice.  Thus a two-tier check is required.
//
//  wxLanguage for specific dialect, and canonical as a fallback/safeguard in case the wxLanguage
//  id appears to be out of date.
//
//
bool i18n_SetLanguage( wxLanguage wxLangId, const wxString& langCode )
{
	const wxLanguageInfo* info = wxLocale::GetLanguageInfo(wxLangId);

	// Check if you can load a similar language in case the current one is not yet provided
	if (info) {
		wxLanguage LangId_fallback = i18n_FallbackToAnotherLang((wxLanguage)info->Language);
		if (LangId_fallback != (wxLanguage)info->Language)
			info = wxLocale::GetLanguageInfo(LangId_fallback);
	}

	// note: language canonical name mismatch probably means wxWidgets version changed since 
	// the user's ini file was provided.  Missing/invalid ID probably means the same thing.
	// If either is true, and the caller provided a canonical name, then let wx do a best
	// match based on the canonical name.

	if (!info || (!langCode.IsEmpty() && (langCode.CmpNoCase(info->CanonicalName) != 0)))
	{
		if (!info)
			Console.Warning( "Invalid language identifier (wxID=%d)", wxLangId );

		if (!langCode.IsEmpty() && (langCode.CmpNoCase(L"default")!=0))
		{
			info = wxLocale::FindLanguageInfo(langCode);
			if (!info)
				Console.Warning( "Unrecognized language canonical name '%ls'", WX_STR(langCode) );
		}
	}

	if (!info) return false;
	if (wxGetLocale() && (info->Language == wxGetLocale()->GetLanguage())) return true;
	
	ScopedPtr<wxLocale> locale( new wxLocale(info->Language) );

	if( !locale->IsOk() )
	{
		Console.Warning( L"SetLanguage: '%s' [%s] is not supported by the operating system",
			WX_STR(i18n_GetBetterLanguageName(info)), WX_STR(locale->GetCanonicalName())
		);
		return false;
	}

	wxLangId = (wxLanguage)locale->GetLanguage();
	
	if (wxLangId == wxLANGUAGE_UNKNOWN)
	{
		Console.WriteLn("System-default language is unknown?  Defaulting back to English/US.");
		wxLangId = wxLANGUAGE_ENGLISH_US;
	}

	// English/US is built in, so no need to load MO/PO files.
	if( pxIsEnglish(wxLangId) )
	{
		locale.DetachPtr();
		return true;
	}
	
	Console.WriteLn( L"Loading language translation databases for '%s' [%s]",
		WX_STR(i18n_GetBetterLanguageName(info)), WX_STR(locale->GetCanonicalName())
	);

	static const wxChar* dictFiles[] =
	{
		L"pcsx2_Main",
		L"pcsx2_Iconized"
	};
	
	bool foundone = false;
	for (uint i=0; i<ArraySize(dictFiles); ++i)
	{
		if (!dictFiles[i]) continue;

		if (!locale->AddCatalog(dictFiles[i]))
			Console.Indent().WriteLn(Color_StrongYellow, "%ls not found -- translation dictionary may be incomplete.", dictFiles[i]);
		else
			foundone = true;
	}

	if (!foundone)	
	{
		Console.Warning("SetLanguage: Requested translation is not implemented yet.");
		return false;
	}

	locale.DetachPtr();
	return true;
}
Exemplo n.º 7
0
void DDateTable::mousePressEvent(QMouseEvent *e)
{
    if (e->type() != QEvent::MouseButtonPress)
    {
        // the KDatePicker only reacts on mouse press events:
        return;
    }

    if (!isEnabled())
    {
        QApplication::beep();
        return;
    }

    int row, col, pos;

    QPoint mouseCoord = e->pos();
    row = mouseCoord.y() * d->numWeekRows / height();

    if (layoutDirection() == Qt::RightToLeft)
    {
        col = d->numDayColumns - (mouseCoord.x() * d->numDayColumns / width()) - 1;
    }
    else
    {
        col = mouseCoord.x() * d->numDayColumns / width();
    }

    if (row < 1 || col < 0)
    {  // the user clicked on the frame of the table
        return;
    }

    // Rows and columns are zero indexed.  The (row - 1) below is to avoid counting
    // the row with the days of the week in the calculation.

    // new position and date
    pos               = (d->numDayColumns * (row - 1)) + col;
    QDate clickedDate = dateFromPos(pos);

    // set the new date. If it is in the previous or next month, the month will
    // automatically be changed, no need to do that manually...
    // validity checking done inside setDate
    setDate(clickedDate);

    // This could be optimized to only call update over the regions
    // of old and new cell, but 99% of times there is also a call to
    // setDate that already calls update() so no need to optimize that
    // much here
    update();

    emit tableClicked();

    if (e->button() == Qt::RightButton && d->popupMenuEnabled)
    {
        QMenu* const menu = new QMenu();
        menu->addSection(locale().toString(d->date));
        emit aboutToShowContextMenu(menu, clickedDate);
        menu->popup(e->globalPos());
    }
}
Exemplo n.º 8
0
String SubmitInputType::defaultValue() const
{
    return locale().queryString(blink::WebLocalizedString::SubmitButtonDefaultLabel);
}
Exemplo n.º 9
0
void LLFloaterTools::refresh()
{
	const S32 INFO_WIDTH = getRect().getWidth();
	const S32 INFO_HEIGHT = 384;
	LLRect object_info_rect(0, 0, INFO_WIDTH, -INFO_HEIGHT);
	BOOL all_volume = LLSelectMgr::getInstance()->selectionAllPCode( LL_PCODE_VOLUME );

	S32 idx_features = mTab->getPanelIndexByTitle(PANEL_NAMES[PANEL_FEATURES]);
	S32 idx_face = mTab->getPanelIndexByTitle(PANEL_NAMES[PANEL_FACE]);
	S32 idx_contents = mTab->getPanelIndexByTitle(PANEL_NAMES[PANEL_CONTENTS]);

	S32 selected_index = mTab->getCurrentPanelIndex();

	if (!all_volume && (selected_index == idx_features || selected_index == idx_face ||
		selected_index == idx_contents))
	{
		mTab->selectFirstTab();
	}

	mTab->enableTabButton(idx_features, all_volume);
	mTab->enableTabButton(idx_face, all_volume);
	mTab->enableTabButton(idx_contents, all_volume);

	// Refresh object and prim count labels
	LLLocale locale(LLLocale::USER_LOCALE);
	// Added in Link Num value -HgB
	S32 object_count = LLSelectMgr::getInstance()->getSelection()->getRootObjectCount();
	S32 prim_count = LLSelectMgr::getInstance()->getEditSelection()->getObjectCount();
	std::string value_string;
	std::string desc_string;
	if ((gSavedSettings.getBOOL("EditLinkedParts"))&&(prim_count == 1)) //Selecting a single prim in "Edit Linked" mode, show link number
	{
		desc_string = "Link number:";

		LLViewerObject* selected = LLSelectMgr::getInstance()->getSelection()->getFirstObject();
		if (selected && selected->getRootEdit())
		{
			LLViewerObject::child_list_t children = selected->getRootEdit()->getChildren();
			if (children.empty())
			{
				value_string = "0"; // An unlinked prim is "link 0".
			}
			else 
			{
				children.push_front(selected->getRootEdit()); // need root in the list too
				S32 index = 0;
				for (LLViewerObject::child_list_t::iterator iter = children.begin(); iter != children.end(); ++iter)
				{
					index++;
					if ((*iter)->isSelected())
					{
						LLResMgr::getInstance()->getIntegerString(value_string, index);
						break;
					}
				}
			}
		}
	}
	else
	{
		desc_string = "Selected objects:";
		LLResMgr::getInstance()->getIntegerString(value_string, object_count);
	}
	childSetTextArg("link_num_obj_count",  "[DESC]", desc_string);	
	childSetTextArg("link_num_obj_count",  "[NUM]", value_string);
	
	std::string prim_count_string;
	LLResMgr::getInstance()->getIntegerString(prim_count_string, LLSelectMgr::getInstance()->getSelection()->getObjectCount());
	childSetTextArg("prim_count", "[COUNT]", prim_count_string);

	// Refresh child tabs
	mPanelPermissions->refresh();
	mPanelObject->refresh();
	mPanelVolume->refresh();
	mPanelFace->refresh();
	mPanelContents->refresh();
	mPanelLandInfo->refresh();
}
Exemplo n.º 10
0
OptionsDialog::OptionsDialog(QWidget *parent) :
    QWidget(parent, DIALOGWINDOWHINTS),
    ui(new Ui::OptionsDialog),
    model(0),
    mapper(0),
    fRestartWarningDisplayed_Proxy(false),
    fRestartWarningDisplayed_Tor(false),
    fRestartWarningDisplayed_Lang(false),
    fRestartWarningDisplayed_URL(false),
    fProxyIpValid(true),
    fTorIpValid(true)
{
    ui->setupUi(this);

    /* Network elements init */
    ui->proxyIp->setEnabled(false);
    ui->proxyPort->setEnabled(false);
    ui->proxyPort->setValidator(new QIntValidator(1, 65535, this));

    ui->torIp->setEnabled(false);
    ui->torPort->setEnabled(false);
    ui->torPort->setValidator(new QIntValidator(1, 65535, this));
    ui->TorOnly->setEnabled(false);
    ui->torName->setEnabled(false);

    ui->socksVersion->setEnabled(false);
    ui->socksVersion->addItem("5", 5);
    ui->socksVersion->addItem("4", 4);
    ui->socksVersion->setCurrentIndex(0);

    connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));
    connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));
    connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool)));
    connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy()));

    connect(ui->connectTor, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Tor()));
    connect(ui->connectTor, SIGNAL(toggled(bool)), ui->torIp, SLOT(setEnabled(bool)));
    connect(ui->connectTor, SIGNAL(toggled(bool)), ui->torPort, SLOT(setEnabled(bool)));
    connect(ui->connectTor, SIGNAL(toggled(bool)), ui->TorOnly, SLOT(setEnabled(bool)));
    connect(ui->connectTor, SIGNAL(toggled(bool)), ui->torName, SLOT(setEnabled(bool)));
    connect(ui->TorOnly, SIGNAL(toggled(bool)), ui->connectSocks, SLOT(setDisabled(bool)));

    ui->proxyIp->installEventFilter(this);
    ui->torIp->installEventFilter(this);

    /* Window elements init */
#ifdef Q_OS_MAC
    ui->tabWindow->setVisible(false);
#endif

    /* Display elements init */
    QDir translations(":translations");
    ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
    foreach(const QString &langStr, translations.entryList())
    {
        QLocale locale(langStr);

        /** check if the locale name consists of 2 parts (language_country) */
        if(langStr.contains("_"))
        {
#if QT_VERSION >= 0x040800
            /** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */
            ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
            /** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */
            ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
        }
        else
        {
#if QT_VERSION >= 0x040800
            /** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */
            ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
            /** display language strings as "language (locale name)", e.g. "German (de)" */
            ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
        }
    }

#if QT_VERSION >= 0x040700
    ui->thirdPartyTxUrls->setPlaceholderText("https://example.com/tx/%s");
#endif


    ui->unit->setModel(new BitcoinUnits(this));

    /* Widget-to-option mapper */
    mapper = new MonitoredDataMapper(this);
    mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
    mapper->setOrientation(Qt::Vertical);

    /* enable apply button when data modified */
    connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton()));
    /* disable apply button when new data loaded */
    connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton()));
    /* setup/change UI elements when proxy IP is invalid/valid */
    connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool)));
    /* setup/change UI elements when Tor IP is invalid/valid */
    connect(this, SIGNAL(torIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleTorIpValid(QValidatedLineEdit *, bool)));
}
void GroupedIconView::paintEvent(QPaintEvent* e) {
  // This code was adapted from QListView::paintEvent(), changed to use the
  // visualRect() of items, and to draw headers.

  QStyleOptionViewItemV4 option(viewOptions());
  if (isWrapping())
    option.features = QStyleOptionViewItemV2::WrapText;
  option.locale = locale();
  option.locale.setNumberOptions(QLocale::OmitGroupSeparator);
  option.widget = this;

  QPainter painter(viewport());

  const QRect viewport_rect(e->rect().translated(horizontalOffset(), verticalOffset()));
  QVector<QModelIndex> toBeRendered = IntersectingItems(viewport_rect);

  const QModelIndex current = currentIndex();
  const QAbstractItemModel *itemModel = model();
  const QItemSelectionModel *selections = selectionModel();
  const bool focus = (hasFocus() || viewport()->hasFocus()) && current.isValid();
  const QStyle::State state = option.state;
  const QAbstractItemView::State viewState = this->state();
  const bool enabled = (state & QStyle::State_Enabled) != 0;

  int maxSize = (flow() == TopToBottom)
      ? viewport()->size().width() - 2 * spacing()
      : viewport()->size().height() - 2 * spacing();

  QVector<QModelIndex>::const_iterator end = toBeRendered.constEnd();
  for (QVector<QModelIndex>::const_iterator it = toBeRendered.constBegin(); it != end; ++it) {
    if (!it->isValid()) {
      continue;
    }

    option.rect = visualRect(*it);

    if (flow() == TopToBottom)
      option.rect.setWidth(qMin(maxSize, option.rect.width()));
    else
      option.rect.setHeight(qMin(maxSize, option.rect.height()));

    option.state = state;
    if (selections && selections->isSelected(*it))
      option.state |= QStyle::State_Selected;
    if (enabled) {
      QPalette::ColorGroup cg;
      if ((itemModel->flags(*it) & Qt::ItemIsEnabled) == 0) {
        option.state &= ~QStyle::State_Enabled;
        cg = QPalette::Disabled;
      } else {
        cg = QPalette::Normal;
      }
      option.palette.setCurrentColorGroup(cg);
    }
    if (focus && current == *it) {
      option.state |= QStyle::State_HasFocus;
      if (viewState == EditingState)
        option.state |= QStyle::State_Editing;
    }

    itemDelegate()->paint(&painter, option, *it);
  }

  // Draw headers
  foreach (const Header& header, headers_) {
    const QRect header_rect = QRect(
          header_indent_, header.y,
          viewport()->width() - header_indent_ * 2, header_height());

    // Is this header contained in the area we're drawing?
    if (!header_rect.intersects(viewport_rect)) {
      continue;
    }

    // Draw the header
    DrawHeader(model()->index(header.first_row, 0),
               header_rect.translated(-horizontalOffset(), -verticalOffset()),
               &painter);
  }
}
Exemplo n.º 12
0
void PlanTJScheduler::run()
{
    if ( m_haltScheduling ) {
        deleteLater();
        return;
    }
    if ( m_stopScheduling ) {
        return;
    }
    setMaxProgress( PROGRESS_MAX_VALUE );
    { // mutex -->
        m_projectMutex.lock();
        m_managerMutex.lock();

        m_project = new Project();
        loadProject( m_project, m_pdoc );
        m_project->setName( "Schedule: " + m_project->name() ); //Debug
        m_project->stopcalculation = false;
        m_manager = m_project->scheduleManager( m_mainmanagerId );
        Q_CHECK_PTR( m_manager );
        Q_ASSERT( m_manager->expected() );
        Q_ASSERT( m_manager != m_mainmanager );
        Q_ASSERT( m_manager->scheduleId() == m_mainmanager->scheduleId() );
        Q_ASSERT( m_manager->expected() != m_mainmanager->expected() );
        m_manager->setName( "Schedule: " + m_manager->name() ); //Debug
        m_schedule = m_manager->expected();

        bool x = connect(m_manager, SIGNAL(sigLogAdded(Schedule::Log)), this, SLOT(slotAddLog(Schedule::Log)));
        Q_ASSERT( x );

        m_project->initiateCalculation( *m_schedule );
        m_project->initiateCalculationLists( *m_schedule );

        m_usePert = m_manager->usePert();
        m_recalculate = m_manager->recalculate();
        if ( m_recalculate ) {
            m_backward = false;
        } else {
            m_backward = m_manager->schedulingDirection();
        }
        m_project->setCurrentSchedule( m_manager->expected()->id() );

        m_schedule->setPhaseName( 0, i18nc( "@info/plain" , "Init" ) );
        if ( ! m_backward && locale() ) {
            logDebug( m_project, 0, QString( "Schedule project using TJ Scheduler, starting at %1, granularity %2" ).arg( QDateTime::currentDateTime().toString() ).arg( locale()->formatDuration( m_granularity ) ), 0 );
            if ( m_recalculate ) {
                logInfo( m_project, 0, i18nc( "@info/plain" , "Re-calculate project from start time: %1", locale()->formatDateTime( m_project->constraintStartTime() ) ), 0 );
            } else {
                logInfo( m_project, 0, i18nc( "@info/plain" , "Schedule project from start time: %1", locale()->formatDateTime( m_project->constraintStartTime() ) ), 0 );
            }
            logInfo( m_project, 0, i18nc( "@info/plain" , "Project target finish time: %1", locale()->formatDateTime( m_project->constraintEndTime() ) ), 0 );
        }
        if ( m_backward && locale() ) {
            logDebug( m_project, 0, QString( "Schedule project backward using TJ Scheduler, starting at %1, granularity %2" ).arg( locale()->formatDateTime( QDateTime::currentDateTime() ) ).arg( locale()->formatDuration( m_granularity ) ), 0 );
            logInfo( m_project, 0, i18nc( "@info/plain" , "Schedule project from end time: %1", locale()->formatDateTime( m_project->constraintEndTime() ) ), 0 );
        }

        m_managerMutex.unlock();
        m_projectMutex.unlock();
    } // <--- mutex
    setProgress( 2 );
    if ( ! kplatoToTJ() ) {
        result = 1;
        setProgress( PROGRESS_MAX_VALUE );
        return;
    }
    setMaxProgress( PROGRESS_MAX_VALUE );
    connect(m_tjProject, SIGNAL(updateProgressBar(int,int)), this, SLOT(setProgress(int)));

    m_schedule->setPhaseName( 1, i18nc( "@info/plain" , "Schedule" ) );
    logInfo( m_project, 0, "Start scheduling", 1 );
    bool r = solve();
    if ( ! r ) {
        kDebug(planDbg())<<"Scheduling failed";
        result = 2;
        logError( m_project, 0, i18nc( "@info/plain" , "Failed to schedule project" ) );
        setProgress( PROGRESS_MAX_VALUE );
        return;
    }
    if ( m_haltScheduling ) {
        kDebug(planDbg())<<"Scheduling halted";
        logInfo( m_project, 0, "Scheduling halted" );
        deleteLater();
        return;
    }
    m_schedule->setPhaseName( 2, i18nc( "@info/plain" , "Update" ) );
    logInfo( m_project, 0, "Scheduling finished, update project", 2 );
    if ( ! kplatoFromTJ() ) {
        logError( m_project, 0, "Project update failed" );
    }
    setProgress( PROGRESS_MAX_VALUE );
    m_schedule->setPhaseName( 3, i18nc( "@info/plain" , "Finish" ) );
}
Exemplo n.º 13
0
bool sqr::CSceneAmpCoder::DeCode_Ver_H( const CDataChunk& inData,OBJ_HANDLE handle )
{
	CSceneManagerClient* pScene = (CSceneManagerClient*)handle;
	CPkgFile& File = *((CPkgFile*)inData.GetBuffer());

	DeCoder_Com_B_D(File,handle);

	//////////////////////////////////////////////////////////////////////////
	//read specular parameter 无效数据
	uint32 uColor = 0; 
	float  fPower = 0.0f;

	File.Read(&uColor, sizeof(uColor));
	File.Read(&uColor, sizeof(uColor));
	File.Read(&fPower, sizeof(fPower));
	File.Read(&fPower, sizeof(fPower));
	//////////////////////////////////////////////////////////////////////////

	locale loc = locale::global(locale(""));
	uint32 dwNameLen = 0;
	char szBuf[256];
	//////////////////////////////////////////////////////////////////////////
	//region ambient fx name
	SVector<SString>  ambientFxNameList;
	size_t size = 0;
	File.read(&size, sizeof(size_t));
	for ( size_t i = 0; i < size; ++i )
	{
		SString strEffectName = "";

		// 		File.Read(&dwNameLen,sizeof(dwNameLen));
		// 		File.Read(szBuf, sizeof(char)*dwNameLen);
		// 		szBuf[dwNameLen] = 0;
		// 		strEffectFileName = szBuf;

		File.Read(&dwNameLen,sizeof(dwNameLen));
		File.Read(szBuf, sizeof(char)*dwNameLen);
		szBuf[dwNameLen] = 0;
		strEffectName = szBuf;

		//		strEffectFileName = "fx\\setting\\mapfx_ambient_yb\\" + strEffectName + ".efx";

		ambientFxNameList.push_back(strEffectName);
	}
	//////////////////////////////////////////////////////////////////////////

	size = 0;
	File.read(&size, sizeof(size_t));
	if( size == 0 )
		return true;
	else
	{
		for( size_t i = 0; i < size; ++i )
		{
			RegionsInfo *pRgnInfo = new RegionsInfo;

			if( !pRgnInfo )
				return false;
			///scene
			File.read(&pRgnInfo->lightParam.globalAmbient.R,  sizeof(uint8));
			File.read(&pRgnInfo->lightParam.globalAmbient.G,  sizeof(uint8));
			File.read(&pRgnInfo->lightParam.globalAmbient.B,  sizeof(uint8));

			File.read(&pRgnInfo->lightParam.globalDiffuse.R,  sizeof(uint8));
			File.read(&pRgnInfo->lightParam.globalDiffuse.G,  sizeof(uint8));
			File.read(&pRgnInfo->lightParam.globalDiffuse.B,  sizeof(uint8));

			File.read(&pRgnInfo->lightParam.globalSpecular.R, sizeof(uint8));
			File.read(&pRgnInfo->lightParam.globalSpecular.G, sizeof(uint8));
			File.read(&pRgnInfo->lightParam.globalSpecular.B, sizeof(uint8));

#ifndef AMBIENT_SHADOW_COLOR
			File.read(&pRgnInfo->lightParam.globalShadow.R,   sizeof(uint8));
			File.read(&pRgnInfo->lightParam.globalShadow.G,   sizeof(uint8));
			File.read(&pRgnInfo->lightParam.globalShadow.B,   sizeof(uint8));
#else
			uint8 dummy;
			File.read(&dummy,   sizeof(uint8));
			File.read(&dummy,   sizeof(uint8));
			File.read(&dummy,   sizeof(uint8));
#endif

			File.read(&pRgnInfo->lightParam.fogColor.R,		  sizeof(uint8));
			File.read(&pRgnInfo->lightParam.fogColor.G,		  sizeof(uint8));
			File.read(&pRgnInfo->lightParam.fogColor.B,		  sizeof(uint8));

			///player
			File.read(&pRgnInfo->lightParam.playerAmbient.R,  sizeof(uint8));
			File.read(&pRgnInfo->lightParam.playerAmbient.G,  sizeof(uint8));
			File.read(&pRgnInfo->lightParam.playerAmbient.B,  sizeof(uint8));

			File.read(&pRgnInfo->lightParam.playerDiffuse.R,  sizeof(uint8));
			File.read(&pRgnInfo->lightParam.playerDiffuse.G,  sizeof(uint8));
			File.read(&pRgnInfo->lightParam.playerDiffuse.B,  sizeof(uint8));

			File.read(&pRgnInfo->lightParam.playerSpecular.R, sizeof(uint8));
			File.read(&pRgnInfo->lightParam.playerSpecular.G, sizeof(uint8));
			File.read(&pRgnInfo->lightParam.playerSpecular.B, sizeof(uint8));

			File.read(&pRgnInfo->uFogMode,					  sizeof(pRgnInfo->uFogMode));
			File.read(&pRgnInfo->lightParam.fogStart,		  sizeof(float));
			File.read(&pRgnInfo->lightParam.fogEnd,			  sizeof(float));
			File.read(&pRgnInfo->lightParam.fogDensity,       sizeof(float));

			///music name
			File.Read(&dwNameLen,sizeof(dwNameLen));
			File.Read(szBuf, sizeof(char)*dwNameLen);
			pRgnInfo->strMusicName = szBuf;

			///ambient effect
			size_t ambientFxSize = 0;
			File.read(&ambientFxSize, sizeof(ambientFxSize));
			for ( size_t m = 0; m < ambientFxSize; ++m )
			{
				int nIndex = 0;
				File.read(&nIndex, sizeof(nIndex));

				DWORD dwPlayMin = 0;
				File.read(&dwPlayMin, sizeof(dwPlayMin));

				DWORD dwPlayMax = 0;
				File.read(&dwPlayMax, sizeof(dwPlayMax));

				DWORD dwIntervalMin = 0;
				File.read(&dwIntervalMin, sizeof(dwIntervalMin));

				DWORD dwIntervalMax = 0;
				File.read(&dwIntervalMax, sizeof(dwIntervalMax));

				SString strEffectName	 = ambientFxNameList[nIndex];

				//SVector<CRgnAmbientFxInfo*> rgnAmbientFxList;
				CRgnAmbientFxInfo *pTemp = new CRgnAmbientFxInfo;
				pTemp->szFxName		= strEffectName;
				pTemp->nPlayMax		= dwPlayMax;
				pTemp->nPlayMin		= dwPlayMin;
				pTemp->nIntervalMax = dwIntervalMax;
				pTemp->nIntervalMin = dwIntervalMin;

				pRgnInfo->rgnAmbientFxList.push_back(pTemp);
			}

			pScene->m_RgnsList.push_back(pRgnInfo);
		}

		// ----------------------------------------------------------------------------
		// 读取摄像机轨迹动画信息

		uint32 uAnimCount = 0;
		File.read( &uAnimCount, sizeof(uint32) );	
		pScene->m_vecCamPath.resize(uAnimCount, NULL);

		for ( uint i=0; i<uAnimCount; ++i )
		{
			int		pc		= 0;
			File.read( &pc, sizeof(int) );
			if ( pc != NULL )
			{
				CCameraPath	*pNewPath	= new CCameraPath;
				pScene->m_vecCamPath[i] = pNewPath; 

				uint32 uKeyCount = 0;
				File.read( &uKeyCount, sizeof(uint32) );	

				CVector3f	data;
				float		time;
				for ( uint32 i=0; i<uKeyCount; ++i )
				{
					// 读取 摄像机位置帧
					File.read( &data, sizeof(CVector3f) );
					File.read( &time, sizeof(float) );
					pNewPath->AddPositionKey( data, time );

					// 读取 摄像机观察点帧
					File.read( &data, sizeof(CVector3f) );
					File.read( &time, sizeof(float) );
					pNewPath->AddTargetkey( data, time );

					// 读取 摄像机视角帧
					File.read( &data, sizeof(CVector3f) );
					File.read( &time, sizeof(float) );
					pNewPath->AddFovKey( data, time );
				}
			}
		}

		//////////////////////////////////////////////////////////////////////////
		// IsTileVisiable
		CMetaGridMgr& GridMgr = *pScene->m_pGridMgr;
		UINT Size = pScene->m_uWidth*pScene->m_uHeight;
		bool tileVisible = true;
		URegionID ID;
		for(size_t i = 0; i<Size; ++i)
		{
			ID.X = i % pScene->m_uWidth;
			ID.Z = i / pScene->m_uWidth;
			File.read( &tileVisible, sizeof(tileVisible) );

			GridMgr.SetRenderTileVisibleMark(ID, tileVisible);
		}

		//////////////////////////////////////////////////////////////////////////
	}

	locale::global(loc);//恢复全局locale	

	return true;
}
Exemplo n.º 14
0
bool sqr::CSceneAmpCoder::DeCode_Ver_F( const CDataChunk& inData,OBJ_HANDLE handle )
{
	CSceneManagerClient* pScene = (CSceneManagerClient*)handle;
	CPkgFile& File = *((CPkgFile*)inData.GetBuffer());

	DeCoder_Com_B_D(File,handle);

	//////////////////////////////////////////////////////////////////////////
	//read specular parameter 无效数据
	uint32 uColor = 0; 
	float  fPower = 0.0f;

	File.Read(&uColor, sizeof(uColor));
	File.Read(&uColor, sizeof(uColor));
	File.Read(&fPower, sizeof(fPower));
	File.Read(&fPower, sizeof(fPower));
	//////////////////////////////////////////////////////////////////////////

	size_t size = 0;
	File.read(&size, sizeof(size_t));
	if( size == 0 )
		return true;
	else
	{
		locale loc = locale::global(locale(""));
		uint32 dwNameLen = 0;
		char szBuf[256];
		for( size_t i = 0; i < size; ++i )
		{
			RegionsInfo *pRgnInfo = new RegionsInfo;

			if( !pRgnInfo )
				return false;
			///scene
			File.read(&pRgnInfo->lightParam.globalAmbient.R,  sizeof(uint8));
			File.read(&pRgnInfo->lightParam.globalAmbient.G,  sizeof(uint8));
			File.read(&pRgnInfo->lightParam.globalAmbient.B,  sizeof(uint8));

			File.read(&pRgnInfo->lightParam.globalDiffuse.R,  sizeof(uint8));
			File.read(&pRgnInfo->lightParam.globalDiffuse.G,  sizeof(uint8));
			File.read(&pRgnInfo->lightParam.globalDiffuse.B,  sizeof(uint8));

			File.read(&pRgnInfo->lightParam.globalSpecular.R, sizeof(uint8));
			File.read(&pRgnInfo->lightParam.globalSpecular.G, sizeof(uint8));
			File.read(&pRgnInfo->lightParam.globalSpecular.B, sizeof(uint8));

#ifndef AMBIENT_SHADOW_COLOR
			File.read(&pRgnInfo->lightParam.globalShadow.R,   sizeof(uint8));
			File.read(&pRgnInfo->lightParam.globalShadow.G,   sizeof(uint8));
			File.read(&pRgnInfo->lightParam.globalShadow.B,   sizeof(uint8));
#else
			uint8 dummy;
			File.read(&dummy,   sizeof(uint8));
			File.read(&dummy,   sizeof(uint8));
			File.read(&dummy,   sizeof(uint8));
#endif

			File.read(&pRgnInfo->lightParam.fogColor.R,		  sizeof(uint8));
			File.read(&pRgnInfo->lightParam.fogColor.G,		  sizeof(uint8));
			File.read(&pRgnInfo->lightParam.fogColor.B,		  sizeof(uint8));

			///player
			File.read(&pRgnInfo->lightParam.playerAmbient.R,  sizeof(uint8));
			File.read(&pRgnInfo->lightParam.playerAmbient.G,  sizeof(uint8));
			File.read(&pRgnInfo->lightParam.playerAmbient.B,  sizeof(uint8));

			File.read(&pRgnInfo->lightParam.playerDiffuse.R,  sizeof(uint8));
			File.read(&pRgnInfo->lightParam.playerDiffuse.G,  sizeof(uint8));
			File.read(&pRgnInfo->lightParam.playerDiffuse.B,  sizeof(uint8));

			File.read(&pRgnInfo->lightParam.playerSpecular.R, sizeof(uint8));
			File.read(&pRgnInfo->lightParam.playerSpecular.G, sizeof(uint8));
			File.read(&pRgnInfo->lightParam.playerSpecular.B, sizeof(uint8));

			File.read(&pRgnInfo->uFogMode,					  sizeof(pRgnInfo->uFogMode));
			File.read(&pRgnInfo->lightParam.fogStart,		  sizeof(float));
			File.read(&pRgnInfo->lightParam.fogEnd,			  sizeof(float));
			File.read(&pRgnInfo->lightParam.fogDensity,       sizeof(float));

			///music name
			File.Read(&dwNameLen,sizeof(dwNameLen));
			File.Read(szBuf, sizeof(char)*dwNameLen);
			pRgnInfo->strMusicName = szBuf;

			pScene->m_RgnsList.push_back(pRgnInfo);
		}

		// ----------------------------------------------------------------------------
		// 读取摄像机轨迹动画信息

		uint32 uAnimCount = 0;
		File.read( &uAnimCount, sizeof(uint32) );	
		pScene->m_vecCamPath.resize(uAnimCount, NULL);

		for ( uint i=0; i<uAnimCount; ++i )
		{
			int		pc		= 0;
			File.read( &pc, sizeof(int) );
			if ( pc != NULL )
			{
				CCameraPath	*pNewPath	= new CCameraPath;
				pScene->m_vecCamPath[i] = pNewPath; 

				uint32 uKeyCount = 0;
				File.read( &uKeyCount, sizeof(uint32) );	

				CVector3f	data;
				float		time;
				for ( uint32 i=0; i<uKeyCount; ++i )
				{
					// 读取 摄像机位置帧
					File.read( &data, sizeof(CVector3f) );
					File.read( &time, sizeof(float) );
					pNewPath->AddPositionKey( data, time );

					// 读取 摄像机观察点帧
					File.read( &data, sizeof(CVector3f) );
					File.read( &time, sizeof(float) );
					pNewPath->AddTargetkey( data, time );

					// 读取 摄像机视角帧
					File.read( &data, sizeof(CVector3f) );
					File.read( &time, sizeof(float) );
					pNewPath->AddFovKey( data, time );
				}
			}
		}

		locale::global(loc);//恢复全局locale	
	}

	return true;
}
int main()
{
	wcin.imbue(locale("korean"));
	wcout.imbue(locale("korean"));

	typedef enum
	{
		MOVIE_MANAGER = 1,
		SCHEDULE_MANAGER,
		PRICE_MANAGER,
	} ManageApplicationFunction;

	if (FUNCTION_SUCCESS == DBHelper::connectDB())
	{
		for(;;)
		{
			system("cls");
			cout << 
				"극장 관리 시스템\n\n"

				"1. 영화 정보 관리\n"
				"2. 상영 일정 관리\n"
				"3. 가격 정보 관리\n"
				"0. 종료\n\n"

				"선택: ";

			int32_t function = 0;
			switch (inputPositiveInteger(function))
			{
			case FUNCTION_CANCEL:
				return 0;
			case FUNCTION_SUCCESS:
				switch (function)
				{
				case MOVIE_MANAGER:
				{
					MovieManager movieManger;
					continue;
				}
				case SCHEDULE_MANAGER:
				{
					ScheduleManager scheduleManager;
					continue;
				}
				case PRICE_MANAGER:
				{
					PriceManager priceManager;
					continue;
				}
				}
			case FUNCTION_ERROR:
				cout << "\n잘못된 입력입니다.\n";
				system("pause");
			}
		}
	}
	else 
	{
		cout << "데이터베이스 접근에 실패했습니다.\n";		
		system("pause");
	}

	DBHelper::closeDB();
	return 0;
}
Exemplo n.º 16
0
bool parseAricoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
    // return if URI is not valid or is no aricoin: URI
    if(!uri.isValid() || uri.scheme() != QString("aricoin"))
        return false;

    SendCoinsRecipient rv;
    QStringList addressParts = uri.path().split("/", QString::SkipEmptyParts, Qt::CaseSensitive);
    rv.address = addressParts.isEmpty()
      ? ""
      : addressParts.first();
    rv.amount = 0;

#if QT_VERSION < 0x050000
    QList<QPair<QString, QString> > items = uri.queryItems();
#else
    QUrlQuery uriQuery(uri);
    QList<QPair<QString, QString> > items = uriQuery.queryItems();
#endif
    for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
    {
        bool fShouldReturnFalse = false;
        if (i->first.startsWith("req-"))
        {
            i->first.remove(0, 4);
            fShouldReturnFalse = true;
        }

        if (i->first == "label")
        {
            rv.label = i->second;
            fShouldReturnFalse = false;
        }
        if (i->first == "message")
        {
            rv.message = i->second;
            fShouldReturnFalse = false;
        }
        else if (i->first == "amount")
        {
            if(!i->second.isEmpty())
            {
                // Parse amount in C locale with no number separators
                QLocale locale(QLocale::c());
                locale.setNumberOptions(QLocale::OmitGroupSeparator | QLocale::RejectGroupSeparator);
                if(!AricoinUnits::parse(AricoinUnits::ARI, i->second, &rv.amount, locale))
                {
                    return false;
                }
            }
            fShouldReturnFalse = false;
        }

        if (fShouldReturnFalse)
            return false;
    }
    if(out)
    {
        *out = rv;
    }
    return true;
}
Exemplo n.º 17
0
int OctreeServer::civetwebRequestHandler(struct mg_connection* connection) {
    const struct mg_request_info* ri = mg_get_request_info(connection);
    
    OctreeServer* theServer = GetInstance();

#ifdef FORCE_CRASH
    if (strcmp(ri->uri, "/force_crash") == 0 && strcmp(ri->request_method, "GET") == 0) {
        qDebug() << "About to force a crash!\n";
        int foo;
        int* forceCrash = &foo;
        mg_printf(connection, "%s", "HTTP/1.0 200 OK\r\n\r\n");
        mg_printf(connection, "%s", "forcing a crash....\r\n");
        delete[] forceCrash;
        mg_printf(connection, "%s", "did it crash....\r\n");
        return 1;
    }
#endif

    bool showStats = false;
    if (strcmp(ri->uri, "/") == 0 && strcmp(ri->request_method, "GET") == 0) {
        showStats = true;
    }

    if (strcmp(ri->uri, "/resetStats") == 0 && strcmp(ri->request_method, "GET") == 0) {
        theServer->_octreeInboundPacketProcessor->resetStats();
        showStats = true;
    }
    
    if (showStats) {
        uint64_t checkSum;
        // return a 200
        mg_printf(connection, "%s", "HTTP/1.0 200 OK\r\n");
        mg_printf(connection, "%s", "Content-Type: text/html\r\n\r\n");
        mg_printf(connection, "%s", "<html><doc>\r\n");
        mg_printf(connection, "%s", "<pre>\r\n");
        mg_printf(connection, "<b>Your %s Server is running... <a href='/'>[RELOAD]</a></b>\r\n", theServer->getMyServerName());

        tm* localtm = localtime(&theServer->_started);
        const int MAX_TIME_LENGTH = 128;
        char buffer[MAX_TIME_LENGTH];
        strftime(buffer, MAX_TIME_LENGTH, "%m/%d/%Y %X", localtm);
        mg_printf(connection, "Running since: %s", buffer);

        // Convert now to tm struct for UTC
        tm* gmtm = gmtime(&theServer->_started);
        if (gmtm != NULL) {
            strftime(buffer, MAX_TIME_LENGTH, "%m/%d/%Y %X", gmtm);
            mg_printf(connection, " [%s UTM] ", buffer);
        }
        mg_printf(connection, "%s", "\r\n");

        uint64_t now  = usecTimestampNow();
        const int USECS_PER_MSEC = 1000;
        uint64_t msecsElapsed = (now - theServer->_startedUSecs) / USECS_PER_MSEC;
        const int MSECS_PER_SEC = 1000;
        const int SECS_PER_MIN = 60;
        const int MIN_PER_HOUR = 60;
        const int MSECS_PER_MIN = MSECS_PER_SEC * SECS_PER_MIN;

        float seconds = (msecsElapsed % MSECS_PER_MIN)/(float)MSECS_PER_SEC;
        int minutes = (msecsElapsed/(MSECS_PER_MIN)) % MIN_PER_HOUR;
        int hours = (msecsElapsed/(MSECS_PER_MIN * MIN_PER_HOUR));

        mg_printf(connection, "%s", "Uptime: ");
        if (hours > 0) {
            mg_printf(connection, "%d hour%s ", hours, (hours > 1) ? "s" : "" );
        }
        if (minutes > 0) {
            mg_printf(connection, "%d minute%s ", minutes, (minutes > 1) ? "s" : "");
        }
        if (seconds > 0) {
            mg_printf(connection, "%.3f seconds ", seconds);
        }
        mg_printf(connection, "%s", "\r\n");
        mg_printf(connection, "%s", "\r\n");


        // display voxel file load time
        if (theServer->isInitialLoadComplete()) {
            time_t* loadCompleted = theServer->getLoadCompleted();
            if (loadCompleted) {
                tm* voxelsLoadedAtLocal = localtime(loadCompleted);
                const int MAX_TIME_LENGTH = 128;
                char buffer[MAX_TIME_LENGTH];
                strftime(buffer, MAX_TIME_LENGTH, "%m/%d/%Y %X", voxelsLoadedAtLocal);
                mg_printf(connection, "%s File Loaded At: %s", theServer->getMyServerName(), buffer);

                // Convert now to tm struct for UTC
                tm* voxelsLoadedAtUTM = gmtime(theServer->getLoadCompleted());
                if (gmtm != NULL) {
                    strftime(buffer, MAX_TIME_LENGTH, "%m/%d/%Y %X", voxelsLoadedAtUTM);
                    mg_printf(connection, " [%s UTM] ", buffer);
                }
            } else {
                mg_printf(connection, "%s File Persist Disabled...\r\n", theServer->getMyServerName());
            }
            mg_printf(connection, "%s", "\r\n");


            uint64_t msecsElapsed = theServer->getLoadElapsedTime() / USECS_PER_MSEC;;
            float seconds = (msecsElapsed % MSECS_PER_MIN)/(float)MSECS_PER_SEC;
            int minutes = (msecsElapsed/(MSECS_PER_MIN)) % MIN_PER_HOUR;
            int hours = (msecsElapsed/(MSECS_PER_MIN * MIN_PER_HOUR));

            mg_printf(connection, "%s File Load Took: ", theServer->getMyServerName());
            if (hours > 0) {
                mg_printf(connection, "%d hour%s ", hours, (hours > 1) ? "s" : "" );
            }
            if (minutes > 0) {
                mg_printf(connection, "%d minute%s ", minutes, (minutes > 1) ? "s" : "");
            }
            if (seconds >= 0) {
                mg_printf(connection, "%.3f seconds", seconds);
            }
            mg_printf(connection, "%s", "\r\n");

        } else {
            mg_printf(connection, "%s", "Voxels not yet loaded...\r\n");
        }

        mg_printf(connection, "%s", "\r\n");

        mg_printf(connection, "%s", "\r\n");

        mg_printf(connection, "%s", "<b>Configuration:</b>\r\n");

        for (int i = 1; i < theServer->_argc; i++) {
            mg_printf(connection, "%s ", theServer->_argv[i]);
        }
        mg_printf(connection, "%s", "\r\n"); // one to end the config line
        mg_printf(connection, "%s", "\r\n"); // two more for spacing
        mg_printf(connection, "%s", "\r\n");

        // display scene stats
        unsigned long nodeCount = OctreeElement::getNodeCount();
        unsigned long internalNodeCount = OctreeElement::getInternalNodeCount();
        unsigned long leafNodeCount = OctreeElement::getLeafNodeCount();
        
        QLocale locale(QLocale::English);
        const float AS_PERCENT = 100.0;
        mg_printf(connection, "%s", "<b>Current Nodes in scene:</b>\r\n");
        mg_printf(connection, "       Total Nodes: %s nodes\r\n",
                    locale.toString((uint)nodeCount).rightJustified(16, ' ').toLocal8Bit().constData());
        mg_printf(connection, "    Internal Nodes: %s nodes (%5.2f%%)\r\n",
            locale.toString((uint)internalNodeCount).rightJustified(16, ' ').toLocal8Bit().constData(),
            ((float)internalNodeCount / (float)nodeCount) * AS_PERCENT);
        mg_printf(connection, "        Leaf Nodes: %s nodes (%5.2f%%)\r\n", 
            locale.toString((uint)leafNodeCount).rightJustified(16, ' ').toLocal8Bit().constData(),
            ((float)leafNodeCount / (float)nodeCount) * AS_PERCENT);
        mg_printf(connection, "%s", "\r\n");
        mg_printf(connection, "%s", "\r\n");


        // display outbound packet stats
        mg_printf(connection, "<b>%s Outbound Packet Statistics...</b>\r\n", theServer->getMyServerName());
        uint64_t totalOutboundPackets = OctreeSendThread::_totalPackets;
        uint64_t totalOutboundBytes = OctreeSendThread::_totalBytes;
        uint64_t totalWastedBytes = OctreeSendThread::_totalWastedBytes;
        uint64_t totalBytesOfOctalCodes = OctreePacketData::getTotalBytesOfOctalCodes();
        uint64_t totalBytesOfBitMasks = OctreePacketData::getTotalBytesOfBitMasks();
        uint64_t totalBytesOfColor = OctreePacketData::getTotalBytesOfColor();

        const int COLUMN_WIDTH = 10;
        mg_printf(connection, "           Total Outbound Packets: %s packets\r\n",
            locale.toString((uint)totalOutboundPackets).rightJustified(COLUMN_WIDTH, ' ').toLocal8Bit().constData());
        mg_printf(connection, "             Total Outbound Bytes: %s bytes\r\n",
            locale.toString((uint)totalOutboundBytes).rightJustified(COLUMN_WIDTH, ' ').toLocal8Bit().constData());
        mg_printf(connection, "               Total Wasted Bytes: %s bytes\r\n",
            locale.toString((uint)totalWastedBytes).rightJustified(COLUMN_WIDTH, ' ').toLocal8Bit().constData());
        mg_printf(connection, "            Total OctalCode Bytes: %s bytes (%5.2f%%)\r\n",
            locale.toString((uint)totalBytesOfOctalCodes).rightJustified(COLUMN_WIDTH, ' ').toLocal8Bit().constData(),
            ((float)totalBytesOfOctalCodes / (float)totalOutboundBytes) * AS_PERCENT);
        mg_printf(connection, "             Total BitMasks Bytes: %s bytes (%5.2f%%)\r\n",
            locale.toString((uint)totalBytesOfBitMasks).rightJustified(COLUMN_WIDTH, ' ').toLocal8Bit().constData(),
            ((float)totalBytesOfBitMasks / (float)totalOutboundBytes) * AS_PERCENT);
        mg_printf(connection, "                Total Color Bytes: %s bytes (%5.2f%%)\r\n",
            locale.toString((uint)totalBytesOfColor).rightJustified(COLUMN_WIDTH, ' ').toLocal8Bit().constData(),
            ((float)totalBytesOfColor / (float)totalOutboundBytes) * AS_PERCENT);

        mg_printf(connection, "%s", "\r\n");
        mg_printf(connection, "%s", "\r\n");

        // display inbound packet stats
        mg_printf(connection, "<b>%s Edit Statistics... <a href='/resetStats'>[RESET]</a></b>\r\n", 
                        theServer->getMyServerName());
        uint64_t averageTransitTimePerPacket = theServer->_octreeInboundPacketProcessor->getAverageTransitTimePerPacket();
        uint64_t averageProcessTimePerPacket = theServer->_octreeInboundPacketProcessor->getAverageProcessTimePerPacket();
        uint64_t averageLockWaitTimePerPacket = theServer->_octreeInboundPacketProcessor->getAverageLockWaitTimePerPacket();
        uint64_t averageProcessTimePerElement = theServer->_octreeInboundPacketProcessor->getAverageProcessTimePerElement();
        uint64_t averageLockWaitTimePerElement = theServer->_octreeInboundPacketProcessor->getAverageLockWaitTimePerElement();
        uint64_t totalElementsProcessed = theServer->_octreeInboundPacketProcessor->getTotalElementsProcessed();
        uint64_t totalPacketsProcessed = theServer->_octreeInboundPacketProcessor->getTotalPacketsProcessed();

        float averageElementsPerPacket = totalPacketsProcessed == 0 ? 0 : totalElementsProcessed / totalPacketsProcessed;

        mg_printf(connection, "           Total Inbound Packets: %s packets\r\n",
            locale.toString((uint)totalPacketsProcessed).rightJustified(COLUMN_WIDTH, ' ').toLocal8Bit().constData());
        mg_printf(connection, "          Total Inbound Elements: %s elements\r\n",
            locale.toString((uint)totalElementsProcessed).rightJustified(COLUMN_WIDTH, ' ').toLocal8Bit().constData());
        mg_printf(connection, " Average Inbound Elements/Packet: %f elements/packet\r\n", averageElementsPerPacket);
        mg_printf(connection, "     Average Transit Time/Packet: %s usecs\r\n", 
            locale.toString((uint)averageTransitTimePerPacket).rightJustified(COLUMN_WIDTH, ' ').toLocal8Bit().constData());
        mg_printf(connection, "     Average Process Time/Packet: %s usecs\r\n",
            locale.toString((uint)averageProcessTimePerPacket).rightJustified(COLUMN_WIDTH, ' ').toLocal8Bit().constData());
        mg_printf(connection, "   Average Wait Lock Time/Packet: %s usecs\r\n", 
            locale.toString((uint)averageLockWaitTimePerPacket).rightJustified(COLUMN_WIDTH, ' ').toLocal8Bit().constData());
        mg_printf(connection, "    Average Process Time/Element: %s usecs\r\n",
            locale.toString((uint)averageProcessTimePerElement).rightJustified(COLUMN_WIDTH, ' ').toLocal8Bit().constData());
        mg_printf(connection, "  Average Wait Lock Time/Element: %s usecs\r\n", 
            locale.toString((uint)averageLockWaitTimePerElement).rightJustified(COLUMN_WIDTH, ' ').toLocal8Bit().constData());


        int senderNumber = 0;
        NodeToSenderStatsMap& allSenderStats = theServer->_octreeInboundPacketProcessor->getSingleSenderStats();
        for (NodeToSenderStatsMapIterator i = allSenderStats.begin(); i != allSenderStats.end(); i++) {
            senderNumber++;
            QUuid senderID = i->first;
            SingleSenderStats& senderStats = i->second;

            mg_printf(connection, "\r\n             Stats for sender %d uuid: %s\r\n", senderNumber, 
                senderID.toString().toLocal8Bit().constData());

            averageTransitTimePerPacket = senderStats.getAverageTransitTimePerPacket();
            averageProcessTimePerPacket = senderStats.getAverageProcessTimePerPacket();
            averageLockWaitTimePerPacket = senderStats.getAverageLockWaitTimePerPacket();
            averageProcessTimePerElement = senderStats.getAverageProcessTimePerElement();
            averageLockWaitTimePerElement = senderStats.getAverageLockWaitTimePerElement();
            totalElementsProcessed = senderStats.getTotalElementsProcessed();
            totalPacketsProcessed = senderStats.getTotalPacketsProcessed();

            averageElementsPerPacket = totalPacketsProcessed == 0 ? 0 : totalElementsProcessed / totalPacketsProcessed;

            mg_printf(connection, "               Total Inbound Packets: %s packets\r\n",
                locale.toString((uint)totalPacketsProcessed).rightJustified(COLUMN_WIDTH, ' ').toLocal8Bit().constData());
            mg_printf(connection, "              Total Inbound Elements: %s elements\r\n",
                locale.toString((uint)totalElementsProcessed).rightJustified(COLUMN_WIDTH, ' ').toLocal8Bit().constData());
            mg_printf(connection, "     Average Inbound Elements/Packet: %f elements/packet\r\n", averageElementsPerPacket);
            mg_printf(connection, "         Average Transit Time/Packet: %s usecs\r\n", 
                locale.toString((uint)averageTransitTimePerPacket).rightJustified(COLUMN_WIDTH, ' ').toLocal8Bit().constData());
            mg_printf(connection, "         Average Process Time/Packet: %s usecs\r\n",
                locale.toString((uint)averageProcessTimePerPacket).rightJustified(COLUMN_WIDTH, ' ').toLocal8Bit().constData());
            mg_printf(connection, "       Average Wait Lock Time/Packet: %s usecs\r\n", 
                locale.toString((uint)averageLockWaitTimePerPacket).rightJustified(COLUMN_WIDTH, ' ').toLocal8Bit().constData());
            mg_printf(connection, "        Average Process Time/Element: %s usecs\r\n",
                locale.toString((uint)averageProcessTimePerElement).rightJustified(COLUMN_WIDTH, ' ').toLocal8Bit().constData());
            mg_printf(connection, "      Average Wait Lock Time/Element: %s usecs\r\n", 
                locale.toString((uint)averageLockWaitTimePerElement).rightJustified(COLUMN_WIDTH, ' ').toLocal8Bit().constData());

        }


        mg_printf(connection, "%s", "\r\n");
        mg_printf(connection, "%s", "\r\n");

        // display memory usage stats
        mg_printf(connection, "%s", "<b>Current Memory Usage Statistics</b>\r\n");
        mg_printf(connection, "\r\nOctreeElement size... %ld bytes\r\n", sizeof(OctreeElement));
        mg_printf(connection, "%s", "\r\n");

        const char* memoryScaleLabel;
        const float MEGABYTES = 1000000.f;
        const float GIGABYTES = 1000000000.f;
        float memoryScale;
        if (OctreeElement::getTotalMemoryUsage() / MEGABYTES < 1000.0f) {
            memoryScaleLabel = "MB";
            memoryScale = MEGABYTES;
        } else {
            memoryScaleLabel = "GB";
            memoryScale = GIGABYTES;
        }

        mg_printf(connection, "Element Node Memory Usage:       %8.2f %s\r\n", 
            OctreeElement::getVoxelMemoryUsage() / memoryScale, memoryScaleLabel);
        mg_printf(connection, "Octcode Memory Usage:            %8.2f %s\r\n", 
            OctreeElement::getOctcodeMemoryUsage() / memoryScale, memoryScaleLabel);
        mg_printf(connection, "External Children Memory Usage:  %8.2f %s\r\n", 
            OctreeElement::getExternalChildrenMemoryUsage() / memoryScale, memoryScaleLabel);
        mg_printf(connection, "%s", "                                 -----------\r\n");
        mg_printf(connection, "                         Total:  %8.2f %s\r\n", 
            OctreeElement::getTotalMemoryUsage() / memoryScale, memoryScaleLabel);

        mg_printf(connection, "%s", "\r\n");
        mg_printf(connection, "%s", "OctreeElement Children Population Statistics...\r\n");
        checkSum = 0;
        for (int i=0; i <= NUMBER_OF_CHILDREN; i++) {
            checkSum += OctreeElement::getChildrenCount(i);
            mg_printf(connection, "    Nodes with %d children:      %s nodes (%5.2f%%)\r\n", i, 
                locale.toString((uint)OctreeElement::getChildrenCount(i)).rightJustified(16, ' ').toLocal8Bit().constData(),
                ((float)OctreeElement::getChildrenCount(i) / (float)nodeCount) * AS_PERCENT);
        }
        mg_printf(connection, "%s", "                                ----------------------\r\n");
        mg_printf(connection, "                    Total:      %s nodes\r\n", 
            locale.toString((uint)checkSum).rightJustified(16, ' ').toLocal8Bit().constData());

#ifdef BLENDED_UNION_CHILDREN
        mg_printf(connection, "%s", "\r\n");
        mg_printf(connection, "%s", "OctreeElement Children Encoding Statistics...\r\n");
        
        mg_printf(connection, "    Single or No Children:      %10.llu nodes (%5.2f%%)\r\n",
            OctreeElement::getSingleChildrenCount(), ((float)OctreeElement::getSingleChildrenCount() / (float)nodeCount) * AS_PERCENT);
        mg_printf(connection, "    Two Children as Offset:     %10.llu nodes (%5.2f%%)\r\n", 
            OctreeElement::getTwoChildrenOffsetCount(), 
            ((float)OctreeElement::getTwoChildrenOffsetCount() / (float)nodeCount) * AS_PERCENT);
        mg_printf(connection, "    Two Children as External:   %10.llu nodes (%5.2f%%)\r\n", 
            OctreeElement::getTwoChildrenExternalCount(), 
            ((float)OctreeElement::getTwoChildrenExternalCount() / (float)nodeCount) * AS_PERCENT);
        mg_printf(connection, "    Three Children as Offset:   %10.llu nodes (%5.2f%%)\r\n", 
            OctreeElement::getThreeChildrenOffsetCount(), 
            ((float)OctreeElement::getThreeChildrenOffsetCount() / (float)nodeCount) * AS_PERCENT);
        mg_printf(connection, "    Three Children as External: %10.llu nodes (%5.2f%%)\r\n", 
            OctreeElement::getThreeChildrenExternalCount(), 
            ((float)OctreeElement::getThreeChildrenExternalCount() / (float)nodeCount) * AS_PERCENT);
        mg_printf(connection, "    Children as External Array: %10.llu nodes (%5.2f%%)\r\n",
            OctreeElement::getExternalChildrenCount(), 
            ((float)OctreeElement::getExternalChildrenCount() / (float)nodeCount) * AS_PERCENT);

        checkSum = OctreeElement::getSingleChildrenCount() +
                            OctreeElement::getTwoChildrenOffsetCount() + OctreeElement::getTwoChildrenExternalCount() + 
                            OctreeElement::getThreeChildrenOffsetCount() + OctreeElement::getThreeChildrenExternalCount() + 
                            OctreeElement::getExternalChildrenCount();

        mg_printf(connection, "%s", "                                ----------------\r\n");
        mg_printf(connection, "                         Total: %10.llu nodes\r\n", checkSum);
        mg_printf(connection, "                      Expected: %10.lu nodes\r\n", nodeCount);

        mg_printf(connection, "%s", "\r\n");
        mg_printf(connection, "%s", "In other news....\r\n");
        mg_printf(connection, "could store 4 children internally:     %10.llu nodes\r\n",
            OctreeElement::getCouldStoreFourChildrenInternally());
        mg_printf(connection, "could NOT store 4 children internally: %10.llu nodes\r\n", 
            OctreeElement::getCouldNotStoreFourChildrenInternally());
#endif

        mg_printf(connection, "%s", "\r\n");
        mg_printf(connection, "%s", "\r\n");
        mg_printf(connection, "%s", "</pre>\r\n");

        mg_printf(connection, "%s", "</doc></html>");

        return 1;
    } else {
        // have mongoose process this request from the document_root
        return 0;
    }
}
Exemplo n.º 18
0
IIRfilter1stOrder::IIRfilter1stOrder(LockBox *parent, unsigned int configOffset, int a0shift, bool alwaysOn, QStringList *filterTypes, int labelSize, int widgetSize) :
  QWidget(0),
  parent(parent),
  configOffset(configOffset),
  alwaysOn(alwaysOn),
  SETTING_WIDGETS_FROM_CONFIG(false),
  SETTING_WIDGETS_VISIBLE(false),
  SETTING_COEFFICIENTS_FROM_PARAMETERS(false),
  SETTING_PARAMETERS_FROM_COEFFICIENTS(false)
{
  QVBoxLayout *mainLayout = new QVBoxLayout(this);

  a0 = 0x1LL << a0shift;
  gainMultiplier = 1.0;

  // Filter on/off and type
  {
    QHBoxLayout *hLayout = new QHBoxLayout();
    FilterOnCheckBox = new QCheckBox(tr("IIR filter 1:"));
    FilterTypeComboBox = new QComboBox();

    FilterOnCheckBox->setMinimumSize(labelSize, 0);
    FilterOnCheckBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    if (alwaysOn)
    {
      FilterOnCheckBox->setChecked(true);
      FilterOnCheckBox->setEnabled(false);
    }

    for (int i = 0; i < filterTypes->length(); i ++)
    {
      FilterTypeComboBox->addItem(filterTypes->value(i));
    }

    FilterTypeComboBox->setMinimumSize(widgetSize, 0);
    FilterTypeComboBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    hLayout->addWidget(FilterOnCheckBox);
    hLayout->addWidget(FilterTypeComboBox);
    mainLayout->addLayout(hLayout);
  }

  // Corner frequency spin box
  {
    QHBoxLayout *hLayout = new QHBoxLayout();
    freqLabel = new QLabel(tr("Corner freq:"));
    freqSpinBox = new VariableDoubleSpinBox();

    freqLabel->setMinimumSize(labelSize, 0);
    freqLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    freqSpinBox->setSuffix(tr(" Hz"));
    freqSpinBox->setDecimals(0);
    freqSpinBox->setSingleStep(10);

    freqSpinBox->setMinimumSize(widgetSize, 0);
    freqSpinBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    hLayout->addWidget(freqLabel);
    hLayout->addWidget(freqSpinBox);
    mainLayout->addLayout(hLayout);
  }

  // Gain
  {
    QHBoxLayout *hLayout = new QHBoxLayout();
    gainLabel = new QLabel(tr("Gain:"));
    gainSpinBox = new VariableDoubleSpinBox();

    gainLabel->setMinimumSize(labelSize, 0);
    gainLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    gainSpinBox->setSuffix(tr(" dB"));
    gainSpinBox->setDecimals(1);
    gainSpinBox->setSingleStep(1);

    hLayout->addWidget(gainLabel);
    hLayout->addWidget(gainSpinBox);
    mainLayout->addLayout(hLayout);
  }

  // Gain limit
  {
    QHBoxLayout *hLayout = new QHBoxLayout();
    gainLimitLabel = new QLabel(tr("Gain limit:"));
    gainLimitSpinBox = new VariableDoubleSpinBox();

    gainLimitLabel->setMinimumSize(labelSize, 0);
    gainLimitLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    gainLimitSpinBox->setSuffix(tr(" dB"));
    gainLimitSpinBox->setDecimals(0);
    gainLimitSpinBox->setSingleStep(5);

    hLayout->addWidget(gainLimitLabel);
    hLayout->addWidget(gainLimitSpinBox);
    mainLayout->addLayout(hLayout);
  }

  // a0 spin box
  {
    QHBoxLayout *hLayout = new QHBoxLayout();
    a0Label = new QLabel(tr("a0:"));
    a0SpinBox = new QLabel("2<sup>" + locale().toString(a0shift) + "</sup>");

    a0Label->setMinimumSize(labelSize, 0);
    a0Label->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    a0SpinBox->setMinimumSize(widgetSize, 0);
    a0SpinBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    hLayout->addWidget(a0Label);
    hLayout->addWidget(a0SpinBox);
    mainLayout->addLayout(hLayout);
  }

  // a1 spin box
  {
    QHBoxLayout *hLayout = new QHBoxLayout();
    a1Label = new QLabel(tr("a1:"));
    a1SpinBox = new VariableLongLongSpinBox();

    a1Label->setMinimumSize(labelSize, 0);
    a1Label->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    a1SpinBox->setRange(-17179869184, 17179869183);
    a1SpinBox->setSingleStep(1);
    a1SpinBox->setValue(0);

    a1SpinBox->setMinimumSize(widgetSize, 0);
    a1SpinBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    hLayout->addWidget(a1Label);
    hLayout->addWidget(a1SpinBox);
    mainLayout->addLayout(hLayout);
  }

  // b0 spin box
  {
    QHBoxLayout *hLayout = new QHBoxLayout();
    b0Label = new QLabel(tr("b0:"));
    b0SpinBox = new VariableLongLongSpinBox();

    b0Label->setMinimumSize(labelSize, 0);
    b0Label->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    b0SpinBox->setRange(-17179869184, 17179869183);
    b0SpinBox->setSingleStep(1);
    b0SpinBox->setValue(0);

    b0SpinBox->setMinimumSize(widgetSize, 0);
    b0SpinBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    hLayout->addWidget(b0Label);
    hLayout->addWidget(b0SpinBox);
    mainLayout->addLayout(hLayout);
  }

  // b1 spin box
  {
    QHBoxLayout *hLayout = new QHBoxLayout();
    b1Label = new QLabel(tr("b1:"));
    b1SpinBox = new VariableLongLongSpinBox();

    b1Label->setMinimumSize(labelSize, 0);
    b1Label->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    b1SpinBox->setRange(-17179869184, 17179869183);
    b1SpinBox->setSingleStep(1);
    b1SpinBox->setValue(0);

    b1SpinBox->setMinimumSize(widgetSize, 0);
    b1SpinBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    hLayout->addWidget(b1Label);
    hLayout->addWidget(b1SpinBox);
    mainLayout->addLayout(hLayout);
  }

  // Hook up on_FilterTypeChanged
  QObject::connect(FilterOnCheckBox, SIGNAL(toggled(bool)), this, SLOT(on_FilterTypeChanged()));
  QObject::connect(FilterTypeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(on_FilterTypeChanged()));

  // Hook up on_FilterParametersChanged
  QObject::connect(freqSpinBox, SIGNAL(valueChanged(double)), this, SLOT(on_FilterParametersChanged()));
  QObject::connect(gainSpinBox, SIGNAL(valueChanged(double)), this, SLOT(on_FilterParametersChanged()));
  QObject::connect(gainLimitSpinBox, SIGNAL(valueChanged(double)), this, SLOT(on_FilterParametersChanged()));

  // Hook up on_CoefficientsChanged
  QObject::connect(a1SpinBox, SIGNAL(valueChanged(qint64)), this, SLOT(on_CoefficientsChanged()));
  QObject::connect(b0SpinBox, SIGNAL(valueChanged(qint64)), this, SLOT(on_CoefficientsChanged()));
  QObject::connect(b1SpinBox, SIGNAL(valueChanged(qint64)), this, SLOT(on_CoefficientsChanged()));
}
Exemplo n.º 19
0
void DDateTable::paintCell(QPainter* painter, int row, int col)
{
    double w    = (width() / (double) d->numDayColumns) - 1;
    double h    = (height() / (double) d->numWeekRows) - 1;
    QRectF cell = QRectF(0, 0, w, h);
    QString cellText;
    QPen pen;
    QColor cellBackgroundColor, cellTextColor;
    QFont cellFont  = QFontDatabase::systemFont(QFontDatabase::GeneralFont);
    bool workingDay = false;
    int cellWeekDay, pos;

    //Calculate the position of the cell in the grid
    pos = d->numDayColumns * (row - 1) + col;

    //Calculate what day of the week the cell is
    if (col + locale().firstDayOfWeek() <= d->numDayColumns)
    {
        cellWeekDay = col + locale().firstDayOfWeek();
    }
    else
    {
        cellWeekDay = col + locale().firstDayOfWeek() - d->numDayColumns;
    }

    //FIXME This is wrong if the widget is not using the global!
    //See if cell day is normally a working day
    if (locale().weekdays().first() <= locale().weekdays().last())
    {
        if (cellWeekDay >= locale().weekdays().first() &&
            cellWeekDay <= locale().weekdays().last())
        {
            workingDay = true;
        }
    }
    else
    {
        if (cellWeekDay >= locale().weekdays().first() ||
            cellWeekDay <= locale().weekdays().last())
        {
            workingDay = true;
        }
    }

    if (row == 0)
    {
        //We are drawing a header cell

        //If not a normal working day, then use "do not work today" color
        if (workingDay)
        {
            cellTextColor = palette().color(QPalette::WindowText);
        }
        else
        {
            cellTextColor = Qt::darkRed;
        }

        cellBackgroundColor = palette().color(QPalette::Window);

        //Set the text to the short day name and bold it
        cellFont.setBold(true);
        cellText = locale().dayName(cellWeekDay, QLocale::ShortFormat);

    }
    else
    {
        //We are drawing a day cell

        //Calculate the date the cell represents
        QDate cellDate = dateFromPos(pos);
        bool validDay  = cellDate.isValid();

        // Draw the day number in the cell, if the date is not valid then we don't want to show it
        if (validDay)
        {
            cellText = QString::number(cellDate.day());
        }
        else
        {
            cellText = QLatin1String("");
        }

        if (! validDay || cellDate.month() != d->date.month())
        {
            // we are either
            // ° painting an invalid day
            // ° painting a day of the previous month or
            // ° painting a day of the following month or
            cellBackgroundColor = palette().color(backgroundRole());
            cellTextColor       = palette().color(QPalette::Disabled, QPalette::Text);
        }
        else
        {
            //Paint a day of the current month

            // Background Colour priorities will be (high-to-low):
            // * Selected Day Background Colour
            // * Customized Day Background Colour
            // * Normal Day Background Colour

            // Background Shape priorities will be (high-to-low):
            // * Customized Day Shape
            // * Normal Day Shape

            // Text Colour priorities will be (high-to-low):
            // * Customized Day Colour
            // * Day of Pray Colour (Red letter)
            // * Selected Day Colour
            // * Normal Day Colour

            //Determine various characteristics of the cell date
            bool selectedDay = (cellDate == date());
            bool currentDay  = (cellDate == QDate::currentDate());
            bool dayOfPray   = (cellDate.dayOfWeek() == Qt::Sunday);
            // TODO: Uncomment if QLocale ever gets the feature...
            //bool dayOfPray = ( cellDate.dayOfWeek() == locale().dayOfPray() );
            bool customDay   = (d->useCustomColors && d->customPaintingModes.contains(cellDate.toJulianDay()));

            //Default values for a normal cell
            cellBackgroundColor = palette().color(backgroundRole());
            cellTextColor = palette().color(foregroundRole());

            // If we are drawing the current date, then draw it bold and active
            if (currentDay)
            {
                cellFont.setBold(true);
                cellTextColor = palette().color(QPalette::LinkVisited);
            }

            // if we are drawing the day cell currently selected in the table
            if (selectedDay)
            {
                // set the background to highlighted
                cellBackgroundColor = palette().color(QPalette::Highlight);
                cellTextColor = palette().color(QPalette::HighlightedText);
            }

            //If custom colors or shape are required for this date
            if (customDay)
            {
                Private::DatePaintingMode mode = d->customPaintingModes[cellDate.toJulianDay()];

                if (mode.bgMode != NoBgMode)
                {
                    if (!selectedDay)
                    {
                        cellBackgroundColor = mode.bgColor;
                    }
                }

                cellTextColor = mode.fgColor;
            }

            //If the cell day is the day of religious observance, then always color text red unless Custom overrides
            if (! customDay && dayOfPray)
            {
                cellTextColor = Qt::darkRed;
            }

        }
    }

    //Draw the background
    if (row == 0)
    {
        painter->setPen(cellBackgroundColor);
        painter->setBrush(cellBackgroundColor);
        painter->drawRect(cell);
    }
    else if (cellBackgroundColor != palette().color(backgroundRole()) || pos == d->hoveredPos)
    {
        QStyleOptionViewItem opt;
        opt.initFrom(this);
        opt.rect = cell.toRect();

        if (cellBackgroundColor != palette().color(backgroundRole()))
        {
            opt.palette.setBrush(QPalette::Highlight, cellBackgroundColor);
            opt.state |= QStyle::State_Selected;
        }

        if (pos == d->hoveredPos && opt.state & QStyle::State_Enabled)
        {
            opt.state |= QStyle::State_MouseOver;
        }
        else
        {
            opt.state &= ~QStyle::State_MouseOver;
        }

        opt.showDecorationSelected = true;
        opt.viewItemPosition       = QStyleOptionViewItem::OnlyOne;
        style()->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, this);
    }

    //Draw the text
    painter->setPen(cellTextColor);
    painter->setFont(cellFont);
    painter->drawText(cell, Qt::AlignCenter, cellText, &cell);

    //Draw the base line
    if (row == 0)
    {
        painter->setPen(palette().color(foregroundRole()));
        painter->drawLine(QPointF(0, h), QPointF(w, h));
    }

    // If the day cell we just drew is bigger than the current max cell sizes,
    // then adjust the max to the current cell
    if (cell.width() > d->maxCell.width())
    {
        d->maxCell.setWidth(cell.width());
    }

    if (cell.height() > d->maxCell.height())
    {
        d->maxCell.setHeight(cell.height());
    }
}
Exemplo n.º 20
0
OptionsDialog::OptionsDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::OptionsDialog),
    model(0),
    mapper(0),
    fProxyIpValid(true)
{
    ui->setupUi(this);
    GUIUtil::restoreWindowGeometry("nOptionsDialogWindow", this->size(), this);

    /* Main elements init */
    ui->databaseCache->setMinimum(nMinDbCache);
    ui->databaseCache->setMaximum(nMaxDbCache);
    ui->threadsScriptVerif->setMinimum(-(int)boost::thread::hardware_concurrency());
    ui->threadsScriptVerif->setMaximum(MAX_SCRIPTCHECK_THREADS);

    /* Network elements init */
#ifndef USE_UPNP
    ui->mapPortUpnp->setEnabled(false);
#endif

    ui->proxyIp->setEnabled(false);
    ui->proxyPort->setEnabled(false);
    ui->proxyPort->setValidator(new QIntValidator(1, 65535, this));

    /** SOCKS version is only selectable for default proxy and is always 5 for IPv6 and Tor */
    ui->socksVersion->setEnabled(false);
    ui->socksVersion->addItem("5", 5);
    ui->socksVersion->addItem("4", 4);
    ui->socksVersion->setCurrentIndex(0);

    connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));
    connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));
    connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool)));

    ui->proxyIp->installEventFilter(this);

    /* Window elements init */
#ifdef Q_OS_MAC
    /* remove Window tab on Mac */
    ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow));
#endif

    /* Display elements init */
    QDir translations(":translations");
    ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
    foreach(const QString &langStr, translations.entryList())
    {
        QLocale locale(langStr);

        /** check if the locale name consists of 2 parts (language_country) */
        if(langStr.contains("_"))
        {
#if QT_VERSION >= 0x040800
            /** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */
            ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
            /** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */
            ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
        }
        else
        {
#if QT_VERSION >= 0x040800
            /** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */
            ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
            /** display language strings as "language (locale name)", e.g. "German (de)" */
            ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
        }
    }
#if QT_VERSION >= 0x040700
    ui->thirdPartyTxUrls->setPlaceholderText("https://example.com/tx/%s");
#endif

    ui->unit->setModel(new BitmarkUnits(this));
    ui->transactionFee->setSingleStep(CTransaction::nMinTxFee);

    /* Widget-to-option mapper */
    mapper = new MonitoredDataMapper(this);
    mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
    mapper->setOrientation(Qt::Vertical);

    /* setup/change UI elements when proxy IP is invalid/valid */
    connect(this, SIGNAL(proxyIpChecks(QValidatedLineEdit *, int)), this, SLOT(doProxyIpChecks(QValidatedLineEdit *, int)));
}
Exemplo n.º 21
0
void DateTimeChooserImpl::writeDocument(WebCore::SharedBuffer* data)
{
    String stepString = String::number(m_parameters.step);
    String stepBaseString = String::number(m_parameters.stepBase, 11, WTF::TruncateTrailingZeros);
    IntRect anchorRectInScreen = m_chromeClient->rootViewToScreen(m_parameters.anchorRectInRootView);
    String todayLabelString;
    String otherDateLabelString;
    if (m_parameters.type == WebCore::InputTypeNames::month) {
        todayLabelString = locale().queryString(WebLocalizedString::ThisMonthButtonLabel);
        otherDateLabelString = locale().queryString(WebLocalizedString::OtherMonthLabel);
    } else if (m_parameters.type == WebCore::InputTypeNames::week) {
        todayLabelString = locale().queryString(WebLocalizedString::ThisWeekButtonLabel);
        otherDateLabelString = locale().queryString(WebLocalizedString::OtherWeekLabel);
    } else {
        todayLabelString = locale().queryString(WebLocalizedString::CalendarToday);
        otherDateLabelString = locale().queryString(WebLocalizedString::OtherDateLabel);
    }

    addString("<!DOCTYPE html><head><meta charset='UTF-8'><style>\n", data);
    data->append(pickerCommonCss, sizeof(pickerCommonCss));
    data->append(pickerButtonCss, sizeof(pickerButtonCss));
    data->append(suggestionPickerCss, sizeof(suggestionPickerCss));
    data->append(calendarPickerCss, sizeof(calendarPickerCss));
    addString("</style></head><body><div id=main>Loading...</div><script>\n"
        "window.dialogArguments = {\n", data);
    addProperty("anchorRectInScreen", anchorRectInScreen, data);
    addProperty("min", valueToDateTimeString(m_parameters.minimum, m_parameters.type), data);
    addProperty("max", valueToDateTimeString(m_parameters.maximum, m_parameters.type), data);
    addProperty("step", stepString, data);
    addProperty("stepBase", stepBaseString, data);
    addProperty("required", m_parameters.required, data);
    addProperty("currentValue", valueToDateTimeString(m_parameters.doubleValue, m_parameters.type), data);
    addProperty("locale", m_parameters.locale.string(), data);
    addProperty("todayLabel", todayLabelString, data);
    addProperty("clearLabel", locale().queryString(WebLocalizedString::CalendarClear), data);
    addProperty("weekLabel", locale().queryString(WebLocalizedString::WeekNumberLabel), data);
    addProperty("weekStartDay", m_locale->firstDayOfWeek(), data);
    addProperty("shortMonthLabels", m_locale->shortMonthLabels(), data);
    addProperty("dayLabels", m_locale->weekDayShortLabels(), data);
    addProperty("isLocaleRTL", m_locale->isRTL(), data);
    addProperty("isRTL", m_parameters.isAnchorElementRTL, data);
    addProperty("mode", m_parameters.type.string(), data);
    if (m_parameters.suggestions.size()) {
        Vector<String> suggestionValues;
        Vector<String> localizedSuggestionValues;
        Vector<String> suggestionLabels;
        for (unsigned i = 0; i < m_parameters.suggestions.size(); i++) {
            suggestionValues.append(valueToDateTimeString(m_parameters.suggestions[i].value, m_parameters.type));
            localizedSuggestionValues.append(m_parameters.suggestions[i].localizedValue);
            suggestionLabels.append(m_parameters.suggestions[i].label);
        }
        addProperty("suggestionValues", suggestionValues, data);
        addProperty("localizedSuggestionValues", localizedSuggestionValues, data);
        addProperty("suggestionLabels", suggestionLabels, data);
        addProperty("inputWidth", static_cast<unsigned>(m_parameters.anchorRectInRootView.width()), data);
        addProperty("showOtherDateEntry", WebCore::RenderTheme::theme().supportsCalendarPicker(m_parameters.type), data);
        addProperty("otherDateLabel", otherDateLabelString, data);
        addProperty("suggestionHighlightColor", WebCore::RenderTheme::theme().activeListBoxSelectionBackgroundColor().serialized(), data);
        addProperty("suggestionHighlightTextColor", WebCore::RenderTheme::theme().activeListBoxSelectionForegroundColor().serialized(), data);
    }
    addString("}\n", data);

    data->append(pickerCommonJs, sizeof(pickerCommonJs));
    data->append(suggestionPickerJs, sizeof(suggestionPickerJs));
    data->append(calendarPickerJs, sizeof(calendarPickerJs));
    addString("</script></body>\n", data);
}
Exemplo n.º 22
0
int main (int argc, char * const argv[]) {
	time_t startTime = time(0);
	time_t currentTime;
	unsigned long long sec;

#ifndef MACOSX
	locale::global(locale("en_US.UTF-8"));
#else
	//This points to the file, where lowercase versions for diacritisised characters can be found. The version of GCC that Xcode uses has broken locale system.
#ifdef DATA_DIR
	string uml = DATA_DIR;
#else
	string uml = "/Users/ventzi/Desktop/курсове - университет/ATTEMPT/software/TreeTester all";
#endif
	uml += "/umlauts.txt";
	buildLowercasingTable(uml);
#endif //#ifdef MACOSX
		
	/*	chudInitialize();
	chudMarkPID(getpid(),1);
	chudAcquireRemoteAccess();
	chudStartRemotePerfMonitor("testthetester");*/
		
	wcout << "DATA_SET: " << DATA_SET << endl;

	wifstream input;
	wifstream internal;
	wofstream output;

	bool files_loaded = false;
	if (argc > 1 && argc != 4 && argc != 3) {
		wcout << "Incorrect number of arguments: " << (argc - 1) << "! Usage:\n   " << argv[0] << " [input [internal] output]\n";
		exit(1);
	} else if (argc == 4 || argc == 3) {
		files_loaded = true;
		input.open(argv[1]);
		if (argc == 4)
			internal.open(argv[2]);
		output.open(argv[argc - 1]);
	}
	
	if (!files_loaded) {
	if (1) {
		//HomeCenter data
//	} else if (DATA_SET == "HomeCentre") {
//		NonTerminal::idBase.reset(500);
//		input.open("/Users/ventzi/Desktop/курсове - университет/ATTEMPT/data/HomeCentre/new_manual.txt");
		//English-Spanish data
//	} else if (DATA_SET == "en-sp") {
//		input.open("/Users/ventzi/Desktop/курсове - университет/ATTEMPT/data/en-sp/pairs.txt");
		//English-German data
//	} else if (DATA_SET == "en-de") {
//		input.open("/Users/ventzi/Desktop/курсове - университет/ATTEMPT/data/en-de/10k/pairs.txt");
		//German News data
	} else if (DATA_SET == "de-news") {
		input.open("/Users/ventzi/Desktop/курсове - университет/ATTEMPT/data/de-news/weaver/de-news.de.bitpar.clean");
		internal.open("/Users/ventzi/Desktop/курсове - университет/ATTEMPT/data/de-news/de-news.de.DOP.internal.only.txt");
		output.open("/Users/ventzi/Desktop/курсове - университет/ATTEMPT/data/de-news/de-news.de.DOP.grammar.txt");
	} else {
		exit(15);
	}
	}
	
	//	exit(66);
	
	if (input.fail()) {
		wcout << "!!!Cannot open the pairs file!!!" << endl;
		exit(1);
	}
	
	if (internal.fail()) {
		wcout << "!!!Cannot open the internals file!!!" << endl;
		exit(1);
	}
	
	DOPTree tree;
	int counter = 1;
	
//	PCFGRulesMap PCFGRules;
	
	output.unsetf(ios::fixed);
	output.precision(16);

//	currentTime = time(0);
	
//	DOPTree::internalOnlyLabels = wstringSet();
	if (internal.is_open())
		while (!internal.eof()) {
			wstring label;
			internal >> label;
			DOPTree::internalOnlyLabels.insert(label);
			wcout << "Got internalOnlyLabel " << label << endl;
		}
//	internalOnlyLabels.insert(L"#EOS#");
	
	tree = L"(NP (D the)(NPadj (Adj green)(N house)))";
	tree.collectPCFGRules(wcout);
	tree = L"(NP (D the)(NPadj (Adj small)(N house)))";
	tree.collectPCFGRules(wcout);
	
	
	int treeNo = 10;
	while (0 && !input.eof()) {
		input >> tree;
		if (tree.sentLength() > 0) {
			++counter;
			//			if (counter <= treeNo) continue;
//			wcout << "Tree №" << counter - 1 << ":" << endl;
			//			treePair.printXML();
//			wcout << tree;
			wcout << ".";
			tree.collectPCFGRules(output);
//			wcout << endl;
			//			treePair.removeExtraNodes();
			//			treePair.printTaggedSentences();
			//			treePair.printSentences();
			//			treePair.freezeLinks();
			//			treePair.printBracketed();
			//			wcout << endl;
			if (counter > treeNo) break;
		} else {
			wcout << "Tree №" << counter << ": !!!ERROR!!!" << endl;
		}
	}
	wcout << endl;
	
	input.close();
	
	DOPTree::outputPCFGRules(wcout);
/*	for (PCFGRulesMap::const_iterator it = PCFGRules.begin(); it != PCFGRules.end(); ++it) {
		for (PCFGRulesMap::value_type::second_type::second_type::const_iterator rit = it->second.second.begin(); rit != it->second.second.end(); ++rit) {
			wcout << it->first << "\t" << rit->first << "\t" << ((1.0*rit->second)/it->second.first) << endl;
//			output << it->first << "\t" << rit->first << "\t" << ((1.0*rit->second)/it->second.first) << endl;
		}
	}*/
	output.close();
	
	/*	chudStopRemotePerfMonitor();
	chudReleaseRemoteAccess();*/
	
	currentTime = time(0);
	tm* local = localtime(&currentTime);
	sec = difftime(currentTime, startTime);
	wcout << endl << "Elapsed: " << sec << "sec" << endl;
	wcout << "Finished at " << asctime(local);
	
	return 0;
}
Exemplo n.º 23
0
unsigned __stdcall tcpEchod(void *pArguments)
{
	CBlockingSocket *cs = (CBlockingSocket *)pArguments;
	CBlockingSocket ClientSocket = *cs;//用局部变量保存线程传进来的地址传递的参数,防止主线程中socket被改写。

	//1. The client sends a request to the server to ask for the size of a specific file.
	char filename[FPL] = {0};
	char buffer[12+FPL] = {0};
	ClientSocket.Recv(buffer,sizeof(buffer));
	Message msg;
	msg.read(buffer);
	memcpy(filename, msg.getData(), msg.getTotalLength()-12);
	cout << "  File requested from the client: " << filename << endl;

	fstream fs;
	locale::global(locale(""));//将全局区域设为操作系统默认区域
	//setlocale(LC_ALL,"Chinese-simplified");//设置中文环境
	fs.open(filename, ios::in|ios::binary);
	locale::global(locale("C"));//还原全局区域设定
	//setlocale(LC_ALL,"C");//还原
	if(!fs)
	{
		cout << "  " << filename << " does not exist." << endl;
		msg.setSize(-1);
		msg.write(buffer);
		ClientSocket.Send(buffer,msg.getTotalLength());
	}
	else
	{
		//2. The server sends back a reply with the size of the file if file exists.
		fs.seekg(0,ios::end);
		int filelen = fs.tellg();
		fs.seekg(0,ios::beg);
		msg.setSize(filelen);
		msg.write(buffer);
		ClientSocket.Send(buffer,msg.getTotalLength());

		//3. The client creates a separate thread, and send request for the file data (optional implementation: the
		//   client may create 2 or more threads for downloading, each thread for a part of the file in a separate
		//   connection).
		ClientSocket.Recv(buffer,sizeof(buffer));
		msg.read(buffer);

		//4. The server accepts the data download request, and starts a new thread to send the file to the client
		//   (if the client uses more than 1 thread for downloading, the server should start more than 1 thread
		//	 for the corresponding connection request).
		char buffer2[BDP] = {0};
		char *buffer3 = new char[12+BDP];
		if(filelen <= BDP)
		{
			fs.read(buffer2,filelen);
			msg.setTotalLength(12+filelen);
			msg.setData(buffer2);
			msg.write(buffer3);
			ClientSocket.Send(buffer3,12+filelen);
		}
		else
		{
			int count = 0;
			for(int block=0; block<filelen/BDP; ++block)
			{
				fs.read(buffer2, BDP);
				msg.setTotalLength(12+(unsigned short)BDP);
				msg.setPosition(count);
				count += BDP;
				msg.setSize(BDP);
				msg.setData(buffer2);
				msg.write(buffer3);
				ClientSocket.Send(buffer3,12+BDP);
			}
			fs.read(buffer2, filelen%BDP);
			msg.setTotalLength(12+(unsigned short)filelen%BDP);
			msg.setPosition(count);
			msg.setSize(BDP);
			msg.setData(buffer2);
			msg.write(buffer3);
			ClientSocket.Send(buffer3,12+filelen%BDP);
		}
		//msg.setSize(0);
		//msg.setData(NULL);
		//msg.write(buffer3);
		//ClientSocket.Send(buffer3,12);
		cout << "  Sent file back to the client: " << filename << endl;
		delete[] buffer3;
	}
	fs.close();
	
	ClientSocket.Close();
	return 0;
}
Exemplo n.º 24
0
void LLManip::renderTickValue(const LLVector3& pos, F32 value, const std::string& suffix, const LLColor4 &color)
{
	LLLocale locale(LLLocale::USER_LOCALE);

	const LLFontGL* big_fontp = LLResMgr::getInstance()->getRes( LLFONT_SANSSERIF );
	const LLFontGL* small_fontp = LLResMgr::getInstance()->getRes( LLFONT_SANSSERIF_SMALL );

	std::string val_string;
	std::string fraction_string;
	F32 val_to_print = llround(value, 0.001f);
	S32 fractional_portion = llround(fmodf(llabs(val_to_print), 1.f) * 100.f);
	if (val_to_print < 0.f)
	{
		if (fractional_portion == 0)
		{
			val_string = llformat("-%d%s", lltrunc(llabs(val_to_print)), suffix.c_str());
		}
		else
		{
			val_string = llformat("-%d", lltrunc(llabs(val_to_print)));
		}
	}
	else
	{
		if (fractional_portion == 0)
		{
			val_string = llformat("%d%s", lltrunc(llabs(val_to_print)), suffix.c_str());
		}
		else
		{
			val_string = llformat("%d", lltrunc(val_to_print));
		}
	}

	BOOL hud_selection = mObjectSelection->getSelectType() == SELECT_TYPE_HUD;
	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	LLVector3 render_pos = pos;
	if (hud_selection)
	{
		F32 zoom_amt = gAgent.mHUDCurZoom;
		F32 inv_zoom_amt = 1.f / zoom_amt;
		// scale text back up to counter-act zoom level
		render_pos = pos * zoom_amt;
		glScalef(inv_zoom_amt, inv_zoom_amt, inv_zoom_amt);
	}

	LLColor4 shadow_color = LLColor4::black;
	shadow_color.mV[VALPHA] = color.mV[VALPHA] * 0.5f;

	if (fractional_portion != 0)
	{
		fraction_string = llformat("%c%02d%s", LLResMgr::getInstance()->getDecimalPoint(), fractional_portion, suffix.c_str());

		gViewerWindow->setupViewport(1, -1);
		hud_render_utf8text(val_string, render_pos, *big_fontp, LLFontGL::NORMAL, -1.f * big_fontp->getWidthF32(val_string), 3.f, shadow_color, hud_selection);
		hud_render_utf8text(fraction_string, render_pos, *small_fontp, LLFontGL::NORMAL, 1.f, 3.f, shadow_color, hud_selection);

		gViewerWindow->setupViewport();
		hud_render_utf8text(val_string, render_pos, *big_fontp, LLFontGL::NORMAL, -1.f * big_fontp->getWidthF32(val_string), 3.f, color, hud_selection);
		hud_render_utf8text(fraction_string, render_pos, *small_fontp, LLFontGL::NORMAL, 1.f, 3.f, color, hud_selection);
	}
	else
	{
		gViewerWindow->setupViewport(1, -1);
		hud_render_utf8text(val_string, render_pos, *big_fontp, LLFontGL::NORMAL, -0.5f * big_fontp->getWidthF32(val_string), 3.f, shadow_color, hud_selection);
		gViewerWindow->setupViewport();
		hud_render_utf8text(val_string, render_pos, *big_fontp, LLFontGL::NORMAL, -0.5f * big_fontp->getWidthF32(val_string), 3.f, color, hud_selection);
	}
	glPopMatrix();
}
Exemplo n.º 25
0
    void LootState::Init(const std::string& cmdLineGame) {
        // Do some preliminary locale / UTF-8 support setup here, in case the settings file reading requires it.
        //Boost.Locale initialisation: Specify location of language dictionaries.
        boost::locale::generator gen;
        gen.add_messages_path(g_path_l10n.string());
        gen.add_messages_domain("loot");

        //Boost.Locale initialisation: Generate and imbue locales.
        locale::global(gen(Language(Language::english).Locale() + ".UTF-8"));
        boost::filesystem::path::imbue(locale());

        // Check if the LOOT local app data folder exists, and create it if not.
        if (!fs::exists(g_path_local)) {
            BOOST_LOG_TRIVIAL(info) << "Local app data LOOT folder doesn't exist, creating it.";
            try {
                fs::create_directory(g_path_local);
            }
            catch (exception& e) {
                _initErrors.push_back((format(translate("Error: Could not create LOOT settings file. %1%")) % e.what()).str());
            }
        }
        if (fs::exists(g_path_settings)) {
            try {
                loot::ifstream in(g_path_settings);
                _settings = YAML::Load(in);
                in.close();
            }
            catch (exception& e) {
                _initErrors.push_back((format(translate("Error: Settings parsing failed. %1%")) % e.what()).str());
            }
        }
        // Check if the settings are valid (or if they don't exist).
        if (!AreSettingsValid()) {
            _settings = GetDefaultSettings();
        }

        //Set up logging.
        boost::log::add_file_log(
            boost::log::keywords::file_name = g_path_log.string().c_str(),
            boost::log::keywords::auto_flush = true,
            boost::log::keywords::format = (
            boost::log::expressions::stream
            << "[" << boost::log::expressions::format_date_time< boost::posix_time::ptime >("TimeStamp", "%H:%M:%S") << "]"
            << " [" << boost::log::trivial::severity << "]: "
            << boost::log::expressions::smessage
            )
            );
        boost::log::add_common_attributes();
        bool enableDebugLogging = false;
        if (_settings["enableDebugLogging"]) {
            enableDebugLogging = _settings["enableDebugLogging"].as<bool>();
        }
        if (enableDebugLogging)
            boost::log::core::get()->set_logging_enabled(true);
        else
            boost::log::core::get()->set_logging_enabled(false);

        // Log some useful info.
        BOOST_LOG_TRIVIAL(info) << "LOOT Version: " << g_version_major << "." << g_version_minor << "." << g_version_patch;
        BOOST_LOG_TRIVIAL(info) << "LOOT Build Revision: " << g_build_revision;
#ifdef _WIN32
        // Check if LOOT is being run through Mod Organiser.
        bool runFromMO = GetModuleHandle(ToWinWide("hook.dll").c_str()) != NULL;
        if (runFromMO) {
            BOOST_LOG_TRIVIAL(info) << "LOOT is being run through Mod Organiser.";
        }
#endif

        // The CEF debug log is appended to, not overwritten, so it gets really long.
        // Delete the current CEF debug log.
        fs::remove(g_path_local / "CEFDebugLog.txt");

        // Now that settings have been loaded, set the locale again to handle translations.
        if (_settings["language"] && _settings["language"].as<string>() != Language(Language::english).Locale()) {
            BOOST_LOG_TRIVIAL(debug) << "Initialising language settings.";
            loot::Language lang(_settings["language"].as<string>());
            BOOST_LOG_TRIVIAL(debug) << "Selected language: " << lang.Name();

            //Boost.Locale initialisation: Generate and imbue locales.
            locale::global(gen(lang.Locale() + ".UTF-8"));
            boost::filesystem::path::imbue(locale());
        }

        // Detect games & select startup game
        //-----------------------------------

        //Detect installed games.
        BOOST_LOG_TRIVIAL(debug) << "Detecting installed games.";
        try {
            _games = ToGames(GetGameSettings(_settings));
        }
        catch (YAML::Exception& e) {
            BOOST_LOG_TRIVIAL(error) << "Games' settings parsing failed. " << e.what();
            _initErrors.push_back((format(translate("Error: Games' settings parsing failed. %1%")) % e.what()).str());
            // Now redo, but with no games settings, so only the hardcoded defaults get loaded. It means the user can
            // at least still then edit them.
            _games = ToGames(GetGameSettings(YAML::Node()));
        }

        try {
            BOOST_LOG_TRIVIAL(debug) << "Selecting game.";
            SelectGame(cmdLineGame);
            BOOST_LOG_TRIVIAL(debug) << "Initialising game-specific settings.";
            _currentGame->Init(true);
            // Update game path in settings object.
            _settings["games"] = ToGameSettings(_games);
        }
        catch (loot::error &e) {
            if (e.code() == loot::error::no_game_detected) {
                _initErrors.push_back(e.what());
            }
            else {
                BOOST_LOG_TRIVIAL(error) << "Game-specific settings could not be initialised. " << e.what();
                _initErrors.push_back((format(translate("Error: Game-specific settings could not be initialised. %1%")) % e.what()).str());
            }
        }
        BOOST_LOG_TRIVIAL(debug) << "Game selected is " << _currentGame->Name();
    }
Exemplo n.º 26
0
void UIParse::init(wstring str)
{
	infile.open(str.c_str());
	infile.imbue(locale(".936"));
}
Exemplo n.º 27
0
/* SUPER ROUTES */
void mMain::s_locale(){
  tr.setLocale(locale());

  rewrite(route.get("1","/"));
}
Exemplo n.º 28
0
void UIParse::load_the_txt(wstring filename)
{
	infile.close();
	infile.open(filename.c_str());
	infile.imbue(locale(".936"));
}
Exemplo n.º 29
0
OptionsDialog::OptionsDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::OptionsDialog),
    model(0),
    mapper(0),
    fRestartWarningDisplayed_Proxy(false),
    fRestartWarningDisplayed_Lang(false),
    fProxyIpValid(true)
{
    ui->setupUi(this);

    /* Network elements init */
#ifndef USE_UPNP
    ui->mapPortUpnp->setEnabled(false);
#endif

    ui->socksVersion->setEnabled(false);
    ui->socksVersion->addItem("5", 5);
    ui->socksVersion->addItem("4", 4);
    ui->socksVersion->setCurrentIndex(0);

    ui->proxyIp->setEnabled(false);
    ui->proxyPort->setEnabled(false);
    ui->proxyPort->setValidator(new QIntValidator(0, 65535, this));

    connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool)));
    connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));
    connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));

    ui->proxyIp->installEventFilter(this);

    /* Window elements init */
#ifdef Q_WS_MAC
    ui->tabWindow->setVisible(false);
#endif

    /* Display elements init */
    QDir translations(":translations");
    ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
    foreach(const QString &langStr, translations.entryList())
    {
        QLocale locale(langStr);

        /** check if the locale name consists of 2 parts (language_country) */
        if(langStr.contains("_"))
        {
#if QT_VERSION >= 0x040800
            /** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */
            ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
            /** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */
            ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
        }
        else
        {
#if QT_VERSION >= 0x040800
            /** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */
            ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
            /** display language strings as "language (locale name)", e.g. "German (de)" */
            ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
        }
    }

    ui->unit->setModel(new BitcoinUnits(this));

    connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy()));
    connect(ui->lang, SIGNAL(activated(int)), this, SLOT(showRestartWarning_Lang()));

    /* Widget-to-option mapper */
    mapper = new MonitoredDataMapper(this);
    mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
    mapper->setOrientation(Qt::Vertical);

    /* enable save buttons when data modified */
    connect(mapper, SIGNAL(viewModified()), this, SLOT(enableSaveButtons()));
    /* disable save buttons when new data loaded */
    connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableSaveButtons()));
    /* disable/enable save buttons when proxy IP is invalid/valid */
    connect(this, SIGNAL(proxyIpValid(bool)), this, SLOT(setSaveButtonState(bool)));
}
Exemplo n.º 30
0
Arquivo: test.cpp Projeto: leezh/nrex
int main()
{
    ifstream file("test.txt");
    if (!file.is_open())
    {
        std::cout << "could not find test.txt" << std::endl;
        return -2;
    }

    int tests = 0;
    int passed = 0;
    int line_number = 0;

    std::locale locale(std::locale::classic(), new ctype);

    nrex n;
    std::cout << "==================" << std::endl;
    while (!file.eof())
    {
        string line;
        std::getline(file, line);
        line_number++;
        if (line.length() == 0 || line.at(0) == '#')
        {
            continue;
        }

        isstream stream(line);
        stream.imbue(locale);

        string pattern;
        stream >> pattern;
        tests++;
        std::cout << "Line " << line_number << std::endl;

        int captures = 0;
        stream >> captures;

        n.compile(pattern.c_str());
        if (n.capture_size() != captures)
        {
            std::cout << "    FAILED (Compile)" << std::endl;
            continue;
        }

        if (captures == 0)
        {
            std::cout << "    OK" << std::endl;
            passed++;
            continue;
        }

        string text;
        stream >> text;
        if (text.length() == 1 && text.at(0) == '#')
        {
            text.clear();
        }
        nrex_result* results = new nrex_result[captures];
        bool found = n.match(text.c_str(), results);

        bool failed = false;

        int position;
        stream >> position;
        if ((position >= 0) != found || (found && position != results[0].start))
        {
            failed = true;
            std::cout << "    Mismatched starting positions. Expected: ";
            std::cout << position << " Got: " << results[0].start << std::endl;
        }

        for (int i = 0; i < captures; i++)
        {
            string result;
            stream >> result;

            if (result.length() == 1 && result.at(0) == '#')
            {
                result.clear();
            }

            std::string capture;
            if (results[i].length != 0)
            {
                capture = text.substr(results[i].start, results[i].length);
            }

            if (capture != result)
            {
                failed = true;
                std::cout << "    Mismatched results. Expected: '" << result;
                std::cout << "'' Got: '" << capture << "'" << std::endl;
            }
        }

        if (!failed)
        {
            std::cout << "    OK" << std::endl;
            passed++;
        }
        else
        {
            std::cout << "    FAILED (Tests)" << std::endl;
        }

        delete[] results;
    }
    std::cout << "==================" << std::endl;
    std::cout << "Tests: " << tests << std::endl;
    std::cout << "Successes: " << passed << std::endl;
    std::cout << "Failed: " << tests - passed << std::endl;
    if (tests != passed)
    {
        return -1;
    }
    return 0;
}