Exemple #1
0
static void parse( MetaTranslator *tor, const char *initialContext,
		   const char *defaultContext )
{
    QMap<QCString, QCString> qualifiedContexts;
    QStringList namespaces;
    QCString context;
    QCString text;
    QCString com;
    QCString functionContext = initialContext;
    QCString prefix;
    bool utf8 = FALSE;
    bool missing_Q_OBJECT = FALSE;

    yyTok = getToken();
    while ( yyTok != Tok_Eof ) {
	switch ( yyTok ) {
	case Tok_class:
	    /*
	      Partial support for inlined functions.
	    */
	    yyTok = getToken();
	    if ( yyBraceDepth == (int) namespaces.count() &&
		 yyParenDepth == 0 ) {
		do {
		    /*
		      This code should execute only once, but we play
		      safe with impure definitions such as
		      'class Q_EXPORT QMessageBox', in which case
		      'QMessageBox' is the class name, not 'Q_EXPORT'.
		    */
		    functionContext = yyIdent;
		    yyTok = getToken();
		} while ( yyTok == Tok_Ident );

		while ( yyTok == Tok_Gulbrandsen ) {
		    yyTok = getToken();
		    functionContext += "::";
		    functionContext += yyIdent;
		    yyTok = getToken();
		}

		if ( yyTok == Tok_Colon ) {
		    missing_Q_OBJECT = TRUE;
		} else {
		    functionContext = defaultContext;
		}
	    }
	    break;
	case Tok_namespace:
	    yyTok = getToken();
	    if ( yyTok == Tok_Ident ) {
		QCString ns = yyIdent;
		yyTok = getToken();
		if ( yyTok == Tok_LeftBrace &&
		     yyBraceDepth == (int) namespaces.count() + 1 )
		    namespaces.append( QString(ns) );
	    }
	    break;
	case Tok_tr:
	case Tok_trUtf8:
	    utf8 = ( yyTok == Tok_trUtf8 );
	    yyTok = getToken();
	    if ( match(Tok_LeftParen) && matchString(&text) ) {
		com = "";
		if ( match(Tok_RightParen) || (match(Tok_Comma) &&
			matchString(&com) && match(Tok_RightParen)) ) {
		    if ( prefix.isNull() ) {
			context = functionContext;
			if ( !namespaces.isEmpty() )
			    context.prepend( (namespaces.join(QString("::")) +
					      QString("::")).latin1() );
		    } else {
			context = prefix;
		    }
		    prefix = (const char *) 0;

		    if ( qualifiedContexts.contains(context) )
			context = qualifiedContexts[context];
		    tor->insert( MetaTranslatorMessage(context, text, com,
						       QString::null, utf8) );

		    if ( lacks_Q_OBJECT.contains(context) ) {
			qWarning( "%s:%d: Class '%s' lacks Q_OBJECT macro",
				  (const char *) yyFileName, yyLineNo,
				  (const char *) context );
			lacks_Q_OBJECT.remove( context );
		    } else {
			needs_Q_OBJECT.insert( context, 0 );
		    }
		}
	    }
	    break;
	case Tok_translate:
	    utf8 = FALSE;
	    yyTok = getToken();
	    if ( match(Tok_LeftParen) &&
		 matchString(&context) &&
		 match(Tok_Comma) &&
		 matchString(&text) ) {
		com = "";
		if ( match(Tok_RightParen) ||
		     (match(Tok_Comma) &&
		      matchString(&com) &&
		      (match(Tok_RightParen) ||
		       match(Tok_Comma) &&
		       matchEncoding(&utf8) &&
		       match(Tok_RightParen))) )
		    tor->insert( MetaTranslatorMessage(context, text, com,
						       QString::null, utf8) );
	    }
	    break;
	case Tok_Q_OBJECT:
	    missing_Q_OBJECT = FALSE;
	    yyTok = getToken();
	    break;
	case Tok_Ident:
	    if ( !prefix.isNull() )
		prefix += "::";
	    prefix += yyIdent;
	    yyTok = getToken();
	    if ( yyTok != Tok_Gulbrandsen )
		prefix = (const char *) 0;
	    break;
	case Tok_Comment:
	    com = yyComment;
	    com = com.simplifyWhiteSpace();
	    if ( com.left(sizeof(MagicComment) - 1) == MagicComment ) {
		com.remove( 0, sizeof(MagicComment) - 1 );
		int k = com.find( ' ' );
		if ( k == -1 ) {
		    context = com;
		} else {
		    context = com.left( k );
		    com.remove( 0, k + 1 );
		    tor->insert( MetaTranslatorMessage(context, "", com,
						       QString::null, FALSE) );
		}

		/*
		  Provide a backdoor for people using "using
		  namespace". See the manual for details.
		*/
		k = 0;
		while ( (k = context.find("::", k)) != -1 ) {
		    qualifiedContexts.insert( context.mid(k + 2), context );
		    k++;
		}
	    }
	    yyTok = getToken();
	    break;
	case Tok_Arrow:
	    yyTok = getToken();
	    if ( yyTok == Tok_tr || yyTok == Tok_trUtf8 )
		qWarning( "%s:%d: Cannot invoke tr() like this",
			  (const char *) yyFileName, yyLineNo );
	    break;
	case Tok_Gulbrandsen:
	    // at top level?
	    if ( yyBraceDepth == (int) namespaces.count() && yyParenDepth == 0 )
		functionContext = prefix;
	    yyTok = getToken();
	    break;
	case Tok_RightBrace:
	case Tok_Semicolon:
	    if ( yyBraceDepth >= 0 &&
		 yyBraceDepth + 1 == (int) namespaces.count() )
		namespaces.remove( namespaces.fromLast() );
	    if ( yyBraceDepth == (int) namespaces.count() ) {
		if ( missing_Q_OBJECT ) {
		    if ( needs_Q_OBJECT.contains(functionContext) ) {
			qWarning( "%s:%d: Class '%s' lacks Q_OBJECT macro",
				  (const char *) yyFileName, yyLineNo,
				  (const char *) functionContext );
		    } else {
			lacks_Q_OBJECT.insert( functionContext, 0 );
		    }
		}
		functionContext = defaultContext;
		missing_Q_OBJECT = FALSE;
	    }
	    yyTok = getToken();
	    break;
	default:
	    yyTok = getToken();
	}
    }

    if ( yyBraceDepth != 0 )
	fprintf( stderr,
		 "%s:%d: Unbalanced braces in C++ code (or abuse of the C++"
		  " preprocessor)\n",
		  (const char *)yyFileName, yyBraceLineNo );
    else if ( yyParenDepth != 0 )
	fprintf( stderr,
		 "%s:%d: Unbalanced parentheses in C++ code (or abuse of the C++"
		 " preprocessor)\n",
		 (const char *)yyFileName, yyParenLineNo );
}
Exemple #2
0
QQmlEngine* MScore::qml()
      {
      if (_qml == 0) {
            //-----------some qt bindings
            _qml = new QQmlEngine;
#ifdef Q_OS_WIN
            QStringList importPaths;
            QDir dir(QCoreApplication::applicationDirPath() + QString("/../qml"));
            importPaths.append(dir.absolutePath());
            _qml->setImportPathList(importPaths);
#endif
#ifdef Q_OS_MAC
            QStringList importPaths;
            QDir dir(mscoreGlobalShare + QString("/qml"));
            importPaths.append(dir.absolutePath());
            _qml->setImportPathList(importPaths);
#endif
            qmlRegisterType<MsProcess>  ("MuseScore", 1, 0, "QProcess");
            qmlRegisterType<FileIO, 1>  ("FileIO",    1, 0, "FileIO");
            //-----------mscore bindings
            qmlRegisterUncreatableType<Direction>("MuseScore", 1, 0, "Direction", tr("You can't create an enumeration"));

            qmlRegisterType<MScore>     ("MuseScore", 1, 0, "MScore");
            qmlRegisterType<MsScoreView>("MuseScore", 1, 0, "ScoreView");
//            qmlRegisterType<QmlPlugin>  ("MuseScore", 1, 0, "MuseScore");
            qmlRegisterType<Score>      ("MuseScore", 1, 0, "Score");
            qmlRegisterType<Segment>    ("MuseScore", 1, 0, "Segment");
            qmlRegisterType<Chord>      ("MuseScore", 1, 0, "Chord");
            qmlRegisterType<Note>       ("MuseScore", 1, 0, "Note");
            qmlRegisterType<NoteHead>   ("MuseScore", 1, 0, "NoteHead");
            qmlRegisterType<Accidental> ("MuseScore", 1, 0, "Accidental");
            qmlRegisterType<Rest>       ("MuseScore", 1, 0, "Rest");
            qmlRegisterType<Measure>    ("MuseScore", 1, 0, "Measure");
            qmlRegisterType<Cursor>     ("MuseScore", 1, 0, "Cursor");
            qmlRegisterType<StaffText>  ("MuseScore", 1, 0, "StaffText");
            qmlRegisterType<Part>       ("MuseScore", 1, 0, "Part");
            qmlRegisterType<Staff>      ("MuseScore", 1, 0, "Staff");
            qmlRegisterType<Harmony>    ("MuseScore", 1, 0, "Harmony");
            qmlRegisterType<PageFormat> ("MuseScore", 1, 0, "PageFormat");
            qmlRegisterType<TimeSig>    ("MuseScore", 1, 0, "TimeSig");
            qmlRegisterType<KeySig>     ("MuseScore", 1, 0, "KeySig");
            qmlRegisterType<Slur>       ("MuseScore", 1, 0, "Slur");
            qmlRegisterType<Tie>        ("MuseScore", 1, 0, "Tie");
            qmlRegisterType<NoteDot>    ("MuseScore", 1, 0, "NoteDot");
            qmlRegisterType<FiguredBass>("MuseScore", 1, 0, "FiguredBass");
            qmlRegisterType<Text>       ("MuseScore", 1, 0, "MText");
            qmlRegisterType<Lyrics>     ("MuseScore", 1, 0, "Lyrics");
            qmlRegisterType<FiguredBassItem>("MuseScore", 1, 0, "FiguredBassItem");
            qmlRegisterType<LayoutBreak>("MuseScore", 1, 0, "LayoutBreak");
            qmlRegisterType<Hook>       ("MuseScore", 1, 0, "Hook");
            qmlRegisterType<Stem>       ("MuseScore", 1, 0, "Stem");
            qmlRegisterType<StemSlash>  ("MuseScore", 1, 0, "StemSlash");
            qmlRegisterType<Beam>       ("MuseScore", 1, 0, "Beam");
            qmlRegisterType<Excerpt>    ("MuseScore", 1, 0, "Excerpt");
            qmlRegisterType<BarLine>    ("MuseScore", 1, 0, "BarLine");

            qmlRegisterType<FractionWrapper>   ("MuseScore", 1, 1, "Fraction");
            qRegisterMetaType<FractionWrapper*>("FractionWrapper*");

            qmlRegisterUncreatableType<Element>("MuseScore", 1, 0,
               "Element", tr("you cannot create an element"));

            //classed enumerations
            qmlRegisterUncreatableType<MSQE_TextStyleType>("MuseScore", 1, 0, "TextStyleType", tr("You can't create an enum"));
            qmlRegisterUncreatableType<MSQE_BarLineType>("MuseScore", 1, 0, "BarLineType", tr("You can't create an enum"));

            //-----------virtual classes
            qmlRegisterType<ChordRest>();
            qmlRegisterType<SlurTie>();
            qmlRegisterType<Spanner>();
            }
      return _qml;
      }
Exemple #3
0
static QStringList idsToNames(QVector<ID> ids) {
    QStringList decs;
    foreach (ID id, ids) {
        decs.append(Factory::name(id).c_str());
    }
void QEnhancedTableView::copySelectionToExcel() {
    if (!model()) return;
    if (!selectionModel()) return;
    QModelIndexList sel=selectionModel()->selectedIndexes();
    QSet<int> rows, cols;
    int colmin=0;
    int rowmin=0;
    for (int i=0; i<sel.size(); i++) {
        int r=sel[i].row();
        int c=sel[i].column();
        rows.insert(r);
        cols.insert(c);
        if (i==0) {
            colmin=c;
            rowmin=r;
        } else {
            if (c<colmin) colmin=c;
            if (r<rowmin) rowmin=r;
        }
    }
    QList<int> rowlist=QList<int>::fromSet(rows);
    qSort(rowlist.begin(), rowlist.end());
    QList<int> collist=QList<int>::fromSet(cols);
    qSort(collist.begin(), collist.end());
    int rowcnt=rowlist.size();
    int colcnt=collist.size();
    QList<QStringList> data;

    // header row:
    //
    //  <EMPTY> | <HOR_HEDER1> | <HOR_HEADER2> | ...
    QStringList hrow;
    hrow.append(""); // empty header for first column (vertical headers!)
    for (int c=0; c<colcnt; c++) {
        hrow.append(QString("\"%1\"").arg(model()->headerData(collist[c], Qt::Horizontal).toString()));
    }
    data.append(hrow);

    // now add dta rows:
    //
    //               <~~~~~~~~~ colcnt times ~~~~~~~~~~>
    //  <VER_HEADER> | <EMPTY> | <EMPTY> | ... | <EMPTY>
    for (int r=0; r<rowcnt; r++) {
        QStringList row;
        row.append(QString("\"%1\"").arg(model()->headerData(rowlist[r], Qt::Vertical).toString())); // vertical header
        for (int c=0; c<colcnt; c++) {
            row.append(""); // empty columns for data
        }
        data.append(row);
    }
    for (int i=0; i<sel.size(); i++) {
        int r=rowlist.indexOf(sel[i].row());
        int c=collist.indexOf(sel[i].column());
        QVariant vdata=sel[i].data(Qt::EditRole);
        QString txt="";
        switch (vdata.type()) {
            case QVariant::Int:
            case QVariant::LongLong:
            case QVariant::UInt:
            case QVariant::ULongLong:
            case QVariant::Bool:
                txt=vdata.toString();
                break;
            case QVariant::Double:
                txt=QLocale().toString(vdata.toDouble());
                break;
            case QVariant::PointF:
                txt=QLocale().toString(vdata.toPointF().x());
                break;
            default:
                txt=QString("\"%1\"").arg(vdata.toString());
                break;
        }
        if ((r>=0) && (c>=0) && (r<=data.size()) && (c<=colcnt))data[r+1][c+1]=txt;
    }

    QString result="";
    for (int r=0; r<data.size(); r++) {
        result+=data[r].join("\t")+"\n";
    }
    QApplication::clipboard()->setText(result);
}
/**
 * Constructor
 */
SystemSettings::SystemSettings(): UAVDataObject(OBJID, ISSINGLEINST, ISSETTINGS, NAME)
{
    // Create fields
    QList<UAVObjectField *> fields;
    QStringList GUIConfigDataElemNames;
    GUIConfigDataElemNames.append("0");
    GUIConfigDataElemNames.append("1");
    GUIConfigDataElemNames.append("2");
    GUIConfigDataElemNames.append("3");
    fields.append( new UAVObjectField(QString("GUIConfigData"), QString("bits"), UAVObjectField::UINT32, GUIConfigDataElemNames, QStringList(), QString("")));
    QStringList AirSpeedMaxElemNames;
    AirSpeedMaxElemNames.append("0");
    fields.append( new UAVObjectField(QString("AirSpeedMax"), QString("m/s"), UAVObjectField::FLOAT32, AirSpeedMaxElemNames, QStringList(), QString("")));
    QStringList AirSpeedMinElemNames;
    AirSpeedMinElemNames.append("0");
    fields.append( new UAVObjectField(QString("AirSpeedMin"), QString("m/s"), UAVObjectField::FLOAT32, AirSpeedMinElemNames, QStringList(), QString("")));
    QStringList AirframeTypeElemNames;
    AirframeTypeElemNames.append("0");
    QStringList AirframeTypeEnumOptions;
    AirframeTypeEnumOptions.append("FixedWing");
    AirframeTypeEnumOptions.append("FixedWingElevon");
    AirframeTypeEnumOptions.append("FixedWingVtail");
    AirframeTypeEnumOptions.append("VTOL");
    AirframeTypeEnumOptions.append("HeliCP");
    AirframeTypeEnumOptions.append("QuadX");
    AirframeTypeEnumOptions.append("QuadP");
    AirframeTypeEnumOptions.append("Hexa");
    AirframeTypeEnumOptions.append("Octo");
    AirframeTypeEnumOptions.append("Custom");
    AirframeTypeEnumOptions.append("HexaX");
    AirframeTypeEnumOptions.append("OctoV");
    AirframeTypeEnumOptions.append("OctoCoaxP");
    AirframeTypeEnumOptions.append("OctoCoaxX");
    AirframeTypeEnumOptions.append("HexaCoax");
    AirframeTypeEnumOptions.append("Tri");
    AirframeTypeEnumOptions.append("GroundVehicleCar");
    AirframeTypeEnumOptions.append("GroundVehicleDifferential");
    AirframeTypeEnumOptions.append("GroundVehicleMotorcycle");
    fields.append( new UAVObjectField(QString("AirframeType"), QString(""), UAVObjectField::ENUM, AirframeTypeElemNames, AirframeTypeEnumOptions, QString("")));
    QStringList ThrustControlElemNames;
    ThrustControlElemNames.append("0");
    QStringList ThrustControlEnumOptions;
    ThrustControlEnumOptions.append("Throttle");
    ThrustControlEnumOptions.append("Collective");
    ThrustControlEnumOptions.append("None");
    fields.append( new UAVObjectField(QString("ThrustControl"), QString(""), UAVObjectField::ENUM, ThrustControlElemNames, ThrustControlEnumOptions, QString("")));

    // Initialize object
    initializeFields(fields, (quint8 *)&data, NUMBYTES);
    // Set the default field values
    setDefaultFieldValues();
    // Set the object description
    setDescription(DESCRIPTION);

    // Set the Category of this object type
    setCategory(CATEGORY);

    connect(this, SIGNAL(objectUpdated(UAVObject *)), SLOT(emitNotifications()));
}
Exemple #6
0
// Index any files that are attached.
void IndexRunner::indexAttachment(qint32 lid, Resource &r) {
    if (!officeFound)
        return;
    QLOG_DEBUG() << "indexing attachment to note " << lid;
    if (!keepRunning || pauseIndexing) {
        indexTimer->start();
        return;
    }
    ResourceTable rtable(db);
    qint32 reslid = rtable.getLid(r.guid);
    if (lid <= 0) {
        indexTimer->start();
        return;
    }
    QLOG_DEBUG() << "Resource " << reslid;
    QString extension = "";
    ResourceAttributes attributes;
    if (r.attributes.isSet())
        attributes = r.attributes;
    if (attributes.fileName.isSet()) {
        extension = attributes.fileName;
        int i = extension.indexOf(".");
	if (i != -1)
	  extension = extension.mid(i);
    }
    if (extension != ".doc"  && extension != ".xls"  && extension != ".ppt" &&
        extension != ".docx" && extension != ".xlsx" && extension != ".pptx" &&
        extension != ".pps"  && extension != ".pdf"  && extension != ".odt"  &&
        extension != ".odf"  && extension != ".ott"  && extension != ".odm"  &&
        extension != ".html" && extension != ".txt"  && extension != ".oth"  &&
        extension != ".ods"  && extension != ".ots"  && extension != ".odg"  &&
        extension != ".otg"  && extension != ".odp"  && extension != ".otp"  &&
        extension != ".odb"  && extension != ".oxt"  && extension != ".htm"  &&
        extension != ".docm")
                return;

    QString file = global.fileManager.getDbaDirPath() + QString::number(reslid) +extension;
    QFile dataFile(file);
    if (!dataFile.exists()) {
        QDir dir(global.fileManager.getDbaDirPath());
        QStringList filterList;
        filterList.append(QString::number(lid)+".*");
        QStringList list= dir.entryList(filterList, QDir::Files);
        if (list.size() > 0) {
            file = global.fileManager.getDbaDirPath()+list[0];
        }
    }

    QString outDir = global.fileManager.getTmpDirPath();

    QProcess sofficeProcess;
    QString cmd = "soffice --headless --convert-to txt:\"Text\" --outdir "
                    +outDir + " "
                    +file;

    sofficeProcess.start(cmd,
                         QIODevice::ReadWrite|QIODevice::Unbuffered);

    QLOG_DEBUG() << "Starting soffice ";
    sofficeProcess.waitForStarted();
    QLOG_DEBUG() << "Waiting for completion";
    sofficeProcess.waitForFinished();
    int rc = sofficeProcess.exitCode();
    QLOG_DEBUG() << "soffice Errors:" << sofficeProcess.readAllStandardError();
    QLOG_DEBUG() << "soffice Output:" << sofficeProcess.readAllStandardOutput();
    QLOG_DEBUG() << "return code:" << rc;
    if (rc == 255) {
        QLOG_ERROR() << "soffice not found.  Disabling attachment indexing.";
        this->officeFound = false;
        return;
    }
    QFile txtFile(outDir+QString::number(reslid) +".txt");
    if (txtFile.open(QIODevice::ReadOnly)) {
        QString text;
        text = txtFile.readAll();
        NSqlQuery sql(db);
        db->lockForWrite();
        sql.prepare("Insert into SearchIndex (lid, weight, source, content) values (:lid, :weight, 'recognition', :content)");
        sql.bindValue(":lid", lid);
        sql.bindValue(":weight", 100);
        sql.bindValue(":content", text);
        QLOG_DEBUG() << "Adding note resource to index DB";
        sql.exec();
        db->unlock();
        txtFile.close();
    }
    QDir dir;
    dir.remove(outDir+QString::number(reslid) +".txt");
}
Exemple #7
0
void LogViewWindow::createLog(LogFile * pLog, int iId, QString * pszFile)
{
	if(!pLog)
		return;

	QRegExp rx;
	QString szLog, szLogDir, szInputBuffer, szOutputBuffer, szLine, szTmp;
	QString szDate = pLog->date().toString("yyyy.MM.dd");

	/* Fetching previous export path and concatenating with generated filename
	 * adjustFilePath is for file paths not directory paths */
	szLog = KVI_OPTION_STRING(KviOption_stringLogsExportPath).trimmed();
	if (!szLog.isEmpty())
		szLog += KVI_PATH_SEPARATOR_CHAR;
	szLog += QString("%1_%2.%3_%4").arg(pLog->typeString(),pLog->name(),pLog->network(),szDate);
	KviFileUtils::adjustFilePath(szLog);

	// Getting output file path from the user, with overwrite confirmation
	if(!KviFileDialog::askForSaveFileName(
			szLog,
			__tr2qs_ctx("Export Log - KVIrc","log"),
			szLog,
			QString(),
			false,
			true,
			true,
			this))
		return;

	/* Save export directory - this directory path is also used in the HTML export
	 * and info is used when working with pszFile */
	QFileInfo info(szLog);
	szLogDir = info.absoluteDir().absolutePath();
	KVI_OPTION_STRING(KviOption_stringLogsExportPath) = szLogDir;

	/* Reading in log file - LogFiles are read in as bytes, so '\r' isn't
	 * sanitised by default */
	pLog->getText(szInputBuffer);
	QStringList lines = szInputBuffer.replace('\r', "").split('\n');

	switch(iId)
	{
		case LogFile::PlainText:
		{
			/* Only append extension if it isn't there already (e.g. a specific
			 * file is to be overwritten) */
			if(!szLog.endsWith(".txt"))
				szLog += ".txt";

			// Scan the file
			for(QStringList::Iterator it = lines.begin(); it != lines.end(); ++it)
			{
				szTmp = (*it);
				szLine = KviControlCodes::stripControlBytes(szTmp);

				// Remove icons' code
				rx.setPattern("^\\d{1,3}\\s");
				szLine.replace(rx,"");

				// Remove link from a user speaking, deal with (and keep) various ranks
				// e.g.: <!ncHelLViS69>  -->  <HelLViS69>
				rx.setPattern("\\s<([+%@&~!]?)!nc");
				szLine.replace(rx," <\\1");

				// Remove link from a nick in a mask
				// e.g.: !nFoo [~bar@!hfoo.bar]  -->  Foo [~bar@!hfoo.bar]
				rx.setPattern("\\s!n");
				szLine.replace(rx," ");

				// Remove link from a host in a mask
				// e.g.: Foo [~bar@!hfoo.bar]  -->  Foo [[email protected]]
				rx.setPattern("@!h");
				szLine.replace(rx,"@");

				// Remove link from a channel
				// e.g.: !c#KVIrc  -->  #KVIrc
				rx.setPattern("!c#");
				szLine.replace(rx,"#");

				szOutputBuffer += szLine;
				szOutputBuffer += "\n";
			}

			break;
		}
		case LogFile::HTML:
		{
			/* Only append extension if it isn't there already (e.g. a specific
			 * file is to be overwritten) */
			if(!szLog.endsWith(".html"))
				szLog += ".html";

			szTmp = QString("KVIrc %1 %2").arg(KVI_VERSION).arg(KVI_RELEASE_NAME);
			QString szNick = "";
			bool bFirstLine = true;

			QString szTitle;
			switch(pLog->type())
			{
				case LogFile::Channel:
					szTitle = __tr2qs_ctx("Channel %1 on %2","log").arg(pLog->name(),pLog->network());
				break;
				case LogFile::Console:
					szTitle = __tr2qs_ctx("Console on %1","log").arg(pLog->network());
				break;
				case LogFile::Query:
					szTitle = __tr2qs_ctx("Query with %1 on %2","log").arg(pLog->name(),pLog->network());
				break;
				case LogFile::DccChat:
					szTitle = __tr2qs_ctx("DCC Chat with %1","log").arg(pLog->name());
				break;
				case LogFile::Other:
					szTitle = __tr2qs_ctx("Something on %1","log").arg(pLog->network());
				break;
			}

			// Prepare HTML document
			szOutputBuffer += "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n";
			szOutputBuffer += "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">\n";
			szOutputBuffer += "<head>\n";
			szOutputBuffer += "\t<meta http-equiv=\"content-type\" content=\"application/xhtml+xml; charset=utf-8\" />\n";
			szOutputBuffer += "\t<meta name=\"author\" content=\"" + szTmp + "\" />\n";
			szOutputBuffer += "\t<title>" + szTitle + "</title>\n";
			szOutputBuffer += "</head>\n<body>\n";
			szOutputBuffer += "<h2>" + szTitle + "</h2>\n<h3>Date: " + szDate + "</h3>\n";

			// Scan the file
			for(QStringList::Iterator it = lines.begin(); it != lines.end(); ++it)
			{
				szTmp = (*it);

				// Find who has talked
				QString szTmpNick = szTmp.section(" ",2,2);
				if((szTmpNick.left(1) != "<") && (szTmpNick.right(1) != ">"))
					szTmpNick = "";

				// locate msgtype
				QString szNum = szTmp.section(' ',0,0);
				bool bOk;
				int iMsgType = szNum.toInt(&bOk);

				// only human text for now...
				if(iMsgType != 24 && iMsgType != 25  && iMsgType != 26)
					continue;

				// remove msgtype tag
				szTmp = szTmp.remove(0,szNum.length()+1);

				szTmp = KviHtmlGenerator::convertToHtml(szTmp,true);

				// insert msgtype icon at start of the current text line
				KviMessageTypeSettings msg(KVI_OPTION_MSGTYPE(iMsgType));
				QString szIcon = g_pIconManager->getSmallIconResourceName((KviIconManager::SmallIcon)msg.pixId());
				szTmp.prepend("<img src=\"" + szIcon + "\" alt=\"\" /> ");

				/*
				 * Check if the nick who has talked is the same of the above line.
				 * If so, we have to put the line as it is, otherwise we have to
				 * open a new paragraph
				 */
				if(szTmpNick != szNick)
				{
					/*
					 * People is not the same, close the paragraph opened
					 * before and open a new one
					 */
					if(!bFirstLine)
						szOutputBuffer += "</p>\n";
					szTmp.prepend("<p>");

					szNick = szTmpNick;
				} else {
					// Break the line
					szTmp.prepend("<br />\n");
				}

				szOutputBuffer += szTmp;
				bFirstLine = false;
			}

			// Close the last paragraph
			szOutputBuffer += "</p>\n";

			// regexp to search all embedded icons
			rx.setPattern("<img src=\"smallicons:([^\"]+)");
			int iIndex = szOutputBuffer.indexOf(rx);
			QStringList szImagesList;

			// search for icons
			while (iIndex >= 0)
			{
				int iLength = rx.matchedLength();
				QString szCap = rx.cap(1);

				// if the icon isn't in the images list then add
				if(szImagesList.indexOf(szCap) == -1)
					szImagesList.append(szCap);
				iIndex = szOutputBuffer.indexOf(rx, iIndex + iLength);
			}

			// get current theme path
			QString szCurrentThemePath;
			g_pApp->getLocalKvircDirectory(szCurrentThemePath,KviApplication::Themes,KVI_OPTION_STRING(KviOption_stringIconThemeSubdir));
			szCurrentThemePath += KVI_PATH_SEPARATOR_CHAR;

			// current coresmall path
			szCurrentThemePath += "coresmall";
			szCurrentThemePath += KVI_PATH_SEPARATOR_CHAR;

			// check if coresmall exists in current theme
			if(!KviFileUtils::directoryExists(szCurrentThemePath))
			{
				// get global coresmall path
				g_pApp->getGlobalKvircDirectory(szCurrentThemePath,KviApplication::Pics,"coresmall");
				KviQString::ensureLastCharIs(szCurrentThemePath,QChar(KVI_PATH_SEPARATOR_CHAR));
			}

			// copy all icons to the log destination folder
			for(int i=0; i < szImagesList.count(); i++)
			{
				QString szSourceFile = szCurrentThemePath + szImagesList.at(i);
				QString szDestFile = szLogDir + szImagesList.at(i);
				KviFileUtils::copyFile(szSourceFile,szDestFile);
			}

			// remove internal tags
			rx.setPattern("<qt>|</qt>|smallicons:");
			szOutputBuffer.replace(rx,"");
			szOutputBuffer.replace(">!nc",">");
			szOutputBuffer.replace("@!nc","@");
			szOutputBuffer.replace("%!nc","%");

			// Close the document
			szOutputBuffer += "</body>\n</html>\n";

			break;
		}
	}

	// File overwriting already dealt with when file path was obtained
	QFile log(szLog);
	if(!log.open(QIODevice::WriteOnly | QIODevice::Text))
		return;

	if(pszFile)
	{
		*pszFile = "";
		*pszFile = info.filePath();
	}

	// Ensure we're writing in UTF-8
	QTextStream output(&log);
	output.setCodec("UTF-8");
	output << szOutputBuffer;

	// Close file descriptors
	log.close();
}
Exemple #8
0
// parsing
QHash<QString, QVariant> Parser::parse(QStringList argv)
{
	QHash<QString, QVariant> map;

	QStringListIterator it(argv);
	QString programName = it.next();

	QString optionPrefix;
	QString flagPrefix;
	QListIterator<PositionalDef *> positionals(m_positionals);
	QStringList expecting;

	getPrefix(optionPrefix, flagPrefix);

	while (it.hasNext())
	{
		QString arg = it.next();

		if (!expecting.isEmpty())
		// we were expecting an argument
		{
			QString name = expecting.first();
			/*
						if (map.contains(name))
							throw ParsingError(
								QString("Option %2%1 was given multiple times").arg(name,
			   optionPrefix));
			*/
			map[name] = QVariant(arg);

			expecting.removeFirst();
			continue;
		}

		if (arg.startsWith(optionPrefix))
		// we have an option
		{
			// qDebug("Found option %s", qPrintable(arg));

			QString name = arg.mid(optionPrefix.length());
			QString equals;

			if ((m_argStyle == ArgumentStyle::Equals ||
				 m_argStyle == ArgumentStyle::SpaceAndEquals) &&
				name.contains("="))
			{
				int i = name.indexOf("=");
				equals = name.mid(i + 1);
				name = name.left(i);
			}

			if (m_options.contains(name))
			{
				/*
				if (map.contains(name))
					throw ParsingError(QString("Option %2%1 was given multiple times")
										   .arg(name, optionPrefix));
*/
				OptionDef *option = m_options[name];
				if (option->type == otSwitch)
					map[name] = true;
				else // if (option->type == otOption)
				{
					if (m_argStyle == ArgumentStyle::Space)
						expecting.append(name);
					else if (!equals.isNull())
						map[name] = equals;
					else if (m_argStyle == ArgumentStyle::SpaceAndEquals)
						expecting.append(name);
					else
						throw ParsingError(QString("Option %2%1 reqires an argument.")
											   .arg(name, optionPrefix));
				}

				continue;
			}

			throw ParsingError(QString("Unknown Option %2%1").arg(name, optionPrefix));
		}

		if (arg.startsWith(flagPrefix))
		// we have (a) flag(s)
		{
			// qDebug("Found flags %s", qPrintable(arg));

			QString flags = arg.mid(flagPrefix.length());
			QString equals;

			if ((m_argStyle == ArgumentStyle::Equals ||
				 m_argStyle == ArgumentStyle::SpaceAndEquals) &&
				flags.contains("="))
			{
				int i = flags.indexOf("=");
				equals = flags.mid(i + 1);
				flags = flags.left(i);
			}

			for (int i = 0; i < flags.length(); i++)
			{
				QChar flag = flags.at(i);

				if (!m_flags.contains(flag))
					throw ParsingError(QString("Unknown flag %2%1").arg(flag, flagPrefix));

				OptionDef *option = m_flags[flag];
				/*
								if (map.contains(option->name))
									throw ParsingError(QString("Option %2%1 was given multiple
				   times")
														   .arg(option->name, optionPrefix));
				*/
				if (option->type == otSwitch)
					map[option->name] = true;
				else // if (option->type == otOption)
				{
					if (m_argStyle == ArgumentStyle::Space)
						expecting.append(option->name);
					else if (!equals.isNull())
						if (i == flags.length() - 1)
							map[option->name] = equals;
						else
							throw ParsingError(QString("Flag %4%2 of Argument-requiring Option "
													   "%1 not last flag in %4%3")
												   .arg(option->name, flag, flags, flagPrefix));
					else if (m_argStyle == ArgumentStyle::SpaceAndEquals)
						expecting.append(option->name);
					else
						throw ParsingError(QString("Option %1 reqires an argument. (flag %3%2)")
											   .arg(option->name, flag, flagPrefix));
				}
			}

			continue;
		}

		// must be a positional argument
		if (!positionals.hasNext())
			throw ParsingError(QString("Don't know what to do with '%1'").arg(arg));

		PositionalDef *param = positionals.next();

		map[param->name] = arg;
	}

	// check if we're missing something
	if (!expecting.isEmpty())
		throw ParsingError(QString("Was still expecting arguments for %2%1").arg(
			expecting.join(QString(", ") + optionPrefix), optionPrefix));

	while (positionals.hasNext())
	{
		PositionalDef *param = positionals.next();
		if (param->required)
			throw ParsingError(
				QString("Missing required positional argument '%1'").arg(param->name));
		else
			map[param->name] = param->def;
	}

	// fill out gaps
	QListIterator<OptionDef *> iter(m_optionList);
	while (iter.hasNext())
	{
		OptionDef *option = iter.next();
		if (!map.contains(option->name))
			map[option->name] = option->def;
	}

	return map;
}
Exemple #9
0
QTime timeBox::createTime ( bool *ok )
{
//	QString entry;
	int h = 0, m = 0, is = 0;
	double s = 0.0;
	QTime qt;
	bool valueFound = false, badEntry = false , checkValue = false;

//Initialize bool for result
	if ( ok != NULL ) *ok = false;

//	QString errMsg = i18n( "Unable to parse %1 entry. Specify a %1 value as a simple integer, a floating-point number, or a triplet of values using colons or spaces as separators." );

	QString entry = text().stripWhiteSpace();

	//Try simplest cases: integer or double representation

	h = entry.toInt( &checkValue );
	if ( checkValue ) {
		qt = QTime( h, 0, 0 );
		valueFound = true;
		if ( ok != NULL ) *ok = true;
		return qt;
	} else {
		double x = entry.toDouble( &checkValue );
		if ( checkValue ) {
			int seconds = int(x * 3600);
			QTime qt(0,0,0);
			qt.addSecs(seconds);
			valueFound = true;
			if ( ok != NULL ) *ok = true;
			return qt;
		}
	}

	//no success yet...try assuming multiple fields

	if ( !valueFound ) { 
		QStringList fields;
		
		//check for colon-delimiters or space-delimiters
		if ( entry.contains(':') ) 
			fields = QStringList::split( ':', entry );
		else fields = QStringList::split( " ", entry ); 

		// If two fields we will add a third one, and then parse with 
		// the 3-field code block. If field[1] is a double, convert 
		// it to integer mins, and convert the remainder to secs
		 
		if ( fields.count() == 2 ) {
			double mx = fields[1].toDouble( &checkValue );
			if ( checkValue ) {
				fields[1] = QString("%1").arg( int(mx) );
				fields.append( QString("%1").arg( int( 60.0*(mx - int(mx)) ) ) );
			} else {
				fields.append( QString( "0" ) );
			}
		}
		
		// Three fields space-delimited ( h/d m s ); 
		// ignore all after 3rd field

		if ( fields.count() >= 3 ) {
			fields[0].replace( QRegExp("h"), "" );
			fields[1].replace( QRegExp("m"), "" );
			fields[2].replace( QRegExp("s"), "" );
		}
		//See if first two fields parse as integers.
		//
		h = fields[0].toInt( &checkValue );
		if ( !checkValue ) badEntry = true;
		m = fields[1].toInt( &checkValue );
		if ( !checkValue ) badEntry = true;
		s = fields[2].toDouble( &checkValue );
		if ( !checkValue ) badEntry = true;

		if ( !badEntry ) {
			valueFound = true;
			is = (int)s;

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

			QTime qt(h,m,is);
			return qt;

		} else {
			if ( ok != NULL ) *ok = false;
		}
	}

//	 if ( !valueFound )
//		KMessageBox::sorry( 0, errMsg.arg( "Angle" ), i18n( "Could Not Set Value" ) );


	return qt;
}
Exemple #10
0
/** Adds user values from the GUI into the Python script
* @param runFiles :: a comma separated list of data file names
* @param whiteBeam :: The filename of the white beam run
* @param absRunFiles :: run files for absolute normalization
* @param absWhiteBeam :: run file for absolute white beam normalization
* @param saveName :: filename for output saving
*/
void deltaECalc::createProcessingScript(const QStringList &runFiles,
                                        const QString &whiteBeam,
                                        const QStringList &absRunFiles,
                                        const QString &absWhiteBeam,
                                        const QString &saveName) {
  QString pyCode = "import Direct.DirectEnergyConversion as direct\n";
  pyCode += QString("mono_sample = direct.DirectEnergyConversion('%1')\n")
                .arg(m_sets.cbInst->currentText());
  // Turn off printing to stdout
  pyCode += QString("mono_sample.prop_man.log_to_mantid = True\n");

  addAnalysisOptions(pyCode);
  addMaskingCommands(pyCode);
  // Check save formats
  QStringList fileExts;
  if (m_sets.save_ckSPE->isChecked()) {
    fileExts.append("'spe'");
  }
  if (m_sets.save_ckNexus->isChecked()) {
    fileExts.append("'nxs'");
  }
  if (m_sets.save_ckNxSPE->isChecked()) {
    fileExts.append("'nxspe'");
  }

  if (fileExts.size() == 0)
    pyCode += "mono_sample.prop_man.save_format = None\n";
  else
    pyCode +=
        "mono_sample.prop_man.save_format = " + fileExts.join(",") + "\n\n";

  // Create the python variables. The strings are wrapped with r'' for slash
  // safety
  QString pyRunFiles = createPyListAsString(runFiles);
  QString eiGuess = m_sets.leEGuess->text();
  QString pyWhiteBeam =
      (whiteBeam.isEmpty()) ? "None" : QString("r'" + whiteBeam + "'");
  // Absolute values
  QString pyAbsRunFiles = createPyListAsString(absRunFiles);
  QString absEiGuess = m_sets.leVanEi->text();
  QString pyAbsWhiteBeam =
      (absWhiteBeam.isEmpty()) ? "None" : QString("r'" + absWhiteBeam + "'");
  // SE Offset value
  QString seOffset = m_sets.seOffsetEdit->text();
  QString pySeOffset = (seOffset.isEmpty()) ? "None" : seOffset;
  // SE Motor Name
  QString motorName = m_sets.motorNameEdit->text();
  QString pyMotorName =
      (motorName.isEmpty()) ? "None" : QString("r'" + motorName + "'");

  QString None = "None";
  auto rebin = None;
  auto map_file = None;
  pyCode += "mono_sample.prop_man.motor_name = " + pyMotorName + "\n";
  pyCode += "mono_sample.prop_man.motor_offset = " + pySeOffset + "\n";

  if (m_sets.ckSumSpecs->isChecked() || runFiles.size() == 1) {
    if (m_sets.ckSumSpecs->isChecked())
      pyCode += "mono_sample.prop_man.sum_runs = True\n";

    QString pySaveName;
    if (saveName.isEmpty()) {
      pyCode += "mono_sample.prop_man.save_file_name = None\n";

    } else {
      pyCode += "mono_sample.prop_man.save_file_name = r'" + saveName + "'\n";
    }
    pyCode +=
        QString("mono_sample.convert_to_energy(%1, %2, %3, %4, %5, %6, %7)");
    pyCode = pyCode.arg(pyWhiteBeam, pyRunFiles, eiGuess, rebin, map_file,
                        pyAbsRunFiles, pyAbsWhiteBeam);
  } else {
    QString pySaveName;
    if (saveName.isEmpty()) {
      pySaveName = "r'" + QFileInfo(saveName).absolutePath() + "'";
      pyCode += "mono_sample.prop_man.save_file = " + pySaveName + "\n";
    }
    pyCode += "rfiles = " + pyRunFiles + "\n";
    if (absRunFiles.isEmpty()) {
      pyCode += "for run in rfiles:\n"
                "  mono_sample.convert_to_energy(run, %1, %2)\n";
      pyCode = pyCode.arg(eiGuess, pyWhiteBeam);
    } else {
      pyCode += "abs_rfiles = " + pyAbsRunFiles + "\n";
      pyCode += "for run, abs in zip(rfiles, abs_rfiles):\n"
                "  mono_sample.convert_to_energy(%1, run, %2, %3,abs, %6)\n";
      pyCode = pyCode.arg(pyWhiteBeam, eiGuess, rebin, map_file, pyAbsRunFiles,
                          pyAbsWhiteBeam);
      //                         pyWhiteBeam,pyRunFiles,
      //                         eiGuess,rebin,map_file,pyAbsRunFiles,
      //                         pyAbsWhiteBeam
    }
  }
  m_pyScript = pyCode;
}
void vtkDataMeshInteractor::setAttribute(const QString & attributeName)
{
    vtkPointSet * pointSet = vtkPointSet::SafeDownCast(d->metaDataSet->GetDataSet());
    if ( ! pointSet )
        return;

    vtkDataSetAttributes * attributes = NULL;
    vtkMapper * mapper2d = d->actor2d->GetMapper();
    vtkMapper * mapper3d = d->actor3d->GetMapper();
    if (pointSet->GetPointData()->HasArray(qPrintable(attributeName)))
    {
        attributes = pointSet->GetPointData();
        mapper2d->SetScalarModeToUsePointFieldData();
        mapper3d->SetScalarModeToUsePointFieldData();
    }
    else if (pointSet->GetCellData()->HasArray(qPrintable(attributeName)))
    {
        attributes = pointSet->GetCellData();
        mapper2d->SetScalarModeToUseCellFieldData();
        mapper3d->SetScalarModeToUseCellFieldData();
    }

    if (attributes)
    {

        if(d->colorParam)
            d->colorParam->hide();
        if(d->LUTParam)
        {
            QStringList luts;
            const std::vector<std::string> & vec = vtkLookupTableManager::GetAvailableLookupTables();
            for(std::vector<std::string>::const_iterator it = vec.begin(); it < vec.end(); ++it)
                luts.append(QString::fromStdString(*it));
            d->LUTParam->clear();
            foreach(QString lut, luts)
                d->LUTParam->addItem(lut);

            d->attribute = attributes->GetArray(qPrintable(attributeName));
            attributes->SetActiveScalars(qPrintable(attributeName));

            d->LUTParam->show();
        }

        mapper2d->SelectColorArray(qPrintable(attributeName));
        mapper3d->SelectColorArray(qPrintable(attributeName));

        this->setLut(d->lut.first);

        mapper2d->SetScalarVisibility(1);
        mapper3d->SetScalarVisibility(1);
    }
    else
    {
        if(d->LUTParam)
            d->LUTParam->hide();
        if(d->colorParam)
            d->colorParam->show();

        d->attribute = NULL;
        mapper2d->SetScalarVisibility(0);
        mapper3d->SetScalarVisibility(0);
    }
    d->render->Render();
}
Exemple #12
0
Indicator * CUS::calculate ()
{
  Config config;
  QStringList varList;
  QDict<PlotLine> lines;
  lines.setAutoDelete(TRUE);

  checkIncludes();

  Indicator *output = new Indicator;
  output->setDateFlag(dateFlag);
  output->setLogScale(logScale);
  
  int loop;
  for (loop = 0; loop < (int) formulaList.count(); loop++)
  {
    // check if whole line is a comment
    QString s = formulaList[loop].left(2);
    if ( ! s.compare("//"))
      continue;

    if (formulaList[loop].contains(":="))
    {
      QStringList l = QStringList::split(":=", formulaList[loop], FALSE);
      if (l.count() != 2)
      {
        qDebug("CUS::calculate: line %i parm missing", loop);
        return output;
      }
      
      QString var = l[0].stripWhiteSpace();
      if (varList.findIndex(var) != -1)
      {
        qDebug("CUS::calculate: line %i duplicate variable: %s", loop, var.latin1());
        return output;
      }
      varList.append(var);

      QStringList l2 = QStringList::split("(", l[1], FALSE);
      if (l2.count() != 2)
      {
        qDebug("CUS::calculate: line %i bad indicator format", loop);
        return output;
      }
      
      QString plugin = l2[0].stripWhiteSpace();
      QString parms = l2[1];
      parms.truncate(parms.find(")", 0, TRUE));
      parms = parms.stripWhiteSpace();
      while(parms.contains(" "))
        parms = parms.remove(parms.find(" ", 0, TRUE), 1);

      IndicatorPlugin *plug = config.getIndicatorPlugin(plugin);
      if (! plug)
      {
        qDebug("CUS::calculate: %s plugin not loaded", plugin.latin1());
        config.closePlugin(plugin);
        return output;
      }
      plug->setIndicatorInput(data);

      l = QStringList::split(",", parms, FALSE);
      int loop2;
      QPtrList<PlotLine> inList;
      inList.setAutoDelete(FALSE);
      for (loop2 = 0; loop2 < (int) l.count(); loop2++)
      {
        if (varList.findIndex(l[loop2]) != -1)
          inList.append(lines.find(l[loop2]));
        else
        {
          int itype = inputTypeList.findIndex(l[loop2]);
          if (itype != -1)
          {
            PlotLine *in = data->getInput((BarData::InputType) itype);
            if (! in)
            {
              qDebug("CUS::calculate:line%i parm%i: input not found", loop, loop2);
              return output;
            }

            lines.replace(l[loop2], in);
            inList.append(in);
          }
        }
      }

      PlotLine *out = plug->calculateCustom(parms, inList);
      if (! out)
      {
        qDebug("CUS::calculate: line %i: no PlotLine returned: %s", loop, parms.latin1());
        config.closePlugin(plugin);
        return output;
      }

      lines.replace(var, out);
    }

    createPlot(formulaList[loop], lines, output);
  }

  return output;
}
Exemple #13
0
QStringList Q3FileDialog::macGetOpenFileNames(const QString &filter, QString *pwd,
                                             QWidget *parent, const char* /*name*/,
                                             const QString& caption, QString *selectedFilter,
                                             bool multi, bool directory)
{
    OSErr err;
    QStringList retstrl;

    NavDialogCreationOptions options;
    NavGetDefaultDialogCreationOptions(&options);
    options.modality = kWindowModalityAppModal;
    options.optionFlags |= kNavDontConfirmReplacement | kNavSupportPackages;
    if (!multi)
        options.optionFlags &= ~kNavAllowMultipleFiles;
    if(!caption.isEmpty())
        options.windowTitle = CFStringCreateWithCharacters(NULL, (UniChar *)caption.unicode(),
                                                           caption.length());

    static const int w = 450, h = 350;
    options.location.h = options.location.v = -1;
    if(parent && parent->isVisible()) {
        Qt::WindowType wt = parent->window()->windowType();
        if (wt != Qt::Desktop && wt != Qt::Sheet && wt != Qt::Drawer) {
            options.modality = kWindowModalityWindowModal;
            options.parentWindow = qt_mac_window_for(parent);
        } else {
            parent = parent->window();
            QString s = parent->windowTitle();
            options.clientName = CFStringCreateWithCharacters(NULL, (UniChar *)s.unicode(), s.length());
            options.location.h = (parent->x() + (parent->width() / 2)) - (w / 2);
            options.location.v = (parent->y() + (parent->height() / 2)) - (h / 2);

            QRect r = QApplication::desktop()->screenGeometry(
                QApplication::desktop()->screenNumber(parent));
            if(options.location.h + w > r.right())
                options.location.h -= (options.location.h + w) - r.right() + 10;
            if(options.location.v + h > r.bottom())
                options.location.v -= (options.location.v + h) - r.bottom() + 10;
        }
    } else if(QWidget *p = qApp->mainWidget()) {
        static int last_screen = -1;
        int scr = QApplication::desktop()->screenNumber(p);
        if(last_screen != scr) {
            QRect r = QApplication::desktop()->screenGeometry(scr);
            options.location.h = (r.x() + (r.width() / 2)) - (w / 2);
            options.location.v = (r.y() + (r.height() / 2)) - (h / 2);
        }
    }

    QList<qt_mac_filter_name*> filts = makeFiltersList(filter);
    qt_mac_nav_filter_type t;
    t.index = 0;
    t.filts = &filts;
    if(filts.count() > 1) {
        int i = 0;
        CFStringRef *arr = (CFStringRef *)malloc(sizeof(CFStringRef) * filts.count());
        for (QList<qt_mac_filter_name*>::Iterator it = filts.begin(); it != filts.end(); ++it) {
            QString rg = (*it)->description;
            arr[i++] = CFStringCreateWithCharacters(NULL, (UniChar *)rg.unicode(), rg.length());
        }
        options.popupExtension = CFArrayCreate(NULL, (const void **)arr, filts.count(), NULL);
    }

    NavDialogRef dlg;
    if(directory) {
        if(NavCreateChooseFolderDialog(&options, make_navProcUPP(), NULL, NULL, &dlg)) {
            qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__);
            return retstrl;
        }
    } else {
        if(NavCreateGetFileDialog(&options, NULL, make_navProcUPP(), NULL,
                                  make_navFilterUPP(), (void *) (filts.isEmpty() ? NULL : &t),
                                  &dlg)) {
            qDebug("Shouldn't happen %s:%d", __FILE__, __LINE__);
            return retstrl;
        }
    }
    if(pwd && !pwd->isEmpty()) {
        FSRef fsref;
        if(qt_mac_create_fsref(*pwd, &fsref) == noErr) {
            AEDesc desc;
            if(AECreateDesc(typeFSRef, &fsref, sizeof(FSRef), &desc) == noErr)
                NavCustomControl(dlg, kNavCtlSetLocation, (void*)&desc);
        }
    }

    NavDialogRun(dlg);
    if (selectedFilter) {
        NavMenuItemSpec navSpec;
        bzero(&navSpec, sizeof(NavMenuItemSpec));
        qt_mac_filter_name *sel_filt_name = makeFiltersList(*selectedFilter).at(0);
        for (int i = 0; i < filts.count(); ++i) {
            const qt_mac_filter_name *filter = filts.at(i);
            if (sel_filt_name->description == filter->description
                    && sel_filt_name->regxp == filter->regxp
                    && sel_filt_name->filter == filter->filter) {
                navSpec.menuType = i;
                break;
            }
        }
        NavCustomControl(dlg, kNavCtlSelectCustomType, &navSpec);
    }
    if(options.modality == kWindowModalityWindowModal) { //simulate modality
        QWidget modal_widg(parent, __FILE__ "__modal_dlg",
                           Qt::WType_TopLevel | Qt::WStyle_Customize | Qt::WStyle_DialogBorder);
        modal_widg.createWinId();
        QApplicationPrivate::enterModal(&modal_widg);
        while(g_nav_blocking)
            qApp->processEvents(QEventLoop::WaitForMoreEvents);
        QApplicationPrivate::leaveModal(&modal_widg);
    }

    if(!(NavDialogGetUserAction(dlg) &
          (kNavUserActionOpen | kNavUserActionChoose | kNavUserActionNewFolder))) {
        NavDialogDispose(dlg);
        return retstrl;
    }
    NavReplyRecord ret;
    NavDialogGetReply(dlg, &ret);
    NavDialogDispose(dlg);

    long count;
    err = AECountItems(&(ret.selection), &count);
    if(!ret.validRecord || err != noErr || !count) {
        NavDisposeReply(&ret);
        return retstrl;
    }

    for(long index = 1; index <= count; index++) {
        FSRef ref;
        err = AEGetNthPtr(&(ret.selection), index, typeFSRef, 0, 0, &ref, sizeof(ref), 0);
        if(err != noErr)
            break;

        if(!str_buffer) {
            qAddPostRoutine(cleanup_str_buffer);
            str_buffer = (UInt8 *)malloc(1024);
        }
        FSRefMakePath(&ref, str_buffer, 1024);
        retstrl.append(QString::fromUtf8((const char *)str_buffer));
    }
    NavDisposeReply(&ret);
    if(selectedFilter)
        *selectedFilter = filts.at(t.index)->filter;
    while (!filts.isEmpty())
        delete filts.takeFirst();
    return retstrl;
}
static QVariant getDeviceRegistryProperty(::HDEVINFO DeviceInfoSet,
        ::PSP_DEVINFO_DATA DeviceInfoData,
        ::DWORD property)
{
    ::DWORD dataType = 0;
    ::DWORD dataSize = 0;
    QVariant v;

    ::SetupDiGetDeviceRegistryProperty(DeviceInfoSet,
                                       DeviceInfoData,
                                       property,
                                       &dataType,
                                       0,
                                       0,
                                       &dataSize);

    QByteArray data(dataSize, 0);

    if (::SetupDiGetDeviceRegistryProperty(DeviceInfoSet,
                                           DeviceInfoData,
                                           property,
                                           0,
                                           reinterpret_cast<unsigned char*>(data.data()),
                                           dataSize,
                                           0)) {

        switch (dataType) {

        case REG_EXPAND_SZ:
        case REG_SZ: {
            QString s;
            if (dataSize) {
                s = QString::fromWCharArray(((const wchar_t *)data.constData()));
            }
            v = QVariant(s);
            break;
        }

        case REG_MULTI_SZ: {
            QStringList l;
            if (dataSize) {
                int i = 0;
                for (;;) {
                    QString s = QString::fromWCharArray((const wchar_t *)data.constData() + i);
                    i += s.length() + 1;

                    if (s.isEmpty())
                        break;
                    l.append(s);
                }
            }
            v = QVariant(l);
            break;
        }

        case REG_NONE:
        case REG_BINARY: {
            QString s;
            if (dataSize) {
                s = QString::fromWCharArray((const wchar_t *)data.constData(), data.size() / 2);
            }
            v = QVariant(s);
            break;
        }

        case REG_DWORD_BIG_ENDIAN:
        case REG_DWORD: {
            Q_ASSERT(data.size() == sizeof(int));
            int i = 0;
            ::memcpy((void *)(&i), data.constData(), sizeof(int));
            v = i;
            break;
        }

        default:
            v = QVariant();
        }

    }

    return v;
}
/* 主窗口
 * 初始化
 * modelIndex -> Index2 -> 指标表
 * model -> data > 数据表
 */
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
//    Qt::WindowFlags flags=Qt::Dialog;
//    flags =  Qt::WindowMinimizeButtonHint&~Qt::WindowMaximizeButtonHint;
//    setWindowFlags(flags);

    setupUi(this);
    //modelIndex  --index2


    kjAnalytics =new DynamicArray();
    kjAnalyticsAll =new DynamicArray();

    modelIndex = new QSqlRelationalTableModel(this);
    QString tableNameI="Index2";
    modelIndex->setTable (tableNameI);
    modelIndex->setEditStrategy (QSqlTableModel::OnManualSubmit);
    modelIndex->select ();


    //model -- data
    model= new QSqlRelationalTableModel(this);
    tableName="data_all";
    model->setTable (tableName);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    this->setHeader ();
    //生成年份下拉筐的备选项
    model->select ();

    //model -- data2
    model2=new QSqlRelationalTableModel(this);
    QString tableName2="data2";
    model2->setTable (tableName2);
    model2->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model2->select();

    //model -- data3
    model3=new QSqlRelationalTableModel(this);
    QString tableName3="data3";
    model3->setTable (tableName3);
    model3->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model3->select();

    //model -- data4
    model4=new QSqlRelationalTableModel(this);
    QString tableName4="data4";
    model4->setTable (tableName4);
    model4->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model4->select();

    AllIndexTable();
    typeModel = new QStringListModel;
    typeModel1 = new QStringListModel;

    tableName="data_all";
    model->setTable (tableName);
    //生成年份下拉筐的备选项
    model->select ();
    int rowC  = model->rowCount ();
    QStringList qsl;
    qsl.append ("全部");

    for (int i = 0; i < rowC ; ++i) {
        if(!qsl.contains (model->record (i).value ("year").toString ()))
            qsl.append (model->record (i).value ("year").toString ());
    }


    typeModel->setStringList (qsl);
    year_comboBox->setModel (typeModel);
    year_comboBox->show ();

    //设置表格控件显示内容 model
    model->setTable (tableName);
    setHeader ();
    setFilter ();
    model->setSort(0,Qt::AscendingOrder);
    model->select();


    all_tableView->setModel (model);
    all_tableView->hideColumn (0);





    //        QTableView *view = new QTableView;
    //        view->setModel(model2);
    //        //view->hideColumn(0); // don't show the ID
    //        view->show();

    //    QTableView *view1 = new QTableView;
    //    view1->setModel(model3);
    //    //view->hideColumn(0); // don't show the ID
    //    view1->show();


}
Exemple #16
0
void createTorrent::on_makeTorrent_Button_clicked()
{
    QString program = "/home/oyashi/Downloads/libtorrent-rasterbar-1.1.0/examples/make_torrent";
    QString outputFile = uiCreateTor->outputFileLineEdit->text();


    QMessageBox msgBox;

    if(!filePath.isEmpty()){
        if(!outputFile.isEmpty()){
            QString outputFileName = outputFile + ".torrent";
            QStringList arguments;
            arguments << filePath << "-o" << outputFileName ;

            if(!uiCreateTor->trackerLineEdit->text().isEmpty()){
                arguments.append("-t");
                arguments.append(uiCreateTor->trackerLineEdit->text());

            }

            if(!uiCreateTor->trackerLineEdit_2->text().isEmpty()){
                arguments.append("-t");
                arguments.append(uiCreateTor->trackerLineEdit_2->text());

            }

            if(!uiCreateTor->commentLineEdit->text().isEmpty()){
                arguments.append("-c");
                arguments.append(uiCreateTor->commentLineEdit->text());

            }

            if(!uiCreateTor->webSeedLineEdit->text().isEmpty()){
                arguments.append("-w");
                arguments.append(uiCreateTor->webSeedLineEdit->text());

            }

            if(!uiCreateTor->createdByLineEdit->text().isEmpty()){
                arguments.append("-C");
                arguments.append(uiCreateTor->createdByLineEdit->text());

            }

            QProcess *myProcess = new QProcess(this);
            myProcess->start(program,arguments);

            if(myProcess->waitForFinished(1000)){
                msgBox.setText("Torrent created successfully");
                msgBox.exec();
            }
        }
        else{
            msgBox.setText("Please provide the output file name");
            msgBox.exec();
        }
    }
    else{
        msgBox.setText("Please select the input file");
        msgBox.exec();
    }




}
//modify
void MainWindow::setValue (int indexNum, int rowNum)
{

    if(rowNum>-1)
    {

        QString textName="";
        QStringList qsl;

        QString str;
        QStringList list;

        QString strName;
        QStringList listName;

        QString order;


        double doubleIndex=0;
        int lowIndexValue = 0;
        int highIndexValue =0;
        //storder 计算影响因子最高的指数

        //                QTableView *view1 = new QTableView;
        //                view1->setModel(model);
        //                //view->hideColumn(0); // don't show the ID
        //                view1->show();


        if(indexNum!=0)//compute sub index
        {
            doubleIndex = model2->record(rowNum).value(indexNum+2).toDouble();
            lowIndexValue = int(getLow(indexNum, rowNum));
            highIndexValue = int(getHigh(indexNum,rowNum));
            //            modelIndex->setFilter("Code2 ='" + getColumnName(index)+"'");

            textName = getIndexName(indexNum);

            //        QString str;
            //        QStringList list;

            //        str = "Some  text\n\twith  strange whitespace.";
            //        list = str.split(QRegExp("\\s+"));
            // list: [ "Some", "text", "with", "strange", "whitespace." ]


            str = model3->record (rowNum).value (indexNum+2).toString ();
            list = str.split (QRegExp("\\,"));

            strName = model4->record (rowNum).value (indexNum+2).toString ();
            listName = strName.split (QRegExp("\\,"));
            //        QTableView *view1 = new QTableView;
            //        view1->setModel(model3);
            //        view1->show();

            //        QTableView *view2 = new QTableView;
            //        view2->setModel(model4);
            //        view2->show();
            //        //     view->hideColumn(0); // don't show the ID

            int columnC = list.count ();

            for (int i = 0; i < columnC-1; ) {
                //int x = listName.value (i).toInt ();

                QString index3 = "X"+QString::number (getColumnName(indexNum).right(3).toInt ()+listName.value (i).toInt ()+1);
                QString itemFilter = "Code3 ='"+index3+"'";
                modelIndex->setFilter (itemFilter);
                modelIndex->select ();

                //            QTableView *view2 = new QTableView;
                //            view2->setModel(modelIndex);
                //            view2->show();
                //     view->hideColumn(0); // don't show the ID

                //int z = modelIndex->rowCount ();
                for (int j = 0; j < modelIndex->rowCount (); j++) {
                    QString s =  modelIndex->record (j).value ("Name").toString ();
                     order = QString::number (i+1)+ "  "+ s+" "+list.value (i);
                     qsl.append (order);
                    i++;
                }




            }
        }
        else// compute main index
        {

            AlldynamicArrayinit ();
            doubleIndex =  computeIndexAll (rowNum);
            lowIndexValue = int(getAllLow(rowNum));
            highIndexValue = int(getAllHigh(rowNum));

            textName = "总成指数";

            str = computeOrderAll (rowNum);
            list = str.split (QRegExp("\\,"));

            strName = computeOrderNameAll(rowNum);
            listName = strName.split (QRegExp("\\,"));


            for (int i = 0; i < 7; ++i) {
                    QString s =  getIndexName (listName[i].toInt ()+1);
                     order = QString::number (i+1)+ "  "+ s+" "+list.value (i);
                     qsl.append (order);
                }

        }




        typeModel1->setStringList (qsl);
        order_comboBox->setModel (typeModel1);

        this->left_verticalSlider->setValue(lowIndexValue);
        this->right_verticalSlider->setValue(highIndexValue);


        int intIndexValue = int(doubleIndex);
        this->index_progressBar->setValue (intIndexValue);


        //        QStringList qsl1;
        //        qsl1.append ("全部");
        //        int rowC = model->rowCount ();

        //        for (int i = 0; i < rowC ; ++i) {
        //            if(!qsl1.contains (model->record (i).value ("year").toString ()))
        //                qsl1.append (model->record (i).value ("year").toString ());
        //        }

        //        typeModel->setStringList (qsl1);
        //        year_comboBox->setModel (typeModel);


        QString indexValue = QString::number (doubleIndex);

        QString explain =  getInfo(doubleIndex,lowIndexValue,highIndexValue);

        //QString report = getReport(doubleIndex,lowIndexValue,highIndexValue);

        this->index_lineEdit->setText (indexValue);
        this->explain_textEdit->setText (explain);

        QString time = model->record (rowNum).value ("year").toString ();//queryModel->record (rowNum).value ("year").toString ();
        time += "年 第";
        time += model->record (rowNum).value ("quarter").toString ();//queryModel->record (rowNum).value ("quarter").toString ();
        time += "季度";
        this->year_lineEdit->setText (time);

        textEdit_IndexName->setText(textName);




    }
    else
    {
        order_comboBox->clear ();
        index_progressBar->setValue (0);
        left_verticalSlider->setValue(0);
        right_verticalSlider->setValue(100);
        year_lineEdit->setText ("年度和季度");
        explain_textEdit->setText ("指标解释");
        index_lineEdit->setText ("计算结果");
        this->textEdit_IndexName->setText("指数名称");

    }


}
void Configuration::save()
{
    KConfigGroup configuration = m_applet->config();
    QStringList controls;

    if (m_controlsUi.openCheckBox->isChecked())
    {
        controls.append("open");
    }

    if (m_controlsUi.playPauseCheckBox->isChecked())
    {
        controls.append("playPause");
    }

    if (m_controlsUi.stopCheckBox->isChecked())
    {
        controls.append("stop");
    }

    if (m_controlsUi.playPreviousCheckBox->isChecked())
    {
        controls.append("playPrevious");
    }

    if (m_controlsUi.playNextCheckBox->isChecked())
    {
        controls.append("playNext");
    }

    if (m_controlsUi.positionCheckBox->isChecked())
    {
        controls.append("position");
    }

    if (m_controlsUi.volumeCheckBox->isChecked())
    {
        controls.append("volume");
    }

    if (m_controlsUi.muteCheckBox->isChecked())
    {
        controls.append("mute");
    }

    if (m_controlsUi.playlistCheckBox->isChecked())
    {
        controls.append("playlist");
    }

    if (m_controlsUi.fullScreenCheckBox->isChecked())
    {
        controls.append("fullScreen");
    }

    configuration.writeEntry("controls", controls);
    configuration.writeEntry("playOnStartup", m_generalUi.startPlaybackCheckBox->isChecked());
    configuration.writeEntry("enableDBus", m_generalUi.dbusCheckBox->isChecked());
    configuration.writeEntry("inhibitNotifications", m_generalUi.inhibitNotificationsCheckBox->isChecked());
    configuration.writeEntry("showToolTipOnTrackChange", m_generalUi.showTooltipOnTrackChange->value());

    static_cast<KConfigDialog*>(parent())->enableButtonApply(false);

    emit accepted();
}
Exemple #19
0
void GisClient::createObject(const Stream &s, const QList<QPoint> &coordinates)
{
    QStringList coordinatsStreamList;
    foreach (QPoint p, coordinates) {
        coordinatsStreamList.append(QString("%1   %2").arg(p.x()).arg(p.y()));
    }
Exemple #20
0
 QStringList Addressbook::protocols()
 {
     QStringList protocols;
     protocols.append("messaging/irc");
     return protocols;
 }
bool QgsAfsSharedData::getFeature( QgsFeatureId id, QgsFeature &f, const QgsRectangle &filterRect, QgsFeedback *feedback )
{
  QMutexLocker locker( &mMutex );

  // If cached, return cached feature
  QMap<QgsFeatureId, QgsFeature>::const_iterator it = mCache.constFind( id );
  if ( it != mCache.constEnd() )
  {
    f = it.value();
    return filterRect.isNull() || ( f.hasGeometry() && f.geometry().intersects( filterRect ) );
  }

  // When fetching from server, fetch all attributes and geometry by default so that we can cache them
  QStringList fetchAttribNames;
  QList<int> fetchAttribIdx;
  fetchAttribIdx.reserve( mFields.size() );
  fetchAttribNames.reserve( mFields.size() );
  for ( int idx = 0, n = mFields.size(); idx < n; ++idx )
  {
    fetchAttribNames.append( mFields.at( idx ).name() );
    fetchAttribIdx.append( idx );
  }

  // Fetch 100 features at the time
  int startId = ( id / 100 ) * 100;
  int stopId = std::min( startId + 100, mObjectIds.length() );
  QList<quint32> objectIds;
  objectIds.reserve( stopId );
  for ( int i = startId; i < stopId; ++i )
  {
    if ( i >= 0 && i < mObjectIds.count() )
      objectIds.append( mObjectIds[i] );
  }

  if ( objectIds.empty() )
  {
    QgsDebugMsg( QStringLiteral( "No valid features IDs to fetch" ) );
    return false;
  }

  // don't lock while doing the fetch
  locker.unlock();

  // Query
  QString errorTitle, errorMessage;

  const QString authcfg = mDataSource.authConfigId();
  const QVariantMap queryData = QgsArcGisRestUtils::getObjects(
                                  mDataSource.param( QStringLiteral( "url" ) ), authcfg, objectIds, mDataSource.param( QStringLiteral( "crs" ) ), true,
                                  fetchAttribNames, QgsWkbTypes::hasM( mGeometryType ), QgsWkbTypes::hasZ( mGeometryType ),
                                  filterRect, errorTitle, errorMessage, feedback );

  if ( queryData.isEmpty() )
  {
//    const_cast<QgsAfsProvider *>( this )->pushError( errorTitle + ": " + errorMessage );
    QgsDebugMsg( QStringLiteral( "Query returned empty result" ) );
    return false;
  }

  // but re-lock while updating cache
  locker.relock();
  const QVariantList featuresData = queryData[QStringLiteral( "features" )].toList();
  if ( featuresData.isEmpty() )
  {
    QgsDebugMsgLevel( QStringLiteral( "Query returned no features" ), 3 );
    return false;
  }
  for ( int i = 0, n = featuresData.size(); i < n; ++i )
  {
    const QVariantMap featureData = featuresData[i].toMap();
    QgsFeature feature;
    int featureId = startId + i;

    // Set attributes
    if ( !fetchAttribIdx.isEmpty() )
    {
      const QVariantMap attributesData = featureData[QStringLiteral( "attributes" )].toMap();
      feature.setFields( mFields );
      QgsAttributes attributes( mFields.size() );
      for ( int idx : qgis::as_const( fetchAttribIdx ) )
      {
        QVariant attribute = attributesData[mFields.at( idx ).name()];
        if ( attribute.isNull() )
        {
          // ensure that null values are mapped correctly for PyQGIS
          attribute = QVariant( QVariant::Int );
        }

        // date/datetime fields must be converted
        if ( mFields.at( idx ).type() == QVariant::DateTime || mFields.at( idx ).type() == QVariant::Date )
          attribute = QgsArcGisRestUtils::parseDateTime( attribute );

        if ( !mFields.at( idx ).convertCompatible( attribute ) )
        {
          QgsDebugMsg( QStringLiteral( "Invalid value %1 for field %2 of type %3" ).arg( attributesData[mFields.at( idx ).name()].toString(), mFields.at( idx ).name(), mFields.at( idx ).typeName() ) );
        }
        attributes[idx] = attribute;
        if ( mFields.at( idx ).name() == QStringLiteral( "OBJECTID" ) )
        {
          featureId = startId + objectIds.indexOf( attributesData[mFields.at( idx ).name()].toInt() );
        }
      }
      feature.setAttributes( attributes );
    }

    // Set FID
    feature.setId( featureId );

    // Set geometry
    const QVariantMap geometryData = featureData[QStringLiteral( "geometry" )].toMap();
    std::unique_ptr< QgsAbstractGeometry > geometry = QgsArcGisRestUtils::parseEsriGeoJSON( geometryData, queryData[QStringLiteral( "geometryType" )].toString(),
        QgsWkbTypes::hasM( mGeometryType ), QgsWkbTypes::hasZ( mGeometryType ) );
    // Above might return 0, which is OK since in theory empty geometries are allowed
    if ( geometry )
      feature.setGeometry( QgsGeometry( std::move( geometry ) ) );
    feature.setValid( true );
    mCache.insert( feature.id(), feature );
  }

  // If added to cache, return feature
  it = mCache.constFind( id );
  if ( it != mCache.constEnd() )
  {
    f = it.value();
    return filterRect.isNull() || ( f.hasGeometry() && f.geometry().intersects( filterRect ) );
  }

  return false;
}
static void createGtkrc( bool exportColors, const QPalette& cg, bool exportGtkTheme, const QString& gtkTheme, int version )
{
    // lukas: why does it create in ~/.kde/share/config ???
    // pfeiffer: so that we don't overwrite the user's gtkrc.
    // it is found via the GTK_RC_FILES environment variable.
    QSaveFile saveFile( writableGtkrc(version) );
    if ( !saveFile.open(QIODevice::WriteOnly) )
        return;

    QTextStream t ( &saveFile );
    t.setCodec( QTextCodec::codecForLocale () );

    t << i18n(
            "# created by KDE, %1\n"
            "#\n"
            "# If you do not want KDE to override your GTK settings, select\n"
            "# Appearance -> Colors in the System Settings and disable the checkbox\n"
            "# \"Apply colors to non-KDE4 applications\"\n"
            "#\n"
            "#\n", QDateTime::currentDateTime().toString());

    if ( 2==version ) {  // we should maybe check for MacOS settings here
        t << endl;
        t << "gtk-alternative-button-order = 1" << endl;
        t << endl;
    }

    if (exportGtkTheme)
    {
        QString gtkStyle;
        if (gtkTheme.toLower() == QLatin1String("oxygen"))
            gtkStyle = QStringLiteral("oxygen-gtk");
        else
            gtkStyle = gtkTheme;

        bool exist_gtkrc = false;
        QByteArray gtkrc = getenv(gtkEnvVar(version));
        QStringList listGtkrc = QFile::decodeName(gtkrc).split(QStringLiteral(":"));
        if (listGtkrc.contains(saveFile.fileName()))
            listGtkrc.removeAll(saveFile.fileName());
        listGtkrc.append(QDir::homePath() + userGtkrc(version));
        listGtkrc.append(QDir::homePath() + "/.gtkrc-2.0-kde");
        listGtkrc.append(QDir::homePath() + "/.gtkrc-2.0-kde4");
        listGtkrc.removeAll(QLatin1String(""));
        listGtkrc.removeDuplicates();
        for (int i = 0; i < listGtkrc.size(); ++i)
        {
            if ((exist_gtkrc = QFile::exists(listGtkrc.at(i))))
                break;
        }

        if (!exist_gtkrc)
        {
            QString gtk2ThemeFilename;
            gtk2ThemeFilename = QStringLiteral("%1/.themes/%2/gtk-2.0/gtkrc").arg(QDir::homePath()).arg(gtkStyle);
            if (!QFile::exists(gtk2ThemeFilename)) {
                QStringList gtk2ThemePath;
                gtk2ThemeFilename.clear();
                QByteArray xdgDataDirs = getenv("XDG_DATA_DIRS");
                gtk2ThemePath.append(QDir::homePath() + "/.local");
                gtk2ThemePath.append(QFile::decodeName(xdgDataDirs).split(QStringLiteral(":")));
                gtk2ThemePath.removeDuplicates();
                for (int i = 0; i < gtk2ThemePath.size(); ++i)
                {
                    gtk2ThemeFilename = QStringLiteral("%1/themes/%2/gtk-2.0/gtkrc").arg(gtk2ThemePath.at(i)).arg(gtkStyle);
                    if (QFile::exists(gtk2ThemeFilename))
                        break;
                    else
                        gtk2ThemeFilename.clear();
                }
            }

            if (!gtk2ThemeFilename.isEmpty())
            {
                t << "include \"" << gtk2ThemeFilename << "\"" << endl;
                t << endl;
                t << "gtk-theme-name=\"" << gtkStyle << "\"" << endl;
                t << endl;
                if (gtkStyle == QLatin1String("oxygen-gtk"))
                    exportColors = false;
            }
        }

    }

    if (exportColors)
    {
        t << "style \"default\"" << endl;
        t << "{" << endl;
        t << "  bg[NORMAL] = " << color( cg.color( QPalette::Active, QPalette::Background ) ) << endl;
        t << "  bg[SELECTED] = " << color( cg.color(QPalette::Active, QPalette::Highlight) ) << endl;
        t << "  bg[INSENSITIVE] = " << color( cg.color( QPalette::Active, QPalette::Background ) ) << endl;
        t << "  bg[ACTIVE] = " << color( cg.color( QPalette::Active, QPalette::Mid ) ) << endl;
        t << "  bg[PRELIGHT] = " << color( cg.color( QPalette::Active, QPalette::Background ) ) << endl;
        t << endl;
        t << "  base[NORMAL] = " << color( cg.color( QPalette::Active, QPalette::Base ) ) << endl;
        t << "  base[SELECTED] = " << color( cg.color(QPalette::Active, QPalette::Highlight) ) << endl;
        t << "  base[INSENSITIVE] = " << color( cg.color( QPalette::Active, QPalette::Background ) ) << endl;
        t << "  base[ACTIVE] = " << color( cg.color(QPalette::Active, QPalette::Highlight) ) << endl;
        t << "  base[PRELIGHT] = " << color( cg.color(QPalette::Active, QPalette::Highlight) ) << endl;
        t << endl;
        t << "  text[NORMAL] = " << color( cg.color(QPalette::Active, QPalette::Text) ) << endl;
        t << "  text[SELECTED] = " << color( cg.color(QPalette::Active, QPalette::HighlightedText) ) << endl;
        t << "  text[INSENSITIVE] = " << color( cg.color( QPalette::Active, QPalette::Mid ) ) << endl;
        t << "  text[ACTIVE] = " << color( cg.color(QPalette::Active, QPalette::HighlightedText) ) << endl;
        t << "  text[PRELIGHT] = " << color( cg.color(QPalette::Active, QPalette::HighlightedText) ) << endl;
        t << endl;
        t << "  fg[NORMAL] = " << color ( cg.color( QPalette::Active, QPalette::Foreground ) ) << endl;
        t << "  fg[SELECTED] = " << color( cg.color(QPalette::Active, QPalette::HighlightedText) ) << endl;
        t << "  fg[INSENSITIVE] = " << color( cg.color( QPalette::Active, QPalette::Mid ) ) << endl;
        t << "  fg[ACTIVE] = " << color( cg.color( QPalette::Active, QPalette::Foreground ) ) << endl;
        t << "  fg[PRELIGHT] = " << color( cg.color( QPalette::Active, QPalette::Foreground ) ) << endl;
        t << "}" << endl;
        t << endl;
        t << "class \"*\" style \"default\"" << endl;
        t << endl;

        // tooltips don't have the standard background color
        t << "style \"ToolTip\"" << endl;
        t << "{" << endl;
        QPalette group = QToolTip::palette();
        t << "  bg[NORMAL] = " << color( group.color( QPalette::Active, QPalette::Background ) ) << endl;
        t << "  base[NORMAL] = " << color( group.color( QPalette::Active, QPalette::Base ) ) << endl;
        t << "  text[NORMAL] = " << color( group.color( QPalette::Active, QPalette::Text ) ) << endl;
        t << "  fg[NORMAL] = " << color( group.color( QPalette::Active, QPalette::Foreground ) ) << endl;
        t << "}" << endl;
        t << endl;
        t << "widget \"gtk-tooltip\" style \"ToolTip\"" << endl;
        t << "widget \"gtk-tooltips\" style \"ToolTip\"" << endl;
        t << endl;


        // highlight the current (mouse-hovered) menu-item
        // not every button, checkbox, etc.
        t << "style \"MenuItem\"" << endl;
        t << "{" << endl;
        t << "  bg[PRELIGHT] = " << color( cg.color(QPalette::Highlight) ) << endl;
        t << "  fg[PRELIGHT] = " << color( cg.color(QPalette::HighlightedText) ) << endl;
        t << "}" << endl;
        t << endl;
        t << "class \"*MenuItem\" style \"MenuItem\"" << endl;
        t << endl;
    }
    saveFile.commit();
}
Exemple #23
0
bool KMCupsJobManager::listJobs(const QString& prname, KMJobManager::JobType type, int limit)
{
	IppRequest	req;
	QStringList	keys;
	CupsInfos	*infos = CupsInfos::self();

	// wanted attributes
	keys.append("job-id");
	keys.append("job-uri");
	keys.append("job-name");
	keys.append("job-state");
	keys.append("job-printer-uri");
	keys.append("job-k-octets");
	keys.append("job-originating-user-name");
	keys.append("job-k-octets-completed");
	keys.append("job-media-sheets");
	keys.append("job-media-sheets-completed");
	keys.append("job-priority");
	keys.append("job-billing");

	req.setOperation(IPP_GET_JOBS);

	// add printer-uri
	KMPrinter *mp = KMManager::self()->findPrinter(prname);
	if (!mp)
		return false;

	if (!mp->uri().isEmpty())
	{
		req.addURI(IPP_TAG_OPERATION, "printer-uri", mp->uri().prettyURL());
		/*
		req.setHost(mp->uri().host());
		req.setPort(mp->uri().port());
		*/
	}
	else
		req.addURI(IPP_TAG_OPERATION, "printer-uri", QString("ipp://%1/%2/%3").arg(infos->hostaddr(),
                            (mp&&mp->isClass())?"classes":"printers", prname));

	// other attributes
	req.addKeyword(IPP_TAG_OPERATION, "requested-attributes", keys);
	if (type == KMJobManager::CompletedJobs)
		req.addKeyword(IPP_TAG_OPERATION,"which-jobs",QString::fromLatin1("completed"));
	if (limit > 0)
		req.addInteger(IPP_TAG_OPERATION,"limit",limit);

	// send request
	if (req.doRequest("/"))
		parseListAnswer(req, mp);
	else
		return false;

	return true;
}
Exemple #24
0
int main(int argc, char * argv[]){
    /* первым делом создадим директорию для работы нашей проги */
    pathDBfile = QDir::toNativeSeparators(QDir::homePath()) + separator + ".dplayer";

    if (!QDir(pathDBfile).exists()) {
        qDebug() << "path programm not exists! Create...";
        QDir().mkdir(pathDBfile);
    }

    /* вторым делом подготовим таблицы */
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(pathDBfile + separator + "dbplayer.db");
    if (!db.open()) {
        QString message = db.lastError().text();
        qDebug() << "DB error: " << message;
    }
    QSqlQuery a_query(db);
    QString str = "CREATE TABLE IF NOT EXISTS file ("
        "id integer PRIMARY KEY AUTOINCREMENT NOT NULL, "
        "name VARCHAR(255), "
        "create_date DATETIME"
        ");";
    bool b = a_query.exec(str);
    if (!b) {
        QString message = db.lastError().text();
        qDebug() << "DB Create table [file] error: " << message;
    }
    str = "CREATE TABLE IF NOT EXISTS conf ("
        "name VARCHAR(255) PRIMARY KEY NOT NULL, "
        "value VARCHAR(255) "
        ");";
    b = a_query.exec(str);
    if (!b) {
        QString message = db.lastError().text();
        qDebug() << "DB Create table [file] error: " << message;
    }
    db.close();     // закроем подключение к базе
    /* конец создания таблиц */

    /* инициализируем гуи */
    QGuiApplication app(argc, argv);
    QQmlEngine engine;

    QStringList dataList;
    dataList.append("Item 1");
    dataList.append("Item 2");
    dataList.append("Item 3");
    dataList.append("Item 4");
    //QQmlContext *ctxt = engine.rootContext();
    engine.rootContext()->setContextProperty("myModel", QVariant::fromValue(dataList));

    QQmlComponent component(&engine, QUrl(QStringLiteral("qrc:/main.qml")));


    /* маппим объекты GML с нашими классами */
    QObject * object = component.create();
    watcherTxtDrive chekUSB;
    chekUSB.txtDrive = object->findChild<QObject *>("txtDrive");
    chekUSB.txtMemo = object->findChild<QObject *>("txtMemo");

    /* нужно просканировать наличие УЖЕ подключенных съемных дисков WIN32*/
    QFileInfoList drivers = QDir::drives();
    foreach(QFileInfo drive, drivers) {
        chekUSB.slotDeviceAdded(drive.absoluteFilePath());
    }
void KrPopupMenu::performAction(int id)
{
    QList<QUrl> lst;

    switch (id) {
    case - 1 : // the user clicked outside of the menu
        return ;
    case OPEN_TAB_ID :
        // assuming only 1 file is selected (otherwise we won't get here)
        panel->manager()->newTab(_item->url(), panel);
        break;
    case OPEN_ID :
        foreach(KFileItem fi, _items)
            panel->func->execute(fi.name());
        break;
    case COPY_ID :
        panel->func->copyFiles();
        break;
    case MOVE_ID :
        panel->func->moveFiles();
        break;
    case RENAME_ID :
        panel->func->rename();
        break;
    case TRASH_ID :
        panel->func->deleteFiles(false);
        break;
    case DELETE_ID :
        panel->func->deleteFiles(true);
        break;
    case EJECT_ID :
        krMtMan.eject(_item->url().adjusted(QUrl::StripTrailingSlash).path());
        break;
        /*         case SHRED_ID :
                    if ( KMessageBox::warningContinueCancel( krApp,
                         i18n("<qt>Do you really want to shred <b>%1</b>? Once shred, the file is gone forever.</qt>", item->name()),
                         QString(), KStandardGuiItem::cont(), KStandardGuiItem::cancel(), "Shred" ) == KMessageBox::Continue )
                       KShred::shred( panel->func->files() ->vfs_getFile( item->name() ).adjusted(QUrl::RemoveTrailingSlash).path() );
                  break;*/
    case OPEN_KONQ_ID :
        KToolInvocation::startServiceByDesktopName("konqueror", _item->url().toDisplayString(QUrl::PreferLocalFile));
        break;
    case CHOOSE_ID : // open-with dialog
        lst << _item->url();
        panel->func->displayOpenWithDialog(lst);
        break;
    case MOUNT_ID :
        krMtMan.mount(_item->url().adjusted(QUrl::StripTrailingSlash).path());
        break;
    case NEW_LINK_ID :
        panel->func->krlink(false);
        break;
    case NEW_SYMLINK_ID :
        panel->func->krlink(true);
        break;
    case REDIRECT_LINK_ID :
        panel->func->redirectLink();
        break;
    case EMPTY_TRASH_ID :
        KrTrashHandler::emptyTrash();
        break;
    case RESTORE_TRASHED_FILE_ID :
        KrTrashHandler::restoreTrashedFiles(_items.urlList());
    break;
    case UNMOUNT_ID :
        krMtMan.unmount(_item->url().adjusted(QUrl::StripTrailingSlash).path());
        break;
    case COPY_CLIP_ID :
        panel->func->copyToClipboard();
        break;
    case MOVE_CLIP_ID :
        panel->func->copyToClipboard(true);
        break;
    case PASTE_CLIP_ID :
        panel->func->pasteFromClipboard();
        break;
    case SEND_BY_EMAIL_ID : {
        SLOTS->sendFileByEmail(_items.urlList());
        break;
    }
    case MKDIR_ID :
        panel->func->mkdir();
        break;
    case NEW_TEXT_FILE_ID:
        panel->func->editNew();
        break;
#ifdef SYNCHRONIZER_ENABLED
    case SYNC_SELECTED_ID : {
        QStringList selectedNames;
        foreach(KFileItem item, _items)
            selectedNames << item.name();
        if (panel->otherPanel()->view->numSelected()) {
            KrViewItemList otherItems;
            panel->otherPanel()->view->getSelectedKrViewItems(&otherItems);

            for (KrViewItemList::Iterator it2 = otherItems.begin(); it2 != otherItems.end(); ++it2) {
                QString name = (*it2) ->name();
                if (!selectedNames.contains(name))
                    selectedNames.append(name);
            }
        }
        SLOTS->slotSynchronizeDirs(selectedNames);
    }
    break;
#endif
    case OPEN_TERM_ID : {
        QStringList args;
        if (!_item->isDir())
            args << _item->name();
        SLOTS->runTerminal(_item->url().path(), args);
    }
    break;
    }

    // check if something from the open-with-offered-services was selected
    if (id >= SERVICE_LIST_ID) {
        QStringList names;
        panel->gui->getSelectedNames(&names);
        panel->func->runService(*(offers[ id - SERVICE_LIST_ID ]),
                                panel->func->files()->vfs_getFiles(names));
    }
}
Exemple #26
0
void MainWindow::setupScreenQGVWidgets()
{
    ui->widget_2->setHidden(true);
    ui->sndPitchWidg->setHidden(true);
    ui->scrollArea->setHidden(false);
    ui->screenErr->clear();
    ScreenQGV::EditorType edType = ui->graphicsView->editorType();
    ui->screenName->setReadOnly(false);
    ui->actPieceWidg->setHidden(true);
    ui->label_10->setHidden(true);
    ui->widthRatio->setHidden(true);
    ui->label_13->setHidden(true);
    ui->heightRatio->setHidden(true);
    if(edType == ScreenQGV::MAP || edType == ScreenQGV::SCENE)
    {
        if(edType == ScreenQGV::MAP)
        {
            ui->graphicsView->setEditorType(ScreenQGV::MAP);
            ui->editorType->setText("Map Editor");
            ui->screenName->setText("WorldMap");
            ui->screenName->setReadOnly(true);
            ui->goToScene->clear();
            ui->goToScene->addItem(QString("Go to Scene"));
            ui->goToScene->insertItems(1, m_scenes->list());

            ui->chooseRewardBadge->setHidden(true);
            ui->badgeLine->setHidden(true);

            // This presents the aspect ratio
            // I'm taking this out because right now, I do not have the time to correctly implement this here or in the game player
            /*ui->label_10->setHidden(false);
            ui->widthRatio->setHidden(false);
            ui->label_13->setHidden(false);
            ui->heightRatio->setHidden(false);*/
        }
        else // SCENE
        {
            ui->graphicsView->setEditorType(ScreenQGV::SCENE);
            ui->editorType->setText("Scene Editor");
            ui->goToActivity->clear();
            ui->goToActivity->addItem(QString("Go to Activity"));
            QStringList list = m_pairActs->listWithName(QString("Pairing - "));
            list.append(m_matchActs->listWithName(QString("Matching - ")));
            ui->goToActivity->insertItems(1, list);

            ui->chooseRewardBadge->setHidden(false);
            ui->badgeLine->setHidden(false);
            ui->chooseRewardBadge->clear();
            ui->chooseRewardBadge->addItem(QString("Choose a Reward Badge"));
            ui->chooseRewardBadge->insertItems(1, m_badges->list());
            ui->chooseRewardBadge->setCurrentText(m_badges->badgeName(ui->graphicsView->rewardBadgeId()));
            if(ui->graphicsView->actsAreInScene())
                ui->chooseRewardBadge->setEnabled(true);
        }
        ui->choicesWidg->setHidden(true);
        ui->roundsWidg->setHidden(true);
        ui->maxScoreWidg->setHidden(true);
        ui->selectDictSet->setHidden(true);
        ui->actLine->setHidden(true);
        ui->actRewardWidg->setHidden(true);

        ui->addText->setHidden(false);
        ui->TextLines->setHidden(false);
        ui->textLine->setHidden(false);
        ui->addImg->setHidden(false);
        ui->imgLines->setHidden(false);
        ui->imgLine->setHidden(false);
        ui->addHotspot->setHidden(false);
        ui->hotspotLines->setHidden(false);
        ui->hotspotLine->setHidden(false);
        ui->addBox->setHidden(false);
        ui->boxLines->setHidden(false);
        ui->boxLine->setHidden(false);
        ui->saveEditor->setHidden(false);

        ui->addScreen->setHidden(true);
        ui->editScreen->setHidden(true);
    }
    else if(edType == ScreenQGV::PAIRACT || edType == ScreenQGV::MATCHACT)
    {
        ui->choicesWidg->setHidden(false);
        if(edType == ScreenQGV::MATCHACT)
            ui->roundsWidg->setHidden(false);
        else
            ui->roundsWidg->setHidden(true);
        ui->maxScoreWidg->setHidden(false);
        ui->selectDictSet->setHidden(false);
        ui->actLine->setHidden(false);
        ui->actRewardWidg->setHidden(false);

        ui->addText->setHidden(true);
        ui->TextLines->setHidden(true);
        ui->textLine->setHidden(true);
        ui->addImg->setHidden(true);
        ui->imgLines->setHidden(true);
        ui->imgLine->setHidden(true);
        ui->addHotspot->setHidden(true);
        ui->hotspotLines->setHidden(true);
        ui->hotspotLine->setHidden(true);
        ui->addBox->setHidden(true);
        ui->boxLines->setHidden(true);
        ui->boxLine->setHidden(true);
        ui->saveEditor->setHidden(true);
        ui->chooseRewardBadge->setHidden(true);
        ui->badgeLine->setHidden(true);

        ui->editorType->setText("Activity Editor");
        ui->selectDictSet->clear();
        ui->selectDictSet->addItem(QString("Choose a Dictionary Set"));
        ui->selectDictSet->insertItems(1, m_dictSets->dictSetsList());
        ui->selectDictSet->setCurrentText(m_dictSets->dictSetName(ui->graphicsView->dictSetId()));
        ui->numChoices->setValue(ui->graphicsView->choices());
        ui->numRounds->setValue(ui->graphicsView->rounds());
        ui->maxScore->setValue(ui->graphicsView->maxScore());

        ui->actRewardImg->setPixmap(QPixmap(QString::fromStdWString(ui->graphicsView->getRewardImage())).scaled(50, 50,
                                                                   Qt::KeepAspectRatioByExpanding,
                                                                   Qt::FastTransformation));

        QString qS = QString::fromStdWString(ui->graphicsView->getRewardSoundFile());
        cout << "sound file is " << qS.toStdString() << endl;

        if(ui->graphicsView->getRewardSoundFile() == L"None")
        {
            MainWindow::ui->addSnd->setHidden(false);
        }
        else
        {
            MainWindow::ui->delSnd->setHidden(false);
            MainWindow::ui->sndVolWidg->setHidden(false);
            MainWindow::ui->sndVol->setValue(ui->graphicsView->getRewardSoundVolume());
            MainWindow::ui->sndPitch->setValue(1);
        }
    }
    else // NONE
    {
        ui->scrollArea->setHidden(true);
    }
    ui->stackedWidget->setCurrentWidget(ui->screenEditor);
}
Exemple #27
0
void NgfpReader::attrFromJson (const QJsonValue &j_attr, Attr *attr)
{
    AttrInputType input_type = attr->getInputType();
    QVariant var;

    if (input_type == AttrInputType::Boolean)
    {
        var = j_attr.toBool();
    }

    else if (input_type == AttrInputType::Number)
    {
        var = j_attr.toInt();
    }

    else if (input_type == AttrInputType::String)
    {
        var = j_attr.toString();
    }

    else if (input_type == AttrInputType::StringList ||
             input_type == AttrInputType::PageList)
    {
        QStringList list;
        QJsonArray j_arr = j_attr.toArray(QJsonArray());
        for (int i = 0; i < j_arr.size(); i++)
            list.append(j_arr[i].toString());
        var = list;
    }

    else if (input_type == AttrInputType::DateTime)
    {
        var = QDateTime::fromString(j_attr.toString(), FB_NGFP_DATETIME_FORMAT_DT);
    }

    else if (input_type == AttrInputType::Enum)
    {
        var = j_attr.toInt();
    }

    else if (input_type == AttrInputType::DoubleItems)
    {
        DoubleItemsValue value;
        QJsonArray j_arr = j_attr.toArray(QJsonArray());
        value.def_index = -1;
        for (int i = 0; i < j_arr.size(); i++)
        {
            QJsonValue j_arr_item = j_arr[i];
            value.inners.append(j_arr_item.toObject()["name"].toString());
            value.outers.append(j_arr_item.toObject()["alias"].toString());
            if (!j_arr_item.toObject().value("default").isUndefined())
                value.def_index = i;
        }
        var = QVariant::fromValue<DoubleItemsValue>(value);
    }

    else if (input_type == AttrInputType::TripleItems)
    {
        TripleItemsValue value;
        QJsonArray j_arr = j_attr.toArray(QJsonArray());
        value.def_index = -1;
        for (int i = 0; i < j_arr.size(); i++)
        {
            QJsonValue j_arr_item = j_arr[i];
            value.inners.append(j_arr_item.toObject()["name"].toString());
            value.outers_left.append(j_arr_item.toObject()["alias"].toString());
            value.outers_right.append(j_arr_item.toObject()["alias2"].toString());
            if (!j_arr_item.toObject().value("default").isUndefined())
                value.def_index = i;
        }
        var = QVariant::fromValue<TripleItemsValue>(value);
    }

    else if (input_type == AttrInputType::DepDoubleItems)
    {
        DepDoubleItemsValue value;
        QJsonArray j_arr = j_attr.toArray(QJsonArray());
        value.main.def_index = -1;
        for (int i = 0; i < j_arr.size(); i++)
        {
            QJsonValue j_arr_item = j_arr[i];
            value.main.inners.append(j_arr_item.toObject()["name"].toString());
            value.main.outers.append(j_arr_item.toObject()["alias"].toString());
            if (!j_arr_item.toObject().value("default").isUndefined())
                value.main.def_index = i;
            value.deps.append(DoubleItemsValue());
            QJsonValue j_arr2_val = j_arr_item.toObject()["values"];
            QJsonArray j_arr2 = j_arr2_val.toArray(QJsonArray());
            if (!(j_arr2.size() == 1 &&
                j_arr2[0].toObject()["name"].toString() == "-1" &&
                j_arr2[0].toObject()["alias"].toString() == "--"))
            {
                value.deps.last().def_index = -1;
                for (int i2 = 0; i2 < j_arr2.size(); i2++)
                {
                    QJsonValue j_arr_item2 = j_arr2[i2];
                    value.deps.last().inners.append(j_arr_item2.toObject()["name"].toString());
                    value.deps.last().outers.append(j_arr_item2.toObject()["alias"].toString());
                    if (!j_arr_item2.toObject().value("default").isUndefined())
                        value.deps.last().def_index = i2;
                }
            }
        }
        var = QVariant::fromValue<DepDoubleItemsValue>(value);
    }

    attr->setValueAsVar(var);
}
void MaintainingReader<TokenLookupClass, LookupKey>::validateElement(const LookupKey elementName) const
{
    Q_ASSERT(tokenType() == QXmlStreamReader::StartElement);

    if(m_elementDescriptions.contains(elementName))
    {
        // QHash::value breaks in Metrowerks Compiler
        const ElementDescription<TokenLookupClass, LookupKey> &desc = *m_elementDescriptions.find(elementName);
        const int attCount = m_currentAttributes.count();

        QSet<typename TokenLookupClass::NodeName> encounteredXSLTAtts;

        for(int i = 0; i < attCount; ++i)
        {
            const QXmlStreamAttribute &attr = m_currentAttributes.at(i);
            if(attr.namespaceUri().isEmpty())
            {
                const typename TokenLookupClass::NodeName attrName(TokenLookupClass::toToken(attr.name()));
                encounteredXSLTAtts.insert(attrName);

                if(!desc.requiredAttributes.contains(attrName) &&
                   !desc.optionalAttributes.contains(attrName) &&
                   !m_standardAttributes.contains(attrName) &&
                   !isAnyAttributeAllowed())
                {
                    QString translationString;

                    QList<typename TokenLookupClass::NodeName> all(desc.requiredAttributes.toList() + desc.optionalAttributes.toList());
                    const int totalCount = all.count();
                    QStringList allowed;

                    for(int i = 0; i < totalCount; ++i)
                        allowed.append(QPatternist::formatKeyword(TokenLookupClass::toString(all.at(i))));

                    /* Note, we can't run toString() on attrName, because we're in this branch,
                     * the token lookup doesn't have the string(!).*/
                    const QString stringedName(attr.name().toString());

                    if(totalCount == 0)
                    {
                        translationString = QtXmlPatterns::tr("Attribute %1 cannot appear on the element %2. Only the standard attributes can appear.")
                                            .arg(formatKeyword(stringedName),
                                                 formatKeyword(name()));
                    }
                    else if(totalCount == 1)
                    {
                        translationString = QtXmlPatterns::tr("Attribute %1 cannot appear on the element %2. Only %3 is allowed, and the standard attributes.")
                                            .arg(formatKeyword(stringedName),
                                                 formatKeyword(name()),
                                                 allowed.first());
                    }
                    else if(totalCount == 1)
                    {
                        /* Note, allowed has already had formatKeyword() applied. */
                        translationString = QtXmlPatterns::tr("Attribute %1 cannot appear on the element %2. Allowed is %3, %4, and the standard attributes.")
                                            .arg(formatKeyword(stringedName),
                                                 formatKeyword(name()),
                                                 allowed.first(),
                                                 allowed.last());
                    }
                    else
                    {
                        /* Note, allowed has already had formatKeyword() applied. */
                        translationString = QtXmlPatterns::tr("Attribute %1 cannot appear on the element %2. Allowed is %3, and the standard attributes.")
                                            .arg(formatKeyword(stringedName),
                                                 formatKeyword(name()),
                                                 allowed.join(QLatin1String(", ")));
                    }

                    m_context->error(translationString,
                                     ReportContext::XTSE0090,
                                     currentLocation());
                }
            }
            else if(attr.namespaceUri() == namespaceUri())
            {
                m_context->error(QtXmlPatterns::tr("XSL-T attributes on XSL-T elements must be in the null namespace, not in the XSL-T namespace which %1 is.")
                                                  .arg(formatKeyword(attr.name())),
                                 ReportContext::XTSE0090,
                                 currentLocation());
            }
            /* Else, attributes in other namespaces are allowed, continue. */
        }

        const QSet<typename TokenLookupClass::NodeName> requiredButMissing(QSet<typename TokenLookupClass::NodeName>(desc.requiredAttributes).subtract(encounteredXSLTAtts));

        if(!requiredButMissing.isEmpty())
        {
            error(QtXmlPatterns::tr("The attribute %1 must appear on element %2.")
                             .arg(QPatternist::formatKeyword(TokenLookupClass::toString(*requiredButMissing.constBegin())),
                                  formatKeyword(name())),
                  ReportContext::XTSE0010);
        }
    }
    else
    {
        error(QtXmlPatterns::tr("The element with local name %1 does not exist in XSL-T.").arg(formatKeyword(name())),
              ReportContext::XTSE0010);
    }
}
Exemple #29
0
/*!
  \internal
  Returns the list of fields belonging to a contact
  Never change order of this list ! It has to be regarding
  enum AddressBookFields !!
*/
QStringList OContact::fields()
{
    QStringList list;

    list.append( "Title" );  // Not Used!
    list.append( "FirstName" );
    list.append( "MiddleName" );
    list.append( "LastName" );
    list.append( "Suffix" );
    list.append( "FileAs" );

    list.append( "JobTitle" );
    list.append( "Department" );
    list.append( "Company" );
    list.append( "BusinessPhone" );
    list.append( "BusinessFax" );
    list.append( "BusinessMobile" );

    list.append( "DefaultEmail" );
    list.append( "Emails" );

    list.append( "HomePhone" );
    list.append( "HomeFax" );
    list.append( "HomeMobile" );

    list.append( "BusinessStreet" );
    list.append( "BusinessCity" );
    list.append( "BusinessState" );
    list.append( "BusinessZip" );
    list.append( "BusinessCountry" );
    list.append( "BusinessPager" );
    list.append( "BusinessWebPage" );

    list.append( "Office" );
    list.append( "Profession" );
    list.append( "Assistant" );
    list.append( "Manager" );

    list.append( "HomeStreet" );
    list.append( "HomeCity" );
    list.append( "HomeState" );
    list.append( "HomeZip" );
    list.append( "HomeCountry" );
    list.append( "HomeWebPage" );

    list.append( "Spouse" );
    list.append( "Gender" );
    list.append( "Birthday" );
    list.append( "Anniversary" );
    list.append( "Nickname" );
    list.append( "Children" );

    list.append( "Notes" );
    list.append( "Groups" );

    return list;
}
Exemple #30
0
void MainWin::gotranslate() {
	QString string = ui.leText->text();
	QString current;
	QStringList lst;
	QList<dictfind> curr,burr;
	int maxlen = (string.size()<10)?string.size():10;
	int i,j,k,m,len,pos=0;
	bool kap;
	QList<formfind> finded;
	MTableModel *model = (MTableModel*)ui.result->model();
	model->setColumnCount(6);
	model->clear();
	findres.clear();
	while (string.size()>0) {
		burr.clear();
		for(i=maxlen;(i>0 && burr.size()==0);i--) {
			current = string.left(i);
			finded=getbackforms(current,"*",0,"");
			curr.clear();
			for (j=0;j<finded.size();j++) {
				curr = scanWords(finded[j],true);
				if (curr.size()==0)
					curr = scanWords(katatohira(finded[j]),true);
				for (k = 0; k < curr.size(); k++) {
					kap = true;
					for(m = 0; m < burr.size(); m++) {
						if (wrdCompare(burr[m].word, curr[k].word))
							kap=false;
					}
					if (kap) {
						curr[k].src = current;
						curr[k].begin=pos;
						curr[k].len=current.size();
						burr.append(curr[k]);
					}
				}
			}
		}
		if (burr.size() != 0) {
			findres.append(burr);
			for(i = 0;i < burr.size(); i++) {
				lst.clear();
				lst.append(burr[i].src);
				if (burr[i].src == burr[i].word.word) {
					lst.append("");
				} else {
					lst.append(burr[i].word.word);
				}
				lst.append(burr[i].word.read);
				lst.append(burr[i].word.type);
				lst.append(burr[i].word.trans);
				lst.append(burr[i].comment);
				model->addrow(lst);
			}
			len=current.size();
		} else {len = 1;}
		pos += len;
		string.remove(0,len);
	}
	model->update();
}