コード例 #1
0
ファイル: djvSystem.cpp プロジェクト: mottosso/djv
QStringList djvSystem::searchPath()
{
    //DJV_DEBUG("djvSystem::searchPath");

    QStringList out;

    // Add paths from environment variables.

    QString path = env(djvPathEnv());

    if (! path.isEmpty())
    {
        //DJV_DEBUG_PRINT("DJV_PATH = " << path);

        QString match;
        Q_FOREACH(QChar c, djvFileInfoUtil::listSeparators)
            match += c;
        
        out += path.split(
            QRegExp(QString("[%1]+").arg(match)),
            QString::SkipEmptyParts);
    }

    path = env(ldLibPathEnv());

    if (! path.isEmpty())
    {
        //DJV_DEBUG_PRINT("LD_LIBRARY_PATH = " << path);

        QString match;
        Q_FOREACH(QChar c, djvFileInfoUtil::listSeparators)
            match += c;
        
        //DJV_DEBUG_PRINT("match = " << match);

        out += path.split(
            QRegExp(QString("[%1]+").arg(match)),
            QString::SkipEmptyParts);
    }

    // Add the application path.
    
    //DJV_DEBUG_PRINT("qApp = " << qApp);
        
    const QString applicationPath = qApp->applicationDirPath();

    //DJV_DEBUG_PRINT("application path = " << applicationPath);

    out += applicationPath;
    
    // Add library and translation paths.

    out += QDir(applicationPath + "/../lib").absolutePath();
    out += QDir(applicationPath + "/../translations").absolutePath();

#if defined(DJV_WINDOWS) || defined(DJV_OSX)

    const QString dirName = QDir(qApp->applicationDirPath()).dirName();

    out += QDir(applicationPath + "/../../lib/" + dirName).absolutePath();
    out += QDir(applicationPath + "/../../translations/" + dirName).absolutePath();

#endif

    // Add the build directories.
    
    out += QDir("lib/djvCore").absolutePath();
    out += QDir("lib/djvGui").absolutePath();
    out += QDir("lib/djvViewLib").absolutePath();
    out += QDir("bin/djv_ls").absolutePath();
    out += QDir("bin/djv_info").absolutePath();
    out += QDir("bin/djv_convert").absolutePath();

    // Add the current directory.

    out += ".";

    //DJV_DEBUG_PRINT("out = " << out);

    QSet<QString> set;

    for (int i = 0; i < out.count(); ++i)
        set.insert(out[i]);

    QList<QString> list = set.toList();

    out.clear();
    Q_FOREACH(const QString & s, list)
        out += s;

    return out;
}
コード例 #2
0
ファイル: qgswfsserver.cpp プロジェクト: mola/Quantum-GIS
void QgsWFSServer::startGetFeature( QgsRequestHandler& request, const QString& format, QgsCoordinateReferenceSystem& crs, QgsRectangle* rect )
{
  QByteArray result;
  QString fcString;
  if ( format == "GeoJSON" )
  {
    fcString = "{\"type\": \"FeatureCollection\",\n";
    fcString += " \"bbox\": [ " + QString::number( rect->xMinimum(), 'f', 6 ).remove( QRegExp( "[0]{1,5}$" ) ) + ", " + QString::number( rect->yMinimum(), 'f', 6 ).remove( QRegExp( "[0]{1,5}$" ) ) + ", " + QString::number( rect->xMaximum(), 'f', 6 ).remove( QRegExp( "[0]{1,5}$" ) ) + ", " + QString::number( rect->yMaximum(), 'f', 6 ).remove( QRegExp( "[0]{1,5}$" ) ) + "],\n";
    fcString += " \"features\": [\n";
    result = fcString.toUtf8();
    request.startGetFeatureResponse( &result, format );
  }
  else
  {
    //Prepare url
    //Some client requests already have http://<SERVER_NAME> in the REQUEST_URI variable
    QString hrefString;
    QString requestUrl = getenv( "REQUEST_URI" );
    QUrl mapUrl( requestUrl );
    mapUrl.setHost( QString( getenv( "SERVER_NAME" ) ) );

    //Add non-default ports to url
    QString portString = getenv( "SERVER_PORT" );
    if ( !portString.isEmpty() )
    {
      bool portOk;
      int portNumber = portString.toInt( &portOk );
      if ( portOk )
      {
        if ( portNumber != 80 )
        {
          mapUrl.setPort( portNumber );
        }
      }
    }

    if ( QString( getenv( "HTTPS" ) ).compare( "on", Qt::CaseInsensitive ) == 0 )
    {
      mapUrl.setScheme( "https" );
    }
    else
    {
      mapUrl.setScheme( "http" );
    }

    QList<QPair<QString, QString> > queryItems = mapUrl.queryItems();
    QList<QPair<QString, QString> >::const_iterator queryIt = queryItems.constBegin();
    for ( ; queryIt != queryItems.constEnd(); ++queryIt )
    {
      if ( queryIt->first.compare( "REQUEST", Qt::CaseInsensitive ) == 0 )
      {
        mapUrl.removeQueryItem( queryIt->first );
        mapUrl.addQueryItem( queryIt->first, "DescribeFeatureType" );
      }
      else if ( queryIt->first.compare( "FORMAT", Qt::CaseInsensitive ) == 0 )
      {
        mapUrl.removeQueryItem( queryIt->first );
      }
      else if ( queryIt->first.compare( "OUTPUTFORMAT", Qt::CaseInsensitive ) == 0 )
      {
        mapUrl.removeQueryItem( queryIt->first );
      }
      else if ( queryIt->first.compare( "BBOX", Qt::CaseInsensitive ) == 0 )
      {
        mapUrl.removeQueryItem( queryIt->first );
      }
      else if ( queryIt->first.compare( "FEATUREID", Qt::CaseInsensitive ) == 0 )
      {
        mapUrl.removeQueryItem( queryIt->first );
      }
      else if ( queryIt->first.compare( "FILTER", Qt::CaseInsensitive ) == 0 )
      {
        mapUrl.removeQueryItem( queryIt->first );
      }
      else if ( queryIt->first.compare( "MAXFEATURES", Qt::CaseInsensitive ) == 0 )
      {
        mapUrl.removeQueryItem( queryIt->first );
      }
      else if ( queryIt->first.compare( "PROPERTYNAME", Qt::CaseInsensitive ) == 0 )
      {
        mapUrl.removeQueryItem( queryIt->first );
      }
      else if ( queryIt->first.compare( "_DC", Qt::CaseInsensitive ) == 0 )
      {
        mapUrl.removeQueryItem( queryIt->first );
      }
    }
    mapUrl.addQueryItem( "OUTPUTFORMAT", "XMLSCHEMA" );
    hrefString = mapUrl.toString();

    //wfs:FeatureCollection
    fcString = "<wfs:FeatureCollection";
    fcString += " xmlns:wfs=\"http://www.opengis.net/wfs\"";
    fcString += " xmlns:ogc=\"http://www.opengis.net/ogc\"";
    fcString += " xmlns:gml=\"http://www.opengis.net/gml\"";
    fcString += " xmlns:ows=\"http://www.opengis.net/ows\"";
    fcString += " xmlns:xlink=\"http://www.w3.org/1999/xlink\"";
    fcString += " xmlns:qgs=\"http://www.qgis.org/gml\"";
    fcString += " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"";
    fcString += " xsi:schemaLocation=\"http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/wfs.xsd http://www.qgis.org/gml " + hrefString.replace( "&", "&amp;" ) + "\"";
    fcString += ">";
    result = fcString.toUtf8();
    request.startGetFeatureResponse( &result, format );

    QDomDocument doc;
    QDomElement bbElem = doc.createElement( "gml:boundedBy" );
    QDomElement boxElem = createBoxElem( rect, doc );
    if ( !boxElem.isNull() )
    {
      if ( crs.isValid() )
      {
        boxElem.setAttribute( "srsName", crs.authid() );
      }
      bbElem.appendChild( boxElem );
      doc.appendChild( bbElem );
    }
    result = doc.toByteArray();
    request.sendGetFeatureResponse( &result );
  }
  fcString = "";
}
コード例 #3
0
static QList<ProjectExplorer::Abi> guessGccAbi(const QString &m)
{
    QList<ProjectExplorer::Abi> abiList;

    QString machine = m.toLower();
    if (machine.isEmpty())
        return abiList;

    QStringList parts = machine.split(QRegExp(QLatin1String("[ /-]")));

    ProjectExplorer::Abi::Architecture arch = ProjectExplorer::Abi::UnknownArchitecture;
    ProjectExplorer::Abi::OS os = ProjectExplorer::Abi::UnknownOS;
    ProjectExplorer::Abi::OSFlavor flavor = ProjectExplorer::Abi::UnknownFlavor;
    ProjectExplorer::Abi::BinaryFormat format = ProjectExplorer::Abi::UnknownFormat;
    int width = 0;
    int unknownCount = 0;

    foreach (const QString &p, parts) {
        if (p == QLatin1String("unknown") || p == QLatin1String("pc") || p == QLatin1String("none")
                || p == QLatin1String("gnu") || p == QLatin1String("uclibc")
                || p == QLatin1String("86_64") || p == QLatin1String("redhat") || p == QLatin1String("gnueabi")) {
            continue;
        } else if (p == QLatin1String("i386") || p == QLatin1String("i486") || p == QLatin1String("i586")
                   || p == QLatin1String("i686") || p == QLatin1String("x86")) {
            arch = ProjectExplorer::Abi::X86Architecture;
            width = 32;
        } else if (p.startsWith(QLatin1String("arm"))) {
            arch = ProjectExplorer::Abi::ArmArchitecture;
            width = 32;
        } else if (p == QLatin1String("mipsel")) {
            arch = ProjectExplorer::Abi::MipsArchitecture;
            width = 32;
        } else if (p == QLatin1String("x86_64") || p == QLatin1String("amd64")) {
            arch = ProjectExplorer::Abi::X86Architecture;
            width = 64;
        } else if (p == QLatin1String("powerpc")) {
            arch = ProjectExplorer::Abi::PowerPCArchitecture;
        } else if (p == QLatin1String("w64")) {
            width = 64;
        } else if (p == QLatin1String("linux") || p == QLatin1String("linux6e")) {
            os = ProjectExplorer::Abi::LinuxOS;
            if (flavor == Abi::UnknownFlavor)
                flavor = ProjectExplorer::Abi::GenericLinuxFlavor;
            format = ProjectExplorer::Abi::ElfFormat;
        } else if (p.startsWith(QLatin1String("freebsd"))) {
            os = ProjectExplorer::Abi::BsdOS;
            if (flavor == Abi::UnknownFlavor)
                flavor = ProjectExplorer::Abi::FreeBsdFlavor;
            format = ProjectExplorer::Abi::ElfFormat;
        } else if (p == QLatin1String("meego")) {
            os = ProjectExplorer::Abi::LinuxOS;
            flavor = ProjectExplorer::Abi::MeegoLinuxFlavor;
            format = ProjectExplorer::Abi::ElfFormat;
        } else if (p == QLatin1String("symbianelf")) {
            os = ProjectExplorer::Abi::SymbianOS;
            flavor = ProjectExplorer::Abi::SymbianDeviceFlavor;
            format = ProjectExplorer::Abi::ElfFormat;
            width = 32;
        } else if (p == QLatin1String("mingw32") || p == QLatin1String("win32") || p == QLatin1String("mingw32msvc")) {
            arch = ProjectExplorer::Abi::X86Architecture;
            os = ProjectExplorer::Abi::WindowsOS;
            flavor = ProjectExplorer::Abi::WindowsMSysFlavor;
            format = ProjectExplorer::Abi::PEFormat;
            if (width == 0)
                width = 32;
        } else if (p == QLatin1String("apple")) {
            os = ProjectExplorer::Abi::MacOS;
            flavor = ProjectExplorer::Abi::GenericMacFlavor;
            format = ProjectExplorer::Abi::MachOFormat;
        } else if (p == QLatin1String("darwin10")) {
            width = 64;
        } else if (p == QLatin1String("darwin9")) {
            width = 32;
        } else if (p == QLatin1String("gnueabi")) {
            format = ProjectExplorer::Abi::ElfFormat;
        } else {
            ++unknownCount;
        }
    }

    if (unknownCount == parts.count())
        return abiList;

    if (os == Abi::MacOS && arch != Abi::ArmArchitecture) {
        // Apple does PPC and x86!
        abiList << ProjectExplorer::Abi(arch, os, flavor, format, width);
        abiList << ProjectExplorer::Abi(arch, os, flavor, format, width == 64 ? 32 : 64);
        abiList << ProjectExplorer::Abi(arch == Abi::X86Architecture ? Abi::PowerPCArchitecture : Abi::X86Architecture, os, flavor, format, width);
        abiList << ProjectExplorer::Abi(arch == Abi::X86Architecture ? Abi::PowerPCArchitecture : Abi::X86Architecture, os, flavor, format, width == 64 ? 32 : 64);
    } else if (width == 64) {
        abiList << ProjectExplorer::Abi(arch, os, flavor, format, width);
        abiList << ProjectExplorer::Abi(arch, os, flavor, format, 32);
    } else {
        abiList << ProjectExplorer::Abi(arch, os, flavor, format, width);
    }
    return abiList;
}
コード例 #4
0
ファイル: monitor.cpp プロジェクト: bsv/r245
/**
  * Обнавляет модель монитора в соответствии с установленными
  * параметрами фильтрации.
  */
void Monitor::update()
{
    monitor_model_proxy->setFilterRegExp(QRegExp(""));
}
コード例 #5
0
void TableDialog::apply()
{
	if (colName->text().contains("_")){
		QMessageBox::warning(this, tr("QtiPlot - Warning"),
		tr("For internal consistency reasons the underscore character is replaced with a minus sign."));
	}

	QString name = colName->text().replace("-", "_").remove(QRegExp("\n"));

	int sc = d_table->selectedColumn();
	d_table->setColumnWidth(colWidth->value(), applyToAllBox->isChecked());
	d_table->setColComment(sc, comments->text().replace("\n", " ").replace("\t", " "));
	d_table->setColName(sc, name.replace("_", "-"), enumerateAllBox->isChecked());

	bool rightColumns = applyToRightCols->isChecked();
	int format = formatBox->currentIndex();
	int colType = displayBox->currentIndex();
	switch(colType){
		case 0:
			setNumericFormat(formatBox->currentIndex(), precisionBox->value(), rightColumns);
		break;

		case 1:
			setTextFormat(rightColumns);
		break;

		case 2:
			 setDateTimeFormat(colType, formatBox->currentText(), rightColumns);
		break;

		case 3:
			setDateTimeFormat(colType, formatBox->currentText(), rightColumns);
		break;

		case 4:
			if(format == 0)
				setMonthFormat("MMM", rightColumns);
			else if(format == 1)
				setMonthFormat("MMMM", rightColumns);
			else if(format == 2)
				setMonthFormat("M", rightColumns);
		break;

		case 5:
			if(format == 0)
				setDayFormat("ddd", rightColumns);
			else if(format == 1)
				setDayFormat("dddd", rightColumns);
			else if(format == 2)
				setDayFormat("d", rightColumns);
		break;
	}

	if (rightColumns){
		bool readOnly = boxReadOnly->isChecked();
		for (int i = sc; i<d_table->numCols(); i++){
			d_table->setReadOnlyColumn(i, readOnly);
			d_table->hideColumn(i, boxHideColumn->isChecked());
		}
	} else {
		d_table->setReadOnlyColumn(sc, boxReadOnly->isChecked());
		d_table->hideColumn(sc, boxHideColumn->isChecked());
	}
}
コード例 #6
0
ファイル: adpreader.cpp プロジェクト: AtlantisCD9/Qt
static bool versionIsAtLeast320(const QString &version)
{
    return QRegExp("\\d.\\d\\.\\d").exactMatch(version)
            && (version[0] > '3' || (version[0] == '3' && version[2] >= '2'));
}
コード例 #7
0
ファイル: serveur.cpp プロジェクト: Danz0r77/OpalCoin
QString Serveur::parseCommande(QString comm,bool serveur)
{
    if(comm.startsWith("/"))
    {
        comm.remove(0,1);
        QString pref=comm.split(" ").first();
        QStringList args=comm.split(" ");
        args.removeFirst();
        QString destChan=tab->tabText(tab->currentIndex());
        QString msg=args.join(" ");

        if(pref=="me")
            return "PRIVMSG "+destChan+" ACTION " + msg + "";
        else if(pref=="msg")
            return "MSG "+destChan+" ACTION " + msg + "";
        else if(pref=="join")
        {
            join(msg);
            return " ";
        }
        else if(pref=="quit")
        {
            if(msg == "")
                return "QUIT "+msgQuit;
            else
                return "QUIT "+msg;
        }
        else if(pref=="part")
        {
            tab->removeTab(tab->currentIndex());

            if(msg == "")
            {
                if(msg.startsWith("#"))
                    destChan=msg.split(" ").first();

                if(msgQuit=="")
                    return "PART "+destChan+" using IrcLightClient";
                else
                    return "PART "+destChan+" "+msgQuit;
            }
            else
                return "PART "+destChan+" "+msg;

            conversations.remove(destChan);
        }
        else if(pref=="kick")
        {
            QStringList tableau=msg.split(" ");
            QString c1,c2,c3;
            if(tableau.count() > 0) c1=" "+tableau.first();
            else c1="";
            if(tableau.count() > 1) c2=" "+tableau.at(1);
            else c2="";
            if(tableau.count() > 2) c3=" "+tableau.at(2);
            else c3="";

            if(c1.startsWith("#"))
                return "KICK"+c1+c2+c3;
            else
                return "KICK "+destChan+c1+c2;
        }
        else if(pref=="update")
        {
            updateUsers=true;
            return "WHO "+destChan;
        }
        else if(pref=="ns")
        {
            return "NICKSERV "+msg;
        }
        else if(pref=="nick")
        {
            emit pseudoChanged(msg);
                        ecrire("-> Nickname changed to "+msg);
            return "NICK "+msg;
        }
        else if(pref=="msg")
        {
            return "MSG "+msg;
        }

        else
            return pref+" "+msg;
    }
    else if(!serveur)
	{
        QString destChan=tab->tabText(tab->currentIndex());
                if(comm.endsWith("<br />"))
                    comm=comm.remove(QRegExp("<br />$"));
                ecrire("<b>&lt;"+pseudo+"&gt;</b> "+comm,destChan);

        if(comm.startsWith(":"))
            comm.insert(0,":");

        return "PRIVMSG "+destChan+" "+comm.replace(" ","\t");
    }
	else
	{
		return "";
	}
}
コード例 #8
0
ファイル: csharpimport.cpp プロジェクト: ShermanHuang/kdesdk
/**
 * Implement abstract operation from NativeImportBase.
 * @return success status of operation
 */
bool CSharpImport::parseStmt()
{
    const int srcLength = m_source.count();
    const QString& keyword = m_source[m_srcIndex];
    //uDebug() << '"' << keyword << '"';

    if (keyword == "using") {
        return parseStmtUsing();
    }

    if (keyword == "namespace") {
        return parseStmtNamespace();
    }

//     if (keyword == "package") {
//         m_currentPackage = advance();
//         const QString& qualifiedName = m_currentPackage;
//         const QStringList names = qualifiedName.split('.');
//         for (QStringList::ConstIterator it = names.begin(); it != names.end(); ++it) {
//             QString name = (*it);
//             log(keyword + ' ' + name);
//             UMLObject *ns = Import_Utils::createUMLObject(UMLObject::ot_Package,
//                             name, m_scope[m_scopeIndex], m_comment);
//             m_scope[++m_scopeIndex] = static_cast<UMLPackage*>(ns);
//         }
//         if (advance() != ";") {
//             uError() << "unexpected: " << m_source[m_srcIndex];
//             skipStmt();
//         }
//         return true;
//     }

    if (keyword == "class" || keyword == "interface") {
        return parseStmtClass(keyword);
    }

    if (keyword == "enum") {
        return parseStmtEnum();
    }

    if (keyword == "static") {
        m_isStatic = true;
        return true;
    }

    // if we detected static previously and keyword is { then this is a static block
    if (m_isStatic && keyword == "{") {
        // reset static flag and jump to end of static block
        m_isStatic = false;
        return skipToClosing('{');
    }

    if (keyword == "abstract") {
        m_isAbstract = true;
        return true;
    }
    if (keyword == "public") {
        m_currentAccess = Uml::Visibility::Public;
        return true;
    }
    if (keyword == "protected") {
        m_currentAccess = Uml::Visibility::Protected;
        return true;
    }
    if (keyword == "private") {
        m_currentAccess = Uml::Visibility::Private;
        return true;
    }

    if ((keyword == "override") ||
            (keyword == "virtual") ||
            (keyword == "sealed")) {
        //:TODO: anything to do here?
        return true;
    }

    if (keyword == "#") {   // preprocessor directives
        QString ppdKeyword = advance();
        uDebug() << "found preprocessor directive " << ppdKeyword;
        //:TODO: anything to do here?
        return true;
    }

//     if (keyword == "@") {   // annotation
//         advance();
//         if (m_source[m_srcIndex + 1] == "(") {
//             advance();
//             skipToClosing('(');
//         }
//         return true;
//     }

    if (keyword == "[") {   // ...
        advance();
        skipToClosing('[');
        return true;
    }

    if (keyword == "}") {
        if (m_scopeIndex)
            m_klass = dynamic_cast<UMLClassifier*>(m_scope[--m_scopeIndex]);
        else
            uError() << "too many }";
        return true;
    }

    // At this point, we expect `keyword' to be a type name
    // (of a member of class or interface, or return type
    // of an operation.) Up next is the name of the attribute
    // or operation.
    if (! keyword.contains(QRegExp("^\\w"))) {
        uError() << "ignoring " << keyword <<
                 " at " << m_srcIndex << ", " << m_source.count() << " in " << m_klass;  //:TODO: ->name();
        return false;
    }

    QString typeName = m_source[m_srcIndex];
    typeName = joinTypename(typeName);
    // At this point we need a class.
    if (m_klass == NULL) {
        uError() << "no class set for " << typeName;
        return false;
    }
    QString name = advance();
    QString nextToken;
    if (typeName == m_klass->name() && name == "(") {
        // Constructor.
        nextToken = name;
        name = typeName;
        typeName.clear();
    } else {
        nextToken = advance();
    }
    if (name.contains(QRegExp("\\W"))) {
        uError() << "expecting name in " << name;
        return false;
    }
    if (nextToken == "(") {
        // operation
        UMLOperation *op = Import_Utils::makeOperation(m_klass, name);
        m_srcIndex++;
        while (m_srcIndex < srcLength && m_source[m_srcIndex] != ")") {
            QString typeName = m_source[m_srcIndex];
            if (typeName == "final" || typeName.startsWith("//")) {
                // ignore the "final" keyword and any comments in method args
                typeName = advance();
            }
            typeName = joinTypename(typeName);
            QString parName = advance();
            // the Class might not be resolved yet so resolve it if necessary
            UMLObject *obj = resolveClass(typeName);
            if (obj) {
                // by prepending the package, unwanted placeholder types will not get created
                typeName = obj->fullyQualifiedName(".");
            }
            /* UMLAttribute *att = */ Import_Utils::addMethodParameter(op, typeName, parName);
            if (advance() != ",")
                break;
            m_srcIndex++;
        }
        // before adding the method, try resolving the return type
        UMLObject *obj = resolveClass(typeName);
        if (obj) {
            // using the fully qualified name means that a placeholder type will not be created.
            typeName = obj->fullyQualifiedName(".");
        }
        Import_Utils::insertMethod(m_klass, op, m_currentAccess, typeName,
                                   m_isStatic, m_isAbstract, false /*isFriend*/,
                                   false /*isConstructor*/, m_comment);
        m_isAbstract = m_isStatic = false;
        // reset the default visibility
        m_currentAccess = m_defaultCurrentAccess;
        // At this point we do not know whether the method has a body or not.
        do {
            nextToken = advance();
        } while (nextToken != "{" && nextToken != ";");
        if (nextToken == ";") {
            // No body (interface or abstract)
            return true;
        } else {
            return skipToClosing('{');
        }
    }
    // At this point we know it's some kind of attribute declaration.
    while(1) {
        while (nextToken != "," && nextToken != ";") {
            if (nextToken == "=") {
                if ((nextToken = advance()) == "new") {
                    advance();
                    if ((nextToken = advance()) == "(") {
                        skipToClosing('(');
                        if ((nextToken = advance()) == "{") {
                            skipToClosing('{');
                        } else {
                            skipStmt();
                            break;
                        }
                    } else {
                        skipStmt();
                        break;
                    }
                } else {
                    skipStmt();
                    break;
                }
            } else {
                name += nextToken;  // add possible array dimensions to `name'
            }
            nextToken = advance();
            if (nextToken.isEmpty()) {
                break;
            }
        }
        // try to resolve the class type, or create a placeholder if that fails
        UMLObject *type = resolveClass(typeName);
        UMLObject *o;
        if (type) {
            o = Import_Utils::insertAttribute(m_klass, m_currentAccess, name,
                                              static_cast<UMLClassifier*>(type), m_comment, m_isStatic);
        } else {
            o = Import_Utils::insertAttribute(m_klass, m_currentAccess, name,
                                              typeName, m_comment, m_isStatic);
        }
        // UMLAttribute *attr = static_cast<UMLAttribute*>(o);
        if (nextToken != ",") {
            // reset the modifiers
            m_isStatic = m_isAbstract = false;
            break;
        }
        name = advance();
        nextToken = advance();
    }
    // reset visibility to default
    m_currentAccess = m_defaultCurrentAccess;
    if (m_srcIndex < m_source.count()) {
        if (m_source[m_srcIndex] != ";") {
            uError() << "ignoring trailing items at " << name;
            skipStmt();
        }
    } else {
        uError() << "index out of range: ignoring statement " << name;
        skipStmt();
    }
    return true;
}
コード例 #9
0
QStringList BazaarCommitWidget::fixedBugs() const
{
    return m_bazaarCommitPanelUi.fixedBugsLineEdit->text().split(QRegExp("\\s+"));
}
コード例 #10
0
void XMLSchemaWriter::writeAssociationRoleDecl( UMLClassifier *c, const QString &multi, QTextStream &XMLschema)
{

    bool isAbstract = c->getAbstract();
    bool isInterface = c->isInterface();

    QString elementName = getElementName(c);
    QString doc = c->getDoc();

    if (!doc.isEmpty())
        writeComment(doc, XMLschema);


    // Min/Max Occurs is based on whether it is this a single element
    // or a List (maxoccurs>1). One day this will be done correctly with special
    // multiplicity object that we don't have to figure out what it means via regex.
    QString minOccurs = "0";
    QString maxOccurs = "unbounded";
    if (multi.isEmpty())
    {
        // in this case, association will only specify ONE element can exist
        // as a child
        minOccurs = "1";
        maxOccurs = "1";
    }
    else
    {
        QStringList values = QStringList::split( QRegExp("[^\\d{1,}|\\*]"), multi);

        // could use some improvement here.. for sequences like "0..1,3..5,10" we
        // don't capture the whole "richness" of the multi. Instead we translate it
        // now to minOccurs="0" maxOccurs="10"
        if (values.count() > 0)
        {
            // populate both with the actual value as long as our value isnt an asterix
            // In that case, use special value (from above)
            if(values[0].contains(QRegExp("\\d{1,}")))
                minOccurs = values[0]; // use first number in sequence

            if(values[values.count()-1].contains(QRegExp("\\d{1,}")))
                maxOccurs = values[values.count()-1]; // use only last number in sequence
        }
    }

    // Now declare the class in the association as an element or group.
    //
    // In a semi-arbitrary way, we have decided to make abstract classes into
    // "groups" and concrete classes into "complexTypes".
    //
    // This is because about the only thing you can do with an abstract
    // class (err. node) is inherit from it with a "concrete" element. Therefore,
    // in this manner, we need a group node for abstract classes to lay out the child
    // element choices so that the child, concrete class may be plugged into whatever spot
    // it parent could go. The tradeoff is that "group" nodes may not be extended, so the
    // choices that you lay out here are it (e.g. no more nodes may inherit" from this group)
    //
    // The flipside for concrete classes is that we want to use them as elements in our document.
    // Unfortunately, about all you can do with complexTypes in terms of inheritance, is to
    // use these as the basis for a new node type. This is NOT full inheritence because the new
    // class (err. element node) wont be able to go into the document where it parent went without
    // you heavily editing the schema.
    //
    // Therefore, IF a group is abstract, but has no inheriting sub-classes, there are no choices, and its nigh
    // on pointless to declare it as a group, in this special case, abstract classes get declared
    // as complexTypes.
    //
    // Of course, in OO methodology, you should be able to inherit from
    // any class, but schema just don't allow use to have full inheritence using either groups
    // or complexTypes. Thus we have taken a middle rode. If someone wants to key me into a
    // better way to represent this, I'd be happy to listen. =b.t.
    //
    // UPDATE: partial solution to the above: as of 13-Mar-2003 we now write BOTH a complexType
    //         AND a group declaration for interfaces AND classes which are inherited from.
    //
    if ((isAbstract || isInterface ) && c->findSubClassConcepts().count() > 0)
        XMLschema<<getIndent()<<"<"<<makeSchemaTag("group")
        <<" ref=\""<<makePackageTag(getElementGroupTypeName(c))<<"\"";
    else
        XMLschema<<getIndent()<<"<"<<makeSchemaTag("element")
        <<" name=\""<<getElementName(c)<<"\""
        <<" type=\""<<makePackageTag(getElementTypeName(c))<<"\"";

    // min/max occurs
    if (minOccurs != "1")
        XMLschema<<" minOccurs=\""<<minOccurs<<"\"";

    if (maxOccurs != "1")
        XMLschema<<" maxOccurs=\""<<maxOccurs<<"\"";

    // tidy up the node
    XMLschema<<"/>"<<m_endl;

}
コード例 #11
0
ファイル: csharpimport.cpp プロジェクト: ShermanHuang/kdesdk
/**
 * Parsing the statement 'class' or 'interface'.
 * @return   success status of parsing
 */
bool CSharpImport::parseStmtClass(const QString& keyword)
{
    const QString& name = advance();
    const UMLObject::ObjectType t = (keyword == "class" ? UMLObject::ot_Class : UMLObject::ot_Interface);
    log(keyword + ' ' + name);
    UMLObject *ns = Import_Utils::createUMLObject(t, name, m_scope[m_scopeIndex], m_comment);
    m_scope[++m_scopeIndex] = m_klass = static_cast<UMLClassifier*>(ns);
    m_klass->setAbstract(m_isAbstract);
    m_klass->setStatic(m_isStatic);
    m_klass->setVisibility(m_currentAccess);
    // The UMLObject found by createUMLObject might originally have been created as a
    // placeholder with a type of class but if is really an interface, then we need to
    // change it.
    UMLObject::ObjectType ot = (keyword == "interface" ? UMLObject::ot_Interface : UMLObject::ot_Class);
    m_klass->setBaseType(ot);
    m_isAbstract = m_isStatic = false;
    // if no modifier is specified in an interface, then it means public
    if (m_klass->isInterface()) {
        m_defaultCurrentAccess =  Uml::Visibility::Public;
    }

    if (advance() == ";")    // forward declaration
        return true;

    if (m_source[m_srcIndex] == "<") {
        // template args - preliminary, rudimentary implementation
        // @todo implement all template arg syntax
        uint start = m_srcIndex;
        if (! skipToClosing('<')) {
            uError() << "import C# (" << name << "): template syntax error";
            return false;
        }
        while(1) {
            const QString arg = m_source[++start];
            if (! arg.contains(QRegExp("^[A-Za-z_]"))) {
                uDebug() << "import C# (" << name << "): cannot handle template syntax ("
                            << arg << ")";
                break;
            }
            /* UMLTemplate *tmpl = */ m_klass->addTemplate(arg);
            const QString next = m_source[++start];
            if (next == ">")
                break;
            if (next != ",") {
                uDebug() << "import C# (" << name << "): cannot handle template syntax ("
                            << next << ")";
                break;
            }
        }
        advance();  // skip over ">"
    }

    if (m_source[m_srcIndex] == ":") {   // derivation
        while (m_srcIndex < m_source.count() - 1 && advance() != "{") {
            const QString& baseName = m_source[m_srcIndex];
            // try to resolve the interface we are implementing, if this fails
            // create a placeholder
            UMLObject *interface = resolveClass(baseName);
            if (interface) {
                Import_Utils::createGeneralization(m_klass, static_cast<UMLClassifier*>(interface));
            } else {
                uDebug() << "implementing interface " << baseName
                            << " is not resolvable. Creating placeholder";
                Import_Utils::createGeneralization(m_klass, baseName);
            }
            if (advance() != ",")
                break;
        }
    }

    if (m_source[m_srcIndex] != "{") {
        uError() << "ignoring excess chars at " << name
                    << " (" << m_source[m_srcIndex] << ")";
        skipStmt("{");
    }
    return true;
}
コード例 #12
0
// main method for invoking..
void XMLSchemaWriter::writeClass(UMLClassifier *c)
{

    if (!c) {
        kDebug()<<"Cannot write class of NULL classifier!\n";
        return;
    }

    // find an appropriate name for our file
    QString fileName = findFileName(c,".xsd");

    if (fileName.isEmpty()) {
        emit codeGenerated(c, false);
        return;
    }

    // check that we may open that file for writing
    QFile file;
    if ( !openFile(file, fileName) ) {
        emit codeGenerated(c, false);
        return;
    }

    QTextStream XMLschema(&file);

    // set package namespace tag appropriately
    if(!c->getPackage().isEmpty())
        packageNamespaceTag = c->getPackage();

    // START WRITING

    // 0. FIRST THING: open the xml processing instruction. This MUST be
    // the first thing in the file
    XMLschema<<"<?xml version=\"1.0\"?>"<<m_endl;

    // 1. create the header
    QString headerText = getHeadingFile(".xsd");
    if(!headerText.isEmpty()) {
        headerText.replace(QRegExp("%filename%"),fileName);
        headerText.replace(QRegExp("%filepath%"),file.name());
    }
    if(!headerText.isEmpty())
        XMLschema<<headerText<<m_endl;

    // 2. Open schema element node with appropriate namespace decl
    XMLschema<<"<"<<makeSchemaTag("schema");
    // common namespaces we know will be in the file..
    XMLschema<<" targetNamespace=\""<<packageNamespaceURI+packageNamespaceTag<<"\""<<m_endl;
    XMLschema<<" xmlns:"<<schemaNamespaceTag<<"=\""<<schemaNamespaceURI<<"\"";
    XMLschema<<" xmlns:"<<packageNamespaceTag<<"=\""<<packageNamespaceURI+packageNamespaceTag<<"\"";

    XMLschema<<">"<<m_endl; // close opening declaration

    m_indentLevel++;

    // 3? IMPORT statements -- do we need to do anything here? I suppose if
    // our document has more than one package, which is possible, we are missing
    // the correct import statements. Leave that for later at this time.
    /*
    //only import classes in a different package as this class
    UMLPackageList imports;
    findObjectsRelated(c,imports);
    for(UMLPackage *con = imports.first(); con ; con = imports.next())
        if(con->getPackage() != c->getPackage())
                XMLschema<<"import "<<con->getPackage()<<"."<<cleanName(con->getName())<<";"<<m_endl;
    */

    // 4. BODY of the schema.
    // start the writing by sending this classifier, the "root" for this particular
    // schema, to writeClassifier method, which will subsequently call itself on all
    // related classifiers and thus populate the schema.
    writeClassifier(c, XMLschema);

    // 5. What remains is to make the root node declaration
    XMLschema<<m_endl;
    writeElementDecl(getElementName(c), getElementTypeName(c), XMLschema);

    // 6. Finished: now we may close schema decl
    m_indentLevel--;
    XMLschema<<getIndent()<<"</"<<makeSchemaTag("schema")<<">"<<m_endl; // finished.. close schema node

    // bookeeping for code generation
    emit codeGenerated(c, true);

    // tidy up. no dangling open files please..
    file.close();

    // need to clear HERE, NOT in the destructor because we want each
    // schema that we write to have all related classes.
    writtenClassifiers.clear();
}
コード例 #13
0
MainOptionsPage::MainOptionsPage(QWidget *parent):
        QWidget(parent)
{
    QVBoxLayout *layout = new QVBoxLayout();

    bitcoin_at_startup = new QCheckBox(tr("&Start Ponycoin on window system startup"));
    bitcoin_at_startup->setToolTip(tr("Automatically start Ponycoin after the computer is turned on"));
    layout->addWidget(bitcoin_at_startup);

#ifndef Q_WS_MAC
    minimize_to_tray = new QCheckBox(tr("&Minimize to the tray instead of the taskbar"));
    minimize_to_tray->setToolTip(tr("Show only a tray icon after minimizing the window"));
    layout->addWidget(minimize_to_tray);
#endif

    map_port_upnp = new QCheckBox(tr("Map port using &UPnP"));
    map_port_upnp->setToolTip(tr("Automatically open the Ponycoin client port on the router. This only works when your router supports UPnP and it is enabled."));
    layout->addWidget(map_port_upnp);

#ifndef Q_WS_MAC
    minimize_on_close = new QCheckBox(tr("M&inimize on close"));
    minimize_on_close->setToolTip(tr("Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu."));
    layout->addWidget(minimize_on_close);
#endif

    connect_socks4 = new QCheckBox(tr("&Connect through SOCKS4 proxy:"));
    connect_socks4->setToolTip(tr("Connect to the Ponycoin network through a SOCKS4 proxy (e.g. when connecting through Tor)"));
    layout->addWidget(connect_socks4);

    QHBoxLayout *proxy_hbox = new QHBoxLayout();
    proxy_hbox->addSpacing(18);
    QLabel *proxy_ip_label = new QLabel(tr("Proxy &IP: "));
    proxy_hbox->addWidget(proxy_ip_label);
    proxy_ip = new QLineEdit();
    proxy_ip->setMaximumWidth(140);
    proxy_ip->setEnabled(false);
    proxy_ip->setValidator(new QRegExpValidator(QRegExp("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"), this));
    proxy_ip->setToolTip(tr("IP address of the proxy (e.g. 127.0.0.1)"));
    proxy_ip_label->setBuddy(proxy_ip);
    proxy_hbox->addWidget(proxy_ip);
    QLabel *proxy_port_label = new QLabel(tr("&Port: "));
    proxy_hbox->addWidget(proxy_port_label);
    proxy_port = new QLineEdit();
    proxy_port->setMaximumWidth(55);
    proxy_port->setValidator(new QIntValidator(0, 65535, this));
    proxy_port->setEnabled(false);
    proxy_port->setToolTip(tr("Port of the proxy (e.g. 1234)"));
    proxy_port_label->setBuddy(proxy_port);
    proxy_hbox->addWidget(proxy_port);
    proxy_hbox->addStretch(1);

    layout->addLayout(proxy_hbox);
    QLabel *fee_help = new QLabel(tr("Optional transaction fee per kB that helps make sure your transactions are processed quickly.  Most transactions are 1 kB.  Fee 0.01 recommended."));
    fee_help->setWordWrap(true);
    layout->addWidget(fee_help);

    QHBoxLayout *fee_hbox = new QHBoxLayout();
    fee_hbox->addSpacing(18);
    QLabel *fee_label = new QLabel(tr("Pay transaction &fee"));
    fee_hbox->addWidget(fee_label);
    fee_edit = new BitcoinAmountField();
    fee_edit->setToolTip(tr("Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended."));

    fee_label->setBuddy(fee_edit);
    fee_hbox->addWidget(fee_edit);
    fee_hbox->addStretch(1);

    layout->addLayout(fee_hbox);

    layout->addStretch(1); // Extra space at bottom

    setLayout(layout);

    connect(connect_socks4, SIGNAL(toggled(bool)), proxy_ip, SLOT(setEnabled(bool)));
    connect(connect_socks4, SIGNAL(toggled(bool)), proxy_port, SLOT(setEnabled(bool)));

#ifndef USE_UPNP
    map_port_upnp->setDisabled(true);
#endif
}
コード例 #14
0
ファイル: ircsession.cpp プロジェクト: geekt/quazaa
    void SessionPrivate::processLine(const QByteArray& line)
    {
        Q_Q(Session);
        QString process = readString(line);
        QString prefix, command;
        QStringList params;

        // From RFC 1459:
        //  <message>  ::= [':' <prefix> <SPACE> ] <command> <params> <crlf>
        //  <prefix>   ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ]
        //  <command>  ::= <letter> { <letter> } | <number> <number> <number>
        //  <SPACE>    ::= ' ' { ' ' }
        //  <params>   ::= <SPACE> [ ':' <trailing> | <middle> <params> ]
        //  <middle>   ::= <Any *non-empty* sequence of octets not including SPACE
        //                 or NUL or CR or LF, the first of which may not be ':'>
        //  <trailing> ::= <Any, possibly *empty*, sequence of octets not including
        //                   NUL or CR or LF>

        // parse <prefix>
        if (process.startsWith(QLatin1Char(':')))
        {
            prefix = process.mid(1, process.indexOf(QLatin1Char(' ')) - 1);
            process.remove(0, prefix.length() + 2);

            if (options & Session::StripNicks)
            {
                int index = prefix.indexOf(QRegExp(QLatin1String("[@!]")));
                if (index != -1)
                    prefix.truncate(index);
            }
        }

        // parse <command>
        command = process.mid(0, process.indexOf(QLatin1Char(' ')));
        process.remove(0, command.length() + 1);
        bool isNumeric = false;
        uint code = command.toInt(&isNumeric);

        // parse middle/params
        while (!process.isEmpty())
        {
            if (process.startsWith(QLatin1Char(':')))
            {
                process.remove(0, 1);
                params << process;
                process.clear();
            }
            else
            {
                QString param = process.mid(0, process.indexOf(QLatin1Char(' ')));
                process.remove(0, param.length() + 1);
                params << param;
            }
        }

        // handle PING/PONG
        if (command == QLatin1String("PING"))
        {
            QString arg = params.value(0);
            q->raw(QString(QLatin1String("PONG %1")).arg(arg));
            return;
        }

        // and dump
        if (isNumeric)
        {
            switch (code)
            {
                case Irc::Rfc::RPL_WELCOME:
                {
                    Buffer* buffer = createBuffer(host);
                    buffer->d_func()->setReceiver(prefix);
                    break;
                }

                case Irc::Rfc::RPL_TOPIC:
                {
                    QString topic = params.value(1);
                    QString target = resolveTarget(QString(), topic);
                    Buffer* buffer = createBuffer(target);
                    buffer->d_func()->topic = topic;
                    break;
                }

                case Irc::Rfc::RPL_NAMREPLY:
                {
                    QStringList list = params;
                    list.removeAll(QLatin1String("="));
                    list.removeAll(QLatin1String("@"));
                    list.removeAll(QLatin1String("*"));

                    QString target = resolveTarget(QString(), list.value(1));
                    Buffer* buffer = createBuffer(target);
                    QStringList names = list.value(2).split(QLatin1String(" "), QString::SkipEmptyParts);
                    foreach (const QString& name, names)
                        buffer->d_func()->addName(name);
                    break;
                }

                case Irc::Rfc::RPL_MOTDSTART:
                    motd.clear();
                    break;

                case Irc::Rfc::RPL_MOTD:
                    motd.append(params.value(1) + QLatin1Char('\n'));
                    break;

                case Irc::Rfc::RPL_ENDOFMOTD:
                    if (defaultBuffer)
                        emit defaultBuffer->motdReceived(motd);
                    motd.clear();
                    break;

                default:
                    break;
            }

            if (code == Rfc::RPL_TOPICSET && options & Session::StripNicks)
            {
                QString user = params.value(2);
                int index = user.indexOf(QRegExp(QLatin1String("[@!]")));
                if (index != -1)
                {
                    user.truncate(index);
                    params.replace(2, user);
                }
            }

            if (defaultBuffer)
                emit defaultBuffer->numericMessageReceived(prefix, code, params);

            // join auto-join channels after MOTD
            if (code == Rfc::RPL_ENDOFMOTD || code == Rfc::ERR_NOMOTD)
            {
                foreach (const QString& channel, channels)
                    q->join(channel);
            }
        }
コード例 #15
0
ファイル: qgsdataitem.cpp プロジェクト: HeatherHillers/QGIS
QString QgsDataItem::pathComponent( const QString &string )
{
  return QString( string ).replace( QRegExp( "[\\\\/]" ), "|" );
}
コード例 #16
0
ファイル: get_expr.cpp プロジェクト: Maldela/Macrodyn-Qt
QString get_expr(QString expr, QString &token, const QString &upto, QChar *ch)
{
    return get_expr(expr, token, QRegExp(upto), ch);
}
コード例 #17
0
void ControlWidget::handleLoad()
{
   mpPlaylist->addEntries( GlobalConfigWidget::getClipboard().split(QRegExp("(\r|\n)"),QString::SkipEmptyParts) );
}
コード例 #18
0
ファイル: plugin_cangine.cpp プロジェクト: Mohtadi/projet_c2a
/*
  Message type
"C2ACamion"
"0-02:06:18.040"
"EngSpeed 898,500 rpm"
"Accel    0,0 %"
"TCO      114,30 km/h MD:0  OS:0  DI:0  TP:0  HI:0  EV:0  D1:0/0/0 D2:0/0/0"
"Speed    114,30 km/h CC:0 BR:0 CS:0 PB:0"
"Distance 0,000 km"
"EngHours 1,90 h"
"FuelC    0,0 L"
"EngTemp  +61 degr"
"FuelLev  36,8 %"
"VehID    azerty"
"FMS      02.51 Diag:0 Requ:0"
"Gear     S:* C:*"
"DoorCtr1 P:* R:* S:*"
"DC2 loe  1:* 2:* 3:* 4:* 5:* 6:* 7:* 8:* 9:* 10:*"
"BellowPr FAL:* kPa FAR:* kPa RAL:* kPa RAR:* kPa"
"BrakePr  1:* kPa 2:* kPa"
"Alternat 1:* 2:* 3:* 4:*"
"DateTime *"
"AmbTemp  * degr" */
void CPluginCANGine::parseToMessage ()
{
    QStringList list = m_message.split('\n');

    if (2 < list.count())
    {
        QStringList list_engspeed = list[2].split(QRegExp("\\s+"));
        if (1 < list_engspeed.count())
        {
            m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_ENGSPEED"  , list_engspeed[1]);
        }
    }

    if (3 < list.count())
    {
        QStringList list_accel = list[3].split(QRegExp("\\s+"));
        if (1 < list_accel.count() )
        {
            m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_ACCEL"     , list_accel[1]);
        }
    }

    if (4 < list.count())
    {
        QStringList list_tco = list[4].split(QRegExp("\\s+"));
        if (1 < list_tco.count())
        {
            m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_TCO"       , list_tco[1]);
        }

        if (3 < list_tco.count())
        {
            QStringList list_tco_md = list_tco[3].split(":");
            if (1 < list_tco_md.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_TCO_MD"    , list_tco_md [1]);
            }
        }

        if (4 < list_tco.count())
        {
            QStringList list_tco_os =  list_tco[4].split(":");
            if (1 < list_tco_os.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_TCO_OS"    ,list_tco_os[1]);
            }
        }

        if (5 < list_tco.count())
        {
            QStringList list_tco_di = list_tco[5].split(":");
            if (1 < list_tco_di.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_TCO_DI"    , list_tco_di[1]);
            }
        }

        if (6 < list_tco.count())
        {
            QStringList list_tco_tp = list_tco[6].split(":");
            if (1 < list_tco_tp.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_TCO_TP"    , list_tco_tp[1]);
            }
        }

        if (7 < list_tco.count())
        {
            QStringList list_tco_hi =  list_tco[7].split(":");
            if (1 < list_tco_hi.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_TCO_HI"    ,list_tco_hi[1]);
            }
        }

        if (8 < list_tco.count())
        {
            QStringList list_tco_ev =   list_tco[8].split(":");
            if (1 < list_tco_ev.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_TCO_EV"    , list_tco_ev[1]);
            }
        }

        if (9 < list_tco.count())
        {
            QStringList list_tch_d1 =  list_tco[9].split(":");
            if (1 < list_tch_d1.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_TCO_D1"    , list_tch_d1[1]);
            }
        }

        if (10 < list_tco.count())
        {
            QStringList list_tch_d2 =  list_tco[10].split(":");
            if (1 < list_tch_d2.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_TCO_D2"    , list_tch_d2[1]);
            }
        }
    }

    if (5 < list.count())
    {
        QStringList list_speed = list[5].split(QRegExp("\\s+"));
        if (1 < list_speed.count())
        {
            m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_SPEED"     , list_speed[1]);
        }

        if (3 < list_speed.count())
        {
            QStringList list_speed_cc = list_speed[3].split(":");
            if (1 < list_speed_cc.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_SPEED_CC"  , list_speed_cc[1]);
            }
        }

        if (4 < list_speed.count())
        {
            QStringList list_speed_br = list_speed[4].split(":");
            if (1 < list_speed_br.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_SPEED_BR"  , list_speed_br[1]);
            }
        }

        if (5 < list_speed.count())
        {
            QStringList list_speed_cs = list_speed[5].split(":");
            if (1 < list_speed_cs.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_SPEED_CS"  , list_speed_cs[1]);
            }
        }

        if (6 < list_speed.count())
        {
            QStringList list_speed_pb = list_speed[6].split(":");
            if (1 < list_speed_pb.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_SPEED_PB"  , list_speed_pb[1]);
            }
        }
    }

    if (6 < list.count())
    {
        QStringList list_distance = list[6].split(QRegExp("\\s+"));
        if (1 < list_distance.count())
        {
            m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DISTANCE"  , list_distance[1]);
        }
    }

    if (7 < list.count())
    {
        QStringList list_enghours = list[7].split(QRegExp("\\s+"));
        if (1 < list_enghours.count())
        {
            m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_ENGHOURS"  , list_enghours[1]);
        }
    }

    if (8 < list.count())
    {
        QStringList list_fuelc = list[8].split(QRegExp("\\s+"));
        if (1 < list_fuelc.count())
        {
            m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_FUELC"     , list_fuelc[1]);
        }
    }

    if (9 < list.count())
    {
        QStringList list_engtemp = list[9].split(QRegExp("\\s+"));
        if (1 < list_engtemp.count())
        {
            m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_ENGTEMP"   , list_engtemp[1]);
        }
    }

    if (10 < list.count())
    {
        QStringList list_fuellev = list[10].split(QRegExp("\\s+"));
        if (1 < list_fuellev.count())
        {
            m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_FUELLEV"   , list_fuellev[1]);
        }
    }

    if (11 < list.count())
    {
        QStringList list_vehid =  list[11].split(QRegExp("\\s+"));
        if (1 < list_vehid.count())
        {
            m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_VEHID"     , list_vehid[1]);
        }
    }

    if (12 < list.count())
    {
        QStringList list_fms  =  list[12].split(QRegExp("\\s+"));
        if (1 < list_fms.count())
        {
            m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_FMS"       , list_fms[1]);
        }

        if (2 < list_fms.count())
        {
            QStringList list_fms_diag = list_fms[2].split(":");
            if (1 < list_fms_diag.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_FMS_DIAG"  , list_fms_diag[1]);
            }
        }

        if (3 < list_fms.count())
        {
            QStringList list_fms_requ = list_fms[3].split(":");
            if (1 < list_fms_requ.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_FMS_REQU"  , list_fms_requ[1]);
            }
        }
    }


    if (13 < list.count())
    {
        QStringList list_gear = list[13].split(QRegExp("\\s+"));
        if (1 < list_gear.count())
        {
            QStringList list_gear_s = list_gear[1].split(":");
            if (1 < list_gear_s.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_GEAR_S"    , list_gear_s[1]);
            }
        }

        if (2 < list_gear.count())
        {
            QStringList list_gear_c = list_gear[2].split(":");
            if (1 < list_gear_c.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_GEAR_C"    , list_gear_c[1]);
            }
        }
    }

    if (14 < list.count())
    {
        QStringList list_doorctrl = list[14].split(QRegExp("\\s+"));
        if (1 < list_doorctrl.count())
        {
            QStringList list_doorctrl_p =  list_doorctrl[1].split(":");
            if (1 < list_doorctrl_p.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DOORCTRL_P",list_doorctrl_p[1]);
            }
        }

        if (2 < list_doorctrl.count())
        {
            QStringList list_doorctrl_r =  list_doorctrl[2].split(":");
            if (1 < list_doorctrl_r.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DOORCTRL_R",list_doorctrl_r[1]);
            }
        }

        if (3 < list_doorctrl.count())
        {
            QStringList list_doorctrl_s =  list_doorctrl[3].split(":");
            if (1 < list_doorctrl_s.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DOORCTRL_S",list_doorctrl_s[1]);
            }
        }
    }

    if (15 < list.count())
    {
        QStringList list_dc2 = list[15].split(QRegExp("\\s+"));
        if (1 < list_dc2.count())
        {
            m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DC2"           , list_dc2[1]);
        }

        if (2 < list_dc2.count())
        {
            QStringList list_dc2_loe_1 = list_dc2[2].split(":");
            if (1 < list_dc2_loe_1.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DC2_LOE_1"     , list_dc2_loe_1[1]);
            }
        }

        if (3 < list_dc2.count())
        {
            QStringList list_dc2_loe_2 = list_dc2[3].split(":");
            if (1 < list_dc2_loe_2.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DC2_LOE_2"     , list_dc2_loe_2[1]);
            }
        }

        if (4 < list_dc2.count())
        {
            QStringList list_dc2_loe_3 = list_dc2[4].split(":");
            if (1 < list_dc2_loe_3.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DC2_LOE_3"     , list_dc2_loe_3[1]);
            }
        }

        if (5 < list_dc2.count())
        {
            QStringList list_dc2_loe_4 = list_dc2[5].split(":");
            if (1 < list_dc2_loe_4.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DC2_LOE_4"     , list_dc2_loe_4[1]);
            }
        }

        if (6 < list_dc2.count())
        {
            QStringList list_dc2_loe_5 =  list_dc2[6].split(":");
            if (1 < list_dc2_loe_5.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DC2_LOE_5"     , list_dc2_loe_5[1]);
            }
        }

        if (7 < list_dc2.count())
        {
            QStringList list_dc2_loe_6 =  list_dc2[7].split(":");
            if (1 < list_dc2_loe_6.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DC2_LOE_6"     , list_dc2_loe_6[1]);
            }
        }

        if (8 < list_dc2.count())
        {
            QStringList list_dc2_loe_7 = list_dc2[8].split(":");
            if (1 < list_dc2_loe_7.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DC2_LOE_7"     , list_dc2_loe_7[1]);
            }
        }

        if (9 < list_dc2.count())
        {
            QStringList list_dc2_loe_8 = list_dc2[9].split(":");
            if (1 < list_dc2_loe_8.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DC2_LOE_8"     , list_dc2_loe_8[1]);
            }
        }

        if (10 < list_dc2.count())
        {
            QStringList list_dc2_loe_9 =  list_dc2[10].split(":");
            if (1 < list_dc2_loe_9.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DC2_LOE_9"      ,list_dc2_loe_9[1]);
            }
        }

        if (11 < list_dc2.count())
        {
            QStringList list_dc2_loe_10 = list_dc2[11].split(":");
            if (1 < list_dc2_loe_10.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DC2_LOE_10"    , list_dc2_loe_10[1]);
            }
        }
     }

    if (16 < list.count())
    {
        QStringList list_bollowpr = list[16].split(QRegExp("\\s+"));

        if (1 < list_bollowpr.count())
        {
            QStringList list_bellowpr_fal = list_bollowpr[1].split(":");
            if (1 < list_bellowpr_fal.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_BELLOWPR_FAL"  , list_bellowpr_fal[1]);
            }
        }

        if (3 < list_bollowpr.count())
        {
            QStringList list_bellowpr_far = list_bollowpr[3].split(":");
            if (1 < list_bellowpr_far.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_BELLOWPR_FAR"  , list_bellowpr_far[1]);
            }
        }

        if (5 < list_bollowpr.count())
        {
            QStringList list_bellowpr_ral = list_bollowpr[5].split(":");
            if (1 < list_bellowpr_ral.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_BELLOWPR_RAL"  , list_bellowpr_ral[1]);
            }
        }

        if (7 < list_bollowpr.count())
        {
            QStringList list_bellowpr_rar =  list_bollowpr[7].split(":");
            if (1 < list_bellowpr_rar.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_BELLOWPR_RAR"  , list_bellowpr_rar[1]);
            }
        }
    }

    if (17 < list.count())
    {
        QStringList list_breakprr = list[17].split(QRegExp("\\s+"));
        if (1 < list_breakprr.count())
        {
            QStringList list_brakepr_1 =  list_breakprr[1].split(":");
            if (1 < list_brakepr_1.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_BRAKEPR_1"  , list_brakepr_1[1]);
            }
        }

        if (3 < list_breakprr.count())
        {
            QStringList list_brakepr_2 =  list_breakprr[3].split(":");
            if (1 < list_brakepr_2.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_BRAKEPR_2"  , list_brakepr_2[1]);
            }
        }
    }

    if (18 < list.count())
    {
        QStringList list_alternat = list[18].split(QRegExp("\\s+"));
        if (1 < list_alternat.count())
        {
            QStringList list_alternat_1 = list_alternat[1].split(":");
            if (1 < list_alternat_1.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_ALTERNAT_1" , list_alternat_1[1]);
            }
        }

        if (2 < list_alternat.count())
        {
            QStringList list_alternat_2 = list_alternat[2].split(":");
            if (1 < list_alternat_2.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_ALTERNAT_2" , list_alternat_2[1]);
            }
        }

        if (3 < list_alternat.count())
        {
            QStringList list_alternat_3 = list_alternat[3].split(":");
            if (1 < list_alternat_3.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_ALTERNAT_3" , list_alternat_3[1]);
            }
        }

        if (4 < list_alternat.count())
        {
            QStringList list_alternat_4 = list_alternat[4].split(":");
            if (1 < list_alternat_4.count())
            {
                m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_ALTERNAT_4" , list_alternat_4[1]);
            }
        }
    }

    if (19 < list.count())
    {
        QStringList list_datetime = list[19].split(QRegExp("\\s+"));
        if (1 < list_datetime.count())
        {
            m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DATETIME"   , list_datetime[1]);
        }
    }

    if (20 < list.count())
    {
        QStringList list_ambtemp = list[20].split(QRegExp("\\s+"));
        if (1 < list_ambtemp.count())
        {
            m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_AMBTEMP"    , list_ambtemp[1]);
        }
    }

    emit signalUpdateServices ();
}
コード例 #19
0
	void ChannelConfigWidget::on_InviteSearch__textChanged (const QString& text)
	{
		InviteFilterModel_->setFilterRegExp (QRegExp (text, Qt::CaseInsensitive,
				QRegExp::FixedString));
		InviteFilterModel_->setFilterKeyColumn (1);
	}
コード例 #20
0
ファイル: Zones.cpp プロジェクト: gregf83/GoldenCheetah
// read zone file, allowing for zones with or without end dates
bool Zones::read(QFile &file)
{
    defaults_from_user = false;
    scheme.zone_default.clear();
    scheme.zone_default_is_pct.clear();
    scheme.zone_default_name.clear();
    scheme.zone_default_desc.clear();
    scheme.nzones_default = 0;
    ranges.clear();

    // set up possible warning dialog
    warning = QString();
    int warning_lines = 0;
    const int max_warning_lines = 100;

    // macro to append lines to the warning
    #define append_to_warning(s) \
        if (warning_lines < max_warning_lines) \
	    warning.append(s);  \
        else if (warning_lines == max_warning_lines) \
	    warning.append("...\n"); \
        warning_lines ++;

    // read using text mode takes care of end-lines
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        err = "can't open file";
        return false;
    }
    QTextStream fileStream(&file);

    QRegExp commentrx("\\s*#.*$");
    QRegExp blankrx("^[ \t]*$");
    QRegExp rangerx[] = {
        QRegExp("^\\s*(?:from\\s+)?"                                 // optional "from"
                "((\\d\\d\\d\\d)[-/](\\d{1,2})[-/](\\d{1,2})|BEGIN)" // begin date
                "\\s*([,:]?\\s*(FTP|CP)\\s*=\\s*(\\d+))?"            // optional {CP/FTP = integer (optional %)}
                "\\s*:?\\s*$",                                       // optional :
                Qt::CaseInsensitive),
        QRegExp("^\\s*(?:from\\s+)?"                                 // optional "from"
                "((\\d\\d\\d\\d)[-/](\\d{1,2})[-/](\\d{1,2})|BEGIN)" // begin date
                "\\s+(?:until|to|-)\\s+"                             // until
                "((\\d\\d\\d\\d)[-/](\\d{1,2})[-/](\\d{1,2})|END)?"  // end date
                "\\s*:?,?\\s*((FTP|CP)\\s*=\\s*(\\d+))?"          // optional {CP/FTP = integer (optional %)}
                "\\s*:?\\s*$",                                       // optional :
                Qt::CaseInsensitive)
    };
    QRegExp zonerx("^\\s*([^ ,][^,]*),\\s*([^ ,][^,]*),\\s*"
		   "(\\d+)\\s*(%?)\\s*(?:,\\s*(\\d+|MAX)\\s*(%?)\\s*)?$",
		   Qt::CaseInsensitive);
    QRegExp zonedefaultsx("^\\s*(?:zone)?\\s*defaults?\\s*:?\\s*$",
			  Qt::CaseInsensitive);

    int lineno = 0;

    // the current range in the file
    // ZoneRange *range = NULL;
    bool in_range = false;
    QDate begin = date_zero, end = date_infinity;
    int cp=0;
    QList<ZoneInfo> zoneInfos;

    // true if zone defaults are found in the file (then we need to write them)
    bool zones_are_defaults = false;

    while (! fileStream.atEnd() ) {
        ++lineno;
	QString line = fileStream.readLine();
        int pos = commentrx.indexIn(line, 0);
        if (pos != -1)
            line = line.left(pos);
        if (blankrx.indexIn(line, 0) == 0)
	    goto next_line;

	// check for default zone range definition (may be followed by zone definitions)
	if (zonedefaultsx.indexIn(line, 0) != -1) {
	    zones_are_defaults = true;

	    // defaults are allowed only at the beginning of the file
	    if (ranges.size()) {
		err = "Zone defaults must be specified at head of power.zones file";
		return false;
	    }

	    // only one set of defaults is allowed
	    if (scheme.nzones_default) {
		err = "Only one set of zone defaults may be specified in power.zones file";
		return false;
	    }

	    goto next_line;
	}

	// check for range specification (may be followed by zone definitions)
        for (int r=0; r<2; r++) {
                if (rangerx[r].indexIn(line, 0) != -1) {

                        if (in_range) {

                                // if zones are empty, then generate them
                                ZoneRange range(begin, end, cp);
                                range.zones = zoneInfos;

                                if (range.zones.empty()) {
                                        if (range.cp > 0) setZonesFromCP(range);
                                        else {
                                                err = tr("line %1: read new range without reading "
                                                "any zones for previous one").arg(lineno);
                                                file.close();
                                                return false;
                                        }
                                } else {
                                        qSort(range.zones);
                                }
                                ranges.append(range);
                        }

                        in_range = true;
                        zones_are_defaults = false;
                        zoneInfos.clear();

                        // process the beginning date
                        if (rangerx[r].cap(1) == "BEGIN")
                                begin = date_zero;
                        else {
                                begin = QDate(rangerx[r].cap(2).toInt(),
                                rangerx[r].cap(3).toInt(),
                                rangerx[r].cap(4).toInt());
                        }

                        // process an end date, if any, else it is null
                        if (rangerx[r].cap(5) == "END") end = date_infinity;
                        else if (rangerx[r].cap(6).toInt() || rangerx[r].cap(7).toInt() ||
                                 rangerx[r].cap(8).toInt()) {

                                end = QDate(rangerx[r].cap(6).toInt(),
                                rangerx[r].cap(7).toInt(),
                                rangerx[r].cap(8).toInt());

                        } else {
                                end = QDate();
                        }

                        // set up the range, capturing CP if it's specified
                        // range = new ZoneRange(begin, end);
                        int nCP = (r ? 11 : 7);
                        if (rangerx[r].numCaptures() == (nCP)) cp = rangerx[r].cap(nCP).toInt();
                        else cp = 0;

                        // bleck
                        goto next_line;
                }
        }

	// check for zone definition
        if (zonerx.indexIn(line, 0) != -1) {
	    if (! (in_range || zones_are_defaults)) {
		err = tr("line %1: read zone without "
			 "preceding date range").arg(lineno);
		file.close();
		return false;
	    }

	    int lo = zonerx.cap(3).toInt();

	    // allow for zone specified as % of CP
	    bool lo_is_pct = false;
	    if (zonerx.cap(4) == "%") {
		if (zones_are_defaults) lo_is_pct = true;
		else if (cp > 0) lo = int(lo * cp / 100);
		else {
		    err = tr("attempt to set zone based on % of "
			     "CP without setting CP in line number %1.\n").
			arg(lineno);
		    file.close();
		    return false;
		}
            }

	    int hi;
	    // if this is not a zone defaults specification, process possible hi end of zones
	    if (zones_are_defaults || zonerx.cap(5).isEmpty())
		hi = -1;   // signal an undefined number
	    else if (zonerx.cap(5) == "MAX")
		hi = INT_MAX;
	    else {
		hi = zonerx.cap(5).toInt();

		// allow for zone specified as % of CP
		if (zonerx.cap(5) == "%") {
		    if (cp > 0)
			hi = int(hi * cp / 100);
		    else {
			    err = tr("attempt to set zone based on % of CP "
				    "without setting CP in line number %1.\n").
			        arg(lineno);
			    file.close();
			    return false;
		    }
                }
	    }

	    if (zones_are_defaults) {
		scheme.nzones_default ++;
		scheme.zone_default_is_pct.append(lo_is_pct);
		scheme.zone_default.append(lo);
		scheme.zone_default_name.append(zonerx.cap(1));
		scheme.zone_default_desc.append(zonerx.cap(2));
		defaults_from_user = true;
	    }
	    else {
		ZoneInfo zone(zonerx.cap(1), zonerx.cap(2), lo, hi);
		zoneInfos.append(zone);
	    }
	}
    next_line: {}
    }

    if (in_range) {
        ZoneRange range(begin, end, cp);
        range.zones = zoneInfos;
        if (range.zones.empty()) {
            if (range.cp > 0)
	        setZonesFromCP(range);
	    else {
                err = tr("file ended without reading any zones for last range");
                file.close();
                return false;
	    }
        }
	else {
	    qSort(range.zones);
	}

        ranges.append(range);
    }
    file.close();

    // sort the ranges
    qSort(ranges);

    // set the default zones if not in file
    if (!scheme.nzones_default)  {

        // do we have a zone which is explicitly set?
        for (int i=0; i<ranges.count(); i++) {
                if (ranges[i].zonesSetFromCP == false) {
                        // set the defaults using this one!
                        scheme.nzones_default = ranges[i].zones.count();
                        for (int j=0; j<scheme.nzones_default; j++) {
                                scheme.zone_default.append(((double)ranges[i].zones[j].lo / (double)ranges[i].cp) * 100.00);
                                scheme.zone_default_is_pct.append(true);
                                scheme.zone_default_name.append(ranges[i].zones[j].name);
                                scheme.zone_default_desc.append(ranges[i].zones[j].desc);
                        }
                }
        }

        // still not set then reset to defaults as usual
        if (!scheme.nzones_default) initializeZoneParameters();
    }

    // resolve undefined endpoints in ranges and zones
    for (int nr = 0; nr < ranges.size(); nr ++) {
	// clean up gaps or overlaps in zone ranges
	if (ranges[nr].end.isNull())
	    ranges[nr].end =
		(nr < ranges.size() - 1) ?
		ranges[nr + 1].begin :
		date_infinity;
	else if ((nr < ranges.size() - 1) &&
		 (ranges[nr + 1].begin != ranges[nr].end)) {

	    append_to_warning(tr("Setting end date of range %1 "
				 "to start date of range %2.\n").
			      arg(nr + 1).
			      arg(nr + 2)
			      );

	    ranges[nr].end = ranges[nr + 1].begin;
	}
	else if ((nr == ranges.size() - 1) &&
		 (ranges[nr].end < QDate::currentDate())) {

	    append_to_warning(tr("Extending final range %1 to infinite "
				 "to include present date.\n").arg(nr + 1));

	    ranges[nr].end = date_infinity;
	}

        if (ranges[nr].cp <= 0) {
            err = tr("CP must be greater than zero in zone "
                     "range %1 of power.zones").arg(nr + 1);
            return false;
        }

	if (ranges[nr].zones.size()) {
	    // check that the first zone starts with zero
	    ranges[nr].zones[0].lo = 0;

	    // resolve zone end powers
	    for (int nz = 0; nz < ranges[nr].zones.size(); nz ++) {
		if (ranges[nr].zones[nz].hi == -1)
		    ranges[nr].zones[nz].hi =
			(nz < ranges[nr].zones.size() - 1) ?
			ranges[nr].zones[nz + 1].lo :
			INT_MAX;
		else if ((nz < ranges[nr].zones.size() - 1) &&
			 (ranges[nr].zones[nz].hi != ranges[nr].zones[nz + 1].lo)) {
		    if (abs(ranges[nr].zones[nz].hi - ranges[nr].zones[nz + 1].lo) > 4) {
			append_to_warning(tr("Range %1: matching top of zone %2 "
					     "(%3) to bottom of zone %4 (%5).\n").
					  arg(nr + 1).
					  arg(ranges[nr].zones[nz].name).
					  arg(ranges[nr].zones[nz].hi).
					  arg(ranges[nr].zones[nz + 1].name).
					  arg(ranges[nr].zones[nz + 1].lo)
					  );
                    }
		    ranges[nr].zones[nz].hi = ranges[nr].zones[nz + 1].lo;

		} else if ((nz == ranges[nr].zones.size() - 1) &&
			 (ranges[nr].zones[nz].hi < INT_MAX)) {

		    append_to_warning(tr("Range %1: setting top of zone %2 from %3 to MAX.\n").
				      arg(nr + 1).
				      arg(ranges[nr].zones[nz].name).
				      arg(ranges[nr].zones[nz].hi)
				      );
		    ranges[nr].zones[nz].hi = INT_MAX;
		}
            }
	}
    }

    // mark zones as modified so pages which depend on zones can be updated
    modificationTime = QDateTime::currentDateTime();

    return true;
}
コード例 #21
0
ファイル: serveur.cpp プロジェクト: Danz0r77/OpalCoin
void Serveur::readServeur()
{
        QString message=QString::fromUtf8(this->readAll());


	QString currentChan=tab->tabText(tab->currentIndex());

	if(message.startsWith("PING :"))
	{
		QStringList liste=message.split(" ");
		QString msg="PONG "+liste.at(1);
		sendData(msg);
	}
	else if(message.contains("Nickname is already in use."))
	{
        pseudo=pseudo+"_2";
		pseudo.remove("\r\n");
		sendData("NICK "+pseudo);
		emit pseudoChanged(pseudo);
        ecrire("-> Name changed to "+pseudo);
	}
        else if(updateUsers==true)
	{
		updateUsersList("",message);
	}

    QStringList list=message.split("\r\n");
        foreach(QString msg,list)
        {
            if(msg.contains(QRegExp(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ PRIVMSG ([a-zA-Z0-9\\#]+) :(.+)")))
            {
                QRegExp reg(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ PRIVMSG ([a-zA-Z0-9\\#]+) :(.+)");
                QString msg2=msg;
                    ecrire(msg.replace(reg,"\\2 <b>&lt;\\1&gt;</b> \\3"),"",msg2.replace(reg,"\\2 <\\1> \\3"));
            }
            else if(msg.contains(QRegExp(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ JOIN ([a-zA-Z0-9\\#]+)")))
            {
                QRegExp reg(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ JOIN ([a-zA-Z0-9\\#]+)");
                QString msg2=msg;
                ecrire(msg.replace(reg,"\\2 <i>-> \\1 join \\2</i><br />"),"",msg2.replace(reg,"-> \\1 join \\2"));
                updateUsersList(msg.replace(reg,"\\2"));
            }
            else if(msg.contains(QRegExp(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ PART ([a-zA-Z0-9\\#]+)")))
            {
                QRegExp reg(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ PART ([a-zA-Z0-9\\#]+) :(.+)");
                QString msg2=msg;
                ecrire(msg.replace(reg,"\\2 <i>-> \\1 quit \\2 (\\3)</i><br />"),"",msg2.replace(reg,"-> \\1 quit \\2"));
                updateUsersList(msg.replace(reg,"\\2"));
            }
            else if(msg.contains(QRegExp(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ QUIT (.+)")))
            {
                QRegExp reg(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ QUIT (.+)");
                QString msg2=msg;
                ecrire(msg.replace(reg,"\\2 <i>-> \\1 quit this server (\\2)</i><br />"),"",msg2.replace(reg,"-> \\1 left"));
                updateUsersList(msg.replace(reg,"\\2"));
            }
            else if(msg.contains(QRegExp(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ NICK :(.+)")))
            {
                QRegExp reg(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ NICK :(.+)");
                QString msg2=msg;
                ecrire(msg.replace(reg,"<i>\\1 is now called \\2</i><br />"),"",msg2.replace(reg,"-> \\1 is now called \\2"));
                updateUsersList(currentChan);
            }
            else if(msg.contains(QRegExp(":([a-zA-Z0-9]+)\\![a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ KICK ([a-zA-Z0-9\\#]+) ([a-zA-Z0-9]+) :(.+)")))
            { 
                QRegExp reg(":([a-zA-Z0-9]+)\\!~[a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ KICK ([a-zA-Z0-9\\#]+) ([a-zA-Z0-9]+) :(.+)");
                QString msg2=msg;
                ecrire(msg.replace(reg,"\\2 <i>-> \\1 kicked \\3 (\\4)</i><br />"),"",msg2.replace(reg,"-> \\1 quit \\3"));
                updateUsersList(msg.replace(reg,"\\2"));
            }
            else if(msg.contains(QRegExp(":([a-zA-Z0-9]+)\\![a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ NOTICE ([a-zA-Z0-9]+) :(.+)")))
            {
                if(conversations.contains(currentChan))
                {
                    QRegExp reg(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ NOTICE [a-zA-Z0-9]+ :(.+)");
                    ecrire(msg.replace(reg,"<b>[NOTICE] <i>\\1</i> : \\2 <br />"),currentChan);
                }
                else if(currentChan==serveur)
                {
                    QRegExp reg(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ NOTICE [a-zA-Z0-9]+ :(.+)");
                    ecrire(msg.replace(reg,"<b>[NOTICE] <i>\\1</i> : \\2 <br />"));
                }
            }
            else if(msg.contains("/MOTD command."))
            {
             joins();


            }



        }

        //}
}
コード例 #22
0
ファイル: centerwindow.cpp プロジェクト: jun-zhang/MvGather
void CenterWindow::addMvToPlaylist(QString tvUrl)
{
    myTipWin.show();
    myTipWin.setBusyIndicatorShow(true);
    myTipWin.setText("请求数据中");
    QNetworkAccessManager *manager= new QNetworkAccessManager;
    QNetworkReply *reply = manager->get(QNetworkRequest(QUrl(tvUrl)));
    QEventLoop loop;
    QTimer::singleShot(10000,&loop,SLOT(quit()));
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();
    QByteArray data = reply->readAll();

    QStringList tvNoHrefList;
    //find tvName(title) and QStringList serials//来源名称及剧集列表
    QRegExp rx_title("<span class=\"title\">.*</span>");
    rx_title.setMinimal(true);
    int pos = 0;
    QString title;
    while ((pos = rx_title.indexIn(data, pos)) != -1) {
        title=rx_title.cap(0);
        pos += rx_title.matchedLength();
    }
    QString tvName = title.replace(QRegExp("<span class=\"title\">|</span>"),"");

    if(data.contains("好看的综艺"))//综艺大分类
    {
        //取出地址中的影视ID,http://www.yunfan.com/show/va/6287162973540335925.html
        QString id = tvUrl.split("/").last().replace(".html","");
        QRegExp rx_vlist("\"tv_ico\".*</div>");
        QRegExp rx_vlist_one("source=\'.*\'");
        QStringList vlist;
        rx_vlist.setMinimal(true);
        rx_vlist_one.setMinimal(true);
        pos = 0;
        QString vlistStr;
        while ((pos = rx_vlist.indexIn(data, pos)) != -1) {
            vlistStr=rx_vlist.cap(0);
            pos += rx_vlist.matchedLength();
        }
        pos=0;
        while ((pos = rx_vlist_one.indexIn(vlistStr, pos)) != -1) {
            QString str=rx_vlist_one.cap(0);
            vlist.append(str.replace(QRegExp("source=\'|\'"),""));
            pos += rx_vlist_one.matchedLength();
        }

        foreach (QString v, vlist) {
            QString tvNoHrefListStr;//tvNoHrefList<<tvNoHrefListStr,tvNoHrefListStr:1#href
            QString jsonUrl = QString("http://www.yunfan.com/show/vapage.php?id=%1&site=%2").arg(id).arg(v);
            QNetworkReply *reply = manager->get(QNetworkRequest(QUrl(jsonUrl)));
            QEventLoop loop;
            QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
            loop.exec();
            QByteArray data = reply->readAll();
            pos=0;
            QRegExp rx_href("href=\'.*\'");
            rx_href.setMinimal(true);
            QString href_temp;
            int i=1;
            while ((pos = rx_href.indexIn(data, pos)) != -1 ) {//(pos = rx_href.indexIn(data, pos)) != -1) &&
                href_temp=rx_href.cap(0);
                href_temp.replace(QRegExp("href=\'|\'"),"");
                href_temp.replace("\\","");
                tvNoHrefListStr.append(QString::number(i)+"#"+href_temp.split("#").value(0,"")+"$");
                pos += rx_href.matchedLength();
                i++;
            }
            tvNoHrefList<<tvNoHrefListStr;

        }
コード例 #23
0
void IconFactory::setupSearchPaths() {
  QIcon::setThemeSearchPaths(QStringList() << APP_THEME_PATH);
  qDebug("Available icon theme paths: %s.",
         qPrintable(QIcon::themeSearchPaths().replaceInStrings(QRegExp("^|$"),
                                                               "\'").join(", ")));
}
コード例 #24
0
ファイル: Function.cpp プロジェクト: EzhikTT/NaturalSort
void sortByLexeme(QStringList &sortList)
{
	// Карта для хранения строк с начальной текстовой строкой
	// Ключ карты - начальная строка, значения - остаток строки
	QMap<QString, QStringList> strMap;

	// Карта для хранения строк с начальной числовой строкой
	// Ключ карты - начальная строка, значения - остаток строки
	QMap<double, QStringList> numMap;

	QList<double> sortingKeyNum; // Лист для сортировки числовых ключей

	QStringList sortingKeyStr; // Лист для сортировки строковых ключей

	QStringList res;	// Результирующий лист

	QString temp; // Буфер для текущей обрабатываемой строки

	QString buf; // Буфер для ключа - домена

	QString str; // Буфер для одного из значений ключа - имени адреса

	QString aIter; // Буфер для строкого ключа при формировании выходного списка

	QString aIterKlein; // Буфер для строки из списка для каждой строки из списка

	double num; // Буфер для хранения ключа для числовой карты

	double aIterNum; // Буфер для числового ключа при формировании выходного списка
	
	// Заполнение карты путей
	for(int i=0; i<sortList.count(); i++)
	{
		// Загрузка в бущер текущей строки для сортировки
		temp=sortList[i];
		
		// Заполнение карты по числовому ключу
		if(temp[0].isNumber())
		{
			// Получение ключа
			buf=temp.section(QRegExp("[A-z]"), 0, 0);

			// Перевод ключа из строки в число
			num=buf.toDouble();

			// Получение значения
			str=temp.remove(buf);

			/*// Заполнение карты, если остаток строки не пустой 
			if(!str.isEmpty())
			{*/
				if(numMap.contains(num))
				{
					numMap[num]<<str;
				}
				else
				{ 
					numMap.insert(num, QStringList(str));
				}
			//}
		}
		// Заполнение карты по нечисловому ключу
		else
		{
			// Получение ключа
			buf=temp.section(QRegExp("\\d"), 0, 0);

			// Получение значения
			str=temp.remove(buf);

			/*// Заполнение карты, если остаток строки не пустой 
			if(!str.isEmpty())
			{*/
				if(strMap.contains(buf))
				{
					strMap[buf]<<str;
				}
				else
				{ 
					strMap.insert(buf, QStringList(str));
				}
			//}
		}
	}
	
	// Сортировка карты с числовым ключом
	// Сортировка значений для каждого ключа
	QMap<double, QStringList>::iterator itn=numMap.begin();
	
	for(;itn!=numMap.end(); itn++)
	{
		if(itn.value().count()>1)
		{
			sortByLexeme(itn.value());
		}
	}

	// Записей ключей в лист
	itn=numMap.begin();
	for(;itn!=numMap.end(); itn++)
	{
		sortingKeyNum<<itn.key();
	}

	// Сортировка ключей
	//sortingKeyNum.sort();
	qStableSort(sortingKeyNum.begin(), sortingKeyNum.end());

	// Сортировка карты со строковым ключом
	// Сортировка значений для каждого ключа
	QMap<QString, QStringList>::iterator its=strMap.begin();
	
	for(;its!=strMap.end(); its++)
	{
		if(its.value().count()>1)
		{
			sortByLexeme(its.value());
		}
	}

	// Записей ключей в лист
	its=strMap.begin();
	for(;its!=strMap.end(); its++)
	{
		sortingKeyStr<<its.key();
	}

	// Сортировка ключей
	//sortingKeyStr.sort();
	qStableSort(sortingKeyStr.begin(), sortingKeyStr.end(), caseInsensitiveLessThan);

	// Заполнение выходного листа полями из числовой карты
	for(int j=0; j<sortingKeyNum.count(); j++)
	{
		// Загрузка в бущер текущей строки для ключа
		aIterNum=sortingKeyNum[j];

		// Загрузка в выходной лист значений для определенного ключа 
		for(int k=0; k<numMap[aIterNum].count(); k++)
		{
			// Загрузка в буфер текущей строки для сортировки
			aIterKlein=QString::number(aIterNum)+numMap[aIterNum][k];

			// Добавление строки в выходной лист
			res<<aIterKlein;
		}
	}

	// Заполнение выходного листа полями из строковой карты
	for(int j=0; j<sortingKeyStr.count(); j++)
	{
		// Загрузка в бущер текущей строки для ключа
		aIter=sortingKeyStr[j];

		// Загрузка в выходной лист значений для определенного ключа 
		for(int k=0; k<strMap[aIter].count(); k++)
		{
			// Загрузка в буфер текущей строки для сортировки
			aIterKlein=aIter+strMap[aIter][k];

			// Добавление строки в выходной лист
			res<<aIterKlein;
		}
	}

	// Замена данного листа на возвращаемый
	sortList=res;
}
コード例 #25
0
QString MycosmosController::getViewState(QString &htmlResponse){
    return htmlResponse.replace(QRegExp("^.*__VIEWSTATE\" value=\"([^\"]*)\".*$"),"\\1");
}
コード例 #26
0
void MainDialog::setDisplay( const QString & button, const QString & status, const QString & color )
{
	QString statusText = QString("<p align=\"center\">Status [ <font size=\"+1\" color=\"%1\">%2</font> ]</p>").arg( color ).arg( status );
	mStatusLabel->setText( statusText );
	setWindowTitle(QString(cAppName+" Client [ %1 ] - Version %2, build %3").arg(status).arg(VERSION).arg(QString("$Date$").remove(QRegExp("[^\\d]"))) );
	DisableButton->setText( button );
}
コード例 #27
0
ファイル: qgsnewhttpconnection.cpp プロジェクト: rotulet/QGIS
QgsNewHttpConnection::QgsNewHttpConnection(
  QWidget *parent, const QString& baseKey, const QString& connName, const Qt::WindowFlags& fl )
    : QDialog( parent, fl )
    , mBaseKey( baseKey )
    , mOriginalConnName( connName )
    , mAuthConfigSelect( 0 )
{
  setupUi( this );

  QString service = baseKey.mid( 18, 3 ).toUpper();
  setWindowTitle( tr( "Create a new %1 connection" ).arg( service ) );

  // It would be obviously much better to use mBaseKey also for credentials,
  // but for some strange reason a different hardcoded key was used instead.
  // WFS and WMS credentials were mixed with the same key WMS.
  // Only WMS and WFS providers are using QgsNewHttpConnection at this moment
  // using connection-wms and connection-wfs -> parse credential key fro it.
  mCredentialsBaseKey = mBaseKey.split( '-' ).last().toUpper();

  txtName->setValidator( new QRegExpValidator( QRegExp( "[^\\/]+" ), txtName ) );

  cmbDpiMode->clear();
  cmbDpiMode->addItem( tr( "all" ) );
  cmbDpiMode->addItem( tr( "off" ) );
  cmbDpiMode->addItem( tr( "QGIS" ) );
  cmbDpiMode->addItem( tr( "UMN" ) );
  cmbDpiMode->addItem( tr( "GeoServer" ) );

  mAuthConfigSelect = new QgsAuthConfigSelect( this );
  tabAuth->insertTab( 1, mAuthConfigSelect, tr( "Configurations" ) );

  if ( !connName.isEmpty() )
  {
    // populate the dialog with the information stored for the connection
    // populate the fields with the stored setting parameters

    QSettings settings;

    QString key = mBaseKey + connName;
    QString credentialsKey = "/Qgis/" + mCredentialsBaseKey + '/' + connName;
    txtName->setText( connName );
    txtUrl->setText( settings.value( key + "/url" ).toString() );

    cbxIgnoreGetMapURI->setChecked( settings.value( key + "/ignoreGetMapURI", false ).toBool() );
    cbxIgnoreAxisOrientation->setChecked( settings.value( key + "/ignoreAxisOrientation", false ).toBool() );
    cbxInvertAxisOrientation->setChecked( settings.value( key + "/invertAxisOrientation", false ).toBool() );
    cbxIgnoreGetFeatureInfoURI->setChecked( settings.value( key + "/ignoreGetFeatureInfoURI", false ).toBool() );
    cbxSmoothPixmapTransform->setChecked( settings.value( key + "/smoothPixmapTransform", false ).toBool() );

    int dpiIdx;
    switch ( settings.value( key + "/dpiMode", 7 ).toInt() )
    {
      case 0: // off
        dpiIdx = 1;
        break;
      case 1: // QGIS
        dpiIdx = 2;
        break;
      case 2: // UMN
        dpiIdx = 3;
        break;
      case 4: // GeoServer
        dpiIdx = 4;
        break;
      default: // other => all
        dpiIdx = 0;
        break;
    }
    cmbDpiMode->setCurrentIndex( dpiIdx );

    txtReferer->setText( settings.value( key + "/referer" ).toString() );

    txtUserName->setText( settings.value( credentialsKey + "/username" ).toString() );
    txtPassword->setText( settings.value( credentialsKey + "/password" ).toString() );

    QString authcfg = settings.value( credentialsKey + "/authcfg" ).toString();
    mAuthConfigSelect->setConfigId( authcfg );
    if ( !authcfg.isEmpty() )
    {
      tabAuth->setCurrentIndex( tabAuth->indexOf( mAuthConfigSelect ) );
    }
  }

  if ( mBaseKey != "/Qgis/connections-wms/" )
  {
    if ( mBaseKey == "/Qgis/connections-wcs/" )
    {
      cbxIgnoreGetMapURI->setText( tr( "Ignore GetCoverage URI reported in capabilities" ) );
      cbxIgnoreAxisOrientation->setText( tr( "Ignore axis orientation" ) );
    }
    else
    {
      cbxIgnoreGetMapURI->setVisible( false );
      cbxIgnoreAxisOrientation->setVisible( false );
      cbxInvertAxisOrientation->setVisible( false );
      cbxSmoothPixmapTransform->setVisible( false );
      mGroupBox->layout()->removeWidget( cbxIgnoreGetMapURI );
      mGroupBox->layout()->removeWidget( cbxIgnoreAxisOrientation );
      mGroupBox->layout()->removeWidget( cbxInvertAxisOrientation );
      mGroupBox->layout()->removeWidget( cbxSmoothPixmapTransform );
    }

    cbxIgnoreGetFeatureInfoURI->setVisible( false );
    mGroupBox->layout()->removeWidget( cbxIgnoreGetFeatureInfoURI );

    cmbDpiMode->setVisible( false );
    mGroupBox->layout()->removeWidget( cmbDpiMode );
    lblDpiMode->setVisible( false );
    mGroupBox->layout()->removeWidget( lblDpiMode );

    txtReferer->setVisible( false );
    mGroupBox->layout()->removeWidget( txtReferer );
    lblReferer->setVisible( false );
    mGroupBox->layout()->removeWidget( lblReferer );

    // Adjust height
    int w = width();
    adjustSize();
    resize( w, height() );
  }

  on_txtName_textChanged( connName );
}
コード例 #28
0
ファイル: script.cpp プロジェクト: Babbsdrebbler/qlcplus
QList <QStringList> Script::tokenizeLine(const QString& str, bool* ok)
{
    QList<QStringList> tokens;
    int left = 0;
    int right = 0;
    QString keyword;
    QString value;

    if (str.simplified().startsWith("//") == true || str.simplified().isEmpty() == true)
    {
        tokens << QStringList(); // Return an empty string list for commented lines
    }
    else
    {
        // Truncate everything after the first comment sign
        QString line = str;
        left = line.indexOf("//");
        if (left != -1)
            line.truncate(left);

        left = 0;
        while (left < line.length())
        {
            // Find the next colon to get the keyword
            right = line.indexOf(":", left);
            if (right == -1)
            {
                qDebug() << "Syntax error:" << line.mid(left);
                if (ok != NULL)
                    *ok = false;
                break;
            }
            else
            {
                // Keyword found
                keyword = line.mid(left, right - left);
                left = right + 1;
            }

            // Try to see if there is something inside quotes
            int quoteleft = line.indexOf("\"", left);
            if (quoteleft != -1)
            {
                int quoteright = line.indexOf("\"", quoteleft + 1);
                if (quoteright != -1)
                {
                    // Don't include the "" in the string
                    value = line.mid(quoteleft, quoteright - quoteleft);
                    left = quoteright + 1;
                }
                else
                {
                    qDebug() << "Syntax error:" << line.mid(quoteleft);
                    if (ok != NULL)
                        *ok = false;
                    break;
                }
            }
            else
            {
                // No quotes. Find the next whitespace.
                right = line.indexOf(QRegExp("\\s"), left);
                if (right == -1)
                {
                    qDebug() << "Syntax error:" << line.mid(left);
                    if (ok != NULL)
                        *ok = false;
                    break;
                }
                else
                {
                    // Value found
                    value = line.mid(left, right - left);
                    left = right + 1;
                }
            }

            tokens << (QStringList() << keyword.trimmed() << value.trimmed());
        }
    }

    if (ok != NULL)
        *ok = true;

    return tokens;
}
コード例 #29
0
ファイル: Haupt.cpp プロジェクト: BackupTheBerlios/qtsbsa-svn
int main(int anzahlArgumente, char *Argumente[]) 
{
	QT_REQUIRE_VERSION(anzahlArgumente, Argumente, "4.2.2")
	QApplication Programm(anzahlArgumente,Argumente);
#ifdef QT_SIDE_BY_SIDE_ASSEMBLY
	/*
		Alle Side-By-Side PlugIns müssen den Schema Hersteller.Qt.PlugIn-XXXX entsprechen!!!
		Wobei XXXX einem Plugin-Namen entspricht. z.B. HansMutermann.Qt.PlugIn-mysql
		All side-by-side plugIns must fit to the pattern vendor.Qt.PlugIn-XXXX!!
		XXXX is the name of the PlugIN. Example: HansMustermann.Qt.PlugIn-mysql
	*/
	QString Manifestname=QCoreApplication::instance()->arguments().at(0)+".manifest";
	QFile Manifest(Manifestname);
	if(Manifest.open(QIODevice::ReadOnly))
	{
		QTextStream Inhalt(&Manifest);
		QString Hersteller;
		QString Plattform;
		int PlattformStart;
		int PlattformEnde;
		int HerstellerStart;
		int HerstellerEnde;
		QString Zeile;
		while(!Inhalt.atEnd())
		{
			//Wie ist der Platfom/Hersteller meiner Qt Lib??
			Zeile=Inhalt.readLine();
			//Jedes Qt Programm benötigt QtCore. Darauf kann man sicher testen.
			if(Zeile.contains("QtCore"))
			{
				PlattformStart=Zeile.indexOf("processorArchitecture");				
				PlattformStart=Zeile.indexOf(QRegExp("[x,X,i]"),PlattformStart+21);//wo fängt der Platformtext an 21=Länge processorArchitecture
				PlattformEnde=Zeile.indexOf(QRegExp("[\",\']"),PlattformStart+1);
				Plattform=Zeile.mid(PlattformStart,PlattformEnde-PlattformStart);
				HerstellerStart=Zeile.indexOf("name");
				HerstellerStart=Zeile.indexOf(QRegExp("[\",\']"),HerstellerStart+4)+1;
				HerstellerEnde=Zeile.indexOf(QRegExp("[\",\']"),HerstellerStart+1);
				Hersteller=Zeile.mid(HerstellerStart,HerstellerEnde-HerstellerStart).split('.').first();				
				break;
			}
		}
		Manifest.close();
		//Welche Verzeichnise haben wir??
		//Die Plug-INs als Side-by-Side Assekmblys gehen nicht, da Qt immer in unterverzeichnissen suchen will!!
		QDir WindowsSXS(QProcess::systemEnvironment().filter("SystemRoot").first().split('=').last()+"\\winsxs");
		QStringList VerzeichnisseMitPlugINs=WindowsSXS.entryList(QStringList(Plattform+"_"+Hersteller+".Qt.PlugIn-*"),QDir::Dirs|QDir::CaseSensitive);
		/*for(int Verzeichnis=0;Verzeichnis<VerzeichnisseMitPlugINs.size();Verzeichnis++)
		{
			QCoreApplication::addLibraryPath(WindowsSXS.path().replace('/','\\')+"\\"+VerzeichnisseMitPlugINs.at(Verzeichnis));
		}*/
		QString GemeinsamesVerzeichnis=QProcess::systemEnvironment().filter("CommonProgramFiles").first().split('=').last()+"\\"+Hersteller+"\\Qt\\"+qVersion();
		/*
			Also diese Lösung bis es in Qt geht:
			Die Plug-Is befinden sich unter %CommonProgramFiles%\Entwicklername\Qt\Version\plugins
		*/		
		QCoreApplication::setLibraryPaths(QStringList(GemeinsamesVerzeichnis+"\\plugins"));
		//Übersetzungen für Qt
		QTranslator QtUebersetzung;
		QtUebersetzung.load("qt_"+QLocale::system().name().left(QLocale::system().name().indexOf("_")),GemeinsamesVerzeichnis+"\\Uebersetzungen");
		QCoreApplication::instance()->installTranslator(&QtUebersetzung);
	}	
#else
	QTranslator QtSystem;
	// Ein Gruss an die Doku von Qt 4.2
	QtSystem.load("qt_" + QLocale::system().name(),QLibraryInfo::location(QLibraryInfo::TranslationsPath));
	Programm.installTranslator(&QtSystem);
#endif
	
	QTranslator Meine;	
	Meine.load(":/Uebersetzungen/Uebersetzung");	
	Programm.installTranslator(&Meine);
	QFrankQtSBSADlgHaupt Hauptdialog;
	Hauptdialog.show();
	return Programm.exec(); 
}
コード例 #30
0
ファイル: movieexporter.cpp プロジェクト: chchwy/pencil2d
/** Runs the specified command (should be ffmpeg), and lets
 *  writeFrame pipe data into it 1 frame at a time.
 *
 *  @param[in]  strCmd A string containing the command to execute and
 *              all of its arguments
 *  @param[out] progress A function that takes one float argument
 *              (the percentage of the ffmpeg operation complete) and
 *              may display the output to the user in any way it
 *              sees fit.
 *  @param[in]  writeFrame A function that takes two arguments, a
 *              process (the ffmpeg process) and an integer
 *              (frames processed or -1, see full description).
 *              This function should write a single frame to the
 *              process. The function returns true value if it
 *              actually wrote a frame.
 *
 *  This function operates generally as follows:
 *  1. Spawn process with the command from strCmd
 *  2. Check ffmpeg's output for a progress update.
 *  3. Add frames with writeFrame until it returns false.
 *  4. Repeat from step 2 until all frames have been written.
 *
 *  The idea is that there are two forms of processing occuring
 *  simultaneously, generating frames to send to ffmpeg, and ffmpeg
 *  encoding those frames. Whether these this actually occur
 *  concurrently or one after another appears to depend on the environment.
 *
 *  The writeFrame function deserves a bit of extra details. It does
 *  not only return false when there is an error in generating or
 *  writing a frame, it also does it when it wants to "return control"
 *  to the rest of the executeFFMpegPipe function for the purposes of
 *  reading updates from ffmpeg's output. This should be done every
 *  once in a while if possible, but with some formats (specifically gif),
 *  all frames must be loaded before any processing can continue, so
 *  there is no point returning false for it until all frames have
 *  been written. writeFrame is also responsible for closing the writeChannel
 *  of the process when it has finished writing all frames. This indicates
 *  to executeFFMpegPipe that it no longer needs to call writeFrame.
 *
 *  @return Returns Status::OK if everything went well, and Status::FAIL
 *  and error is detected (usually a non-zero exit code for ffmpeg).
 */
Status MovieExporter::executeFFMpegPipe(QString strCmd, std::function<void(float)> progress, std::function<bool(QProcess&, int)> writeFrame)
{
    qDebug() << strCmd;

    QProcess ffmpeg;
    ffmpeg.setReadChannel(QProcess::StandardOutput);
    // FFmpeg writes to stderr only for some reason, so we just read both channels together
    ffmpeg.setProcessChannelMode(QProcess::MergedChannels);
    ffmpeg.start(strCmd);
    if (ffmpeg.waitForStarted())
    {
        int framesGenerated = 0;
        int lastFrameProcessed = 0;
        const int frameStart = mDesc.startFrame;
        const int frameEnd = mDesc.endFrame;
        while(ffmpeg.state() == QProcess::Running)
        {
            if (mCanceled)
            {
                ffmpeg.terminate();
                return Status::CANCELED;
            }

            // Check FFmpeg progress

            int framesProcessed = -1;
            if(ffmpeg.waitForReadyRead(10))
            {
                QString output(ffmpeg.readAll());
                QStringList sList = output.split(QRegExp("[\r\n]"), QString::SkipEmptyParts);
                for (const QString& s : sList)
                {
                    qDebug() << "[ffmpeg]" << s;
                }
                if(output.startsWith("frame="))
                {
                    lastFrameProcessed = framesProcessed = output.mid(6, output.indexOf(' ')).toInt();
                }
            }

            if(!ffmpeg.isWritable())
            {
                continue;
            }

            while(writeFrame(ffmpeg, framesProcessed))
            {
                framesGenerated++;

                const float percentGenerated = framesGenerated / static_cast<float>(frameEnd - frameStart);
                const float percentConverted = lastFrameProcessed / static_cast<float>(frameEnd - frameStart);
                progress((percentGenerated + percentConverted) / 2);
            }
            const float percentGenerated = framesGenerated / static_cast<float>(frameEnd - frameStart);
            const float percentConverted = lastFrameProcessed / static_cast<float>(frameEnd - frameStart);
            progress((percentGenerated + percentConverted) / 2);
        }

        QString output(ffmpeg.readAll());
        QStringList sList = output.split(QRegExp("[\r\n]"), QString::SkipEmptyParts);
        for (const QString& s : sList)
        {
            qDebug() << "[ffmpeg]" << s;
        }

        if(ffmpeg.exitStatus() != QProcess::NormalExit)
        {
            qDebug() << "ERROR: FFmpeg crashed";
            return Status::FAIL;
        }
    }
    else
    {
        qDebug() << "ERROR: Could not start FFmpeg.";
        return Status::FAIL;
    }

    return Status::OK;
}