void WindowsPlatformIntegration::runApplication(const QString &command, const QUrl &url) const
{
	if (command.isEmpty())
	{
		QDesktopServices::openUrl(url);

		return;
	}

	const int indexOfExecutable = command.indexOf(QLatin1String(".exe"), 0, Qt::CaseInsensitive);

	if (indexOfExecutable == -1)
	{
		Console::addMessage(tr("Failed to run command \"%1\", file is not executable").arg(command), OtherMessageCategory, ErrorMessageLevel);

		return;
	}

	const QString application = command.left(indexOfExecutable + 4);
	QStringList arguments = command.mid(indexOfExecutable + 5).split(QLatin1Char(' '), QString::SkipEmptyParts);
	const int indexOfPlaceholder = arguments.indexOf(QLatin1String("%1"));

	if (url.isValid())
	{
		if (indexOfPlaceholder > -1)
		{
			arguments.replace(indexOfPlaceholder, arguments.at(indexOfPlaceholder).arg(url.isLocalFile() ? QDir::toNativeSeparators(url.toLocalFile()) : url.url()));
		}
		else
		{
			arguments.append(url.isLocalFile() ? QDir::toNativeSeparators(url.toLocalFile()) : url.url());
		}
	}
	else if (indexOfPlaceholder > -1)
	{
		arguments.removeAt(indexOfPlaceholder);
	}

	if (!QProcess::startDetached(application, arguments))
	{
		Console::addMessage(tr("Failed to run command \"%1\" (arguments: \"%2\")").arg(command).arg(arguments.join(QLatin1Char(' '))), OtherMessageCategory, ErrorMessageLevel);
	}
}
void NCSLocalApplicationBridge::start(QString applicationPath,NCSCommandArguments arguments)
{
    QVector<NCSCommandFileArgument> fileArgs = arguments.fileArguments();
    QStringList argLiterals = arguments.literals();
    for (int i = 0; i <fileArgs.size();i++)
    {
        int literalIndex = argLiterals.indexOf(fileArgs[i].literal);
        if (literalIndex != -1)
        {
            if (fileArgs[i].filename != "")
            {
                if (!QFileInfo(fileArgs[i].filename).isAbsolute())
                    fileArgs[i].filename == QDir::currentPath() + "/" + fileArgs[i].filename;
                argLiterals.replace(literalIndex, fileArgs[i].filename);
            }
        }
    }

    m_runProcessName = applicationPath;
    m_process->start(applicationPath,argLiterals);
}
예제 #3
0
/* prepareGeneralSettings()
 * Called : By selectFunction()
 * Performs : Sets up the General Settings Tab
 */
void Settings::prepareGeneralSettings()
{
    flag[5]=true;

    //once flag is set we need not have the signals as
    //the settings are saved only at ok
    disconnect(printersCombo,SIGNAL(currentIndexChanged( const QString &)),this,
               SLOT(setPrinterFlag( const QString&)));
    databaseRB->setChecked(settings->value("general/mode",true).toBool());
    manualRB->setChecked(!settings->value("general/mode",false).toBool());

    QList<QPrinterInfo> plist;
    QPrinterInfo pinfo;
    plist=pinfo.availablePrinters();

    QStringList printers;
    for(int i=0;i<plist.size();i++)
        printers<<plist[i].printerName();
    int index=printers.indexOf( settings->value("general/printer","Unavailable").toString());

    QString temp,dprinter=pinfo.defaultPrinter().printerName();
    temp=dprinter;
    //highlighting default printer
    temp+="(Default)";
    printers.replace(printers.indexOf(dprinter),temp);
    //inserting all the printers
    printersCombo->insertItems(0,printers);

    //checking whether the current printer is there in the list newly generated
    //if not there show a msg saying "No printer assigned"
    if(index==-1)
    {
        printersCombo->insertItem(0,"No Printer Assigned");
        QMessageBox::information(this,"DocmaQ Settings","No Printer Assingned.Select a printer from the Available Printers ");
    }
    else
        printersCombo->setCurrentIndex(index);

    connect(printersCombo,SIGNAL(currentIndexChanged( const QString &)),this,SLOT(setPrinterFlag( const QString&)),Qt::UniqueConnection);
}
예제 #4
0
QString Entry::formattedField(Tellico::Data::FieldPtr field_, FieldFormat::Request request_) const {
  if(!field_) {
    return QString();
  }

  // don't format the value unless it's requested to do so
  if(request_ == FieldFormat::AsIsFormat) {
    return field(field_);
  }

  const FieldFormat::Type flag = field_->formatType();
  if(field_->hasFlag(Field::Derived)) {
    DerivedValue dv(field_);
    // format sub fields and whole string
    return FieldFormat::format(dv.value(EntryPtr(const_cast<Entry*>(this)), true), flag, request_);
  }

  // if auto format is not set or FormatNone, then just return the value
  if(flag == FieldFormat::FormatNone) {
    return m_coll->prepareText(field(field_));
  }

  if(!m_formattedFields.contains(field_->name())) {
    QString formattedValue;
    if(field_->type() == Field::Table) {
      QStringList rows;
      // we only format the first column
      foreach(const QString& row, FieldFormat::splitTable(field(field_->name()))) {
        QStringList columns = FieldFormat::splitRow(row);
        QStringList newValues;
        foreach(const QString& value, FieldFormat::splitValue(columns.at(0))) {
          newValues << FieldFormat::format(value, field_->formatType(), FieldFormat::DefaultFormat);
        }
        if(!columns.isEmpty()) {
          columns.replace(0, newValues.join(FieldFormat::delimiterString()));
        }
        rows << columns.join(FieldFormat::columnDelimiterString());
      }
      formattedValue = rows.join(FieldFormat::rowDelimiterString());
    } else {
예제 #5
0
bool AbstractVersion::initVerName(QString VerName)
{
    verNumber = new int;
    verType = new VersionType;

    QStringList tempVerNameList;
    tempVerNameList = VerName.split("_");
    if (tempVerNameList.length() > 1 && tempVerNameList.at(0) == "pre" && QString(tempVerNameList.at(1)).remove(5,QString(tempVerNameList.at(1)).length()) == "alpha")
    {
        tempVerNameList.pop_front();
        if (QString(tempVerNameList.at(0)).remove(0,5).length() > 0)
        {
            tempVerNameList.replace(0,QString(tempVerNameList.at(0)).remove(0,5));
        }
        else
        {
            tempVerNameList.pop_front();
        }

        tempVerNameList.push_front("pre-alpha");
    }
    if(tempVerNameList.length() <= 1)
    {
        tempVerNameList = VerName.split(" ");
        if (tempVerNameList.length() <= 1)
        {
            return false;
        }
    }
    bool *okToInt = new bool;
    *verType = stringToVersionType(tempVerNameList.at(0));
    *verNumber = QString(tempVerNameList.at(1)).toInt(okToInt);
    if (*okToInt == true)
    {
        return true;
    }
    return false;
}
예제 #6
0
void Workspace::readProperties( const KConfigGroup& cfg )
{
  QStringList selectedSheets = cfg.readPathEntry( "SelectedSheets", QStringList() );

  if ( selectedSheets.isEmpty() ) {
   /* If SelectedSheets config entry is not there, then it's
    * probably the first time the user has started KSysGuard. We
    * then "restore" a special default configuration. */
    selectedSheets << "ProcessTable.sgrd";
    selectedSheets << "SystemLoad2.sgrd";
  } else if(selectedSheets[0] != "ProcessTable.sgrd") {
    //We need to make sure that this is really is the process table on the first tab. No GUI way of changing this, but should make sure anyway.
    //Plus this migrates users from the kde3 setup
    selectedSheets.removeAll("ProcessTable.sgrd");
    selectedSheets.prepend( "ProcessTable.sgrd");
  }

  int oldSystemLoad = selectedSheets.indexOf("SystemLoad.sgrd");
  if(oldSystemLoad != -1) {
    selectedSheets.replace(oldSystemLoad, "SystemLoad2.sgrd");
  }

  KStandardDirs* kstd = KGlobal::dirs();
  QString filename;
  for ( QStringList::Iterator it = selectedSheets.begin(); it != selectedSheets.end(); ++it ) {
    filename = kstd->findResource( "data", "ksysguard/" + *it);
    if(!filename.isEmpty()) {
      restoreWorkSheet( filename, false);
    }
  }

  int idx = cfg.readEntry( "currentSheet", 0 );
  if (idx < 0 || idx > count() - 1) {
    idx = 0;
  }
  setCurrentIndex(idx);
}
예제 #7
0
QString MainWindow::removeWhiteSpaceCharacters()
{
    QString materialSource = this->ui->textEdit->text();

    // Split the source into separate lines
    QStringList materialSplited = materialSource.split(QRegExp("\n"), QString::SkipEmptyParts);

    for (int lineNumber = 0; lineNumber < materialSplited.size(); ++lineNumber)
    {
        QString line = materialSplited.at(lineNumber);

        // Remove whitespace characters from the current line
        QString trimmedLine = line.trimmed();

        if (trimmedLine.isEmpty() == true) {
            // This replaces the line with whitespace characters
            // with an empty line
            materialSplited.replace(lineNumber, trimmedLine);
        }
    }

    return materialSplited.join("\n");

}
예제 #8
0
QString KBBThemeManager::value(const KBBScalableGraphicWidget::itemType itemType, const QString &styleElement)
{
	const QString id = elementId(itemType);
    QString style;
    QString v;
	
	QDomNode node = m_root.firstChild();
	while(!node.isNull()) {
        if (node.toElement().attribute(QLatin1Literal("id")) == id)
            style = node.toElement().attribute(QLatin1Literal("style"));
		node = node.nextSibling();
	}
	
    QStringList styleList = style.split(QLatin1Char(';'));
	for (int i = 0; i < styleList.size(); i++) {
		styleList.replace(i, styleList.at(i).trimmed());
        if (styleList.at(i).startsWith(styleElement + QLatin1Char(':'))) {
			QString s = styleList.at(i);
			v = s.right(s.length()-styleElement.length()-1);
		}
	}
	
	return v;
}
QString NotifyPluginConfiguration::parseNotifyMessage()
{
	// tips:
	// check of *.wav files exist needed for playing phonon queues;
	// if phonon player don't find next file in queue, it buzz

	QString str,str1;
	str1= getSayOrder();
	str = QString("%L1 ").arg(getSpinBoxValue());
	int position = 0xFF;
	// generate queue of sound files to play
	notifyMessageList.clear();

        if(QFile::exists(QDir::toNativeSeparators(getSoundCollectionPath() + "/" + getCurrentLanguage()+"/"+getSound1()+".wav")))
                notifyMessageList.append(QDir::toNativeSeparators(getSoundCollectionPath() + "/" + getCurrentLanguage()+"/"+getSound1()+".wav"));
	else
                if(QFile::exists(QDir::toNativeSeparators(getSoundCollectionPath() + "/default/"+getSound1()+".wav")))
                        notifyMessageList.append(QDir::toNativeSeparators(getSoundCollectionPath() + "/default/"+getSound1()+".wav"));

	if(getSound2()!="")
	{
                if(QFile::exists(QDir::toNativeSeparators(getSoundCollectionPath() + "/" +  getCurrentLanguage()+"/"+getSound2()+".wav")))
                        notifyMessageList.append(QDir::toNativeSeparators(getSoundCollectionPath() + "/" +  getCurrentLanguage()+"/"+getSound2()+".wav"));
		else
                        if(QFile::exists(QDir::toNativeSeparators(getSoundCollectionPath() + "/default/"+getSound2()+".wav")))
                                notifyMessageList.append(QDir::toNativeSeparators(getSoundCollectionPath() + "/default/"+getSound2()+".wav"));
	}

	if(getSound3()!="")
	{
                if(QFile::exists(QDir::toNativeSeparators(getSoundCollectionPath()+ "/" + getCurrentLanguage()+"/"+getSound3()+".wav")))
                        notifyMessageList.append(QDir::toNativeSeparators(getSoundCollectionPath()+ "/" + getCurrentLanguage()+"/"+getSound3()+".wav"));
		else
                        if(QFile::exists(QDir::toNativeSeparators(getSoundCollectionPath()+"/default/"+getSound3()+".wav")))
                                notifyMessageList.append(QDir::toNativeSeparators(getSoundCollectionPath()+"/default/"+getSound3()+".wav"));
	}

	switch(str1.at(0).toAscii())
	{
		case 'N'://NEVER:
		   str = getSound1()+" "+getSound2()+" "+getSound3();
		   position = 0xFF;
		   break;

		case 'B'://BEFORE:
		   str = QString("%L1 ").arg(getSpinBoxValue())+getSound1()+" "+getSound2()+" "+getSound3();
		   position = 0;
		   break;

		case 'A'://AFTER:
			switch(str1.at(6).toAscii())
			{
			case 'f':
				str = getSound1()+QString(" %L1 ").arg(getSpinBoxValue())+getSound2()+" "+getSound3();
				position = 1;
				break;
			case 's':
				str = getSound1()+" "+getSound2()+QString(" %L1").arg(getSpinBoxValue())+" "+getSound3();
				position = 2;
				break;
			case 't':
				str = getSound1()+" "+getSound2()+" "+getSound3()+QString(" %L1").arg(getSpinBoxValue());
				position = 3;
				break;
			}
			break;
	}

	if(position!=0xFF)
	{
		QStringList numberParts = QString("%1").arg(getSpinBoxValue()).trimmed().split(".");
		QStringList numberFiles;

		if((numberParts.at(0).size()==1) || (numberParts.at(0).toInt()<20))
		{
			//if(numberParts.at(0)!="0")
				numberFiles.append(numberParts.at(0));
		} else {
			int i=0;
			if(numberParts.at(0).right(2).toInt()<20 && numberParts.at(0).right(2).toInt()!=0) {
				if(numberParts.at(0).right(2).toInt()<10)
					numberFiles.append(numberParts.at(0).right(1));
				else
					numberFiles.append(numberParts.at(0).right(2));
				i=2;
			}
			for(;i<numberParts.at(0).size();i++)
			{
				numberFiles.prepend(numberParts.at(0).at(numberParts.at(0).size()-i-1));
				if(numberFiles.first()==QString("0")) {
					numberFiles.removeFirst();
					continue;
				}
				if(i==1)
					numberFiles.replace(0,numberFiles.first()+'0');
				if(i==2)
					numberFiles.insert(1,"100");
				if(i==3)
					numberFiles.insert(1,"1000");
			}
		}

		if(numberParts.size()>1) {
			numberFiles.append("point");
			if((numberParts.at(1).size()==1)  /*|| (numberParts.at(1).toInt()<20)*/)
				numberFiles.append(numberParts.at(1));
			else {
				if(numberParts.at(1).left(1)=="0")
					numberFiles.append(numberParts.at(1).left(1));
				else
					numberFiles.append(numberParts.at(1).left(1)+'0');
				numberFiles.append(numberParts.at(1).right(1));
			}
		}
		foreach(QString fileName,numberFiles) {
			fileName+=".wav";
                        QString filePath = QDir::toNativeSeparators(getSoundCollectionPath()+"/"+ getCurrentLanguage()+"/"+fileName);
			if(QFile::exists(filePath))
                                notifyMessageList.insert(position++,QDir::toNativeSeparators(getSoundCollectionPath()+ "/"+getCurrentLanguage()+"/"+fileName));
			else {
                                if(QFile::exists(QDir::toNativeSeparators(getSoundCollectionPath()+"/default/"+fileName)))
                                        notifyMessageList.insert(position++,QDir::toNativeSeparators(getSoundCollectionPath()+"/default/"+fileName));
				else {
					notifyMessageList.clear();
					break; // if no some of *.wav files, then don't play number!
				}
			}
		}
예제 #10
0
QString TutorModel::fmtAxisRecord(LPTutorRecordStr pRecord)
{
    qint16 *p = (qint16 *)pRecord->record.pData;
    QStringList list = pRecord->strList;
    if(p[0] < 5 && p[0] >=0)
    {
        list.replace(0, (pRecord->record.nStep==0 ? tr("Home * "):QString("%1 * ").arg(pRecord->record.nStep)) );
		list.replace(1, m_strListAxist.at(list.at(1).toInt()));//!!!!!!
        list.replace(2, QString::number(p[1]/100.0, 'f', 2)+" ");
		list.replace(3, m_strListAxist.at(list.at(3).toInt()));
        list.replace(4, QString::number(p[2])+" ");
		list.replace(5, m_strListAxist.at(list.at(5).toInt()));
		list.replace(6, m_strListAxist.at(list.at(6).toInt()));
        list.replace(7, QString::number(p[5])+" ");
		list.replace(8, m_strListAxist.at(list.at(8).toInt()));
        list.replace(9, QString::number(p[6]/100.0, 'f', 2)+" ");
		list.replace(10, m_strListAxist.at(list.at(10).toInt()));
        list.replace(11, QString::number(p[3]/100.0, 'f', 2));
        if( (p[4] & 0x0101) == 0)//去除减速位置和速度显示;
        {
            for(int i = 0; i < 5; i++)
                list.removeAt(5);
        }
        else if( (p[4] & 0x0100) == 0)//提前结束位置不使能;
        {
            list.removeAt(5);
        }
        else if( (p[4] & 0x0001) == 0)//提前减速不使能;
        {
            list.removeAt(6);
            list.removeAt(6);
        }
        return list.join("");
    }
    else if(p[0] == 5)//C轴;
    {
        list.replace(0, (pRecord->record.nStep==0 ? tr("Home * "):QString("%1 * ").arg(pRecord->record.nStep)));
		list.replace(1, m_strListAxist.at(list.at(1).toInt()));
        list.replace(2, m_strListAxist.at(list.at(2).toInt()));
		list.replace(3, m_strListAxist.at(list.at(3).toInt()));
        list.replace(4, QString::number(p[2]/100.0, 'f', 2));
        return list.join("");
    }

}
예제 #11
0
void widgetDataView::runMetodoRoundRobin(int nDatos)
{
    int vector[nDatos][2];
    for(int i=0; i<nDatos; i++){
        vector[i][0]= ui->tblData->item(i,2)->text().toInt();
        vector[i][1]= 0;
    }

    int mayor = 0;
    for(int i=0; i<nDatos; i++){
        if(mayor < vector[i][0]){
            mayor = vector[i][0];
        }
    }

    int nuevasColumnas;
    nuevasColumnas = (mayor / this->qRoundRobin);
    if((mayor % this->qRoundRobin) > 0  ){
        nuevasColumnas++;
    }

    QStringList lista;
    lista<<"Id proceso"<<"Llegada"<<"Duracion"<<"T. Retorno";
    ui->tblData->setColumnCount(lista.count()+nuevasColumnas);
    for(int i=0; i<nuevasColumnas; i++){
        ui->tblData->setColumnWidth(4+i,ui->tblData->rowHeight(0));
        lista<<QString("C").append(QString().setNum(i+1));
    }

    ui->tblData->setHorizontalHeaderLabels(lista);

    QColor cColor;
        cColor.setNamedColor("green");

    int matriz[nDatos][nuevasColumnas];
    int suma = 0;

    QStringList l;

    for(int i=0; i<mayor; i++){
        for(int j=0; j<nDatos; j++){
            matriz[j][i]=0;
            if(vector[j][0]>0){
                if(vector[j][0] < this->qRoundRobin){
                    matriz[j][i] = vector[j][0];
                    vector[j][0] = 0;
                }
                else{
                    matriz[j][i] = matriz[j][i] + this->qRoundRobin;
                    vector[j][0] = vector[j][0] - this->qRoundRobin;
                }
            }
            suma = suma + matriz[j][i];
            if(matriz[j][i]>0){
                vector[j][1] = suma;
                if(i<1){
                    l<<QString().setNum(suma);
                }
                else{
                    l.replace(j,QString().setNum(suma));
                }
                //qDebug()<<matriz[j][i]<<"    "<<vector[j][1]<<"    "<<suma<<"     "<<j;
                QTableWidgetItem* tCiclo = new QTableWidgetItem();
                tCiclo->setText(QString().setNum(matriz[j][i]));
                tCiclo->setBackgroundColor(cColor);
                ui->tblData->setItem(j,i+4,tCiclo);
            }
        }
        //qDebug()<<endl;
    }

    float tPromedio = 0;

    for(int i=0; i<nDatos; i++){
        //qDebug()<<"\t"<<vector[i][1]<<"\t"<<l.value(i);
        QTableWidgetItem* tRespuesta = new QTableWidgetItem();
        tRespuesta->setText(l.value(i));
        ui->tblData->setItem(i,3,tRespuesta);
        tPromedio = tPromedio + (l.value(i).toFloat());
    }

    tPromedio = tPromedio / (l.count());
    ui->lblOut->setText("Metodo Round Robin Expulsivo, C[i] = Iteracion i\nTiempo promedio: "+QString().setNum(tPromedio));
    ui->lblOut->setVisible(true);

    //qDebug()<<endl;
}
예제 #12
0
void favorites2::updateFavorite( bool edit )
{
	DialogMsg msg( m_parentWidget,this ) ;

	utility::hideQWidget thisWidget( this ) ;

	auto dev = m_ui->lineEditEncryptedFolderPath->toPlainText() ;
	auto path = m_ui->lineEditMountPath->toPlainText() ;
	auto mOpts = m_ui->lineEditMountOptions->toPlainText() ;

	if( m_reverseMode ){

		if( mOpts.isEmpty() ){

			mOpts = favorites::reverseModeOption ;
		}else{
			mOpts += QString( "," ) + favorites::reverseModeOption ;
		}
	}

	if( m_volumeNeedNoPassword ){

		if( mOpts.isEmpty() ){

			mOpts = favorites::volumeNeedNoPassword ;
		}else{
			mOpts += QString( "," ) + favorites::volumeNeedNoPassword ;
		}
	}

	if( m_mountReadOnly ){

		if( mOpts.isEmpty() ){

			mOpts = favorites::mountReadOnly ;
		}else{
			mOpts += QString( "," ) + favorites::mountReadOnly ;
		}
	}

	if( dev.isEmpty() ){

		thisWidget.hide() ;
		return msg.ShowUIOK( tr( "ERROR!" ),tr( "Encrypted Folder Address Field Is Empty" ) ) ;
	}
	if( path.isEmpty() ){

		thisWidget.hide() ;
		return msg.ShowUIOK( tr( "ERROR!" ),tr( "Mount Point Path Field Is Empty" ) ) ;
	}

	m_ui->tableWidget->setEnabled( false ) ;

	auto _option = []( const QString& e )->QString{

		if( e.isEmpty() ){

			return "N/A" ;
		}else{
			return e ;
		}
	} ;

	auto autoMount = [ this ](){

		if( m_ui->cbAutoMount->isChecked() ){

			return "true" ;
		}else{
			return "false" ;
		}
	}() ;

	auto configPath = m_ui->lineEditConfigFilePath->toPlainText() ;
	auto idleTimeOUt = m_ui->lineEditIdleTimeOut->toPlainText() ;

	if( m_type == favorites::type::sshfs ){

		if( !configPath.isEmpty() ){

			if( mOpts.isEmpty() ){

				mOpts = "IdentityAgent=" + configPath ;
			}else{
				mOpts += ",IdentityAgent=" + configPath ;
			}
		}

		if( !idleTimeOUt.isEmpty() ){

			if( mOpts.isEmpty() ){

				mOpts = "IdentityFile=" + idleTimeOUt ;
			}else{
				mOpts += ",IdentityFile=" + idleTimeOUt ;
			}
		}

		configPath.clear() ;
		idleTimeOUt.clear() ;
	}

	QStringList e = { dev,
			  path,
			  autoMount,
			  _option( configPath ),
			  _option( idleTimeOUt ),
			  _option( mOpts ) } ;
	if( edit ){

		auto f = this->getEntry( m_editRow ) ;

		m_settings.replaceFavorite( f,e ) ;
	}else{
		dev.replace( "sshfs ","" ) ;

		if( utility::platformIsWindows() ){

			if( !utility::isDriveLetter( path ) ){

				e.replace( 1,path + "/" + utility::split( dev,'/' ).last() ) ;
			}
		}else{
			e.replace( 1,path + "/" + utility::split( dev,'/' ).last() ) ;
		}

		m_settings.addToFavorite( e ) ;
	}

	m_ui->lineEditEncryptedFolderPath->clear() ;
	m_ui->lineEditMountPath->clear() ;
	m_ui->lineEditConfigFilePath->clear() ;
	m_ui->lineEditIdleTimeOut->clear() ;
	m_ui->lineEditMountOptions->clear() ;

	m_ui->cbReverseMode->setChecked( false ) ;
	m_ui->cbReadOnlyMode->setChecked( false ) ;
	m_ui->cbVolumeNoPassword->setChecked( false ) ;
	m_ui->cbAutoMount->setChecked( false ) ;

	m_ui->lineEditEncryptedFolderPath->clear() ;
	m_ui->lineEditMountPath->clear() ;

	this->showUpdatedEntry( e ) ;

	m_ui->tableWidget->setEnabled( true ) ;
}
예제 #13
0
파일: igmp.cpp 프로젝트: Raman325/ostinato
QVariant IgmpProtocol::fieldData(int index, FieldAttrib attrib,
        int streamIndex) const
{
    switch (index)
    {
        case kRsvdMrtCode:
        {
            uint mrt = 0;
            quint8 mrcode = 0;

            if (msgType() == kIgmpV3Query)
            {
                mrt = data.max_response_time();
                mrcode = quint8(mrc(mrt));
            }
            else if (msgType() == kIgmpV2Query)
            {
                mrt = data.max_response_time();
                mrcode = mrt & 0xFF;
            }


            switch(attrib)
            {
            case FieldName:
                if (isQuery())
                    return QString("Max Response Time");
                else
                    return QString("Reserved");
            case FieldValue:
                return mrt;
            case FieldTextValue:
                return QString("%1").arg(mrt);
            case FieldFrameValue:
                return QByteArray(1, mrcode);
            default:
                break;
            }
            break;
        }
        case kGroupAddress:
        {
            quint32 grpIp = ipUtils::ipAddress(
                data.group_address().v4(),
                data.group_prefix(),
                ipUtils::AddrMode(data.group_mode()),
                data.group_count(),
                streamIndex);

            switch(attrib)
            {
            case FieldName:            
                return QString("Group Address");
            case FieldValue:
            case FieldTextValue:
                return QHostAddress(grpIp).toString();
            case FieldFrameValue:
            {
                QByteArray fv;
                fv.resize(4);
                qToBigEndian(grpIp, (uchar*) fv.data());
                return fv;
            }
            default:
                break;
            }
            break;
        }
        case kSources:
        {
            switch(attrib)
            {
            case FieldName:            
                return QString("Source List");
            case FieldValue:
            {
                QStringList list;

                for (int i = 0; i < data.sources_size(); i++)
                    list.append(QHostAddress(data.sources(i).v4()).toString());
                return list;
            }
            case FieldFrameValue:
            {
                QByteArray fv;
                fv.resize(4 * data.sources_size());
                for (int i = 0; i < data.sources_size(); i++)
                    qToBigEndian(data.sources(i).v4(), (uchar*)(fv.data()+4*i));
                return fv;
            }
            case FieldTextValue:
            {
                QStringList list;

                for (int i = 0; i < data.sources_size(); i++)
                    list.append(QHostAddress(data.sources(i).v4()).toString());
                return list.join(", ");
            }
            default:
                break;
            }
            break;
        }
        case kGroupRecords:
        {
            switch(attrib)
            {
            case FieldValue:
            {
                QVariantList grpRecords = GmpProtocol::fieldData(
                        index, attrib, streamIndex).toList();

                for (int i = 0; i < data.group_records_size(); i++)
                {
                    QVariantMap grpRec = grpRecords.at(i).toMap();
                    OstProto::Gmp::GroupRecord rec = data.group_records(i);

                    grpRec["groupRecordAddress"] = QHostAddress(
                                rec.group_address().v4()).toString();

                    QStringList sl;
                    for (int j = 0; j < rec.sources_size(); j++)
                        sl.append(QHostAddress(rec.sources(j).v4()).toString());
                    grpRec["groupRecordSourceList"] = sl;

                    grpRecords.replace(i, grpRec);
                }
                return grpRecords;
            }
            case FieldFrameValue:
            {
                QVariantList list = GmpProtocol::fieldData(
                        index, attrib, streamIndex).toList();
                QByteArray fv;

                for (int i = 0; i < data.group_records_size(); i++)
                {
                    OstProto::Gmp::GroupRecord rec = data.group_records(i);
                    QByteArray rv = list.at(i).toByteArray();

                    rv.insert(4, QByteArray(4+4*rec.sources_size(), char(0)));
                    qToBigEndian(rec.group_address().v4(), 
                            (uchar*)(rv.data()+4));
                    for (int j = 0; j < rec.sources_size(); j++)
                    {
                        qToBigEndian(rec.sources(j).v4(),
                                (uchar*)(rv.data()+8+4*j));
                    }

                    fv.append(rv);
                }
                return fv;
            }
            case FieldTextValue:
            {
                QStringList list = GmpProtocol::fieldData(
                        index, attrib, streamIndex).toStringList();

                for (int i = 0; i < data.group_records_size(); i++)
                {
                    OstProto::Gmp::GroupRecord rec = data.group_records(i);
                    QString recStr = list.at(i);
                    QString str;

                    str.append(QString("Group: %1").arg(
                        QHostAddress(rec.group_address().v4()).toString()));

                    str.append("; Sources: ");
                    QStringList sl;
                    for (int j = 0; j < rec.sources_size(); j++)
                        sl.append(QHostAddress(rec.sources(j).v4()).toString());
                    str.append(sl.join(", "));

                    recStr.replace("XXX", str);
                    list.replace(i, recStr);
                }
                return list.join("\n").insert(0, "\n");
            }
            default:
                break;
            }
            break;
        }
        default:
            break;
    }

    return GmpProtocol::fieldData(index, attrib, streamIndex);
}
예제 #14
0
파일: main.cpp 프로젝트: CIP-SSA/odktools
void processTableData(QDomNode tableNode, QDomNode recordNode, QString tableName, QString fieldsStatement, QString recordId) {
    QString valuesStatement;
    QDomNode childTableNodeData;
    QString variableName;
    QDomNode variableNode;
    QString variableValue;
    int fieldCounter = 0;

    valuesStatement = "";

    //Pass through the fields in the table so as to extract their value from the record node
    childTableNodeData = tableNode.firstChild();

    while (!childTableNodeData.isNull()) {
        fieldCounter = fieldCounter + 1;

        if (childTableNodeData.toElement().tagName() == "field") {
            variableName = childTableNodeData.toElement().attribute("mysqlcode", "None");
            variableNode = recordNode.toElement().elementsByTagName(variableName).item(0);

            if(variableNode.toElement().text() == "") {
                if (fieldCounter == nodeDepth) {
                    //Handles generation of primary key Id and adds to the recordKeys list
                    variableValue = recordId;

                    if (recordKeys.size() < nodeDepth) {
                        recordKeys.append(variableValue);
                    }
                    else {
                        recordKeys.replace(nodeDepth - 1, variableValue);
                    }
                }
                else if (fieldCounter < nodeDepth) {
                    //Referenced key get it from the recordKeys list
                    variableValue = recordKeys.at(fieldCounter - 1);
                }
                else {
                    //Current field is not among the primary key fields
                    variableValue = "";
                }
            }
            else {
                //Check if the main table (vManifestMainTable) and the key field (vManifestMainVariable) then add the key field in keys list
                if (tableName == vManifestMainTable and variableName == vManifestMainVariable) {
                    if (recordKeys.size() < nodeDepth) {
                        recordKeys.append(variableValue);
                    }
                    else {
                        recordKeys.replace(nodeDepth - 1, variableNode.toElement().text());
                    }
                }

                variableValue = variableNode.toElement().text();
            }

            valuesStatement = valuesStatement + "'" + variableValue + "', ";
        }

        //Get the next child table node for the data
        childTableNodeData = childTableNodeData.nextSibling();
    }

    createSQLStatement(tableName, fieldsStatement, valuesStatement);
}
예제 #15
0
void UTableRecycleBin::setLanguage(QString pathToTheFileLanguage)
{
    emit languageIsChange(pathToTheFileLanguage);

    QSettings langFile(pathToTheFileLanguage,
                       QSettings::IniFormat);
    langFile.setIniCodec(QTextCodec::codecForName(textCodec.toUtf8()));

    langFile.beginGroup("TABLERECYCLEBIN");

    setWindowTitle(langFile.value("Title").toString());

    actionDeleteItem->setText(langFile.value("Delete").toString());
    actionRestoreItem->setText(langFile.value("Restore").toString());

    QStringList lst;

    for(int i = 0; i < countColumns; i++)
        lst.append("");

    lst.replace(indexColumnTitle,
                langFile.value("ColumnTitle").toString());

    lst.replace(indexColumnVisible,
                langFile.value("ColumnVisible").toString());

    lst.replace(indexColumnDateOfCreating,
                langFile.value("ColumnDateOfCreating").toString());

    lst.replace(indexColumnCountTextSymbols,
                langFile.value("ColumnCountTextSymbols").toString());

    lst.replace(indexColumnCountTextLines,
                langFile.value("ColumnCountTextLines").toString());

    lst.replace(indexColumnDateLastChange,
                langFile.value("ColumnDateLastChange").toString());

    lst.replace(indexColumnLock,
                langFile.value("ColumnLock").toString());

    lst.replace(indexColumnDateOfLastRemoval,
                langFile.value("ColumnDateOfLastRemoval").toString());

    lst.replace(indexColumnDateOfLastRestore,
                langFile.value("ColumnDateOfLastRestore").toString());

    langFile.endGroup();

    actionVisibleNote->setText(lst.at(indexColumnVisible));
    actionDateCreateNote->setText(lst.at(indexColumnDateOfCreating));
    actionCountTextSymbols->setText(lst.at(indexColumnCountTextSymbols));
    actionCountTextLine->setText(lst.at(indexColumnCountTextLines));
    actionDateLastChange->setText(lst.at(indexColumnDateLastChange));
    actionLock->setText(lst.at(indexColumnLock));
    actionDateOfLastRemoval->setText(lst.at(indexColumnDateOfLastRemoval));
    actionDateOfLastRestore->setText(lst.at(indexColumnDateOfLastRestore));

    setColumnCount(countColumns);
    setHorizontalHeaderLabels(lst);

    QSettings ini(absolutePathToTheConfigurationProgram(),
                  QSettings::IniFormat);
    ini.setIniCodec(QTextCodec::codecForName(textCodec.toUtf8()));

    int magicNumber = 9934343245;
    // если записи нет
    if(ini.value("TableRecycleBin/WidthColumnTitle", magicNumber).toInt()
            == magicNumber)
        // ширина колонок подбираетс¤ по текст в них
        resizeColumnsToContents();
    else
        // установить пользовательскую ширину столбцов
        loadWidthColumns();
}
예제 #16
0
파일: legenditem.cpp 프로젝트: KDE/kst-plot
void LegendItem::paint(QPainter *painter) {
  if (!isVisible()) {
    return;
  }

  RelationList legendItems;
  if (_auto) {
    legendItems = plot()->renderItem(PlotRenderItem::Cartesian)->relationList();
  } else {
    legendItems = _relations;
  }

  int count = legendItems.count();
  if (count <= 0) { // no legend or box if there are no legend items
    return;
  }


  QFont font(_font);
  font.setPointSizeF(view()->scaledFontSize(_fontScale, *painter->device()));

  painter->setFont(font);

  // generate string list of relation names
  QStringList names;
  bool allAuto = true;
  bool sameX = true;
  bool sameYUnits = true;

  LabelInfo label_info = legendItems.at(0)->xLabelInfo();
  QString yUnits =  legendItems.at(0)->yLabelInfo().units;

  for (int i = 0; i<count; i++) {
    RelationPtr relation = legendItems.at(i);
    if (relation->descriptiveNameIsManual()) {
      allAuto = false;
    }
    if (relation->xLabelInfo() != label_info) {
      sameX = false;
    }
    // sameYUnits is false if any non empty units are defined differently.
    if (yUnits.isEmpty()) {
      yUnits = relation->yLabelInfo().units;
    } else if (relation->yLabelInfo().units != yUnits) {
      if (!relation->yLabelInfo().units.isEmpty()) {
        sameYUnits = false;
      }
    }
  }

  if (!allAuto) {
    for (int i = 0; i<count; i++) {
      names.append(legendItems.at(i)->descriptiveName());
    }
  } else {
    for (int i = 0; i<count; i++) {
      RelationPtr relation = legendItems.at(i);
      QString label = relation->titleInfo().singleRenderItemLabel();
      if (label.isEmpty()) {
        label_info = relation->yLabelInfo();
        QString y_label = label_info.name;
        if (!sameYUnits) {
          if (!label_info.units.isEmpty()) {
            y_label = tr("%1 \\[%2\\]", "axis labels.  %1 is quantity, %2 is units.  eg Time [s].  '[' must be escaped.").arg(y_label).arg(label_info.units);
          }
        }
        if (!y_label.isEmpty()) {
          LabelInfo xlabel_info = relation->xLabelInfo();
          if (!sameX) {
            label = tr("%1 vs %2", "describes a plot. %1 is X axis.  %2 is Y axis").arg(y_label).arg(xlabel_info.name);
          } else if (xlabel_info.quantity.isEmpty()) {
            label = y_label;
          } else if (xlabel_info.quantity != xlabel_info.name) {
            label = tr("%1 vs %2", "describes a plot. %1 is X axis.  %2 is Y axis").arg(y_label).arg(xlabel_info.name);
          } else {
            label = y_label;
          }
        } else {
          label = relation->descriptiveName();
        }
      }
      int i_dup = names.indexOf(label);
      if (i_dup<0) {
        names.append(label);
      } else {
        RelationPtr dup_relation = legendItems.at(i_dup);
        if (!dup_relation->yLabelInfo().file.isEmpty()) {
          names.replace(i_dup, label + " (" + dup_relation->yLabelInfo().escapedFile() + ')');
        }
        if (!relation->yLabelInfo().file.isEmpty()) {
          names.append(label + " (" + relation->yLabelInfo().escapedFile() + ')');
        }
      }
    }
  }


  QSize legendSize(0, 0);
  QSize titleSize(0,0);
  Label::Parsed *parsed = Label::parse(_title);
  int pad = painter->fontMetrics().ascent()/4;
  Label::RenderContext rc(painter->font(), painter);
  Label::renderLabel(rc, parsed->chunk, false, false);

  if (!_title.isEmpty()) {
    titleSize.setWidth(rc.x+3*pad);
    titleSize.setHeight(painter->fontMetrics().height()+pad);
  }

  QList<QSize> sizes;
  int max_w = 0;
  int max_h = 0;
  for (int i = 0; i<count; i++) {
    RelationPtr relation = legendItems.at(i);
    QSize size;
    painter->save();
    size = paintRelation(names.at(i), relation, painter, false);
    painter->restore();
    sizes.append(size);
    max_w = qMax(max_w, size.width());
    max_h = qMax(max_h, size.height());
  }

  // determine number of rows and number of columns
  int n_rows = 0;
  int n_cols = 0;
  if (_verticalDisplay) {
    int h=titleSize.height();
    for (int i = 0; i<count; i++) {
      h+=sizes.at(i).height();
    }
    int max_legend_height = _plotItem->plotRect().height()*0.6+1;
    n_cols = qMin(count, h / max_legend_height + 1);
    n_rows = count / n_cols;
    while (n_rows*n_cols<count) {
      n_rows++;
    }
  } else {
    int w = 0;
    for (int i = 0; i<count; i++) {
      w+=sizes.at(i).width();
    }
    int max_legend_width = _plotItem->plotRect().width()*0.8+1;
    n_rows = qMin(count, w / max_legend_width+1);
    n_cols = count/n_rows;
    while (n_rows*n_cols<count) {
      n_cols++;
    }
  }

  // determine the dimensions of each column
  QList<QSize> col_sizes;
  for (int i=0; i<n_cols; i++) {
    col_sizes.append(QSize(0,0));
  }
  for (int i = 0; i<count; i++) {
    int col = i/n_rows;
    col_sizes[col].rheight()+= sizes.at(i).height();
    col_sizes[col].setWidth(qMax(sizes.at(i).width(), col_sizes.at(col).width()));
  }

  // determine the dimensions of the legend
  int w = 0;
  int h = 0;
  for (int col = 0; col < n_cols; col++) {
    w += col_sizes.at(col).width();
    h = qMax(h, col_sizes.at(col).height());
  }
  legendSize.setHeight(h + titleSize.height());
  legendSize.setWidth(qMax(titleSize.width(), w));
  setViewRect(rect().x(), rect().y(), legendSize.width()+pad, legendSize.height()+pad);

  // Now paint everything
  painter->drawRect(rect());

  int x=rect().x();
  int y=rect().y();

  if (!_title.isEmpty()) {
    rc.y = rect().y() + titleSize.height()-pad;
    rc.x = qMax(rect().x()+pad, rect().x() + legendSize.width()/2 - titleSize.width()/2);
    Label::renderLabel(rc, parsed->chunk, false, true);
    y+= titleSize.height();
  }

  legendSize.setWidth(0);
  legendSize.setHeight(0);
  for (int i = 0; i<count; i++) {
    RelationPtr relation = legendItems.at(i);
    painter->save();
    painter->translate(x,y);
    paintRelation(names.at(i), relation, painter, true);
    painter->restore();

    int col = i/n_rows;
    int row = i%n_rows;
    if (row == n_rows-1) { // end of a column
      x += col_sizes.at(col).width();
      y = rect().y() + titleSize.height();
    } else {
      y += sizes.at(i).height();
    }
  }
  delete parsed;
}
예제 #17
0
void AppModel::handleWeatherNetworkData(QObject *replyObj)
{
    QNetworkReply *networkReply = qobject_cast<QNetworkReply*>(replyObj);
    if (!networkReply)
        return;

    if (!networkReply->error()) {
        QString xmlData = QString::fromUtf8(networkReply->readAll());

        foreach (WeatherData *inf, d->forecast)
            delete inf;
        d->forecast.clear();

        QXmlStreamReader xml(xmlData);
        while (!xml.atEnd()) {
            xml.readNext();

            if (xml.name() == "current_conditions") {
                while (!xml.atEnd()) {
                    xml.readNext();
                    if (xml.name() == "current_conditions")
                        break;
                    if (xml.tokenType() == QXmlStreamReader::StartElement) {
                        if (xml.name() == "condition") {
                            d->now.setWeatherDesc(GET_DATA_ATTR);
                        } else if (xml.name() == "icon") {
                            d->now.setWeather(google2name(GET_DATA_ATTR));
                        } else if (xml.name() == "temp_f") {
                            d->now.setTempString(GET_DATA_ATTR + QChar(176));
                        }
                    }
                }
            }

            if (xml.name() == "forecast_conditions") {
                WeatherData *cur = NULL;

                while (!xml.atEnd()) {
                    xml.readNext();

                    if (xml.name() == "forecast_conditions") {
                        if (cur) {
                            d->forecast.append(cur);
                        }
                        break;
                    } else if (xml.tokenType() == QXmlStreamReader::StartElement) {
                        if (!cur)
                            cur = new WeatherData();
                        if (xml.name() == "day_of_week") {
                            cur->setDayOfWeek(GET_DATA_ATTR);
                        } else if (xml.name() == "icon") {
                            cur->setWeather(google2name(GET_DATA_ATTR));
                        } else if (xml.name() == "low") {
                            QString v = cur->tempString();
                            QStringList parts = v.split("/");
                            if (parts.size() >= 1)
                                parts.replace(0, GET_DATA_ATTR + QChar(176));
                            if (parts.size() == 0)
                                parts.append(GET_DATA_ATTR + QChar(176));

                            cur->setTempString(parts.join("/"));
                        } else if (xml.name() == "high") {
                            QString v = cur->tempString();
                            QStringList parts = v.split("/");
                            if (parts.size() == 2)
                                parts.replace(1, GET_DATA_ATTR + QChar(176));
                            if (parts.size() == 0)
                                parts.append("");
                            if (parts.size() == 1)
                                parts.append(GET_DATA_ATTR + QChar(176));

                            cur->setTempString(parts.join("/"));
                        }
                    }
                }
            }
        }

        if (!(d->ready)) {
            d->ready = true;
            emit readyChanged();
        }

        emit weatherChanged();
    }
    networkReply->deleteLater();
}
예제 #18
0
파일: note.cpp 프로젝트: 0branch/qtide
// ---------------------------------------------------------------------
QStringList Note::select_line1(QStringList mid,QString s,int *pos, int *len)
{
  int i;
  QString com, comment, p, t;

  if (s=="sort") {
    mid.sort();
    return mid;
  }

  if (s=="wrap") {
    sets("inputx_jrx_",q2s(mid.join("\n")));
    return s2q(dors("70 foldtext inputx_jrx_")).split("\n");
  }

  comment=editPage()->getcomment();
  if (comment.isEmpty()) return mid;
  com=comment+" ";

  if (s=="comment") {
    int m=0;
    for(i=0; i<mid.size(); i++)
      if (!matchhead(comment,mid.at(i))) {
        m=1;
        break;
      }
    if (m) {
      for(i=0; i<mid.size(); i++) {
        p=mid.at(i);
        if (p.size())
          p=com+p;
        else
          p=comment;
        mid.replace(i,p);
      }
    } else {
      for(i=0; i<mid.size(); i++) {
        p=mid.at(i);
        if (matchhead(comment,p) && (!matchhead(com+"----",p))
            && (!matchhead(com+"====",p)))
          p=p.mid(comment.size());
        if (p.size() && (p.at(0)==' '))
          p=p.mid(1);
        mid.replace(i,p);
      }
    }
    *len=mid.join("a").size();
    return mid;
  }

  if (s=="plusline1")
    t.fill('-',57);
  else if (s=="plusline2")
    t.fill('=',57);
  else
    return mid;
  t=com + t;
  mid.prepend(t);
  *pos=*pos+1+t.size();
  *len=0;
  return mid;
}
bool QgsAuthIdentCertMethod::updateDataSourceUriItems( QStringList &connectionItems, const QString &authcfg,
    const QString &dataprovider )
{
  Q_UNUSED( dataprovider )
  QMutexLocker locker( &mMutex );

  QgsDebugMsg( QStringLiteral( "Update URI items for authcfg: %1" ).arg( authcfg ) );

  QgsPkiConfigBundle *pkibundle = getPkiConfigBundle( authcfg );
  if ( !pkibundle || !pkibundle->isValid() )
  {
    QgsDebugMsg( QStringLiteral( "Update URI items FAILED: PKI bundle invalid" ) );
    return false;
  }
  QgsDebugMsg( QStringLiteral( "Update URI items: PKI bundle valid" ) );

  QString pkiTempFileBase = QStringLiteral( "tmppki_%1.pem" );

  // save client cert to temp file
  QString certFilePath = QgsAuthCertUtils::pemTextToTempFile(
                           pkiTempFileBase.arg( QUuid::createUuid().toString() ),
                           pkibundle->clientCert().toPem() );
  if ( certFilePath.isEmpty() )
  {
    return false;
  }

  // save client cert key to temp file
  QString keyFilePath = QgsAuthCertUtils::pemTextToTempFile(
                          pkiTempFileBase.arg( QUuid::createUuid().toString() ),
                          pkibundle->clientCertKey().toPem() );
  if ( keyFilePath.isEmpty() )
  {
    return false;
  }

  // save CAs to temp file
  QString caFilePath = QgsAuthCertUtils::pemTextToTempFile(
                         pkiTempFileBase.arg( QUuid::createUuid().toString() ),
                         QgsApplication::authManager()->trustedCaCertsPemText() );
  if ( caFilePath.isEmpty() )
  {
    return false;
  }

  // get common name of the client certificate
  QString commonName = QgsAuthCertUtils::resolvedCertName( pkibundle->clientCert(), false );

  // add uri parameters
  QString userparam = "user='******'";
  int userindx = connectionItems.indexOf( QRegExp( "^user='******'" + certFilePath + "'";
  int sslcertindx = connectionItems.indexOf( QRegExp( "^sslcert='.*" ) );
  if ( sslcertindx != -1 )
  {
    connectionItems.replace( sslcertindx, certparam );
  }
  else
  {
    connectionItems.append( certparam );
  }

  QString keyparam = "sslkey='" + keyFilePath + "'";
  int sslkeyindx = connectionItems.indexOf( QRegExp( "^sslkey='.*" ) );
  if ( sslkeyindx != -1 )
  {
    connectionItems.replace( sslkeyindx, keyparam );
  }
  else
  {
    connectionItems.append( keyparam );
  }

  QString caparam = "sslrootcert='" + caFilePath + "'";
  int sslcaindx = connectionItems.indexOf( QRegExp( "^sslrootcert='.*" ) );
  if ( sslcaindx != -1 )
  {
    connectionItems.replace( sslcaindx, caparam );
  }
  else
  {
    connectionItems.append( caparam );
  }

  return true;
}
예제 #20
0
void ParceTask::run()
{
    Result result;
    result.download = parameters.download;

    if ( parameters.download->data().isEmpty() )
    {
        result.err = DataError;
        emit finished(result);
        return;
    }

    if ( parameters.extentions.isEmpty() )
    {
        result.err = ExtentionsError;
        emit finished(result);
        return;
    }

    QString content =
            QTextCodec::codecForHtml(
                parameters.download->data() )->toUnicode(
                parameters.download->data() );
    QStringList urlList;
    QRegExp parceMask;

    if ( parameters.extentions.contains("*") )
        parceMask.setPattern("(href=\"(https?://)?\\S+/\\d+\\.(\\S+)\")+");
    else
        parceMask.setPattern("(href=\"(https?://)?\\S+/\\d+\\.(" + Common::strFromList(parameters.extentions,
                                                                                  "|") + ")\")+");

    QRegExp removeMask("(href=|\"|src=)");
    int pos = 0;

    while ( ( pos = parceMask.indexIn(content, pos) ) != -1 )
    {
        urlList << parceMask.cap(1).remove(removeMask).replace("//", "/");
        QString &s = urlList.last();
        if (!s.contains("://"))
            s.replace(":/", "://");
        pos += parceMask.matchedLength();
    }

    urlList.removeDuplicates();

    if (parameters.download->url().contains("4chan.org"))
    {
        for (int i = 0; i < urlList.size(); ++i)
        {
            if (urlList.at(i).left(2) == "//")
                urlList[i].prepend("http:");
            else if (urlList.at(i).left(1) == "/")
                urlList[i].prepend("http:/");
        }
    }

    QStringList nameList;

    for (int i = 0; i < urlList.count(); ++i)
    {
        nameList << Common::getFileName( urlList.at(i) );
    }

    int i = nameList.count() - 1;

    while (i >= 0)
    {
        int j = i - 1;

        while (j >= 0)
        {
            if ( nameList.at(i) == nameList.at(j) )
            {
                urlList.removeAt(j);
                nameList.removeAt(j);
                --i;
            }

            --j;
        }

        --i;
    }

    QString scheme = QUrl( parameters.download->url() ).scheme();
    QString domain = Common::getHost( parameters.download->url() );

    for (int i = 0; i < urlList.count(); ++i)
    {
        if ( QUrl( urlList.at(i) ).scheme().isEmpty() )
        {
            urlList.replace( i, urlList.value(i).prepend(scheme +
                                                         QString("://") +
                                                         domain) );
        }
    }

    if (!parameters.external)
    {
        int i = urlList.count() - 1;

        while (i >= 0)
        {
            if (Common::getHost( urlList.at(i) ) != domain)
            {
                urlList.removeAt(i);
            }

            --i;
        }
    }
    if (!parameters.replace)
    {
        int i = urlList.count() - 1;
        while (i >= 0)
        {
            if ( QFileInfo( Common::getFileName(urlList.at(i),
                                                parameters.dir) ).exists() )
            {
                result.existingUrls << urlList.at(i);
                urlList.removeAt(i);
            }

            --i;
        }
    }

    if ( !urlList.isEmpty() )
    {
        QDir dir(parameters.dir);

        if ( !dir.exists() )
        {
            dir.mkpath(parameters.dir);
        }
    }

    if (parameters.savePage)
    {
        QStringList auxUrlList;
        QRegExp auxParceMask("((href|src)=\"(https?://)?\\S+\\.(\\S+)\")+");
        int pos = 0;

        while ( ( pos = auxParceMask.indexIn(content, pos) ) != -1 )
        {
            auxUrlList << auxParceMask.cap(1).remove(removeMask);;
            pos += auxParceMask.matchedLength();
        }

        auxUrlList.removeDuplicates();

        if (parameters.download->url().contains("4chan.org"))
        {
            for (int i = 0; i < auxUrlList.size(); ++i)
            {
                if (auxUrlList.at(i).left(2) == "//")
                    auxUrlList[i].prepend("http:");
                else if (auxUrlList.at(i).left(1) == "/")
                    auxUrlList[i].prepend("http:/");
            }
        }

        for (int i = 0; i < auxUrlList.count(); ++i)
        {
            if (auxUrlList.at(i).contains(".html") || auxUrlList.at(i).contains(".htm")
                    || auxUrlList.at(i).endsWith("/"))
                continue;
            QString d = Common::getHost( auxUrlList.at(i) );

            if (!urlList.contains(auxUrlList.at(i)) && (d == domain || QString() == d))
            {
                if ( QUrl( auxUrlList.at(i) ).scheme().isEmpty() )
                    auxUrlList.replace(i, auxUrlList.value(i).prepend(scheme + QString("://") + domain));
                result.auxUrls << auxUrlList.at(i);
            }
        }

        if ( !result.auxUrls.isEmpty() )
        {
            QDir dir(parameters.dir + QDir::separator() +
                     SavePageTask::AUX_FILES_DIR);

            if ( !dir.exists() )
            {
                dir.mkpath(parameters.dir + QDir::separator() +
                           SavePageTask::AUX_FILES_DIR);
            }
        }
    }

    result.newUrls << urlList;
    result.err = NoError;
    emit finished(result);
}
예제 #21
0
void Student::replecePracticResult(int disciplinId, int pos, const QString &newResult)
{
	QStringList ret = practicResultsMap.value(disciplinId);
	ret.replace(pos, newResult);
	practicResultsMap.insert(disciplinId, ret);
}
예제 #22
0
/*****************************************************************
 *函数名称:reDrawHisDataDisplay
 *函数功能:当历史数据收集器的长度发生变化的时候,点击确定按钮后重绘场景中的
 *                    历史数据显示器控件
 *edit by zqh
 *2011-9-27
 ****************************************************************/
void QHisdDataLoggerDialog::reDrawHisDataDisplay()
{
    int totalSceneNum = pwnd->pSceneSheet.size();
    QList<QGraphicsItem *> Items;
    QGraphicsItem *pItem = NULL;
    QGraphicsItem *pNewItem = NULL;
    int nID = 0;
    int  i = 0;
    int j = 0;
    int k = 0;
    int nsheet = pwnd->nActiveSheetIndex;
    int nOldNum = 0; //原历史数据收集器取样长度
    int nNewNum = pwnd->m_pSamSysParame->m_historyLogData.nSampleLen;//历史数据收集器取样长度
    QStringList *sList = new QStringList();
    QStringList slist;
    Items.clear();

    for(i = 0; i < totalSceneNum;i++)   //扫描所有页面
    {
        pwnd->nActiveSheetIndex = i;
        pwnd->pView->setScene(pwnd->pSceneSheet[i]);
        QPainterPath path;
        path.addRect(0,0,pwnd->pSceneSheet[i]->width(),pwnd->pSceneSheet[i]->height());
        pwnd->pSceneSheet[i]->setSelectionArea(path);
        Items = pwnd->pSceneSheet[i]->selectedItems();
        foreach(QGraphicsItem *item,Items)
            item->setSelected(false);

        for(j = 0; j < Items.size(); j++)   //扫描当前页面的所有控件
        {
            pItem = Items.at(j);//->topLevelItem();
            nID = pItem->data(GROUP_TYPE_KEY).toInt(); //取控件的Key号
            sList->clear();
            slist.clear();
            switch(nID)
            {
                case GROUP_TYPE_HISDATAALARM: //历史数据显示器
                    {
                        slist = pItem->data(GROUP_DATALIST_KEY).toStringList(); //取出每个item的所有数据
                        for(k = 0; k < slist.size();k++)
                            sList->append(slist.at(k));

                        nOldNum = sList->at(99).toInt(); //37
                      //  if(nNewNum != nOldNum)//长度没有改变的时候也要刷新 因为名称会改变
                        //Change by Dylan 2012-3-13
                        {
                            sList->replace(99,QString("%1").arg(nNewNum)); //37
                            int val = nNewNum - nOldNum;
                            if(val < 0) //配方数减少
                            {
                                for(k = 0; k < -val;k++)
                                    sList->removeLast();
                            }
                            else if(val > 0) //配方数增加
                            {
                                for(k = 0; k < val;k++)
                                    sList->append("1");
                            }
                            QDrawGraphics *pDraw = new QDrawGraphics;
                            pNewItem = pDraw->drawHistroyDataDisplayItem(sList);  //重绘配方显示器
                            pNewItem->setData(GROUP_TYPE_KEY,QVariant(GROUP_TYPE_HISDATAALARM));
                            pNewItem->setData(GROUP_DATALIST_KEY,*sList);
                            if(pDraw)
                            {
                                delete pDraw;
                                pDraw = NULL;
                            }
                            pwnd->OnDoubleClik(pItem,pNewItem);
                        } //end if
                    } //end case
                    break;
            } //end switch
        } //end second for
    } //end first for
     pwnd->nActiveSheetIndex = nsheet ; //reset active sheet page
     pwnd->pView->setScene(pwnd->pSceneSheet[nsheet]);
}
예제 #23
0
  QDomDocument createDescribeCoverageDocument( QgsServerInterface *serverIface, const QgsProject *project, const QString &version,
      const QgsServerRequest &request )
  {
    Q_UNUSED( version );

    QDomDocument doc;

    QgsServerRequest::Parameters parameters = request.parameters();

#ifdef HAVE_SERVER_PYTHON_PLUGINS
    QgsAccessControl *accessControl = serverIface->accessControls();
#endif

    //wcs:WCS_Capabilities element
    QDomElement coveDescElement = doc.createElement( QStringLiteral( "CoverageDescription" )/*wcs:CoverageDescription*/ );
    coveDescElement.setAttribute( QStringLiteral( "xmlns" ), WCS_NAMESPACE );
    coveDescElement.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) );
    coveDescElement.setAttribute( QStringLiteral( "xsi:schemaLocation" ), WCS_NAMESPACE + " http://schemas.opengis.net/wcs/1.0.0/describeCoverage.xsd" );
    coveDescElement.setAttribute( QStringLiteral( "xmlns:gml" ), GML_NAMESPACE );
    coveDescElement.setAttribute( QStringLiteral( "xmlns:xlink" ), QStringLiteral( "http://www.w3.org/1999/xlink" ) );
    coveDescElement.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0.0" ) );
    coveDescElement.setAttribute( QStringLiteral( "updateSequence" ), QStringLiteral( "0" ) );
    doc.appendChild( coveDescElement );

    //defining coverage name
    QString coveNames;
    //read COVERAGE
    QMap<QString, QString>::const_iterator cove_name_it = parameters.constFind( QStringLiteral( "COVERAGE" ) );
    if ( cove_name_it != parameters.constEnd() )
    {
      coveNames = cove_name_it.value();
    }
    if ( coveNames.isEmpty() )
    {
      QMap<QString, QString>::const_iterator cove_name_it = parameters.constFind( QStringLiteral( "IDENTIFIER" ) );
      if ( cove_name_it != parameters.constEnd() )
      {
        coveNames = cove_name_it.value();
      }
    }

    QStringList coveNameList;
    if ( !coveNames.isEmpty() )
    {
      coveNameList = coveNames.split( ',' );
      for ( int i = 0; i < coveNameList.size(); ++i )
      {
        coveNameList.replace( i, coveNameList.at( i ).trimmed() );
      }
    }

    QStringList wcsLayersId = QgsServerProjectUtils::wcsLayerIds( *project );
    for ( int i = 0; i < wcsLayersId.size(); ++i )
    {
      QgsMapLayer *layer = project->mapLayer( wcsLayersId.at( i ) );
      if ( !layer )
      {
        continue;
      }
      if ( layer->type() != QgsMapLayer::LayerType::RasterLayer )
      {
        continue;
      }
#ifdef HAVE_SERVER_PYTHON_PLUGINS
      if ( !accessControl->layerReadPermission( layer ) )
      {
        continue;
      }
#endif
      QString name = layer->name();
      if ( !layer->shortName().isEmpty() )
        name = layer->shortName();
      name = name.replace( ' ', '_' );

      if ( coveNameList.size() == 0 || coveNameList.contains( name ) )
      {
        QgsRasterLayer *rLayer = qobject_cast<QgsRasterLayer *>( layer );
        coveDescElement.appendChild( getCoverageOffering( doc, const_cast<QgsRasterLayer *>( rLayer ), project ) );
      }
    }
    return doc;
  }
예제 #24
0
    void SessionPrivate::processLine(const QByteArray& line)
    {
        Q_Q(Session);
        QString process = readString(line);
        QString prefix, command;
        QStringList params;

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

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

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

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

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

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

        // and dump
        if (isNumeric)
        {
            switch (code)
            {
                case Irc::Rfc::RPL_WELCOME:
                {
                    Q_ASSERT(defaultBuffer);
                    defaultBuffer->d_func()->setReceiver(prefix, false);
                    emit q->welcomed();
                    welcomed = true;
                    break;
                }

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

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

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

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

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

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

                default:
                    break;
            }

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

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

            // join auto-join channels after MOTD
            if (code == Rfc::RPL_ENDOFMOTD || code == Rfc::ERR_NOMOTD)
            {
                foreach (const QString& channel, channels)
                    q->join(channel);
            }
        }
예제 #25
0
void ImageThread::processRequestResponse(QUrl url, QByteArray ba, bool cached) {
    QString requestURI;
    QList<_IMAGE>   imageList;
    QList<QUrl>     threadList;
    ParsingStatus   status;
    QString         path;
    qint64 bytesWritten;

    QLOG_TRACE() << "ImageThread :: processRequestResponse (" << url.toString() << ", " << QString(ba);

    requestURI = url.toString();
    path = url.path();

    if (isImage(url)) {
        QFile f;
        QRegExp rx(__IMAGEFILE_REGEXP__, Qt::CaseInsensitive, QRegExp::RegExp2);
        QStringList res;
        int pos;

        pos = 0;

        pos = rx.indexIn(requestURI);
        res = rx.capturedTexts();

        if (pos != -1) {
            f.setFileName(getSavepath()+"/"+res.at(1)+res.at(2));

            if (_saveWithOriginalFilename) {
                _IMAGE tmp;

                for (int i=0; i<images.count(); i++) {
                    if (images.at(i).largeURI.endsWith("/"+res.at(1)+res.at(2))) {
                        tmp = images.at(i);

                        f.setFileName(getSavepath()+"/"+tmp.originalFilename);
                        break;
                    }
                }
            }

            f.open(QIODevice::ReadWrite);
            bytesWritten = f.write(ba);
            f.close();

            if (bytesWritten == ba.size()) {
                setCompleted(requestURI, f.fileName());
            }
            else {
                QLOG_ERROR() << "UIImageOverview :: Couldn't save file from URI " << url.toString();
            }
        }

    }
    else {
        iParser->setURL(url);
        status = iParser->parseHTML(ba);

        if (status.hasErrors) {
            QLOG_ERROR() << "ImageOverview :: Parser error " << iParser->getErrorCode();
            switch (iParser->getErrorCode()) {
            case 404:
                stopDownload();
                processCloseRequest();
                break;

            default:
                break;
            }
        }
        else {
            if (status.isFrontpage) {
                QStringList newTab;
                QString v;

                v = getValues();
                newTab = v.split(";;");
                threadList = iParser->getUrlList();

                foreach (QUrl u, threadList) {
                    newTab.replace(0, u.toString());
                    emit createThreadRequest(newTab.join(";;"));
                }

                if (settings->value("options/close_overview_threads", true).toBool()) {
                    emit closeRequest(this, 0);
                }
            }
            else {
                if (status.hasImages) {
예제 #26
0
int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);
    QStringList args = app.arguments();
    QStringList preargs;
    QString locale;
    int pid = 0;
    int in = -1;
    int out = -1;
    if (args.count() >= 7) {
        // Remove program name
        args.removeFirst();

        bool erase = false;
        if (args.at(0) == "-erase") {
            erase = true;
            args.removeFirst();
        }
        bool usekuiserver = false;
        if (args.at(0) == "-kuiserver") {
            usekuiserver = true;
            args.removeFirst();
        }
        if (QString(args.at(0)).startsWith("-pid:")) {
            pid = QString(args.at(0)).section(':', 1).toInt();
            args.removeFirst();
        }

        if (QString(args.at(0)).startsWith("-locale:")) {
            locale = QString(args.at(0)).section(':', 1);
            args.removeFirst();
        }
        if (args.at(0).startsWith("in="))
            in = args.takeFirst().section('=', -1).toInt();
        if (args.at(0).startsWith("out="))
            out = args.takeFirst().section('=', -1).toInt();
        if (args.at(0).startsWith("preargs="))
            preargs = args.takeFirst().section('=', 1).split(' ', QString::SkipEmptyParts);

        QString render = args.takeFirst();
        QString profile = args.takeFirst();
        QString rendermodule = args.takeFirst();
        QString player = args.takeFirst();
	QUrl srcurl = QUrl::fromEncoded(args.takeFirst().toUtf8());
        QString src = srcurl.path();
        QUrl desturl = QUrl::fromEncoded(args.takeFirst().toUtf8());
        QString dest = desturl.path();
        bool dualpass = false;
        bool doerase;
        QString vpre;

        int vprepos = args.indexOf(QRegExp("vpre=.*"));
        if (vprepos >= 0) {
            vpre=args.at(vprepos);
        }
        QStringList vprelist = vpre.replace("vpre=", "").split(',');
        if (vprelist.size() > 0) {
            args.replaceInStrings(QRegExp("^vpre=.*"), QString("vpre=").append(vprelist.at(0)));
        }

        if (args.contains("pass=2")) {
            // dual pass encoding
            dualpass = true;
            doerase = false;
            args.replace(args.indexOf("pass=2"), "pass=1");
            if (args.contains("vcodec=libx264")) args << QString("passlogfile=%1").arg(dest + ".log");
        } else {
            args.removeAll("pass=1");
            doerase = erase;
        }

        qDebug() << "//STARTING RENDERING: " << erase << "," << usekuiserver << "," << render << "," << profile << "," << rendermodule << "," << player << "," << src << "," << dest << "," << preargs << "," << args << "," << in << "," << out ;
        RenderJob *job = new RenderJob(doerase, usekuiserver, pid, render, profile, rendermodule, player, src, dest, preargs, args, in, out);
        if (!locale.isEmpty()) job->setLocale(locale);
        job->start();
        if (dualpass) {
            if (vprelist.size()>1)
                args.replaceInStrings(QRegExp("^vpre=.*"),QString("vpre=").append(vprelist.at(1)));
            args.replace(args.indexOf("pass=1"), "pass=2");
            RenderJob *dualjob = new RenderJob(erase, usekuiserver, pid, render, profile, rendermodule, player, src, dest, preargs, args, in, out);
            QObject::connect(job, SIGNAL(renderingFinished()), dualjob, SLOT(start()));
        }
        app.exec();
    } else {
        fprintf(stderr, "Kdenlive video renderer for MLT.\nUsage: "
                "kdenlive_render [-erase] [-kuiserver] [-locale:LOCALE] [in=pos] [out=pos] [render] [profile] [rendermodule] [player] [src] [dest] [[arg1] [arg2] ...]\n"
                "  -erase: if that parameter is present, src file will be erased at the end\n"
                "  -kuiserver: if that parameter is present, use KDE job tracker\n"
                "  -locale:LOCALE : set a locale for rendering. For example, -locale:fr_FR.UTF-8 will use a french locale (comma as numeric separator)\n"
                "  in=pos: start rendering at frame pos\n"
                "  out=pos: end rendering at frame pos\n"
                "  render: path to MLT melt renderer\n"
                "  profile: the MLT video profile\n"
                "  rendermodule: the MLT consumer used for rendering, usually it is avformat\n"
                "  player: path to video player to play when rendering is over, use '-' to disable playing\n"
                "  src: source file (usually MLT XML)\n"
                "  dest: destination file\n"
                "  args: space separated libavformat arguments\n");
    }
}
예제 #27
0
void LegendItem::paint(QPainter *painter) {
  if (!isVisible()) {
    return;
  }

  RelationList legendItems;
  if (_auto) {
    legendItems = plot()->renderItem(PlotRenderItem::Cartesian)->relationList();
  } else {
    legendItems = _relations;
  }

  int count = legendItems.count();
  if (count <= 0) { // no legend or box if there are no legend items
    return;
  }


  QList<DrawnLegendItem> legendPixmaps;
  QSize legendSize(0, 0);

  QFont font(_font);
  font.setPointSizeF(view()->viewScaledFontSize(_fontScale));

  // generate string list of relation names
  QStringList names;
  bool allAuto = true;
  bool sameX = true;
  bool sameYUnits = true;

  LabelInfo label_info = legendItems.at(0)->xLabelInfo();
  QString yUnits =  legendItems.at(0)->yLabelInfo().units;

  for (int i = 0; i<count; i++) {
    RelationPtr relation = legendItems.at(i);
    if (relation->descriptiveNameIsManual()) {
      allAuto = false;
    }
    if (relation->xLabelInfo() != label_info) {
      sameX = false;
    }
    // sameYUnits is false if any non empty units are defined differently.
    if (yUnits.isEmpty()) {
      yUnits = relation->yLabelInfo().units;
    } else if (relation->yLabelInfo().units != yUnits) {
      if (!relation->yLabelInfo().units.isEmpty()) {
        sameYUnits = false;
      }
    }
  }

  if (!allAuto) {
    for (int i = 0; i<count; i++) {
      names.append(legendItems.at(i)->descriptiveName());
    }
  } else {
    for (int i = 0; i<count; i++) {
      RelationPtr relation = legendItems.at(i);
      QString label = relation->titleInfo().singleRenderItemLabel();
      if (label.isEmpty()) {
        label_info = relation->yLabelInfo();
        QString y_label = label_info.name;
        if (!sameYUnits) {
          if (!label_info.units.isEmpty()) {
            y_label = i18n("%1 \\[%2\\]").arg(y_label).arg(label_info.units);
          }
        }
        if (!y_label.isEmpty()) {
          LabelInfo xlabel_info = relation->xLabelInfo();
          if (!sameX) {
            label = i18n("%1 vs %2").arg(y_label).arg(xlabel_info.name);
          } else if (xlabel_info.quantity.isEmpty()) {
            label = y_label;
          } else if (xlabel_info.quantity != xlabel_info.name) {
            label = i18n("%1 vs %2").arg(y_label).arg(xlabel_info.name);
          } else {
            label = y_label;
          }
        } else {
          label = relation->descriptiveName();
        }
      }
      int i_dup = names.indexOf(label);
      if (i_dup<0) {
        names.append(label);
      } else {
        RelationPtr dup_relation = legendItems.at(i_dup);
        if (!dup_relation->yLabelInfo().file.isEmpty()) {
          names.replace(i_dup, label + " (" + dup_relation->yLabelInfo().file + ')');
        }
        if (!relation->yLabelInfo().file.isEmpty()) {
          names.append(label + " (" + relation->yLabelInfo().file + ')');
        }
      }
    }
  }

  for (int i = 0; i<count; i++) {
    RelationPtr relation = legendItems.at(i);
    DrawnLegendItem item;
    item.pixmap = QPixmap(LEGENDITEMMAXWIDTH, LEGENDITEMMAXHEIGHT);
    item.size = paintRelation(names.at(i), relation, &item.pixmap, font);

    if (_verticalDisplay) {
      legendSize.setWidth(qMax(legendSize.width(), item.size.width()));
      legendSize.setHeight(legendSize.height() + item.size.height());
    } else {
      legendSize.setHeight(qMax(legendSize.height(), item.size.height()));
      legendSize.setWidth(legendSize.width() + item.size.width());
    }

    legendPixmaps.append(item);
  }

  int x = rect().left();
  int y = rect().top();

  painter->save();

  if (!_title.isEmpty()) {
    // Paint the title
    Label::Parsed *parsed = Label::parse(_title);

    if (parsed) {
      painter->save();

      QPixmap pixmap(400, 100);
      pixmap.fill(Qt::transparent);
      QPainter pixmapPainter(&pixmap);

      Label::RenderContext rc(font, &pixmapPainter);
      QFontMetrics fm(font);
      rc.y = fm.ascent();
      Label::renderLabel(rc, parsed->chunk, false);

      int startPoint = qMax(0, (legendSize.width() / 2) - (rc.x / 2));
      int paddingValue = fm.height() / 4;
    
      setViewRect(viewRect().x(), viewRect().y(), qMax(rc.x, legendSize.width()), rc.y + legendSize.height() + paddingValue * 3);
      painter->drawRect(rect());

      painter->drawPixmap(QPoint(x + startPoint, y + paddingValue), pixmap, QRect(0, 0, rc.x, fm.height()));
      painter->restore();
      y += fm.height() + (paddingValue *2);
      delete parsed;
      parsed = 0;
    }
  } else {
    // No Title
    setViewRect(viewRect().x(), viewRect().y(), legendSize.width(), legendSize.height());
    painter->drawRect(rect());
  }


  foreach(const DrawnLegendItem &item, legendPixmaps) {
    painter->drawPixmap(QPoint(x, y), item.pixmap, QRect(0, 0, item.size.width(), item.size.height()));
    if (_verticalDisplay) {
      y += item.size.height();
    } else {
      x += item.size.width();
    }
  }
예제 #28
0
파일: Dymola.cpp 프로젝트: cephdon/OMOptim
void Dymola::writeParameters(QString &allDsinText,MOParameters *parameters)
{
    QString newLine;

    QStringList lines = allDsinText.split("\n");
    int iLForm = lines.indexOf(QRegExp(".* # lform .*"));
    if(iLForm>-1)
    {
        newLine =  " 0                         # lform    0/1 ASCII/Matlab-binary storage format of results";
        lines.replace(iLForm,newLine);
    }


    MOParameter* pStopTime = parameters->findItem(DymolaParameters::str(DymolaParameters::STOPTIME));
    int iLStopTime = lines.indexOf(QRegExp(".* # StopTime .*"));
    if((iLStopTime>-1) && pStopTime)
    {
        newLine =  "       "
                +pStopTime->getFieldValue(MOParameter::VALUE).toString()
                +"                   # StopTime     Time at which integration stops";
        lines.replace(iLStopTime,newLine);
    }

    MOParameter* pTolerance = parameters->findItem(DymolaParameters::str(DymolaParameters::TOLERANCE));
    int iLTolerance = lines.indexOf(QRegExp(".*  # Tolerance .*"));
    if((iLTolerance>-1) && pTolerance)
    {
        newLine =  "       "
                +pTolerance->getFieldValue(MOParameter::VALUE).toString()
                +"                   # nInterval    Relative precision of signals for \n                            #              simulation, linearization and trimming";
        lines.replace(iLTolerance,newLine);
    }

    MOParameter* pnInterval = parameters->findItem(DymolaParameters::str(DymolaParameters::NINTERVAL));
    int iLnInterval = lines.indexOf(QRegExp(".*  # nInterval .*"));
    if((iLnInterval>-1) && pnInterval)
    {
        newLine =  "       "
                +pnInterval->getFieldValue(MOParameter::VALUE).toString()
                +"                   # nInterval    Number of communication intervals, if > 0";
        lines.replace(iLnInterval,newLine);
    }

    MOParameter* pSolver = parameters->findItem(DymolaParameters::str(DymolaParameters::SOLVER));
    int iLSolver = lines.indexOf(QRegExp(".*  # Algorithm .*"));
    if((iLSolver>-1) && pSolver)
    {
        newLine =  "       "
                +pSolver->getFieldValue(MOParameter::VALUE).toString()
                +"                   # Algorithm    Integration algorithm as integer";
        lines.replace(iLSolver,newLine);
    }

    MOParameter* pFinalFile = parameters->findItem(DymolaParameters::str(DymolaParameters::FINALFILE));
    int iLineLRes = lines.indexOf(QRegExp(".*  # lres     0/1 do not/store results .*"));
    if((iLineLRes>-1) && pFinalFile)
    {
        int lRes;
        switch(pFinalFile->value().toInt())
        {
        case DymolaParameters::DSFINAL :
            lRes = 0;
            break;
        case DymolaParameters::DSRES :
        default :
            lRes = 1;
            break;
        }

        newLine =  "       "
                +QString::number(lRes)
                +"                   # lres     0/1 do not/store results on result file";
        lines.replace(iLineLRes,newLine);
    }


    allDsinText = lines.join("\n");
}
예제 #29
0
void wizardDisk::generateConfirmationText()
{
  // If running in expert mode, we just create a simple config / confirmation
  /*if ( radioExpert->isChecked() ) {
    QStringList filesystem;
    filesystem << "MANUAL" << "/mnt" ;
    sysFinalDiskLayout << filesystem;
    textConfirmation->setText(tr("Installing to file-system mounted at /mnt"));
    return;
  }*/

  QList<QStringList> copyList;
  QStringList summaryList;
  QString tmp, workingDisk, workingSlice, tmpSlice, XtraTmp, startPart, sliceSize;
  int disk = 0;

  // Copy over the list to a new variable we can mangle without modifying the original
  copyList = sysFinalDiskLayout;

  // Start our summary
  summaryList << "";
  summaryList << "<b>" + tr("The disk will be setup with the following configuration:") + "</b>";

  while ( ! copyList.empty() )
  {
    workingDisk = copyList.at(0).at(0);
    workingSlice = copyList.at(0).at(1);
    tmpSlice = workingSlice;

    // Check if this is an install to "Unused Space"
    for (int z=0; z < sysDisks.count(); ++z)
      if ( sysDisks.at(z).at(0) == "SLICE" \
        && sysDisks.at(z).at(2) == workingDisk + workingSlice \
        && sysDisks.at(z).at(4) == "Unused Space" )
          tmpSlice = "free";

    // Check for any mirror for this device
    for (int i=0; i < copyList.count(); ++i) {
       if ( copyList.at(i).at(2).indexOf("MIRROR(" + workingDisk + ")") != -1 )
       {
         summaryList << tr("Disk:") + copyList.at(i).at(0) + " " + tr("Mirroring:") + workingDisk;
         copyList.removeAt(i);
         break;
       }
    }

    // If after doing the mirror, our list is empty, break out
    if ( copyList.empty() )
      break;
    
    // If there is a dedicated /boot partition, need to list that first, see what is found
    for (int i=0; i < copyList.count(); ++i) {
      QStringList mounts = copyList.at(i).at(2).split(",");
      for (int z = 0; z < mounts.size(); ++z) {
        if ( copyList.at(i).at(0) == workingDisk \
          && copyList.at(i).at(1) == workingSlice \
          && mounts.at(z) == "/boot" )
        startPart="/boot";
      }
    }

    // If no dedicated /boot partition, then lets list "/" first
    if(startPart.isEmpty())
        startPart="/";

    // Start by looking for the root partition
    for (int i=0; i < copyList.count(); ++i) {
      QStringList mounts = copyList.at(i).at(2).split(",");
      for (int z = 0; z < mounts.size(); ++z) {
        if ( copyList.at(i).at(0) == workingDisk \
          && copyList.at(i).at(1) == workingSlice \
          && mounts.at(z) == startPart ) {

          // Check if we have any extra arguments to throw on the end
          XtraTmp="";
          if ( ! copyList.at(i).at(5).isEmpty() )
            XtraTmp=" (" + copyList.at(i).at(5) + ")" ;

          // Write the user summary
          summaryList << "";
          summaryList << tr("Partition:") + " " + workingDisk + "(" + workingSlice + "):";
          summaryList << tr("FileSystem:") + " " + copyList.at(i).at(3);
          summaryList << tr("Size:") + " " + copyList.at(i).at(4) + "MB ";

    if ( copyList.at(i).at(3) == "ZFS" || copyList.at(i).at(3) == "ZFS.eli" ) {
      QStringList zDS = copyList.at(i).at(2).split(",/");
      QString zTMP;
      for (int ds = 0; ds < zDS.size(); ++ds) {
        if ( zDS.at(ds) != "/" )
                zDS.replace(ds, "/" + zDS.at(ds));
        if ( zDS.at(ds).indexOf("(") != -1 ) {
    zTMP = zDS.at(ds);
    zTMP.replace("(", " (");
                zDS.replace(ds, zTMP );
        }
      }
            summaryList << tr("ZFS Datasets:<br>") + " " + zDS.join("<br>");
    } else {
            summaryList << tr("Mount:") + " " + copyList.at(i).at(2);
    }
    if ( ! XtraTmp.isEmpty() ) {
            summaryList << tr("Options:") + " " + copyList.at(i).at(5);
          }

          // Done with this item, remove it now
          copyList.removeAt(i);
          break;
        }
      }
    }


    // Now look for SWAP
    for (int i=0; i < copyList.count(); ++i) {
      if ( copyList.at(i).at(0) == workingDisk \
        && copyList.at(i).at(1) == workingSlice \
        && copyList.at(i).at(2) == "SWAP.eli" ) {

        // Write the user summary
        summaryList << "";
        summaryList << tr("Partition:") + " " + workingDisk + "(" + workingSlice + "):";
        summaryList << tr("FileSystem:") + " " + copyList.at(i).at(3);
        summaryList << tr("Size:") + " " + copyList.at(i).at(4) + "MB ";

        // Done with this item, remove it now
        copyList.removeAt(i);
        break;
      }
    }

 
    // Now look for any other partitions
    int count = copyList.count();
    for (int i=0; i < count; ++i) {
      if ( copyList.at(i).at(0) == workingDisk \
        && copyList.at(i).at(1) == workingSlice ) {

        // Check if we have any extra arguments to throw on the end
        XtraTmp="";
        if ( ! copyList.at(i).at(5).isEmpty() )
          XtraTmp=" (" + copyList.at(i).at(5) + ")" ;

        // If we are working on the last partition, set the size to 0 to use remaining disk
        if ( i == (count - 1) ) 
                sliceSize = "0";
        else
                sliceSize=copyList.at(i).at(4);

        // Write the user summary
        summaryList << "";
        summaryList << tr("Partition:") + " " + workingDisk + "(" + workingSlice + "):";
        summaryList << tr("FileSystem:") + " " + copyList.at(i).at(3);
        summaryList << tr("Size:") + " " + copyList.at(i).at(4) + "MB ";
        summaryList << tr("Mount:") + " " + copyList.at(i).at(2);
        if ( ! XtraTmp.isEmpty() ) {
          summaryList << tr("Options:") + " " + copyList.at(i).at(5);
        }

        // Done with this item, remove it now
        copyList.removeAt(i);
        i--;
        count--;
      }
    }

    // Increment our disk counter
    disk++;
  }

  textConfirmation->setText(summaryList.join("<br>"));
}
예제 #30
0
파일: main.cpp 프로젝트: realbardia/silicon
int main(int argc, char *argv[])
{
    // Setup Graphic system raster or native engine ===========================//

    SDataBase *db = new SDataBase( QDir::homePath() + "/.config/silicon/config" );
    if( !db->checkHeadExist("Appearance") )
        db->addHead("Appearance");
    if( !db->checkChildExist("Appearance","graphics_system") )
        db->addChild("Appearance","graphics_system");

    delete db;

    // END =================//


    QtSingleApplication app(argc, argv);
        app.setApplicationName( "Silicon" );
        app.setApplicationVersion( "Empire" );
        app.setQuitOnLastWindowClosed( false );

    QStringList args = QApplication::arguments();
        args.replace( 0 , QDir::currentPath() );

    QString args_str = args.join(";");
    if( app.isRunning() )
    {
        app.sendMessage( args_str );
        return 0;
    }

    SDefaults defaults;
    PerConf prc( defaults.Personal_Configs_file );


    int ret_code;
    if( true /*args.contains("-s") || args.count() == 1*/ )
    {
        QString color_str = prc.readOption( PerConf::HIGHLIGHT );
        QColor color = QPalette().color(QPalette::Highlight);
        if( !color_str.isEmpty() )
            color.setNamedColor( color_str );

        QImage image = SImage::colorize( QImage(":/files/Pixs/splash.png"), color.rgb() );

        QPixmap pixmap(QPixmap::fromImage(image));
        QSplashScreen splash(pixmap);
            splash.show();

        SiliconUI silicon( &prc );
            silicon.readMessage( args_str );
            silicon.show();

        QObject::connect( &app , SIGNAL(messageReceived(QString)) , &silicon , SLOT(readMessage(QString)) , Qt::QueuedConnection );

        splash.finish( &silicon );
        app.setActivationWindow( &silicon );

        silicon.initializeFinished();
        ret_code = app.exec();
    }

    qDebug() << "GoodBye";

    return ret_code;
}