Esempio n. 1
0
double ScrSpinBox::valueFromText ( const QString & text ) const
{
	//Get all our units strings
//CB: Replaced by new CommonStrings versions
// 	QString trStrPT=unitGetStrFromIndex(SC_PT);
// 	QString trStrMM=unitGetStrFromIndex(SC_MM);
// 	QString trStrIN=unitGetStrFromIndex(SC_IN);
// 	QString trStrP =unitGetStrFromIndex(SC_P);
// 	QString trStrCM=unitGetStrFromIndex(SC_CM);
// 	QString trStrC =unitGetStrFromIndex(SC_C);
// 	QString strPT=unitGetUntranslatedStrFromIndex(SC_PT);
// 	QString strMM=unitGetUntranslatedStrFromIndex(SC_MM);
// 	QString strIN=unitGetUntranslatedStrFromIndex(SC_IN);
// 	QString strP =unitGetUntranslatedStrFromIndex(SC_P);
// 	QString strCM=unitGetUntranslatedStrFromIndex(SC_CM);
// 	QString strC =unitGetUntranslatedStrFromIndex(SC_C);
	//Get a copy for use
	QString ts = text.trimmed();
	//Find our suffix
	QString su(unitGetStrFromIndex(m_unitIndex));
	//Replace our pica XpY.Z format with (X*12+Y.Z)pt
	if (CommonStrings::trStrP.localeAwareCompare(CommonStrings::strP)!=0)
		ts.replace(CommonStrings::trStrP, CommonStrings::strP);
	QRegExp rxP;
	if (m_unitIndex==SC_PICAS)
		rxP.setPattern("\\b(\\d+)"+CommonStrings::strP+"?(\\d+\\.?\\d*)?\\b");
	else
		rxP.setPattern("\\b(\\d+)"+CommonStrings::strP+"(\\d+\\.?\\d*)?\\b");
	int posP = 0;
	while (posP >= 0)
	{
// 		qDebug() << "#";
		posP = rxP.indexIn(ts, posP);
		if (posP >= 0)
		{
// 			qDebug() << rxP.cap(1);
// 			qDebug() << rxP.cap(2);
			QString replacement = QString("%1%2").arg(rxP.cap(1).toDouble()*(static_cast<double>(unitGetBaseFromIndex(SC_PICAS))) + rxP.cap(2).toDouble()).arg(CommonStrings::strPT);
			ts.replace(posP, rxP.cap(0).length(), replacement);
// 			qDebug() << ts;
		}
	}
// 	qDebug() << "##" << ts;
	
	ts.replace(",", ".");
	ts.replace("%", "");
	ts.replace("°", "");
	ts.replace(FinishTag, "");
	ts = ts.trimmed();

	if (ts.endsWith(su))
		ts = ts.left(ts.length()-su.length());
	int pos = ts.length();
	while (pos > 0)
	{
		pos = ts.lastIndexOf(".", pos);
		if (pos >= 0) 
		{
			if (pos < static_cast<int>(ts.length()))
			{
				if (!ts[pos+1].isDigit())
					ts.insert(pos+1, "0 ");
			}
			pos--;
		}
	}
	if (ts.endsWith("."))
		ts.append("0");
	//CB FParser doesn't handle unicode well/at all.
	//So, instead of just getting the translated strings and
	//sticking them in as variables in the parser, if they are
	//not the same as the untranslated version, then we replace them.
	//We lose the ability for now to have some strings in languages 
	//that might use them in variables.
	//To return to previous functionality, remove the follow replacement ifs,
	//S&R in the trStr* assignments trStrPT->strPT and remove the current str* ones. 
	//IE, send the translated strings through to the regexp.
	if (CommonStrings::trStrPT.localeAwareCompare(CommonStrings::strPT)!=0)
		ts.replace(CommonStrings::trStrPT, CommonStrings::strPT);
	if (CommonStrings::trStrMM.localeAwareCompare(CommonStrings::strMM)!=0)
		ts.replace(CommonStrings::trStrMM, CommonStrings::strMM);
	if (CommonStrings::trStrIN.localeAwareCompare(CommonStrings::strIN)!=0)
		ts.replace(CommonStrings::trStrIN, CommonStrings::strIN);
	if (CommonStrings::trStrCM.localeAwareCompare(CommonStrings::strCM)!=0)
		ts.replace(CommonStrings::trStrCM, CommonStrings::strCM);
	if (CommonStrings::trStrC.localeAwareCompare(CommonStrings::trStrC)!=0)
		ts.replace(CommonStrings::trStrC, CommonStrings::strC);
	//Replace in our typed text all of the units strings with *unitstring
	QRegExp rx("\\b(\\d+)\\s*("+CommonStrings::strPT+"|"+CommonStrings::strMM+"|"+CommonStrings::strC+"|"+CommonStrings::strCM+"|"+CommonStrings::strIN+")\\b");
	pos = 0;
	while (pos >= 0) {
		pos = rx.indexIn(ts, pos);
		if (pos >= 0) {
			QString replacement = rx.cap(1) + "*" + rx.cap(2);
			ts.replace(pos, rx.cap(0).length(), replacement);
		}
	}

	//Add in the fparser constants using our unit strings, and the conversion factors.
	FunctionParser fp;
// 	setFPConstants(fp);
	fp.AddConstant(CommonStrings::strPT.toStdString(), value2value(1.0, SC_PT, m_unitIndex));
	fp.AddConstant(CommonStrings::strMM.toStdString(), value2value(1.0, SC_MM, m_unitIndex));
	fp.AddConstant(CommonStrings::strIN.toStdString(), value2value(1.0, SC_IN, m_unitIndex));
	fp.AddConstant(CommonStrings::strP.toStdString(), value2value(1.0, SC_P, m_unitIndex));
	fp.AddConstant(CommonStrings::strCM.toStdString(), value2value(1.0, SC_CM, m_unitIndex));
	fp.AddConstant(CommonStrings::strC.toStdString(), value2value(1.0, SC_C, m_unitIndex));

	fp.AddConstant("old", value());
	if (m_constants)
	{
		QMap<QString, double>::ConstIterator itend = m_constants->constEnd();
		QMap<QString, double>::ConstIterator it = m_constants->constBegin();
		while(it != itend)
		{
			fp.AddConstant(it.key().toStdString(), it.value() * unitGetRatioFromIndex(m_unitIndex));
			++it;
		}
	}
	
	int ret = fp.Parse(ts.toStdString(), "", true);
//	qDebug() << "fp return =" << ret;
	if (ret >= 0)
		return 0;
	double erg = fp.Eval(NULL);
//	qDebug() << "fp value =" << erg;
	return erg;
}
bool DocumentNumeratorController::isSameFormat()
{
    QRegExp rx;
    rx.setPattern(formatPattern);
    return rx.exactMatch(previousSymbolStr);
}
Esempio n. 3
0
bool StyleData::setStyle(const char* s, const char* styleName)
{
  static const QRegExp subgroup("^{[^}]*}\\s*");
  static const QRegExp any_clause("^\\\\[a-z][a-z0-9-]*\\s*");

  int len = 0;     // length of a particular RTF formatting control
  int ref_len = 0; // length of the whole formatting section of a style
  int start = s_clause.match(s, 0, &len);
  if (start < 0)
  {
    err("Style sheet '%s' contains no '\\s' clause.\n{%s}\n", styleName, s);
    return FALSE;
  }
  s += start;
  index = (int)atol(s + 2); ASSERT(index > 0);

  // search for the end of pure formatting codes
  const char* end = s + len;
  ref_len = len;
  bool haveNewDefinition = TRUE;
  for(;;)
  {
    if (*end == '{')
    {
      // subgroups are used for \\additive
      if (0 != subgroup.match(end, 0, &len))
        break;
      else
      {
        end += len;
        ref_len += len;
      }
    }
    else if (*end == '\\')
    {
      if (0 == qstrncmp(end, "\\snext", 6))
        break;
      if (0 == qstrncmp(end, "\\sbasedon", 9))
        break;
      if (0 != any_clause.match(end, 0, &len))
        break;
      end += len;
      ref_len += len;
    }
    else if (*end == 0)
    { // no style-definition part, keep default value
      haveNewDefinition = FALSE;
      break;
    }
    else // plain name without leading \\snext
      break;
  }
  delete[] reference;
  reference = new char[ref_len + 1];
  memcpy(reference, s, ref_len); 
  reference[ref_len] = 0;
  if (haveNewDefinition)
  {
    delete[] definition;
    size_t size = 1 + strlen(end);
    definition = new char[size];
    memcpy(definition, end, size);
  }
  return TRUE;
}
Esempio n. 4
0
// -------------------------------------------------------
QString VHDL_File_Info::parseGenerics(QString s, int j)
{
  QRegExp Expr;
  Expr.setCaseSensitive(false);
  int i, p, l, k, n;

  Expr.setPattern("\\bgeneric\\b");
  i = s.find(Expr, j+1);
  if(i < 0)
    return QString("");
  // find opening (
  i = s.find('(', i+4) + 1;
  if(i <= 0)
    return QString("");

  // find closing (
  p = i;
  j = i-1;
  do {
    j = s.find(')', j+1);
    if(j < 0)
      return QString("");
    p = s.find('(', p+1);
    if(p >= 0 && p > j) p = -1;
  } while (p >= 0);

  s = s.mid(i, j-i);
  s.remove('\n');
  s.remove('\t');

  // find generic names, types and defaults in parameter specification
  l = i = 0;
  QString types = "", t, defs = "", d;
  while((i=s.find(':', i)) >= 0) {
    j = s.find(';', i+2);
    n = s.find(":=", i+2);
    d = "";
    if(n >= 0 && (n < j || j < 0) ) {
      j = s.find(';', n+2);
      if(j < 0) {
	d = s.mid(n+2);
	d = d.simplifyWhiteSpace();
	s = s.left(n);
      } else {
	d = s.mid(n+2, j-n-1);
	d.remove(';');
	d = d.simplifyWhiteSpace();
	s.remove(n, j-n);
      }
      j = s.find(';', n);
    }
    if(j < 0) {
      t = s.mid(i+1);
      t.remove(';');
      t = t.simplifyWhiteSpace();
      s = s.left(i);
    } else {
      t = s.mid(i+1, j-i);
      t.remove(';');
      t = t.simplifyWhiteSpace();
      s.remove(i, j-i);
    }
    if ((k = t.find(' ')) >= 0)
      t = t.mid(k+1);
    t = t.simplifyWhiteSpace();
    k = s.find(';',l+2);
    k = (s.mid(l,k-l).count(',')) + 1;
    while (k-->0) {
      types = types + t + ",";
      defs = defs + d + ",";
    }
    i--;
    l = i;
  }

  s.remove(' ');
  s.replace(';', ',');
  GenTypes=types=types.left(types.length()-1);
  GenDefs=defs=defs.left(defs.length()-1);
  return s;
}
Esempio n. 5
0
static bool idContainsWrongLetter(const QString& id)
{
    static QRegExp idExpr(QStringLiteral("[a-z_][a-zA-Z0-9_]*"));
    return !idExpr.exactMatch(id);
}
Esempio n. 6
0
void AlbumPropsEdit::slotTitleChanged(const QString& newtitle)
{
    QRegExp emptyTitle = QRegExp("^\\s*$");
    bool enable = (!emptyTitle.exactMatch(newtitle) && !newtitle.isEmpty());
    enableButtonOk(enable);
}
Esempio n. 7
0
// -------------------------------------------------------
VHDL_File_Info::VHDL_File_Info(QString File, bool isfile)
{
  if (isfile) {
    QFile f(File);
    if(!f.open(QIODevice::ReadOnly))
      File = "";
    else {
      QByteArray FileContent = f.readAll();
      File = QString(FileContent);
    }
    f.close();
  }
  
  QString s;
  PortNames = "";
  int i=0, j, k=0;
  while((i=File.find("--", i)) >= 0) { // remove all VHDL comments
    j = File.find('\n', i+2);          // This also finds "--" within a ...
    if(j < 0)                          // string, but as no strings are ...
      File = File.left(i);             // allowed in entity headers, it ...
    else                               // does not matter.
      File.remove(i, j-i);
  }

  QRegExp Expr;
  Expr.setCaseSensitive(false);
  for(;;) {
    k--;
    Expr.setPattern("\\bentity\\b");  // start of last entity
    k = File.findRev(Expr, k);
    if(k < 0)
      return;

    Expr.setPattern("\\bend\\b");    // end of last entity
    i = File.find(Expr, k+7);
    if(i < 0)
      return;
    s = File.mid(k+7, i-k-7);  // cut out entity declaration

    Expr.setPattern("\\b");
    i = s.find(Expr);
    if(i < 0)
      return;
    j = s.find(Expr, i+1);
    if(j < 0)
      return;
    EntityName = s.mid(i, j-i);  // save entity name

    i = s.find(Expr, j+1);
    if(i < 0)
      return;
    j = s.find(Expr, i+1);
    if(j < 0)
      return;
    if(s.mid(i, j-i).lower() == "is")   // really found start of entity ?
      break;

    if(k < 1)    // already searched the whole text
      return;
  }

  // parse ports, i.e. network connections; and generics, i.e. parameters
  GenNames = parseGenerics(s,j);
  PortNames = parsePorts(s,j);
}
QgsProviderRegistry::QgsProviderRegistry( const QString& pluginPath )
{
    // At startup, examine the libs in the qgis/lib dir and store those that
    // are a provider shared lib
    // check all libs in the current plugin directory and get name and descriptions
    //TODO figure out how to register and identify data source plugin for a specific
    //TODO layer type
#if 0
    char **argv = qApp->argv();
    QString appDir = argv[0];
    int bin = appDir.findRev( "/bin", -1, false );
    QString baseDir = appDir.left( bin );
    QString mLibraryDirectory = baseDir + "/lib";
#endif
    mLibraryDirectory = pluginPath;
    mLibraryDirectory.setSorting( QDir::Name | QDir::IgnoreCase );
    mLibraryDirectory.setFilter( QDir::Files | QDir::NoSymLinks );

#if defined(Q_OS_WIN) || defined(__CYGWIN__)
    mLibraryDirectory.setNameFilters( QStringList( "*.dll" ) );
#elif ANDROID
    mLibraryDirectory.setNameFilters( QStringList( "*provider.so" ) );
#else
    mLibraryDirectory.setNameFilters( QStringList( "*.so" ) );
#endif

    QgsDebugMsg( QString( "Checking %1 for provider plugins" ).arg( mLibraryDirectory.path() ) );

    if ( mLibraryDirectory.count() == 0 )
    {
        QString msg = QObject::tr( "No QGIS data provider plugins found in:\n%1\n" ).arg( mLibraryDirectory.path() );
        msg += QObject::tr( "No vector layers can be loaded. Check your QGIS installation" );

        QgsMessageOutput* output = QgsMessageOutput::createMessageOutput();
        output->setTitle( QObject::tr( "No Data Providers" ) );
        output->setMessage( msg, QgsMessageOutput::MessageText );
        output->showMessage();
        return;
    }

    // provider file regex pattern, only files matching the pattern are loaded if the variable is defined
    QString filePattern = getenv( "QGIS_PROVIDER_FILE" );
    QRegExp fileRegexp;
    if ( !filePattern.isEmpty() )
    {
        fileRegexp.setPattern( filePattern );
    }

    QListIterator<QFileInfo> it( mLibraryDirectory.entryInfoList() );
    while ( it.hasNext() )
    {
        QFileInfo fi( it.next() );

        if ( !fileRegexp.isEmpty() )
        {
            if ( fileRegexp.indexIn( fi.fileName() ) == -1 )
            {
                QgsDebugMsg( "provider " + fi.fileName() + " skipped because doesn't match pattern " + filePattern );
                continue;
            }
        }

        QLibrary myLib( fi.filePath() );
        if ( !myLib.load() )
        {
            QgsDebugMsg( QString( "Checking %1: ...invalid (lib not loadable): %2" ).arg( myLib.fileName() ).arg( myLib.errorString() ) );
            continue;
        }

        //MH: Added a further test to detect non-provider plugins linked to provider plugins.
        //Only pure provider plugins have 'type' not defined
        isprovider_t *hasType = ( isprovider_t * ) cast_to_fptr( myLib.resolve( "type" ) );
        if ( hasType )
        {
            QgsDebugMsg( QString( "Checking %1: ...invalid (has type method)" ).arg( myLib.fileName() ) );
            continue;
        }

        // get the description and the key for the provider plugin
        isprovider_t *isProvider = ( isprovider_t * ) cast_to_fptr( myLib.resolve( "isProvider" ) );
        if ( !isProvider )
        {
            QgsDebugMsg( QString( "Checking %1: ...invalid (no isProvider method)" ).arg( myLib.fileName() ) );
            continue;
        }

        // check to see if this is a provider plugin
        if ( !isProvider() )
        {
            QgsDebugMsg( QString( "Checking %1: ...invalid (not a provider)" ).arg( myLib.fileName() ) );
            continue;
        }

        // looks like a provider. get the key and description
        description_t *pDesc = ( description_t * ) cast_to_fptr( myLib.resolve( "description" ) );
        if ( !pDesc )
        {
            QgsDebugMsg( QString( "Checking %1: ...invalid (no description method)" ).arg( myLib.fileName() ) );
            continue;
        }

        providerkey_t *pKey = ( providerkey_t * ) cast_to_fptr( myLib.resolve( "providerKey" ) );
        if ( !pKey )
        {
            QgsDebugMsg( QString( "Checking %1: ...invalid (no providerKey method)" ).arg( myLib.fileName() ) );
            continue;
        }

        // add this provider to the provider map
        mProviders[pKey()] = new QgsProviderMetadata( pKey(), pDesc(), myLib.fileName() );

        // load database drivers
        databaseDrivers_t *pDatabaseDrivers = ( databaseDrivers_t * ) cast_to_fptr( myLib.resolve( "databaseDrivers" ) );
        if ( pDatabaseDrivers )
        {
            mDatabaseDrivers = pDatabaseDrivers();
        }

        // load directory drivers
        directoryDrivers_t *pDirectoryDrivers = ( directoryDrivers_t * ) cast_to_fptr( myLib.resolve( "directoryDrivers" ) );
        if ( pDirectoryDrivers )
        {
            mDirectoryDrivers = pDirectoryDrivers();
        }

        // load protocol drivers
        protocolDrivers_t *pProtocolDrivers = ( protocolDrivers_t * ) cast_to_fptr( myLib.resolve( "protocolDrivers" ) );
        if ( pProtocolDrivers )
        {
            mProtocolDrivers = pProtocolDrivers();
        }

        // now get vector file filters, if any
        fileVectorFilters_t *pFileVectorFilters = ( fileVectorFilters_t * ) cast_to_fptr( myLib.resolve( "fileVectorFilters" ) );
        if ( pFileVectorFilters )
        {
            QString fileVectorFilters = pFileVectorFilters();

            if ( !fileVectorFilters.isEmpty() )
                mVectorFileFilters += fileVectorFilters;

            QgsDebugMsg( QString( "Checking %1: ...loaded ok (%2 file filters)" ).arg( myLib.fileName() ).arg( fileVectorFilters.split( ";;" ).count() ) );
        }

        // now get raster file filters, if any
        // this replaces deprecated QgsRasterLayer::buildSupportedRasterFileFilter
        buildsupportedrasterfilefilter_t *pBuild =
            ( buildsupportedrasterfilefilter_t * ) cast_to_fptr( myLib.resolve( "buildSupportedRasterFileFilter" ) );
        if ( pBuild )
        {
            QString fileRasterFilters;
            pBuild( fileRasterFilters );

            QgsDebugMsg( "raster filters: " + fileRasterFilters );
            if ( !fileRasterFilters.isEmpty() )
                mRasterFileFilters += fileRasterFilters;

            QgsDebugMsg( QString( "Checking %1: ...loaded ok (%2 file filters)" ).arg( myLib.fileName() ).arg( fileRasterFilters.split( ";;" ).count() ) );
        }
    }
} // QgsProviderRegistry ctor
Esempio n. 9
0
void ScenarioHighlighter::applyCommentStyle(const QString &, const QRegExp &reg)
{
    this->setFormat(0, reg.cap(0).size(), QColor("#228b22"));
    this->setCurrentBlockState(STATE_COMMENT);
}
Esempio n. 10
0
void SourceHighlighter::highlightBlock(const QString &text)
{
    int state = previousBlockState();
    int len = text.length();
    int start = 0;
    int pos = 0;
    QRegExp regex;

    while (pos >= 0 && pos < len && len > 0) {
        switch (state) {
        default:
        case Normal:
            regex.setPattern(QLatin1String("[<&]"));
            pos = regex.indexIn(text, pos);
            if (pos >= 0) {
                if (text.at(pos) == QLatin1Char('<')) {
                    start = pos;
                    if (text.mid(pos, 4) == QLatin1String("<!--")) {
                        state = InComment;
                    } else {
                        state = InTag;
                    }
                    ++pos;
                } else if (text.at(pos) == QLatin1Char('&')) {
                    regex.setPattern(QLatin1String("&[a-zA-Z0-9]+;"));
                    if (regex.indexIn(text, pos) == pos) {
                        setFormat(pos, regex.matchedLength(), formats[Entity]);
                    }
                    ++pos;
                }
            }
            break;
        case InComment:
            regex.setPattern(QLatin1String("-->"));
            pos = regex.indexIn(text, pos);
            if (pos >= 0) {
                state = Normal;
                pos += 3;
                setFormat(start, pos - start, formats[Comment]);
                ++pos;
            } else {
                setFormat(start, len - start, formats[Comment]);
            }
            break;
         case InTag:
            regex.setPattern(QLatin1String("[>\"]"));
            pos = regex.indexIn(text, pos);
            if (pos >= 0) {
                if (text.at(pos) == QLatin1Char('>')) {
                    state = Normal;
                    ++pos;
                    setFormat(start, pos - start, formats[Tag]);
                } else if (text.at(pos) == QLatin1Char('"')) {
                    setFormat(start, pos - start, formats[Tag]);
                    start = pos;
                    state = InAttribute;
                    ++pos;
                }
            } else {
                setFormat(start, len-start, formats[Tag]);
            }
            break;
        case InAttribute:
            regex.setPattern(QLatin1String("\""));
            pos = regex.indexIn(text, pos);
            if (pos >= 0) {
                setFormat(start, pos - start, formats[Attribute]);
                state = InTag;
                start = ++pos;
            } else {
                setFormat(start, len - start, formats[Attribute]);
            }
            break;
        }
    }
    setCurrentBlockState(state);
}
Esempio n. 11
0
bool StringReplacerProc::init(KConfig* c, const QString& configGroup){
    //kDebug() << "StringReplacerProc::init: Running";
    QString wordsFilename =
        KGlobal::dirs()->saveLocation( "data" ,QLatin1String( "kttsd/stringreplacer/" ), false );
    if ( wordsFilename.isEmpty() ) return false;
    wordsFilename += configGroup;
    KConfigGroup config( c, configGroup );
    wordsFilename = config.readEntry( "WordListFile", wordsFilename );

    // Open existing word list.
    QFile file( wordsFilename );
    if ( !file.open( QIODevice::ReadOnly ) )
    {
        //kDebug() << "StringReplacerProc::init: couldn't open file " << wordsFilename;
        return false;
    }
    QDomDocument doc( QLatin1String( "" ) );
    if ( !doc.setContent( &file ) ) {
        //kDebug() << "StringReplacerProc::init: couldn't get xml from file " << wordsFilename;
        file.close();
        return false;
    }
    file.close();

    // Clear list.
    m_matchList.clear();
    m_substList.clear();

    // Name setting.
    // QDomNodeList nameList = doc.elementsByTagName( "name" );
    // QDomNode nameNode = nameList.item( 0 );
    // m_widget->nameLineEdit->setText( nameNode.toElement().text() );

    // Language Codes setting.  List may be single element of comma-separated values,
    // or multiple elements.
    m_languageCodeList.clear();
    QDomNodeList languageList = doc.elementsByTagName( QLatin1String( "language-code" ) );
    for ( int ndx=0; ndx < languageList.count(); ++ndx )
    {
        QDomNode languageNode = languageList.item( ndx );
        m_languageCodeList += languageNode.toElement().text().split( QLatin1Char(','), QString::SkipEmptyParts);
    }

    // AppId.  Apply this filter only if DCOP appId of application that queued
    // the text contains this string.  List may be single element of comma-separated values,
    // or multiple elements.
    m_appIdList.clear();
    QDomNodeList appIdList = doc.elementsByTagName( QLatin1String( "appid" ) );
    for ( int ndx=0; ndx < appIdList.count(); ++ndx )
    {
        QDomNode appIdNode = appIdList.item( ndx );
        m_appIdList += appIdNode.toElement().text().split( QLatin1Char( ',' ), QString::SkipEmptyParts);
    }

    // Word list.
    QDomNodeList wordList = doc.elementsByTagName(QLatin1String( "word" ) );
    const int wordListCount = wordList.count();
    for (int wordIndex = 0; wordIndex < wordListCount; ++wordIndex)
    {
        QDomNode wordNode = wordList.item(wordIndex);
        QDomNodeList propList = wordNode.childNodes();
        QString wordType;
        QString matchCase = QLatin1String( "No" ); // Default for old (v<=3.5.3) config files with no <case/>.
        QString match;
        QString subst;
        const int propListCount = propList.count();
        for (int propIndex = 0; propIndex < propListCount; ++propIndex)
        {
            QDomNode propNode = propList.item(propIndex);
            QDomElement prop = propNode.toElement();
            if (prop.tagName() == QLatin1String( "type" )) wordType = prop.text();
            if (prop.tagName() == QLatin1String( "case" )) matchCase = prop.text();
            if (prop.tagName() == QLatin1String( "match" ))
            {
                match = prop.text();
                cdataUnescape( &match );
            }
            if (prop.tagName() == QLatin1String( "subst" ))
            {
                subst = prop.text();
                cdataUnescape( &subst );
            }
        }
        // Build Regular Expression for each word's match string.
        QRegExp rx;
        rx.setCaseSensitivity(matchCase == QLatin1String( "Yes" )?Qt::CaseInsensitive:Qt::CaseSensitive);
        if ( wordType == QLatin1String( "Word" ) )
        {
                // TODO: Does \b honor strange non-Latin1 encodings?
            rx.setPattern( QLatin1String( "\\b" ) + match + QLatin1String( "\\b" ) );
        }
        else
        {
            rx.setPattern( match );
        }
            // Add Regular Expression to list (if valid).
        if ( rx.isValid() )
        {
            m_matchList.append( rx );
            m_substList.append( subst );
        }
    }
    return true;
}
Esempio n. 12
0
void SyntaxHighlighter::loadConfiguration(const QString &filename)
{
	if(filename!="")
	{
		attribs_map attribs;
		QString elem, expr_type, group;
		bool groups_decl=false, chr_sensitive=false,
				bold=false, italic=false,
				underline=false, partial_match=false;
		QTextCharFormat format;
		QRegExp regexp;
		QColor bg_color, fg_color;
		vector<QString>::iterator itr, itr_end;

		try
		{
			clearConfiguration();
			XMLParser::restartParser();
			XMLParser::setDTDFile(GlobalAttributes::CONFIGURATIONS_DIR +
														GlobalAttributes::DIR_SEPARATOR +
														GlobalAttributes::OBJECT_DTD_DIR +
														GlobalAttributes::DIR_SEPARATOR +
														GlobalAttributes::CODE_HIGHLIGHT_CONF +
														GlobalAttributes::OBJECT_DTD_EXT,
														GlobalAttributes::CODE_HIGHLIGHT_CONF);

			XMLParser::loadXMLFile(filename);

			if(XMLParser::accessElement(XMLParser::CHILD_ELEMENT))
			{
				do
				{
					if(XMLParser::getElementType()==XML_ELEMENT_NODE)
					{
						elem=XMLParser::getElementName();

						if(elem==ParsersAttributes::WORD_SEPARATORS)
						{
							XMLParser::getElementAttributes(attribs);
							word_separators=attribs[ParsersAttributes::VALUE];
						}
						else if(elem==ParsersAttributes::WORD_DELIMITERS)
						{
							XMLParser::getElementAttributes(attribs);
							word_delimiters=attribs[ParsersAttributes::VALUE];
						}
						else if(elem==ParsersAttributes::IGNORED_CHARS)
						{
							XMLParser::getElementAttributes(attribs);
							ignored_chars=attribs[ParsersAttributes::VALUE];
						}
						else if(elem==ParsersAttributes::COMPLETION_TRIGGER)
						{
							XMLParser::getElementAttributes(attribs);

							if(attribs[ParsersAttributes::VALUE].size() >= 1)
								completion_trigger=attribs[ParsersAttributes::VALUE].at(0);
						}

						/*	If the element is what defines the order of application of the groups
								highlight in the (highlight-order). Is in this block that are declared
								the groups used to highlight the source code. ALL groups
								in this block must be declared before they are built
								otherwise an error will be triggered. */
						else if(elem==ParsersAttributes::HIGHLIGHT_ORDER)
						{
							//Marks a flag indication that groups are being declared
							groups_decl=true;
							XMLParser::savePosition();
							XMLParser::accessElement(XMLParser::CHILD_ELEMENT);
							elem=XMLParser::getElementName();
						}

						if(elem==ParsersAttributes::GROUP)
						{
							XMLParser::getElementAttributes(attribs);
							group=attribs[ParsersAttributes::NAME];

							/* If the parser is on the group declaration block and not in the build block
								 some validations are made. */
							if(groups_decl)
							{
								//Raises an error if the group was declared before
								if(find(groups_order.begin(), groups_order.end(), group)!=groups_order.end())
								{
									throw Exception(Exception::getErrorMessage(ERR_REDECL_HL_GROUP).arg(group),
																	ERR_REDECL_HL_GROUP,__PRETTY_FUNCTION__,__FILE__,__LINE__);
								}
								//Raises an error if the group is being declared and build at the declaration statment (not permitted)
								else if(attribs.size() > 1 || XMLParser::hasElement(XMLParser::CHILD_ELEMENT))
								{
									throw Exception(Exception::getErrorMessage(ERR_DEF_INV_GROUP_DECL)
																	.arg(group).arg(ParsersAttributes::HIGHLIGHT_ORDER),
																	ERR_REDECL_HL_GROUP,__PRETTY_FUNCTION__,__FILE__,__LINE__);
								}

								groups_order.push_back(group);
							}
							//Case the parser is on the contruction block and not in declaration of groups
							else
							{
								//Raises an error if the group is being constructed by a second time
								if(initial_exprs.count(group)!=0)
								{
									throw Exception(Exception::getErrorMessage(ERR_DEF_DUPLIC_GROUP).arg(group),
																	ERR_DEF_DUPLIC_GROUP,__PRETTY_FUNCTION__,__FILE__,__LINE__);
								}
								//Raises an error if the group is being constructed without being declared
								else if(find(groups_order.begin(), groups_order.end(), group)==groups_order.end())
								{
									throw Exception(Exception::getErrorMessage(ERR_DEF_NOT_DECL_GROUP)
																	.arg(group).arg(ParsersAttributes::HIGHLIGHT_ORDER),
																	ERR_DEF_NOT_DECL_GROUP,__PRETTY_FUNCTION__,__FILE__,__LINE__);
								}
								//Raises an error if the group does not have children element
								else if(!XMLParser::hasElement(XMLParser::CHILD_ELEMENT))
								{
									throw Exception(Exception::getErrorMessage(ERR_DEF_EMPTY_GROUP).arg(group),
																	ERR_DEF_EMPTY_GROUP,__PRETTY_FUNCTION__,__FILE__,__LINE__);
								}

								chr_sensitive=(attribs[ParsersAttributes::CASE_SENSITIVE]==ParsersAttributes::_TRUE_);
								italic=(attribs[ParsersAttributes::ITALIC]==ParsersAttributes::_TRUE_);
								bold=(attribs[ParsersAttributes::BOLD]==ParsersAttributes::_TRUE_);
								underline=(attribs[ParsersAttributes::UNDERLINE]==ParsersAttributes::_TRUE_);
								partial_match=(attribs[ParsersAttributes::PARTIAL_MATCH]==ParsersAttributes::_TRUE_);
								fg_color.setNamedColor(attribs[ParsersAttributes::FOREGROUND_COLOR]);

								//If the attribute isn't defined the bg color will be transparent
								if(attribs[ParsersAttributes::BACKGROUND_COLOR].isEmpty())
								 bg_color.setRgb(0,0,0,0);
								else
								 bg_color.setNamedColor(attribs[ParsersAttributes::BACKGROUND_COLOR]);

								if(!attribs[ParsersAttributes::LOOKAHEAD_CHAR].isEmpty())
									lookahead_char[group]=attribs[ParsersAttributes::LOOKAHEAD_CHAR][0];

								format.setFontItalic(italic);
								format.setFontUnderline(underline);

								if(bold)
									format.setFontWeight(QFont::Bold);
								else
									format.setFontWeight(QFont::Normal);

								format.setForeground(fg_color);
								format.setBackground(bg_color);
								formats[group]=format;


								XMLParser::savePosition();
								XMLParser::accessElement(XMLParser::CHILD_ELEMENT);

								if(chr_sensitive)
									regexp.setCaseSensitivity(Qt::CaseSensitive);
								else
									regexp.setCaseSensitivity(Qt::CaseInsensitive);

								this->partial_match[group]=partial_match;

								do
								{
									if(XMLParser::getElementType()==XML_ELEMENT_NODE)
									{
										XMLParser::getElementAttributes(attribs);
										expr_type=attribs[ParsersAttributes::TYPE];
										regexp.setPattern(attribs[ParsersAttributes::VALUE]);

										if(attribs[ParsersAttributes::REGULAR_EXP]==ParsersAttributes::_TRUE_)
											regexp.setPatternSyntax(QRegExp::RegExp2);
										else if(attribs[ParsersAttributes::WILDCARD]==ParsersAttributes::_TRUE_)
											regexp.setPatternSyntax(QRegExp::Wildcard);
										else
											regexp.setPatternSyntax(QRegExp::FixedString);

										if(expr_type=="" ||
											 expr_type==ParsersAttributes::SIMPLE_EXP ||
											 expr_type==ParsersAttributes::INITIAL_EXP)
											initial_exprs[group].push_back(regexp);
										else
											final_exprs[group].push_back(regexp);
									}
								}
								while(XMLParser::accessElement(XMLParser::NEXT_ELEMENT));
								XMLParser::restorePosition();
							}
						}
					}

					/* Check if there are some other groups to be declared, if not,
							continues to reading to the other part of configuration */
					if(groups_decl && !XMLParser::hasElement(XMLParser::NEXT_ELEMENT))
					{
						groups_decl=false;
						XMLParser::restorePosition();
					}

				}
				while(XMLParser::accessElement(XMLParser::NEXT_ELEMENT));
			}

			itr=groups_order.begin();
			itr_end=groups_order.end();

			while(itr!=itr_end)
			{
				group=(*itr);
				itr++;

				if(initial_exprs[group].size()==0)
				{
					//Raises an error if the group was declared but not constructed
					throw Exception(Exception::getErrorMessage(ERR_GROUP_DECL_NOT_DEFINED).arg(group),
													ERR_GROUP_DECL_NOT_DEFINED,__PRETTY_FUNCTION__,__FILE__,__LINE__);
				}
			}

			conf_loaded=true;
		}
		catch(Exception &e)
		{
			throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e);
		}
	}
}
Esempio n. 13
0
QString SyntaxHighlighter::identifyWordGroup(const QString &word, const QChar &lookahead_chr, int idx, int &match_idx, int &match_len)
{
	QRegExp expr;
	vector<QString>::iterator itr, itr_end;
	vector<QRegExp>::iterator itr_exp, itr_exp_end;
	vector<QRegExp> *vet_expr=nullptr;
	QString group;
	bool match=false, part_mach=false;
	MultiLineInfo *info=nullptr;

	//Try to get the multiline info for the current block
	info=getMultiLineInfo(idx, idx, current_block);

	/* Case the highlighter is in the middle of a multiline code block,
		 a different action is executed: check if the current word does not
		 matches with one of final expresion of the group indicating that the
		 group highlighting must be interrupted after the current word */
	if(info)
	{
		group=info->group;

		//Checking if the word is not a highlight ending for the group
		itr_exp=final_exprs[group].begin();
		itr_exp_end=final_exprs[group].end();
		part_mach=partial_match[group];

		while(itr_exp!=itr_exp_end && !match)
		{
			expr=(*itr_exp);

			if(part_mach)
			{
				match_idx=word.indexOf(expr);
				match_len=expr.matchedLength();
				match=(match_idx >= 0);
			}
			else
			{
				if(expr.patternSyntax()==QRegExp::FixedString)
					match=((expr.pattern().compare(word, expr.caseSensitivity())==0));
				else
					match=expr.exactMatch(word);

				if(match)
				{
					match_idx=0;
					match_len=word.length();
				}
			}

			if(match && lookahead_char.count(group) > 0 && lookahead_chr!=lookahead_char.at(group))
				match=false;

			itr_exp++;
		}

		/* If the word matches configures a multiline info with the
			 values retrieved from the regexp matching */
		if(match)
		{
			info->end_col=idx + match_idx + match_len-1;
			info->end_block=current_block;
		}
		else
		{
			match_idx=0;
			match_len=word.length();
		}

		return(group);
	}
	else
	{
		itr=groups_order.begin();
		itr_end=groups_order.end();

		while(itr!=itr_end && !match)
		{
			group=(*itr);
			vet_expr=&initial_exprs[group];
			itr++;

			itr_exp=vet_expr->begin();
			itr_exp_end=vet_expr->end();
			part_mach=partial_match[group];

			while(itr_exp!=itr_exp_end && !match)
			{
				expr=(*itr_exp);

				if(part_mach)
				{
					match_idx=word.indexOf(expr);
					match_len=expr.matchedLength();
					match=(match_idx >= 0);
				}
				else
				{
					if(expr.patternSyntax()==QRegExp::FixedString)
						match=((expr.pattern().compare(word, expr.caseSensitivity())==0));
					else
						match=expr.exactMatch(word);

					if(match)
					{
						match_idx=0;
						match_len=word.length();
					}
				}

				if(match && lookahead_char.count(group) > 0 && lookahead_chr!=lookahead_char.at(group))
					match=false;

				itr_exp++;
			}

			/* Case the word matches with one of group regexp check if this latter
				 has final expressions which indicates that the group treats multiline blocks.
				 This way alocates a info with the initial configurations */
			if(match && final_exprs.count(group))
			{
				if(!info)
				{
					info=new MultiLineInfo;
					info->group=group;
					info->start_col=idx + match_idx + match_len;
					info->start_block=current_block;
					multi_line_infos.push_back(info);
				}
			}
		}

		if(!match) group="";
		return(group);
	}
}
// Check if the current block is inside a "here document" and format it accordingly.
bool Highlighter::isHereDocument (const QString &text)
{
    QTextCharFormat blockFormat;
    blockFormat.setForeground (QColor (126, 0, 230));
    QTextCharFormat delimFormat = blockFormat;
    delimFormat.setFontWeight (QFont::Bold);
    QString delimStr;
    /* Kate uses something like "<<(?:\\s*)([\\\\]{,1}[^\\s]+)" */
    QRegExp delim = QRegExp ("<<(?:\\s*)([\\\\]{,1}[A-Za-z0-9_]+)|<<(?:\\s*)(\'[A-Za-z0-9_]+\')|<<(?:\\s*)(\"[A-Za-z0-9_]+\")");
    int pos, i;

    /* format the start delimiter */
    if (previousBlockState() != delimState - 1
        && currentBlockState() != delimState - 1
        && (pos = delim.indexIn (text)) >= 0)
    {
        i = 1;
        while ((delimStr = delim.cap (i)).isEmpty() && i <= 3)
        {
            ++i;
            delimStr = delim.cap (i);
        }
        /* remove quotes */
        if (delimStr.contains ('\''))
            delimStr = delimStr.split ('\'').at (1);
        if (delimStr.contains ('\"'))
            delimStr = delimStr.split ('\"').at (1);
        /* remove the start backslash if it exists */
        if (QString (delimStr.at (0)) == "\\")
            delimStr = delimStr.remove (0, 1);

        if (!delimStr.isEmpty())
        {
            setCurrentBlockState (delimState);
            setFormat (text.indexOf (delimStr, pos),
                       delimStr.length(),
                       delimFormat);

            TextBlockData *data = static_cast<TextBlockData *>(currentBlock().userData());
            data->insertInfo (delimStr);
            data->insertInfo (true);
            setCurrentBlockUserData (data);

            return false;
        }
    }

    if (previousBlockState() == delimState - 1 || previousBlockState() == delimState)
    {
        QTextBlock block = currentBlock().previous();
        TextBlockData *data = static_cast<TextBlockData *>(block.userData());
        delimStr = data->delimiter();
        if (text == delimStr
            || (text.startsWith (delimStr)
                && text.indexOf (QRegExp ("\\s+")) == delimStr.length()))
        {
            /* format the end delimiter */
            setFormat (0,
                       delimStr.length(),
                       delimFormat);

            /* we need this in docChanged() */
            data = static_cast<TextBlockData *>(currentBlock().userData());
            data->insertInfo (true);
            setCurrentBlockUserData (data);

            return false;
        }
        else
        {
            /* format the contents */
            TextBlockData *data = static_cast<TextBlockData *>(currentBlock().userData());
            data->insertInfo (delimStr);
            setCurrentBlockUserData (data);
            setCurrentBlockState (delimState - 1);
            setFormat (0, text.length(), blockFormat);
            return true;
        }
    }

    return false;
}
Esempio n. 15
0
void ScriptExtender::scanFile(const QString& filename){

	QFile file(filename);
	if (!file.open(QIODevice::ReadOnly | QIODevice::Text )){
		qDebug() << "Error launching script";
		return;
		}
	QString in = file.readAll();

	QRegExp rx;


	rx = QRegExp( "<FILTER>(.+)</FILTER>" );
	rx.setMinimal(true);
	if (!rx.indexIn(in,0))return;
	QString filter = rx.cap(1);

	//for each found function
	rx = QRegExp( "<FUNCTION>(.+)</FUNCTION>" );
	rx.setMinimal(true);
	for (int pos = 0; (pos = rx.indexIn(in, pos)) != -1; pos += rx.matchedLength()) {
		QStringList split = rx.cap(1).split(" ");

		switch (split.size()){
			case 1:
				slotlist << SSlot("",split.at(0), slotlist.size(), QRegExp(filter),filename );
				break;
			case 2:
				slotlist << SSlot(split.at(0), split.at(1),slotlist.size(), QRegExp(filter),filename );
				break;
			default:
			qDebug() << "<FUNCTION>....</FUNCTION> with illegal content";
			}

		}



	rx = QRegExp( "<ACTION>(.+)</ACTION>" );
	rx.setMinimal(true);
	for (int pos = 0; (pos = rx.indexIn(in, pos)) != -1; pos += rx.matchedLength()) {

		QRegExp tx;

		
		tx = QRegExp( "<TEXT>(.+)</TEXT>" );
		if (!tx.indexIn(rx.cap(1),0))return;
		QString text = tx.cap(1);

		tx = QRegExp( "<SLOT>(.+)</SLOT>" );
		if (!tx.indexIn(rx.cap(1),0))return;
		QString slot = tx.cap(1);

		const char** icon = xpm(rx.cap(1));
		actionlist << SAction(icon,text,QString("1%1").arg(slot),QRegExp(filter));

		}

	//qDebug() << " sssssss" <<  SLOT(test());



	}
Esempio n. 16
0
QWidget *VariantDelegate::createEditor(QWidget *parent,
        const QStyleOptionViewItem & /* option */,
        const QModelIndex &index) const
{
    if (index.column() != 2)
        return 0;

    QVariant originalValue = index.model()->data(index, Qt::UserRole);
    if (!isSupportedType(originalValue.type()))
        return 0;

    QLineEdit *lineEdit = new QLineEdit(parent);
    lineEdit->setFrame(false);

    QRegExp regExp;

    switch (originalValue.type()) {
    case QVariant::Bool:
        regExp = boolExp;
        break;
    case QVariant::ByteArray:
        regExp = byteArrayExp;
        break;
    case QVariant::Char:
        regExp = charExp;
        break;
    case QVariant::Color:
        regExp = colorExp;
        break;
    case QVariant::Date:
        regExp = dateExp;
        break;
    case QVariant::DateTime:
        regExp = dateTimeExp;
        break;
    case QVariant::Double:
        regExp = doubleExp;
        break;
    case QVariant::Int:
    case QVariant::LongLong:
        regExp = signedIntegerExp;
        break;
    case QVariant::Point:
        regExp = pointExp;
        break;
    case QVariant::Rect:
        regExp = rectExp;
        break;
    case QVariant::Size:
        regExp = sizeExp;
        break;
    case QVariant::Time:
        regExp = timeExp;
        break;
    case QVariant::UInt:
    case QVariant::ULongLong:
        regExp = unsignedIntegerExp;
        break;
    default:
        ;
    }

    if (!regExp.isEmpty()) {
        QValidator *validator = new QRegExpValidator(regExp, lineEdit);
        lineEdit->setValidator(validator);
    }

    return lineEdit;
}
Esempio n. 17
0
static BtInfo parseBtLine(const QString& line)
{
  int index;

  // the syntax types we support are
  // a) #24 0xb688ff8e in QApplication::notify (this=0xbf997e8c, receiver=0x82607e8, e=0xbf997074) at kernel/qapplication.cpp:3115
  // b) #39 0xb634211c in g_main_context_dispatch () from /usr/lib/libglib-2.0.so.0
  // c) #41 0x0805e690 in ?? ()
  // d) #5  0xffffe410 in __kernel_vsyscall ()


  // try a) cap #number(1), address(2), function(3), filename(4), linenumber(5)
  static QRegExp rxa("^#(\\d+)\\s+(0x\\w+)\\s+in\\s+(.+)\\s+at\\s+(.+):(\\d+)$");
  index = rxa.indexIn(line);
  if (index == 0) {
    BtInfo info;
    info.original = line;
    info.filename = rxa.cap(4);
    info.function = rxa.cap(3);
    info.address = rxa.cap(2);
    info.line = rxa.cap(5).toInt();
    info.step = rxa.cap(1).toInt();
    info.type = BtInfo::Source;
    return info;
  }

  // try b) cap #number(1), address(2), function(3), lib(4)
  static QRegExp rxb("^#(\\d+)\\s+(0x\\w+)\\s+in\\s+(.+)\\s+from\\s+(.+)$");
  index = rxb.indexIn(line);
  if (index == 0) {
    BtInfo info;
    info.original = line;
    info.filename = rxb.cap(4);
    info.function = rxb.cap(3);
    info.address = rxb.cap(2);
    info.line = -1;
    info.step = rxb.cap(1).toInt();
    info.type = BtInfo::Lib;
    return info;
  }

  // try c) #41 0x0805e690 in ?? ()
  static QRegExp rxc("^#(\\d+)\\s+(0x\\w+)\\s+in\\s+\\?\\?\\s+\\(\\)$");
  index = rxc.indexIn(line);
  if (index == 0) {
    BtInfo info;
    info.original = line;
    info.filename = QString();
    info.function = QString();
    info.address = rxc.cap(2);
    info.line = -1;
    info.step = rxc.cap(1).toInt();
    info.type = BtInfo::Unknown;
    return info;
  }

  // try d) #5  0xffffe410 in __kernel_vsyscall ()
  static QRegExp rxd("^#(\\d+)\\s+(0x\\w+)\\s+in\\s+(.+)$");
  index = rxd.indexIn(line);
  if (index == 0) {
    BtInfo info;
    info.original = line;
    info.filename = QString();
    info.function = rxd.cap(3);
    info.address = rxd.cap(2);
    info.line = -1;
    info.step = rxd.cap(1).toInt();
    info.type = BtInfo::Unknown;
    return info;
  }

  kDebug() << "Unknown backtrace line:" << line;

  BtInfo info;
  info.type = BtInfo::Invalid;
  return info;
}
Esempio n. 18
0
bool AssetResourceRequest::urlIsAssetHash() const {
    static const QString ATP_HASH_REGEX_STRING { "^atp:([A-Fa-f0-9]{64})(\\.[\\w]+)?$" };

    QRegExp hashRegex { ATP_HASH_REGEX_STRING };
    return hashRegex.exactMatch(_url.toString());
}
Esempio n. 19
0
Duration Duration::fromString(const QString &s, Format format, bool *ok) {
    if (ok) *ok = false;
    QRegExp matcher;
    Duration tmp;
    switch (format) {
        case Format_Hour: {
            matcher.setPattern("^(\\d*)h(\\d*)m$" );
            int pos = matcher.indexIn(s);
            if (pos > -1) {
                tmp.addHours(matcher.cap(1).toUInt());
                tmp.addMinutes(matcher.cap(2).toUInt());
                if (ok) *ok = true;
            }
            break;
        }
        case Format_DayTime: {
            matcher.setPattern("^(\\d*) (\\d*):(\\d*):(\\d*)\\.(\\d*)$" );
            int pos = matcher.indexIn(s);
            if (pos > -1) {
                tmp.addDays(matcher.cap(1).toUInt());
                tmp.addHours(matcher.cap(2).toUInt());
                tmp.addMinutes(matcher.cap(3).toUInt());
                tmp.addSeconds(matcher.cap(4).toUInt());
                tmp.addMilliseconds(matcher.cap(5).toUInt());
                if (ok) *ok = true;
            }
            break;
        }
        case Format_HourFraction: {
            // should be in double format
            bool res;
            double f = QLocale().toDouble(s, &res);
            if (ok) *ok = res;
            if (res) {
                return Duration((qint64)(f)*3600*1000);
            }
            break;
        }
        default:
            qFatal("Unknown format");
            break;
    }
    return tmp;
}
Esempio n. 20
0
namespace KTp
{

TextParser* TextParser::s_instance = NULL;

/**
 * RegExp for url detection
 */
static QRegExp s_urlPattern(QString::fromLatin1("\\b((?:(?:([a-z][\\w\\.-]+:/{1,3})|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|\\}\\]|[^\\s`!()\\[\\]{};:'\".,<>?%1%2%3%4%5%6])|[a-z0-9.\\-+_]+@[a-z0-9.\\-]+[.][a-z]{1,5}[^\\s/`!()\\[\\]{};:'\".,<>?%1%2%3%4%5%6]))")
                            .arg(QChar(0x00AB)).arg(QChar(0x00BB)).arg(QChar(0x201C)).arg(QChar(0x201D)).arg(QChar(0x2018)).arg(QChar(0x2019)));

TextParser::TextParser(QObject* parent)
    : QObject(parent)
{
}

TextParser* TextParser::instance()
{
    if (!s_instance) {
        s_instance = new TextParser(0);
    }

    return s_instance;
}

TextUrlData TextParser::extractUrlData(const QString& text, bool doUrlFixup)
{
    TextUrlData data;
    QString htmlText(text);
    s_urlPattern.setCaseSensitivity(Qt::CaseInsensitive);

    int pos = 0;
    int urlLen = 0;

    QString protocol;
    QString href;

    while ((pos = s_urlPattern.indexIn(htmlText, pos)) >= 0) {
        urlLen = s_urlPattern.matchedLength();
        href = htmlText.mid(pos, urlLen);

        data.urlRanges << QPair<int, int>(pos, href.length());
        pos += href.length();

        if (doUrlFixup) {
            protocol.clear();
            if (s_urlPattern.cap(2).isEmpty()) {
                QString urlPatternCap1(s_urlPattern.cap(1));
                if (urlPatternCap1.contains(QLatin1Char('@'))) {
                    protocol = QLatin1String("mailto:");
                } else if (urlPatternCap1.startsWith(QLatin1String("ftp."), Qt::CaseInsensitive)) {
                    protocol = QLatin1String("ftp://");
                } else {
                    protocol = QLatin1String("http://");
                }
            }

            href = protocol + href;
            data.fixedUrls.append(href);
        }
    }
    return data;
}

TextParser::~TextParser()
{
}

}
Esempio n. 21
0
// -------------------------------------------------------
QString VHDL_File_Info::parsePorts(QString s, int j)
{
  QRegExp Expr;
  Expr.setCaseSensitive(false);
  int i, p, l, k;

  Expr.setPattern("\\bport\\b");  // start of interface definition
  i = s.find(Expr, j+1);
  if(i < 0)
    return QString("");
  // find opening (
  i = s.find('(', i+4) + 1;
  if(i <= 0)
    return QString("");

  // find closing (
  p = i;
  j = i-1;
  do {
    j = s.find(')', j+1);
    if(j < 0)
      return QString("");
    p = s.find('(', p+1);
    if(p >= 0 && p > j) p = -1;
  } while (p >= 0);

  s = s.mid(i, j-i);
  s.remove('\n');
  s.remove('\t');

  // find port names and types in parameter specification
  l = i = 0;    // remove all VHDL identifiers (e.g. ": out bit;")
  QString types = "", t;
  while((i=s.find(':', i)) >= 0) {
    j = s.find(';', i+2);
    if(j < 0) {
      t = s.mid(i+1);
      t.remove(';');
      t = t.simplifyWhiteSpace();
      s = s.left(i);
    } else {
      t = s.mid(i+1, j-i);
      t.remove(';');
      t = t.simplifyWhiteSpace();
      s.remove(i, j-i);
    }
    if ((k = t.find(' ')) >= 0)
      t = t.mid(k+1);
    t = t.simplifyWhiteSpace();
    k = s.find(';',l+2);
    k = (s.mid(l,k-l).count(',')) + 1;
    while (k-->0) types = types + t + ",";
    i--;
    l = i;
  }

  s.remove(' ');
  s.replace(';', ',');
  TypeNames=types=types.left(types.length()-1);
  return s;
}
Esempio n. 22
0
/* Check if file meets the find's requirements*/
void KQuery::processQuery( KFileItem* file)
{
  QRegExp *filename_match;

    if ( file->name() == "." || file->name() == ".." )
      return;

    bool matched=false;

    for ( filename_match = m_regexps.first(); !matched && filename_match; filename_match = m_regexps.next() )
    {
      matched |=  filename_match->isEmpty()  ||
                  (filename_match->exactMatch( file->url().fileName( true ) ) );
    }
    if (!matched)
      return;

    switch( m_sizemode )
    {
        case 1: // "at least"
            if ( file->size() < m_sizeboundary1 ) return;
            break;
        case 2: // "at most"
            if ( file->size() > m_sizeboundary1 ) return;
            break;
        case 3: // "equal"
            if ( file->size() != m_sizeboundary1 ) return;
            break;
        case 4: // "between"
            if ( (file->size() < m_sizeboundary1) || (file->size() > m_sizeboundary2) ) return;
            break;
        case 0: // "none" -> fall to default
        default:
            break;
    }

    // make sure it's in the correct date range
    // what about 0 times?
    if ( m_timeFrom && m_timeFrom > file->time(KIO::UDS_MODIFICATION_TIME) )
      return;
    if ( m_timeTo && m_timeTo < file->time(KIO::UDS_MODIFICATION_TIME) )
      return;

    // username / group match
    if ( (!m_username.isEmpty()) && (m_username != file->user()) )
       return;
    if ( (!m_groupname.isEmpty()) && (m_groupname != file->group()) )
       return;

    // file type
    switch (m_filetype)
    {
      case 0:
        break;
      case 1: // plain file
        if ( !S_ISREG( file->mode() ) )
          return;
        break;
      case 2:
        if ( !file->isDir() )
          return;
        break;
      case 3:
        if ( !file->isLink() )
          return;
        break;
      case 4:
        if ( !S_ISCHR ( file->mode() ) && !S_ISBLK ( file->mode() ) &&
              !S_ISFIFO( file->mode() ) && !S_ISSOCK( file->mode() ) )
              return;
        break;
      case 5: // binary
        if ( (file->permissions() & 0111) != 0111 || file->isDir() )
          return;
        break;
      case 6: // suid
        if ( (file->permissions() & 04000) != 04000 ) // fixme
          return;
        break;
      default:
        if (!m_mimetype.isEmpty() && !m_mimetype.contains(file->mimetype()))
          return;
    }

    // match datas in metainfo...
    if ((!m_metainfo.isEmpty())  && (!m_metainfokey.isEmpty()))
    {
       bool foundmeta=false;
       QString filename = file->url().path();

       if(filename.startsWith("/dev/"))
          return;

       KFileMetaInfo metadatas(filename);
       KFileMetaInfoItem metaitem;
       QStringList metakeys;
       QString strmetakeycontent;

       if(metadatas.isEmpty())
          return;

       metakeys=metadatas.supportedKeys();
       for ( QStringList::Iterator it = metakeys.begin(); it != metakeys.end(); ++it )
       {
          if (!metaKeyRx->exactMatch(*it))
             continue;
          metaitem=metadatas.item(*it);
          strmetakeycontent=metaitem.string();
          if(strmetakeycontent.find(m_metainfo)!=-1)
          {
             foundmeta=true;
             break;
          }
       }
       if (!foundmeta)
          return;
    }

    // match contents...
    QString matchingLine;
    if (!m_context.isEmpty())
    {

       if( !m_search_binary && ignore_mimetypes.findIndex(file->mimetype()) != -1 ) {
         kdDebug() << "ignoring, mime type is in exclusion list: " << file->url() << endl;
         return;
       }

       bool found = false;
       bool isZippedOfficeDocument=false;
       int matchingLineNumber=0;

       // FIXME: doesn't work with non local files

       QString filename;
       QTextStream* stream=0;
       QFile qf;
       QRegExp xmlTags;
       QByteArray zippedXmlFileContent;

       // KWord's and OpenOffice.org's files are zipped...
       if( ooo_mimetypes.findIndex(file->mimetype()) != -1 ||
           koffice_mimetypes.findIndex(file->mimetype()) != -1 )
       {
         KZip zipfile(file->url().path());
         KZipFileEntry *zipfileEntry;

         if(zipfile.open(IO_ReadOnly))
         {
           const KArchiveDirectory *zipfileContent = zipfile.directory();

           if( koffice_mimetypes.findIndex(file->mimetype()) != -1 )
             zipfileEntry = (KZipFileEntry*)zipfileContent->entry("maindoc.xml");
           else
             zipfileEntry = (KZipFileEntry*)zipfileContent->entry("content.xml"); //for OpenOffice.org

           if(!zipfileEntry) {
             kdWarning() << "Expected XML file not found in ZIP archive " << file->url() << endl;
             return;
           }

           zippedXmlFileContent = zipfileEntry->data();
           xmlTags.setPattern("<.*>");
           xmlTags.setMinimal(true);
           stream = new QTextStream(zippedXmlFileContent, IO_ReadOnly);
           stream->setEncoding(QTextStream::UnicodeUTF8);
           isZippedOfficeDocument = true;
         } else {
           kdWarning() << "Cannot open supposed ZIP file " << file->url() << endl;
         }
       } else if( !m_search_binary && !file->mimetype().startsWith("text/") &&
           file->url().isLocalFile() ) {
         KMimeType::Format f = KMimeType::findFormatByFileContent(file->url().path());
         if ( !f.text ) {
           kdDebug() << "ignoring, not a text file: " << file->url() << endl;
           return;
         }
       }

       if(!isZippedOfficeDocument) //any other file or non-compressed KWord
       {
         filename = file->url().path();
         if(filename.startsWith("/dev/"))
            return;
         qf.setName(filename);
         qf.open(IO_ReadOnly);
         stream=new QTextStream(&qf);
         stream->setEncoding(QTextStream::Locale);
       }

       while ( ! stream->atEnd() )
       {
          QString str = stream->readLine();
          matchingLineNumber++;

          if (str.isNull()) break;
          if(isZippedOfficeDocument)
            str.replace(xmlTags, "");

          if (m_regexpForContent)
          {
             if (m_regexp.search(str)>=0)
             {
                matchingLine=QString::number(matchingLineNumber)+": "+str;
                found = true;
                break;
             }
          }
          else
          {
             if (str.find(m_context, 0, m_casesensitive) != -1)
             {
                matchingLine=QString::number(matchingLineNumber)+": "+str;
                found = true;
                break;
             }
          }
          kapp->processEvents();
       }
       delete stream;

       if (!found)
          return;
    }
    emit addFile(file,matchingLine);
}
Esempio n. 23
0
void BankPhoneAlgo::matchNumber(const QString &number, bool &match, const QRegExp& exp, const QStringList& lists)
{
    match = false;

    // judge right(5)
    for(int i = 0; i <lists.count(); i++)
    {
        if(exp.exactMatch(lists.at(i)))
        {
            if(number.length() == 5)
            {
                if(lists.at(i).contains("+86"))
                {
                    QString tmp = lists.at(i);
                    tmp.replace("+86","");
                    if(number == tmp)
                    {
                        match = true;
                    }
                } else if(lists.at(i).left(2) == "86")
                {
                    QString tmp = lists.at(i);
                    tmp.replace("86","");
                    if(number == tmp)
                    {
                        match = true;
                    }
                } else
                {
                    if(number == lists.at(i))
                    {
                        match = true;
                    }
                }
            }
            else
            {
                if(lists.at(i).contains("+86"))
                {
                    QString num = number;
                    if(num.contains("+86"))
                    {
                        num.replace("+86","");
                    }
                    if(num.left(2) == "86")
                    {
                        num.replace("86","");
                    }
                    QString tmp = lists.at(i);
                    tmp.replace("+86","");
                    if(num == tmp)
                    {
                        match = true;
                    }
                }
                if(lists.at(i).left(2) == "86")
                {
                    QString num = number;
                    if(num.contains("+86"))
                    {
                        num.replace("+86","");
                    }
                    if(num.left(2) == "86")
                    {
                        num.replace("86","");
                    }
                    QString tmp = lists.at(i);
                    tmp.replace("86","");
                    if(num == tmp)
                    {
                        match = true;
                    }
                }
            }
        }
    }
}
Esempio n. 24
0
void EditorsDialog::slotJobExited( bool normalExit, int exitStatus )
{
    if (!normalExit)
    {
        KMessageBox::sorry( this, i18n("Log failed with exitStatus == %1").arg( exitStatus), i18n("Log Failed") );
        return;
    }

    static QRegExp re("([^\\s]+)\\s([^\\s]+)\\s([^\\s]+)\\s([^\\s]+)\\s([^\\s]+)\\s"
                        "([^\\s]+)\\s([^\\s]+)\\s([^\\s]+)\\s([^\\s]+)\\s(.*)");
    static QRegExp subre("([^\\s]+)\\s([^\\s]+)\\s([^\\s]+)\\s([^\\s]+)\\s"
                        "([^\\s]+)\\s([^\\s]+)\\s([^\\s]+)\\s([^\\s]+)\\s(.*)");
	QString lastfilename;

    QStringList lines = QStringList::split( "\n", m_output );
    int found = 0;
    for (size_t i=0; i<lines.count(); ++i) {
        QString s = lines[i].simplifyWhiteSpace();
    	kdDebug(9006) << "editors:---" << s << "---" << endl;
    	kdDebug(9006) << "       : lastfile was " << lastfilename << endl;

        if (re.exactMatch(s)) {
            QString file = re.cap( 1 );
            QString locker = re.cap( 2 );
            QString date = re.cap(5)+" "+re.cap(4)+" "+re.cap(7)+" "+re.cap(6);
            
            m_textBrowser->append( "<b>"+i18n("File")+": <code>"+file+"</code></b>" );
            m_textBrowser->append( "<b>"+i18n("User")+":</b> "+locker );
            m_textBrowser->append( "<b>"+i18n("Date")+":</b> "+date );
            m_textBrowser->append( "<hr>" );
            found++;

            lastfilename = file;
        } else {
	        if (subre.exactMatch(s)) {
				QString file = lastfilename;
				QString locker = subre.cap( 1 );
				QString date = subre.cap(4)+" "+subre.cap(3)+" "+subre.cap(6)+" "+subre.cap(5);
				
				m_textBrowser->append( "<b>"+i18n("File")+": <code>"+file+"</code></b>" );
				m_textBrowser->append( "<b>"+i18n("User")+":</b> "+locker );
				m_textBrowser->append( "<b>"+i18n("Date")+":</b> "+date );
				m_textBrowser->append( "<hr>" );
				found++;
 			}
    	}
	}

    if (!found)
        m_textBrowser->append(i18n("No files from your query are marked as being edited."));

    m_textBrowser->source();

    if (m_cvsJob) {
        disconnectDCOPSignal( m_cvsJob->app(), m_cvsJob->obj(), "jobExited(bool, int)", "slotJobExited(bool, int)" );
        delete m_cvsJob;
        m_cvsJob=NULL;
    }
}
bool  DocumentNumeratorController::isValidSymbol(QString symbol)
{
    QRegExp rx;
    rx.setPattern(formatPattern);
    return rx.exactMatch(symbol);
}
Esempio n. 26
0
void video_tudou::parseVideo(QString xml)
{
    switch (this->_step)
    {
        case 1:
        //
        // Retrieving the video id
        //
        {
            QRegExp expression;
            QString iid;
            expression = QRegExp("var iid = ([0-9]+)");
            expression.indexIn(xml);
            if (expression.indexIn(xml) !=-1)
            {
                iid = expression.cap(1);
                tempFile = new QTemporaryFile(QDir::tempPath() + "/clipgrab-info--XXXXXX");
                _finished = false;
                if (this->_url.isValid())
                {
                    _step = 2;
                    _redirectLevel = 0;
                    QNetworkRequest request;
                    request.setUrl(QUrl("http://v2.tudou.com/v2/cdn?id="+iid));
                    _currentNetworkReply = this->_networkAccessManager->get(request);
                    this->_redirectLevel = 0;
                }
            }
            else
            {
                emit error("Could not retrieve video iid.", this);
            }

            break;
        }

        case 2:
        {
            QRegExp expression;
            expression = QRegExp("ti?tl?e?=\"(.*)\"");
            expression.setMinimal(true);
            expression.indexIn(xml);
            qDebug() << xml;
            if (expression.indexIn(xml) !=-1)
            {
                _title = expression.cap(1);
                qDebug() << _title;

                expression = QRegExp("<f.*>(.*)</f>");
                expression.setMinimal(true);
                if (expression.indexIn(xml) !=-1)
                {
                    videoQuality newQuality;
                    newQuality.quality = tr("normal");
                    newQuality.videoUrl = expression.cap(1).replace("&amp;", "&");
                    newQuality.containerName = ".flv";
                    _supportedQualities.append(newQuality);
                    qDebug() << "------"+newQuality.videoUrl+"------";
                    emit analysingFinished();
                }
                else
                {
                    emit error("Could not retrieve video url");
                }
            }
            else
            {
                emit error("Could not retrieve video title");
            }
        }
    }
}
Esempio n. 27
0
void Dialog::on_thousandPushButton_clicked()
{
    on_samplePushButton_clicked(0);
    on_encodePushButton_clicked();
    on_transferPushButton_clicked(0);
    if( encodeMethod == "one-hot" )
    {
        QRegExp filter ;
        filter.setPattern( "\\d*\\.\\d*" );
        QRegExp filter1;
        filter1.setPattern("(\\d*)(%)");
        QStringList cal;

        //generate A,B,C,D
        QFile operate( "output" );
        int A , B , C , D;
        int tmp;

        //output
        QFile outfile( "sumup" );
        if( !outfile.open( QIODevice::WriteOnly | QIODevice::Text) )
        {
            qDebug() << "sumup open error";
            return;
        }
        QTextStream out( &outfile );

        for( int i = 0 ; i < 1000 ; ++i )
        {
            on_samplePushButton_clicked(0);
            on_encodePushButton_clicked();
            on_transferPushButton_clicked(0);
            QProcess test;
            //system("D:\\libsvm-3.14\\tools\\easy.py train.encode test.encode" );
            //test.start( "D:\\libsvm-3.14\\windows\\svm-predict.exe test.encode.scale train.encode.model output");
            //test.waitForFinished();
            on_findBestPushButton_clicked();
            test.start( "C:\\Users\\lvqicong\\SVM\\libsvm-3.14\\windows\\svm-predict.exe test.encode.scale train.encode.model output" );
    //        test.start( "D:\\libsvm-3.14\\windows\\svm-predict.exe test.encode.scale train.encode.model output" );
            test.waitForFinished();
            QTextStream in( &test );
            QString buff = in.readAll();
    //        qDebug() << buff ;
            filter.indexIn( buff );
            QString buff1 = filter.cap( 0 );
            if( buff1.size() == 0 )
            {
                filter1.indexIn( buff );
                buff1 = filter1.cap( 1 );
            }
            cal.push_back( buff1 );
            //output rate
            out << buff1 << "\t" ;

            if( !operate.open( QIODevice::ReadOnly | QIODevice::Text) )
            {
                qDebug() << "test.encode.output open error";
                return;
            }
            QTextStream result( &operate );
            A = B = C = D = 0;
            for( int i = 0 ; i < positiveTest.size() ; ++i )
            {
                result >> tmp;
                //真的被分成真的
                if( tmp == 1 )
                    A++;
                else
                    B++;
            }
            for( int i = 0 ; i < humanTest.size() ; ++i )
            {
                result >> tmp;
                if( tmp == -1 )
                    D++;
                else
                    C++;
            }
            operate.close();

            //output A,B,C,D
            out << A << "\t" << B << "\t" << C << "\t" << D << endl;

            /*
            if( buff1.toDouble() < 35.0 )
                break;
            */
        }


        /*
        for( int i = 0 ; i < cal.size() ; ++i )
        {
            out << cal.at(i) << endl;
        }
        outfile.close();
        */
    }
Esempio n. 28
0
void ExprShortTextEdit::keyPressEvent(QKeyEvent* e) {

    // If the completer is active pass keys it needs down
    if (completer && completer->popup()->isVisible()) {
        switch (e->key()) {
            case Qt::Key_Enter:
            case Qt::Key_Return:
            case Qt::Key_Escape:
            case Qt::Key_Tab:
            case Qt::Key_Backtab:
                e->ignore();
                return;
            default:
                break;
        }
    }

    // Accept expression
    if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) {
        selectAll();
        finishEdit();
        return;
    } else if (e->key() == Qt::Key_Escape) {
        setText(savedText);
        selectAll();
        finishEdit();
        return;
    } else if (e->key() == Qt::Key_Tab) {
        QWidget::keyPressEvent(e);
        return;
    } else if (!editing) {
        editing = true;
        setColor(true);
        savedText = toPlainText();
    }

    // use the values here as long as we are not using the shortcut to bring up the editor
    bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_E);  // CTRL+E
    if (!isShortcut)  // dont process the shortcut when we have a completer
        QTextEdit::keyPressEvent(e);

    const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier);
    if (!completer || (ctrlOrShift && e->text().isEmpty())) return;

    bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift;

    // grab the line we're on
    QTextCursor tc = textCursor();
    tc.movePosition(QTextCursor::StartOfLine, QTextCursor::KeepAnchor);
    QString line = tc.selectedText();

    // matches the last prefix of a completable variable or function and extract as completionPrefix
    static QRegExp completion("^(?:.*[^A-Za-z0-9_$])?((?:\\$[A-Za-z0-9_]*)|[A-Za-z]+[A-Za-z0-9_]*)$");
    int index = completion.indexIn(line);
    QString completionPrefix;
    if (index != -1 && !line.contains('#')) {
        completionPrefix = completion.cap(1);
        // std::cout<<"we have completer prefix '"<<completionPrefix.toStdString()<<"'"<<std::endl;
    }

    // hide the completer if we have too few characters, we are at end of word
    if (!isShortcut && (hasModifier || e->text().isEmpty() || completionPrefix.length() < 1 || index == -1)) {
        completer->popup()->hide();
    } else {

        // copy the completion prefix in if we don't already have it in the completer
        if (completionPrefix != completer->completionPrefix()) {
            completer->setCompletionPrefix(completionPrefix);
            completer->popup()->setCurrentIndex(completer->completionModel()->index(0, 0));
        }

        // display the completer
        QRect cr = cursorRect();
        cr.setWidth(2 * (completer->popup()->sizeHintForColumn(0) + completer->popup()->sizeHintForColumn(1) +
                         completer->popup()->verticalScrollBar()->sizeHint().width()));
        completer->complete(cr);
        hideTip();
        return;
    }

    // documentation completion
    static QRegExp inFunction("^(?:.*[^A-Za-z0-9_$])?([A-Za-z0-9_]+)\\([^()]*$");
    int index2 = inFunction.indexIn(line);
    if (index2 != -1) {
        QString functionName = inFunction.cap(1);
        QStringList tips = completionModel->getDocString(functionName).split("\n");
        QString tip = "<b>" + tips[0] + "</b>";
        for (int i = 1; i < tips.size(); i++) {
            tip += "<br>" + tips[i];
        }
        showTip(tip);
    } else {
        hideTip();
    }
}
Esempio n. 29
0
bool LH_MonitoringSource_Aida64::doUpdate()
{
#ifdef Q_OS_WIN
    bool resultVal = true;

    const char* mapnameAida64  = "AIDA64_SensorValues";
    const char* mapnameEverest  = "EVEREST_SensorValues";

    // Create file mapping
    HANDLE filemap = (HANDLE)OpenFileMappingA(FILE_MAP_READ,0,mapnameAida64);
    if(filemap == NULL)
        filemap = (HANDLE)OpenFileMappingA(FILE_MAP_READ,0,mapnameEverest);

    setDataAvailable(filemap != NULL);
    if(dataAvailable())
    {
        char* aidaData = (char*)MapViewOfFile(filemap, FILE_MAP_READ, 0, 0, 0);
        if (aidaData) {
            aidaXml_.setContent(QString("<data>%1</data>").arg(QString(aidaData)));

            QRegExp rx = QRegExp("([^0-9]*)([0-9]+#?\\s?)(.*)");
            rx.setPatternSyntax(QRegExp::RegExp2);

            QDomNode n = aidaXml_.documentElement().firstChild();
            while(!n.isNull()) {
                QDomElement e = n.toElement(); // try to convert the node to an element.
                if(!e.isNull()) {
                    QDomNodeList labelNodes = e.elementsByTagName("label");
                    QDomNodeList valueNodes = e.elementsByTagName("value");

                    if(labelNodes.count()==1 && valueNodes.count()==1)
                    {

                        QString typeName = e.tagName();
                        QString itemName = labelNodes.at(0).toElement().text();
                        QString groupName = (rx.indexIn(reverse(itemName))==-1 ? itemName : reverse(rx.cap(3)) + reverse(rx.cap(1)) );
                        QString valueString = valueNodes.at(0).toElement().text();
                        QString units="";

                        if(typeName=="sys")
                        {
                            typeName = "System";
                            if (itemName.endsWith("FSB")) units="mhz";
                            if (itemName.endsWith("Clock")) units="mhz";
                            if (itemName.endsWith("Utilization")) units="%";
                            if (itemName.endsWith("Memory")) units="MB";
                        }
                        if(typeName=="temp")
                        {
                            typeName = "Temperatures";
                            units=QLatin1Literal("\260C");
                        }
                        if(typeName=="fan")
                        {
                            typeName = "Cooling Fans";
                            units="rpm";
                        }
                        if(typeName=="duty")
                        {
                            typeName = "Fan Speeds";
                        }
                        if(typeName=="volt")
                        {
                            typeName = "Voltage Values";
                            units="V";
                        }

                        bool ok;
                        double valueDouble = valueString.toDouble(&ok);
                        if(ok)
                            updateValue(typeName,groupName,itemName, valueDouble, SensorDefinition(units));
                        else
                            updateValue(typeName,groupName,itemName, valueString, SensorDefinition(units));
                    }
                }
                n = n.nextSibling();
            }


            UnmapViewOfFile(aidaData);
        }
        else
            resultVal = false;
        CloseHandle(filemap);
    }
    else
        resultVal = false;

    return resultVal;
#else
    return false;
#endif
}
Esempio n. 30
0
bool
PlayableProxyModel::nameFilterAcceptsRow( int sourceRow, PlayableItem* pi, const QModelIndex& sourceParent ) const
{
    if ( m_hideEmptyParents && pi->source() )
    {
        if ( !sourceModel()->rowCount( sourceModel()->index( sourceRow, 0, sourceParent ) ) )
        {
            return false;
        }
    }

    const Tomahawk::query_ptr& query = pi->query();
    if ( query )
    {
        Tomahawk::result_ptr r;
        if ( query->numResults() )
            r = query->results().first();

        if ( !m_showOfflineResults && ( r.isNull() || !r->isOnline() ) )
            return false;

        const QRegExp regexp = filterRegExp();
        if ( regexp.isEmpty() )
            return true;

        QStringList sl = regexp.pattern().split( " ", QString::SkipEmptyParts );
        foreach( const QString& s, sl )
        {
            const Tomahawk::track_ptr& track = query->track();
            if ( !track->artist().contains( s, Qt::CaseInsensitive ) &&
                 !track->album().contains( s, Qt::CaseInsensitive ) &&
                 !track->track().contains( s, Qt::CaseInsensitive ) )
            {
                return false;
            }
        }
    }

    const Tomahawk::album_ptr& al = pi->album();
    if ( al )
    {
        QStringList sl = filterRegExp().pattern().split( " ", QString::SkipEmptyParts );

        foreach( const QString& s, sl )
        {
            if ( !al->name().contains( s, Qt::CaseInsensitive ) &&
                 !al->artist()->name().contains( s, Qt::CaseInsensitive ) )
            {
                return false;
            }
        }

        return true;
    }

    const Tomahawk::artist_ptr& ar = pi->artist();
    if ( ar )
    {
        QStringList sl = filterRegExp().pattern().split( " ", QString::SkipEmptyParts );

        foreach( const QString& s, sl )
        {
            if ( !ar->name().contains( s, Qt::CaseInsensitive ) )
            {
                return false;
            }
        }

        return true;
    }

    return true;
}