QString computeSmartFilterRegex(const QStringList &filters)
{
    return QString("(?:_|\\b)(?:%1)(?:_|\\b)").arg(filters.join(QString(")|(?:")));
}
Example #2
0
bool AirportsData::import(QProgressDialog &progress, MainObject *mainObject){


    QHash<QString, QString> airports;
    QString msg;
    QTime tm;
    int ms;

    progress.setValue(0);
    progress.setWindowTitle("Scanning Airport Directories");
    progress.setRange(0, 50000);


    int c = 0;
    int found = 0;
    int air_added = 0;
    ms = tm.restart();
	
    // Removing cache file, if exists()
    if (QFile::exists(mainObject->data_file("airports.txt"))) {
            outLog("*** FGx airportsdata reload: cache file exists!");
            QFile::remove(mainObject->data_file("airports.txt"));
            outLog("*** FGx airportsdata reload: REMOVED AIRPORTS CACHE FILE");
    }

    //= Cache File
    QFile cacheFile( mainObject->data_file("airports.txt") );
    if(!cacheFile.open(QIODevice::WriteOnly | QIODevice::Text)){
            //qDebug() << "TODO Open error cachce file=";
            return true;
    }
    QTextStream out(&cacheFile);


    //================================================
    //* Lets Loop the directories
    //* Get out aiports path from setings and get the the subdir also
    QDirIterator loopAirportsFiles( mainObject->X->airports_path(), QDirIterator::Subdirectories );
    QString xFileName;

    msg = "FGx airportsdata reload: Scanning XML files in "+mainObject->X->airports_path();
    outLog(msg);
    progress.setWindowTitle(msg);
    progress.setRange(0, 50000);

    // Check the fgfs additional argument list,
    // and/or any additional scenery path inputs
    // *** take care NOT to duplicate ***
    QStringList fgfs_args = mainObject->X->get_fgfs_args();
    int i, ind;
    QDir d;
    QString path;
#ifdef Q_OS_WIN
    QChar psep(';');
#else
    QChar psep(':');
#endif
	
    // AIIIIII, found the doubler !, said yves very very loud - well done said pete ;-)
    for (i = 0; i < fgfs_args.size(); i++) {
        msg = fgfs_args.at(i);
        ind = msg.indexOf(QChar('"'));
        if (ind == 0)
            msg = msg.mid(1,msg.length()-2);
        if (msg.indexOf("--fg-scenery=") == 0) {
            // got a scenery folder to scan
            msg = msg.mid(13);
            ind = msg.indexOf(QChar('"'));
            if (ind == 0)
                msg = msg.mid(1,msg.length()-2);
            QStringList path_list = msg.split(psep);
            int pathnumber = 0;
            for( QStringList::ConstIterator entry = path_list.begin(); entry != path_list.end(); entry++) {
                path = *entry;
				pathnumber = pathnumber + 1;
                if (d.exists(path)) {
                    // we have a PATH to check, but we are ONLY checking 'Airports'
                    if ( !(path.indexOf(QChar('/')) == (path.size()-1)) &&
                         !(path.indexOf(QChar('\\')) == (path.size()-1)) )
                        path.append("/");
                    path.append("Airports"); // XML is only in here
                    if (!d.exists(path))
                        continue;
                    QDirIterator loopFiles( path, QDirIterator::Subdirectories );
                    while (loopFiles.hasNext()) {

                        //= Get file handle if there is one
                        xFileName = loopFiles.next();

                        //= Check if file entry is a *.threshold.xml - cos this is what we want
                        if(xFileName.endsWith(".threshold.xml") ){

                            //= Split out "CODE.threshold.xml" with a "."
                            QFileInfo fileInfoThreshold(xFileName);
                            QString airport_code = fileInfoThreshold.fileName().split(".").at(0);

                            //* Update progress
                            if(c % 100 == 0){
                                progress.setValue(c);
                                progress.setLabelText(xFileName);
                                progress.repaint();
                            }

                            QString airport_name("");
                            if(airports.contains(airport_code)){
                                airport_name = airports.value(airport_code);
                            }

                            QStringList cols; // missing in middle is description ??
                            cols << airport_code << airport_name << fileInfoThreshold.absoluteDir().absolutePath() << QString::number(pathnumber);

                            out << cols.join("\t").append("\n");
                            air_added++;

                            found++;
                        }

                        if(progress.wasCanceled()){
                            progress.hide();
                            return true;
                        }
                        c++;
                    }
                }
            }
        }
    }


    cacheFile.close();

    msg.sprintf("*** FGx airportsdata reload: Walked %d files, found %d threshold.xml, appended %d to cache",
                c, found, air_added);
    outLog(msg+", in "+getElapTimeStg(tm.elapsed()));
    progress.hide();
    return false;
}
Example #3
0
QString qstringlist_process (const QString &s, const QString &params, int mode)
{
  QStringList sl;
  QStringList l;
  QString result;
  
  if (mode != QSTRL_PROC_FLT_WITH_SORTCASECARE_SEP && mode != QSTRL_PROC_LIST_FLIP_SEP)
     sl = s.split (QChar::ParagraphSeparator);

  switch (mode)
         {
          case QSTRL_PROC_FLT_WITH_SORTCASECARE_SEP:
                                                    {
                                                     if (s.indexOf (params) == -1)
                                                        return s;
                                                        
                                                     QStringList sl = s.split (params);
                                                     sl.sort();
                                                     result = sl.join (params);
                                                     return result;
                                                    };
                                                    
          case QSTRL_PROC_LIST_FLIP_SEP:  {
                                           if (s.indexOf (params) == -1)
                                              return s;
        
                                           QStringList sl = s.split (params);
                                           sl.sort();
                                                     
                                           foreach (QString t, sl)
                                           l.prepend (t);

                                           result = l.join (params);
                                           return result;
                                          };
                                                                                                   
         
          case QSTRL_PROC_FLT_WITH_SORTNOCASECARE:
                                                 {
                                                  QMap <QString, QString> map;

                                                  foreach (QString value, sl)
                                                          map.insert (value.toLower(), value);

                                                  foreach (QString value, map)
                                                         l.append (value);

                                                  break;
                                                 }

          case QSTRL_PROC_FLT_REMOVE_EMPTY:
                                           {
                                            foreach (QString s, sl)
                                            if (! s.isEmpty())
                                               l.append (s);
                                            break;
                                           };


          case QSTRL_PROC_FLT_REMOVE_DUPS:
                                          {
                                           foreach (QString s, sl)
                                           if (! l.contains (s))
                                               l.append (s);
                                           break;
                                          };

          case QSTRL_PROC_REMOVE_FORMATTING:
                                           {
                                            foreach (QString t, sl)
                                                     l.append (t.simplified());

                                            break;
                                           };

           case QSTRL_PROC_FLT_WITH_REGEXP:
                                          {
                                           l = sl.filter (QRegExp (params));
                                           break;
                                          }

           case QSTRL_PROC_FLT_WITH_SORTCASECARE:
                                                 {
                                                  l = sl;
                                                  l.sort();
                                                  break;
                                                 }


           case QSTRL_PROC_LIST_FLIP:
                                     {
                                      foreach (QString t, sl)
                                              l.prepend (t);
                                      break;
                                     }

           case QSTRL_PROC_FLT_LESS:
                                    {
                                     int t = params.toInt();
                                     foreach (QString s, sl)
                                     if (s.size() > t)
                                        l.append (s);
                                     break;
                                    }

           case QSTRL_PROC_FLT_GREATER:
                                    {
                                     int t = params.toInt();
                                     foreach (QString s, sl)
                                     if (s.size() < t)
                                        l.append (s);
                                     break;
                                    }
         }

  result = l.join ("\n");
  return result;
}
Example #4
0
void dspTimePhasedOpenAPItems::sFillCustom()
{
  if (!_periods->isPeriodSelected())
  {
    if (isVisible())
      QMessageBox::warning( this, tr("Select Calendar Periods"),
                            tr("Please select one or more Calendar Periods") );
    return;
  }

  _columnDates.clear();
  _apopen->setColumnCount(2);

  QString sql("SELECT vend_id, vend_number, vend_name");
  QStringList linetotal;

  int columns = 1;
  QList<XTreeWidgetItem*> selected = _periods->selectedItems();
  for (int i = 0; i < selected.size(); i++)
  {
    PeriodListViewItem *cursor = (PeriodListViewItem*)selected[i];
    QString bucketname = QString("bucket%1").arg(columns++);
    sql += QString(", openAPItemsValue(vend_id, %2) AS %1,"
                   " 'curr' AS %3_xtnumericrole, 0 AS %4_xttotalrole")
          .arg(bucketname)
          .arg(cursor->id())
          .arg(bucketname)
          .arg(bucketname);

    _apopen->addColumn(formatDate(cursor->startDate()), _bigMoneyColumn, Qt::AlignRight, true, bucketname);
    _columnDates.append(DatePair(cursor->startDate(), cursor->endDate()));
    linetotal << QString("openAPItemsValue(vend_id, %1)").arg(cursor->id());
  }

  _apopen->addColumn(tr("Total"), _bigMoneyColumn, Qt::AlignRight, true, "linetotal");
  sql += ", " + linetotal.join("+") + " AS linetotal,"
         " 'curr' AS linetotal_xtnumericrole,"
         " 0 AS linetotal_xttotalrole,"
         " (" + linetotal.join("+") + ") = 0.0 AS xthiddenrole "
         "FROM vend "
         "<? if exists(\"vend_id\") ?>"
         "WHERE (vend_id=<? value (\"vend_id\") ?>)"
         "<? elseif exists(\"vendtype_id\") ?>"
         "WHERE (vend_vendtype_id=<? value (\"vendtype_id\") ?>)"
         "<? elseif exists(\"vendtype_code\") ?>"
         "WHERE (vend_vendtype_id IN (SELECT vendtype_id FROM vendtype WHERE (vendtype_code ~ <? value (\"vendtype_pattern\") ?>))) "
         "<? endif ?>"
         "ORDER BY vend_number;";

  MetaSQLQuery mql(sql);
  ParameterList params;
  if (! setParams(params))
    return;

  q = mql.toQuery(params);
  _apopen->populate(q);
  if (q.lastError().type() != QSqlError::NoError)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }
}
Example #5
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 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._to_stdout = False\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'");
  }
  pyCode += "mono_sample.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 + "'");

  if( m_sets.ckSumSpecs->isChecked() || runFiles.size() == 1)
  {
    QString pySaveName;
    if( saveName.isEmpty() )
    {
      pySaveName = "None";
    }
    else
    {
      pySaveName = "r'" + saveName + "'";
    }
    pyCode += QString("mono_sample.convert_to_energy(%1, %2, %3, %4, %5, %6, %7, motor=%8, offset=%9)");
    pyCode = pyCode.arg(pyRunFiles, eiGuess,pyWhiteBeam,pyAbsRunFiles,absEiGuess, pyAbsWhiteBeam, pySaveName, pyMotorName, pySeOffset);
  }
  else
  {
    QString pySaveName;
    if( saveName.isEmpty() )
    {
      pySaveName = "None";
    }
    else
    {
      pySaveName = "r'" + QFileInfo(saveName).absolutePath() + "'";
    }
    pyCode += "rfiles = " + pyRunFiles + "\n";
    if( absRunFiles.isEmpty() )
    {
      pyCode +=
        "for run in rfiles:\n"
        "  mono_sample.convert_to_energy(run, %1, %2, save_path=%3, motor=%4, offset=%5)\n";
      pyCode = pyCode.arg(eiGuess, pyWhiteBeam, pySaveName, pyMotorName, pySeOffset);
    }
    else
    {
      pyCode += "abs_rfiles = " + pyAbsRunFiles + "\n";
      pyCode +=
        "for run, abs in zip(rfiles, abs_rfiles):\n"
        "  mono_sample.convert_to_energy(run, %1, %2, abs, %3, %4, save_path=%5, motor=%6, offset=%7)\n";
      pyCode = pyCode.arg(eiGuess, pyWhiteBeam, absEiGuess, pyAbsWhiteBeam, pySaveName, pyMotorName, pySeOffset);
    }
  }
  m_pyScript = pyCode;
}
Example #6
0
int main( int argc, char * argv[] )
{
	// first look for data directory
	if( !QDir("data").exists() )
	{
		qWarning( "! %s", qPrintable(QObject::tr("Data directory not found in current working directory! Searching...")) );
		QString newWorkingDirectory;
		QStringList dataSearchPaths;
		dataSearchPaths << "./";
		dataSearchPaths << "../";
		QStringList::const_iterator i;
		for( i = dataSearchPaths.constBegin(); i != dataSearchPaths.constEnd(); ++i )
		{
			QDir dir((*i)+"data");
			if( dir.exists() )
			{
				newWorkingDirectory = (*i);
//				qDebug( "* %s", qPrintable(QObject::tr("Data directory found at \"%1\"").arg(newWorkingDirectory)) );
				break;
			}
		}
		if( newWorkingDirectory.isNull() )
		{
			qFatal( "E %s", qPrintable(QObject::tr("Data directory not found! Tried: \"%1\"!").arg(dataSearchPaths.join("\" \""))) );
		}
		if( !QDir::setCurrent( newWorkingDirectory ) )
		{
			qFatal( "E %s", qPrintable(QObject::tr("Could not change working directory to \"%1\"!").arg(newWorkingDirectory)) );
		}
		qDebug( "* %s", qPrintable(QObject::tr("Changed working directory to \"%1\"").arg(newWorkingDirectory)) );
	}

	// needed for QSettings
	QCoreApplication::setOrganizationName( "Splatterlinge" );
	QCoreApplication::setApplicationName( "Splatterlinge" );

	QTextCodec::setCodecForLocale( QTextCodec::codecForName( "UTF-8" ) );

	QApplication::setDesktopSettingsAware( false );
	QApplication::setStyle( QStyleFactory::create( "Plastique" ) );

	QApplication app( argc, argv );

	MainWindow window;
	window.show();

	return app.exec();
}
Example #7
0
void radeon_profile::on_list_variables_itemClicked(QListWidgetItem *item)
{
    ui->list_vaules->clear();

    if (item->text().contains("----")) // the separator
        return;

    if (envVars.isEmpty())
        return;

    // read variable possible values from file
    QStringList values = envVars.filter(ui->list_variables->currentItem()->text())[0].remove(ui->list_variables->currentItem()->text()+"|").split("#",QString::SkipEmptyParts);

    // if value for this variable is 'user_input' display a window for input
    if (values[0] == "user_input") {
        bool ok;
        QString input = QInputDialog::getText(this, tr("Enter value"), tr("Enter valid value for ") + ui->list_variables->currentItem()->text(), QLineEdit::Normal,"",&ok);

        // look for this variable in list
        int varIndex = selectedVariableVaules.indexOf(QRegExp(ui->list_variables->currentItem()->text()+".+",Qt::CaseInsensitive),0);
        if (!input.isEmpty() && ok) {
            // if value was ok
            if (varIndex == -1)
                // add it to list
                selectedVariableVaules.append(ui->list_variables->currentItem()->text()+"="+input);
            else
                // replace if already exists
                selectedVariableVaules[varIndex] = ui->list_variables->currentItem()->text()+"=\""+input+"\"";
        } else {
            // hehe, looks weird but check ok status is for, when input was empty, and whether user click ok or cancel, dispaly quesion
            if ((varIndex != -1) || ok) {
                if (QMessageBox::question(this, tr("Question"), tr("Remove this item?"), QMessageBox::Yes | QMessageBox::No,QMessageBox::Yes) == QMessageBox::Yes)
                    selectedVariableVaules.removeAt(varIndex);
            }
        }
        ui->txt_summary->setText(selectedVariableVaules.join(" "));
        return;
    }

    // go through list from file and check if it is selected (exists in summary)
    for (int i= 0 ; i< values.count(); i++ ) {
        // look for selected variable in list with variables and its values
        int varIndex = selectedVariableVaules.indexOf(QRegExp(ui->list_variables->currentItem()->text()+".+",Qt::CaseInsensitive),0);

        QListWidgetItem *valItem = new QListWidgetItem();
        valItem->setText(values[i]);

        // if not, add to list where from user can choose, add unchecked
        if (varIndex == -1) {
            valItem->setFlags(item->flags() | Qt::ItemIsUserCheckable);
            valItem->setCheckState(Qt::Unchecked);
        } else {
            // if it is on list, add checked
            if (selectedVariableVaules[varIndex].contains(valItem->text()))
                valItem->setCheckState(Qt::Checked);
            else {
                // other, unchecked
                valItem->setFlags(item->flags() | Qt::ItemIsUserCheckable);
                valItem->setCheckState(Qt::Unchecked);
            }
        }
        ui->list_vaules->addItem(valItem);
    }
}
Example #8
0
/*
 * this method saves the attribute together with the host string that
 * defines the type of object that this attribute is associated to (like
 * position or document) and the hosts database id.
 */
void AttributeMap::save( dbID id )
{
    checkHost();

    QSqlQuery attribQuery;
    attribQuery.prepare( "SELECT id, valueIsList FROM attributes WHERE hostObject=:host AND hostId=:hostId AND name=:name" );

    attribQuery.bindValue( ":host", mHost );
    attribQuery.bindValue( ":hostId", id.toString() );

    Iterator it;
    for ( it = begin(); it != end(); ++it ) {
        Attribute att = it.value();
        kDebug() << ">> oo-  saving attribute with name " << it.key() << " for " << id.toString() << " att-name: " << att.name();

        attribQuery.bindValue( ":name", att.name() );
        attribQuery.exec();

        QString attribId;

        if ( attribQuery.next() ) {
            // the attrib exists. Check the values

            attribId = attribQuery.value(0).toString();  // the id
            if ( att.value().isNull() || att.mDelete ) {
                // the value is empty. the existing entry needs to be dropped
                dbDeleteAttribute( attribId );
                return;
            }
        } else {
            // the attrib does not yet exist. Create if att value is not null.
            if ( att.value().isNull() ) {
                kDebug() << "oo- skip writing of attribute, value is empty";
            } else {
                kDebug() << "oo- writing of attribute name " << att.name();
                QSqlQuery insQuery;
                insQuery.prepare( "INSERT INTO attributes (hostObject, hostId, name, valueIsList, relationTable, "
                                  "relationIDColumn, relationStringColumn) "
                                  "VALUES (:host, :hostId, :name, :valueIsList, :relTable, :relIDCol, :relStringCol )" );
                insQuery.bindValue( ":host", mHost );
                insQuery.bindValue( ":hostId", id.toString() );
                insQuery.bindValue( ":name", att.name() );
                insQuery.bindValue( ":valueIsList", att.listValue() );

                // Write the relation table info. These remain empty for non related attributes.
                insQuery.bindValue( ":relTable", att.mTable );
                insQuery.bindValue( ":relIDCol", att.mIdCol );
                insQuery.bindValue( ":relStringCol", att.mStringCol );

                insQuery.exec();
                dbID attId = KraftDB::self()->getLastInsertID();
                attribId = attId.toString();
            }
        }

        // store the id to be able to drop not longer existent values
        kDebug() << "adding attribute id " << attribId << " for attribute " << att.name();

        // now there is a valid entry in the attribute table. Check the values.
        QSqlQuery valueQuery( "SELECT id, value FROM attributeValues WHERE attributeId=" + attribId );

        typedef QMap<QString, QString> ValueMap;
        ValueMap valueMap;

        while ( valueQuery.next() ) {
            QString idStr = valueQuery.value( 0 ).toString(); // id
            QString valStr = valueQuery.value( 1 ).toString(); // value

            valueMap[valStr] = idStr;
        }

        // create a stringlist with the current values of the attribute
        if ( att.listValue() ) {
            QStringList newValues;
            newValues = att.mValue.toStringList();
            kDebug() << "new values are: " << newValues.join( ", " );

            if ( newValues.empty() ) {
                // delete the entire attribute.
                dbDeleteValue( attribId ); // deletes all values
                dbDeleteAttribute( attribId );
                valueMap.clear();
            } else {
                // we really have new values

                QSqlQuery insValue;
                insValue.prepare( "INSERT INTO attributeValues (attributeId, value) VALUES (:attribId, :val)" );
                insValue.bindValue( ":attribId", attribId );

                // loop over all existing new values of the attribute.
                for ( QStringList::Iterator valIt = newValues.begin(); valIt != newValues.end(); ++valIt ) {
                    QString curValue = *valIt;

                    if ( valueMap.contains( curValue ) ) {
                        // the valueMap is already saved. remove it from the valueMap string
                        kDebug() << "Value " << curValue << " is already present with id " << valueMap[curValue];
                        valueMap.remove( curValue );
                    } else {
                        // the value is not yet there, insert it.
                        insValue.bindValue( ":val", curValue );
                        insValue.exec();
                    }
                }
            }
        } else {
            // only a single entry for the attribte, update if needed.
            QString newValue = att.mValue.toString();  // access the attribute object directly to get the numeric
            kDebug() << "NEW value String: " << newValue;
            // value in case the attribute is bound to a relation table
            if ( newValue.isEmpty() ) {
                // delete the entire attribute
                dbDeleteValue( attribId ); // deletes all values
                dbDeleteAttribute( attribId );
                valueMap.clear();
            } else {
                if ( valueMap.empty() ) {
                    // there is no entry yet that could be updated.
                    QSqlQuery insertQuery;
                    insertQuery.prepare( "INSERT INTO attributeValues (attributeId, value ) VALUES (:id, :val)" );
                    insertQuery.bindValue( ":id", attribId );
                    insertQuery.bindValue( ":val", newValue );

                    insertQuery.exec();
                    kDebug() << "insert new attrib value for non list: " << newValue;

                } else {
                    QString oldValue = valueMap.begin().key();
                    QString id = valueMap.begin().value();

                    if ( newValue != oldValue ) {
                        kDebug() << "Updating " << id << " from " << oldValue << " to " << newValue;
                        QSqlQuery updateQuery;
                        updateQuery.prepare( "UPDATE attributeValues SET value=:val WHERE id=:id" );
                        updateQuery.bindValue( ":val", newValue );
                        updateQuery.bindValue( ":id",  id );
                        kDebug() << "do the update!";
                        updateQuery.exec();
                    }
                    valueMap.remove( oldValue );
                }
            }
        }

        // remove all still existing entries in the valueMap because they point to values which are
        // in the db but were deleted from the attribute
        if ( ! valueMap.isEmpty() ) {
            ValueMap::Iterator mapIt;
            for ( mapIt = valueMap.begin(); mapIt != valueMap.end(); ++mapIt ) {
                QString valId = mapIt.value();
                dbDeleteValue( attribId, valId );
            }
        }
    }
}
Example #9
0
QVariant ServerItem::data(int column, int role) const {
	if (bParent) {
		if (column == 0) {
			switch (role) {
				case Qt::DisplayRole:
					return qsName;
				case Qt::DecorationRole:
					if (itType == FavoriteType)
						return loadIcon(QLatin1String("skin:emblems/emblem-favorite.svg"));
					else if (itType == LANType)
						return loadIcon(QLatin1String("skin:places/network-workgroup.svg"));
					else if (! qsCountryCode.isEmpty())
						return loadIcon(QString::fromLatin1(":/flags/%1.png").arg(qsCountryCode));
					else
						return loadIcon(QLatin1String("skin:categories/applications-internet.svg"));
			}
		}
	} else {
		if (role == Qt::DisplayRole) {
			switch (column) {
				case 0:
					return qsName;
				case 1:
					return (dPing > 0.0) ? QString::number(uiPing) : QVariant();
				case 2:
					return uiUsers ? QString::fromLatin1("%1/%2").arg(uiUsers).arg(uiMaxUsers) : QVariant();
			}
		} else if (role == Qt::ToolTipRole) {
			QStringList qsl;
			foreach(const QHostAddress &qha, qlAddresses)
				qsl << qha.toString();

			double ploss = 100.0;

			if (uiSent > 0)
				ploss = (uiSent - qMin(uiRecv, uiSent)) * 100. / uiSent;

			QString qs;
			qs +=
			    QLatin1String("<table>") +
			    QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Servername"), qsName) +
			    QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Hostname"), qsHostname);

			if (! qsBonjourHost.isEmpty())
				qs += QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Bonjour name"), qsBonjourHost);

			qs +=
			    QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Port")).arg(usPort) +
			    QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Addresses"), qsl.join(QLatin1String(", ")));

			if (! qsUrl.isEmpty())
				qs += QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Website"), qsUrl);

			if (uiSent > 0) {
				qs += QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Packet loss"), QString::fromLatin1("%1% (%2/%3)").arg(ploss, 0, 'f', 1).arg(uiRecv).arg(uiSent));
				if (uiRecv > 0) {
					qs +=
					    QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Ping (80%)"), ConnectDialog::tr("%1 ms").
					            arg(boost::accumulators::extended_p_square(* asQuantile)[1] / 1000., 0, 'f', 2)) +
					    QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Ping (95%)"), ConnectDialog::tr("%1 ms").
					            arg(boost::accumulators::extended_p_square(* asQuantile)[2] / 1000., 0, 'f', 2)) +
					    QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Bandwidth"), ConnectDialog::tr("%1 kbit/s").arg(uiBandwidth / 1000)) +
					    QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Users"), QString::fromLatin1("%1/%2").arg(uiUsers).arg(uiMaxUsers)) +
					    QString::fromLatin1("<tr><th align=left>%1</th><td>%2</td></tr>").arg(ConnectDialog::tr("Version")).arg(MumbleVersion::toString(uiVersion));
				}
			}
			qs += QLatin1String("</table>");
			return qs;
		} else if (role == Qt::BackgroundRole) {
Example #10
0
bool Loader_obj::load_model_data(Model& mdl, QString path){

    qDebug("Parsing obj file...");

    QStringList pathlist = path.split("/",QString::KeepEmptyParts); //KeepEmptyParts
    QString model_name = pathlist.last();

    qDebug("Model name: " + model_name.toUtf8());



    //LOAD MESH DATA
    QFile file(path);
    if (!file.open (QIODevice::ReadOnly))
    {
        qDebug("Model import: Error 1: Model file could not be loaded...");
        return false;
    }
    QTextStream stream ( &file );
    QString line;

    QString mtllib;


    QString current_mesh;
    QMap<QString,QVector<int> >mesh_faces;
    QMap<QString,QString> mesh_mtl;
    QMap<QString,Material* > mtln_mtl;
    QVector<Vector3> model_vertices;
    QVector<Vector3> model_vertex_normals;
    QVector<Vector3> model_vertex_texture_coordinates;

    while( !stream.atEnd() ) {
        line = stream.readLine();
        QStringList list = line.split(QRegExp("\\s+"),QString::SkipEmptyParts); //SkipEmptyParts

        if(!list.empty()){
            if(list.first() == "mtllib"){
                mtllib = list.last();
            }

            else if(list.first() == "v"){
                model_vertices.append(Vector3(  list.value(1).toFloat(),
                                                  list.value(2).toFloat(),
                                                  list.value(3).toFloat()));
            }
            else if(list.first() == "vn"){
                model_vertex_normals.append(Vector3(  list.value(1).toFloat(),
                                                        list.value(2).toFloat(),
                                                        list.value(3).toFloat()));
            }
            else if(list.first() == "vt"){
                model_vertex_texture_coordinates.append(Vector3(  list.value(1).toFloat(),
                                                                    list.value(2).toFloat(),
                                                                    list.value(3).toFloat()));
            }
            else if(list.first() == "g"){
                current_mesh = list.value(1);
            }
            else if(list.first() == "usemtl"){
                mesh_mtl[current_mesh] = list.value(1);
            }
            else if(list.first() == "f"){
                QStringList face_part_1_list = list.value(1).split("/",QString::SkipEmptyParts); //SkipEmptyParts
                QStringList face_part_2_list = list.value(2).split("/",QString::SkipEmptyParts); //SkipEmptyParts
                QStringList face_part_3_list = list.value(3).split("/",QString::SkipEmptyParts); //SkipEmptyParts
                mesh_faces[current_mesh].append(face_part_1_list.value(0).toInt());
                mesh_faces[current_mesh].append(face_part_1_list.value(1).toInt());
                mesh_faces[current_mesh].append(face_part_1_list.value(2).toInt());

                mesh_faces[current_mesh].append(face_part_2_list.value(0).toInt());
                mesh_faces[current_mesh].append(face_part_2_list.value(1).toInt());
                mesh_faces[current_mesh].append(face_part_2_list.value(2).toInt());

                mesh_faces[current_mesh].append(face_part_3_list.value(0).toInt());
                mesh_faces[current_mesh].append(face_part_3_list.value(1).toInt());
                mesh_faces[current_mesh].append(face_part_3_list.value(2).toInt());

            }
        }

    }
    file.close();


    //LOAD MTL DATA

    pathlist.removeAt(pathlist.length()-1);
    QString mtl_path = pathlist.join("/") + "/" + mtllib;
    QString tex_path = pathlist.join("/") + "/";

    QFile mtlfile(mtl_path);
    if (!mtlfile.open (QIODevice::ReadOnly))
    {
        qDebug("Model import: Error 2: Model material file could not be loaded...");
        return false;
    }
    QTextStream mtlstream ( &mtlfile );
    QString mtlline;


    QString current_mtl;
    QMap<QString,Vector3> mtl_ambient_c;          //Ka
    QMap<QString,Vector3> mtl_diffuse_c;          //Kd
    QMap<QString,Vector3> mtl_specular_c;         //Ks
    QMap<QString,float>     mtl_specular_ns;        //Ns
    QMap<QString,float>     mtl_transparency_d;     //d
    QMap<QString,float>     mtl_transparency_tr;    //Tr
    QMap<QString,Vector3> mtl_transparency_tf;    //Tf
    QMap<QString,QString>   mtl_ambient_map;        //map_Ka
    QMap<QString,QString>   mtl_diffuse_map;        //map_Kd
    QMap<QString,QString>   mtl_specular_map;       //map_Ks
    QMap<QString,QString>   mtl_bump_map;           //map_bump
    QMap<QString,int>       mtl_illumination;       //illum

    while( !mtlstream.atEnd() ) {
        mtlline = mtlstream.readLine();
        QStringList list = mtlline.split(QRegExp("\\s+"),QString::SkipEmptyParts); //SkipEmptyParts
        if(!list.empty()){
            if(list.first() == "newmtl"){
                current_mtl = list.last();
            }
            else if(list.first() == "Ka"){
                mtl_ambient_c[current_mtl] = Vector3(list.value(1).toFloat(),
                                                       list.value(2).toFloat(),
                                                       list.value(3).toFloat());
            }
            else if(list.first() == "Kd"){
                mtl_diffuse_c[current_mtl] = Vector3(list.value(1).toFloat(),
                                                       list.value(2).toFloat(),
                                                       list.value(3).toFloat());
            }
            else if(list.first() == "Ks"){
                mtl_specular_c[current_mtl] = Vector3(list.value(1).toFloat(),
                                                        list.value(2).toFloat(),
                                                        list.value(3).toFloat());
            }
            else if(list.first() == "Ns"){
                mtl_specular_ns[current_mtl] = list.value(1).toFloat();

            }
            else if(list.first() == "d"){
                mtl_transparency_d[current_mtl] = list.value(1).toFloat();

            }
            else if(list.first() == "Tr"){
                mtl_transparency_tr[current_mtl] = list.value(1).toFloat();

            }
            else if(list.first() == "Tf"){
                mtl_transparency_tf[current_mtl] = Vector3(list.value(1).toFloat(),
                                                             list.value(2).toFloat(),
                                                             list.value(3).toFloat());
            }
            else if(list.first() == "map_Ka"){
                mtl_ambient_map[current_mtl] = list.value(1).split("\\",QString::SkipEmptyParts).last().toUtf8();
            }
            else if(list.first() == "map_Kd"){
                mtl_diffuse_map[current_mtl] = list.value(1).split("\\",QString::SkipEmptyParts).last().toUtf8();
            }
            else if(list.first() == "map_Ks"){
                mtl_specular_map[current_mtl] = list.value(1).split("\\",QString::SkipEmptyParts).last().toUtf8();
            }
            else if((list.first() == "map_bump") || (list.first() == "bump")){
                mtl_bump_map[current_mtl] = list.value(1).split("\\",QString::SkipEmptyParts).last().toUtf8();
            }
            else if(list.first() == "illum"){
                mtl_illumination[current_mtl] = list.value(1).toInt();
            }
        }

    }


    return true;
}
Example #11
0
// solaris 2.6
char *qt_parsePrintersConf(QList<QPrinterDescription> *printers, bool *found)
{
    QFile pc(QLatin1String("/etc/printers.conf"));
    if (!pc.open(QIODevice::ReadOnly)) {
        if (found)
            *found = false;
        return 0;
    }
    if (found)
        *found = true;

    char *line = new char[1025];
    line[1024] = '\0';

    QString printerDesc;
    int lineLength = 0;

    char *defaultPrinter = 0;

    while (!pc.atEnd() &&
            (lineLength=pc.readLine(line, 1024)) > 0) {
        if (*line == '#') {
            *line = '\0';
            lineLength = 0;
        }
        if (lineLength >= 2 && line[lineLength-2] == '\\') {
            line[lineLength-2] = '\0';
            printerDesc += QString::fromLocal8Bit(line);
        } else {
            printerDesc += QString::fromLocal8Bit(line);
            printerDesc = printerDesc.simplified();
            int i = printerDesc.indexOf(QLatin1Char(':'));
            QString printerName, printerHost, printerComment;
            QStringList aliases;
            if (i >= 0) {
                // have : want |
                int j = printerDesc.indexOf(QLatin1Char('|'));
                if (j >= i)
                    j = -1;
                printerName = printerDesc.mid(0, j < 0 ? i : j);
                if (printerName == QLatin1String("_default")) {
                    i = printerDesc.indexOf(
                        QRegExp(QLatin1String(": *use *=")));
                    while (printerDesc[i] != QLatin1Char('='))
                        i++;
                    while (printerDesc[i] == QLatin1Char('=') || printerDesc[i].isSpace())
                        i++;
                    j = i;
                    while (j < (int)printerDesc.length() &&
                            printerDesc[j] != QLatin1Char(':') && printerDesc[j] != QLatin1Char(','))
                        j++;
                    // that's our default printer
                    defaultPrinter =
                        qstrdup(printerDesc.mid(i, j-i).toAscii().data());
                    printerName = QString();
                    printerDesc = QString();
                } else if (printerName == QLatin1String("_all")) {
                    // skip it.. any other cases we want to skip?
                    printerName = QString();
                    printerDesc = QString();
                }

                if (j > 0) {
                    // try extracting a comment from the aliases
                    aliases = printerDesc.mid(j + 1, i - j - 1).split(QLatin1Char('|'));
#ifndef QT_NO_PRINTDIALOG
                    printerComment = QPrintDialog::tr("Aliases: %1")
                                     .arg(aliases.join(QLatin1String(", ")));
#endif
                }
                // look for signs of this being a remote printer
                i = printerDesc.indexOf(
                    QRegExp(QLatin1String(": *bsdaddr *=")));
                if (i >= 0) {
                    // point k at the end of remote host name
                    while (printerDesc[i] != QLatin1Char('='))
                        i++;
                    while (printerDesc[i] == QLatin1Char('=') || printerDesc[i].isSpace())
                        i++;
                    j = i;
                    while (j < (int)printerDesc.length() &&
                            printerDesc[j] != QLatin1Char(':') && printerDesc[j] != QLatin1Char(','))
                        j++;
                    // and stuff that into the string
                    printerHost = printerDesc.mid(i, j-i);
                    // maybe stick the remote printer name into the comment
                    if (printerDesc[j] == QLatin1Char(',')) {
                        i = ++j;
                        while (printerDesc[i].isSpace())
                            i++;
                        j = i;
                        while (j < (int)printerDesc.length() &&
                                printerDesc[j] != QLatin1Char(':') && printerDesc[j] != QLatin1Char(','))
                            j++;
                        if (printerName != printerDesc.mid(i, j-i)) {
                            printerComment =
                                QLatin1String("Remote name: ");
                            printerComment += printerDesc.mid(i, j-i);
                        }
                    }
                }
            }
            if (printerComment == QLatin1String(":"))
                printerComment = QString(); // for cups
            if (printerName.length())
                qt_perhapsAddPrinter(printers, printerName, printerHost,
                                     printerComment, aliases);
            // chop away the line, for processing the next one
            printerDesc = QString();
        }
    }
    delete[] line;
    return defaultPrinter;
}
bool ScriptMergerCreator::createMergers(const MatchSet& matches,
  vector<Merger*>& mergers) const
{
  bool result = false;
  assert(matches.size() > 0);

  set< pair<ElementId, ElementId> > eids;

  shared_ptr<PluginContext> script;
  Persistent<Object> plugin;
  QStringList matchType;

  // go through all the matches
  for (MatchSet::const_iterator it = matches.begin(); it != matches.end(); ++it)
  {
    const ScriptMatch* sm = dynamic_cast<const ScriptMatch*>(*it);
    // check to make sure all the input matches are building matches.
    if (sm == 0)
    {
      // return an empty result
      return false;
    }
    // add all the element to element pairs to a set
    else
    {
      script = sm->getScript();

      HandleScope handleScope;
      Context::Scope context_scope(script->getContext());

      plugin = sm->getPlugin();
      set< pair<ElementId, ElementId> > s = sm->getMatchPairs();
      eids.insert(s.begin(), s.end());
      if (matchType.contains(sm->getMatchName()) == false)
      {
        matchType.append(sm->getMatchName());
      }
    }
  }

  ScriptMerger* sm = new ScriptMerger(script, plugin, eids);
  // only add the POI merge if there are elements to merge.
  if (sm->hasFunction("mergeSets"))
  {
    if (eids.size() >= 1)
    {
      mergers.push_back(sm);
      result = true;
    }
    else
    {
      delete sm;
    }
  }
  else
  {
    if (eids.size() == 1)
    {
      mergers.push_back(sm);
      result = true;
    }
    else if (eids.size() > 1)
    {
      delete sm;
      mergers.push_back(new MarkForReviewMerger(eids, "Overlapping matches", matchType.join(";"),
        1.0));
      result = true;
    }
    else
    {
      delete sm;
    }
  }

  return result;
}
Example #13
0
QVariant TransferListModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid()) return QVariant();

    BitTorrent::TorrentHandle *const torrent = m_torrents.value(index.row());
    if (!torrent) return QVariant();

    if ((role == Qt::DecorationRole) && (index.column() == TR_NAME))
        return getIconByState(torrent->state());

    if (role == Qt::ForegroundRole)
        return getColorByState(torrent->state());

    if ((role != Qt::DisplayRole) && (role != Qt::UserRole))
        return QVariant();

    switch (index.column()) {
    case TR_NAME:
        return torrent->name();
    case TR_PRIORITY:
        return torrent->queuePosition();
    case TR_SIZE:
        return torrent->wantedSize();
    case TR_PROGRESS:
        return torrent->progress();
    case TR_STATUS:
        return QVariant::fromValue(torrent->state());
    case TR_SEEDS:
        return (role == Qt::DisplayRole) ? torrent->seedsCount() : torrent->totalSeedsCount();
    case TR_PEERS:
        return (role == Qt::DisplayRole) ? torrent->leechsCount() : torrent->totalLeechersCount();
    case TR_DLSPEED:
        return torrent->downloadPayloadRate();
    case TR_UPSPEED:
        return torrent->uploadPayloadRate();
    case TR_ETA:
        return torrent->eta();
    case TR_RATIO:
        return torrent->realRatio();
    case TR_CATEGORY:
        return torrent->category();
    case TR_TAGS: {
            QStringList tagsList = torrent->tags().toList();
            tagsList.sort();
            return tagsList.join(", ");
        }
    case TR_ADD_DATE:
        return torrent->addedTime();
    case TR_SEED_DATE:
        return torrent->completedTime();
    case TR_TRACKER:
        return torrent->currentTracker();
    case TR_DLLIMIT:
        return torrent->downloadLimit();
    case TR_UPLIMIT:
        return torrent->uploadLimit();
    case TR_AMOUNT_DOWNLOADED:
        return torrent->totalDownload();
    case TR_AMOUNT_UPLOADED:
        return torrent->totalUpload();
    case TR_AMOUNT_DOWNLOADED_SESSION:
        return torrent->totalPayloadDownload();
    case TR_AMOUNT_UPLOADED_SESSION:
        return torrent->totalPayloadUpload();
    case TR_AMOUNT_LEFT:
        return torrent->incompletedSize();
    case TR_TIME_ELAPSED:
        return (role == Qt::DisplayRole) ? torrent->activeTime() : torrent->seedingTime();
    case TR_SAVE_PATH:
        return Utils::Fs::toNativePath(torrent->savePath());
    case TR_COMPLETED:
        return torrent->completedSize();
    case TR_RATIO_LIMIT:
        return torrent->maxRatio();
    case TR_SEEN_COMPLETE_DATE:
        return torrent->lastSeenComplete();
    case TR_LAST_ACTIVITY:
        if (torrent->isPaused() || torrent->isChecking())
            return -1;
        return torrent->timeSinceActivity();
    case TR_TOTAL_SIZE:
        return torrent->totalSize();
    }

    return QVariant();
}
Example #14
0
void SendCoinsDialog::on_sendButton_clicked()
{
    if(!model || !model->getOptionsModel())
        return;

    QList<SendCoinsRecipient> recipients;
    bool valid = true;

    for(int i = 0; i < ui->entries->count(); ++i)
    {
        SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
        if(entry)
        {
            if(entry->validate())
            {
                recipients.append(entry->getValue());
            }
            else
            {
                valid = false;
            }
        }
    }

    if(!valid || recipients.isEmpty())
    {
        return;
    }

    fNewRecipientAllowed = false;
    WalletModel::UnlockContext ctx(model->requestUnlock());
    if(!ctx.isValid())
    {
        // Unlock wallet was cancelled
        fNewRecipientAllowed = true;
        return;
    }

    // prepare transaction for getting txFee earlier
    WalletModelTransaction currentTransaction(recipients);
    WalletModel::SendCoinsReturn prepareStatus;
    if (model->getOptionsModel()->getCoinControlFeatures()) // coin control enabled
        prepareStatus = model->prepareTransaction(currentTransaction, CoinControlDialog::coinControl);
    else
        prepareStatus = model->prepareTransaction(currentTransaction);

    // process prepareStatus and on error generate message shown to user
    processSendCoinsReturn(prepareStatus,
        BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), currentTransaction.getTransactionFee()));

    if(prepareStatus.status != WalletModel::OK) {
        fNewRecipientAllowed = true;
        return;
    }

    CAmount txFee = currentTransaction.getTransactionFee();

    // Format confirmation message
    QStringList formatted;
    Q_FOREACH(const SendCoinsRecipient &rcp, currentTransaction.getRecipients())
    {
        // generate bold amount string
        QString amount = "<b>" + BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount);
        amount.append("</b>");
        // generate monospace address string
        QString address = "<span style='font-family: monospace;'>" + rcp.address;
        address.append("</span>");

        QString recipientElement;

        if (!rcp.paymentRequest.IsInitialized()) // normal payment
        {
            if(rcp.label.length() > 0) // label with address
            {
                recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.label));
                recipientElement.append(QString(" (%1)").arg(address));
            }
            else // just address
            {
                recipientElement = tr("%1 to %2").arg(amount, address);
            }
        }
        else if(!rcp.authenticatedMerchant.isEmpty()) // authenticated payment request
        {
            recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.authenticatedMerchant));
        }
        else // unauthenticated payment request
        {
            recipientElement = tr("%1 to %2").arg(amount, address);
        }

        formatted.append(recipientElement);
    }

    QString questionString = tr("Are you sure you want to send?");
    questionString.append("<br /><br />%1");

    if(txFee > 0)
    {
        // append fee string if a fee is required
        questionString.append("<hr /><span style='color:#aa0000;'>");
        questionString.append(BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), txFee));
        questionString.append("</span> ");
        questionString.append(tr("added as transaction fee"));

        // append transaction size
        questionString.append(" (" + QString::number((double)currentTransaction.getTransactionSize() / 1000) + " kB)");
    }

    // add total amount in all subdivision units
    questionString.append("<hr />");
    CAmount totalAmount = currentTransaction.getTotalTransactionAmount() + txFee;
    QStringList alternativeUnits;
    Q_FOREACH(BitcoinUnits::Unit u, BitcoinUnits::availableUnits())
    {
        if(u != model->getOptionsModel()->getDisplayUnit())
            alternativeUnits.append(BitcoinUnits::formatHtmlWithUnit(u, totalAmount));
    }
    questionString.append(tr("Total Amount %1 (= %2)")
        .arg(BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), totalAmount))
        .arg(alternativeUnits.join(" " + tr("or") + " ")));

    QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"),
        questionString.arg(formatted.join("<br />")),
        QMessageBox::Yes | QMessageBox::Cancel,
        QMessageBox::Cancel);

    if(retval != QMessageBox::Yes)
    {
        fNewRecipientAllowed = true;
        return;
    }

    // now send the prepared transaction
    WalletModel::SendCoinsReturn sendStatus = model->sendCoins(currentTransaction);
    // process sendStatus and on error generate message shown to user
    processSendCoinsReturn(sendStatus);

    if (sendStatus.status == WalletModel::OK)
    {
        accept();
        CoinControlDialog::coinControl->UnSelectAll();
        coinControlUpdateLabels();
    }
    fNewRecipientAllowed = true;
}
Example #15
0
        }
        _tray->setToolTip(tr("Disconnected from %1").arg(
                accountNames.join(QLatin1String(", "))));
#else
        QStringList messages;
        messages.append(tr("Disconnected from accounts:"));
        foreach (AccountStatePtr a, problemAccounts) {
            QString message = tr("Account %1: %2").arg(
                    a->account()->displayName(), a->stateString(a->state()));
            if (! a->connectionErrors().empty()) {
                message += QLatin1String("\n");
                message += a->connectionErrors().join(QLatin1String("\n"));
            }
            messages.append(message);
        }
        _tray->setToolTip(messages.join(QLatin1String("\n\n")));
#endif
        return;
    }

    if (allSignedOut) {
        _tray->setIcon(Theme::instance()->folderOfflineIcon(true));
        _tray->setToolTip(tr("Please sign in"));
        return;
    }

    // display the info of the least successful sync (eg. do not just display the result of the latest sync)
    QString trayMessage;
    FolderMan *folderMan = FolderMan::instance();
    Folder::Map map = folderMan->map();
    SyncResult overallResult = FolderMan::accountStatus(map.values());
Example #16
0
void Converter::generateServerMethod(KODE::Code& code, const Binding& binding, const Operation& operation, KODE::Class &newClass, bool first)
{
    const Message message = mWSDL.findMessage( operation.input().message() );
    Message outputMessage;
    if (operation.operationType() != Operation::OneWayOperation) {
        outputMessage = mWSDL.findMessage( operation.output().message() );
    }

    const QString operationName = operation.name();
    const QString methodName = mNameMapper.escape( lowerlize( operationName ) );

    KODE::Function virtualMethod(methodName);
    virtualMethod.setVirtualMode(KODE::Function::PureVirtual);

    QString condition = "method == \"" + operationName + "\"";
    if ( binding.type() == Binding::SOAPBinding ) {
        const SoapBinding soapBinding( binding.soapBinding() );
        const SoapBinding::Operation op = soapBinding.operations().value( operation.name() );
        if (!op.action().isEmpty()) {
            condition += "|| soapAction == \"" + op.action() + "\"";
        }
    }
    code += QString(first ? "" : "else ") + "if (" + condition + ") {";
    code.indent();

    QStringList inputVars;
    const Part::List parts = message.parts();
    for (int partNum = 0; partNum < parts.count(); ++partNum) {
        const Part part = parts.at(partNum);
        const QString lowerName = lowerlize( part.name() );
        const QString argType = mTypeMap.localType( part.type(), part.element() );
        //qDebug() << "localInputType" << part.type().qname() << part.element().qname() << "->" << argType;
        if ( argType != "void" ) {
            const QString varName = mNameMapper.escape( lowerName );

            code += argType + ' ' + varName + ";" + COMMENT;

            QString soapValueVarName = "request";
            if (soapStyle(binding) == SoapBinding::RPCStyle) {
                // RPC comes with a wrapper element, dig into it here
                soapValueVarName = "val";
                if (partNum > 0) {
                    soapValueVarName += QString::number(partNum+1);
                }
                code += QString::fromLatin1("const KDSoapValue %1 = request.childValues().at(%2);").arg(soapValueVarName).arg(partNum) + COMMENT;
            }

            // what if there's more than one?
            code.addBlock( demarshalVar( part.type(), part.element(), varName, argType, soapValueVarName ) );

            inputVars += varName;
            newClass.addIncludes( mTypeMap.headerIncludes( part.type() ) );
            virtualMethod.addArgument( mTypeMap.localInputType( part.type(), part.element() ) + ' ' + varName );
        }
    }

    const Part::List outParts = outputMessage.parts();
    if (outParts.count() > 1) {
        qWarning("ERROR: multiple output parameters are not supported (operation %s) - please report"
                 " this with your wsdl file to [email protected]", qPrintable(operation.name()));
        virtualMethod.setReturnType("void /*UNSUPPORTED*/");
    } else if (outParts.isEmpty()) {
        code += operationName + '(' + inputVars.join(", ") + ");";
        virtualMethod.setReturnType("void");
    } else {
        QString retType;
        QString retInputType;
        //bool isBuiltin = false;
        //bool isComplex = false;
        Part retPart;
        Q_FOREACH( const Part& outPart, outParts /* only one */ ) {
            retType = mTypeMap.localType( outPart.type(), outPart.element() );
            retInputType = mTypeMap.localInputType( outPart.type(), outPart.element() );
            //isBuiltin = mTypeMap.isBuiltinType( outPart.type(), outPart.element() );
            //isComplex = mTypeMap.isComplexType( outPart.type(), outPart.element() );
            retPart = outPart;
        }
        const QString methodCall = methodName + '(' + inputVars.join(", ") + ')';
        if (retType == "void") {
            code += methodCall + ";" + COMMENT;
        } else {
            code += retType + " ret = " + methodCall + ";" + COMMENT;
        }
        code += "if (!hasFault()) {";
        code.indent();

        bool qualified;
        const QName elemName = elementNameForPart( retPart, &qualified );

        if (soapStyle(binding) == SoapBinding::RPCStyle) {
            code += QString("KDSoapValue wrapper(\"%1\", QVariant());").arg(outputMessage.name());
            code.addBlock( serializeElementArg( retPart.type(), retPart.element(), elemName, "ret", "wrapper.childValues()", true, qualified ) );
            code += "response = wrapper;";
        } else {
            code.addBlock( serializeElementArg( retPart.type(), retPart.element(), elemName, "ret", "response", false, qualified ) );
        }

        code.unindent();
        code += "}";
        Q_ASSERT(!retType.isEmpty());
        virtualMethod.setReturnType(retType);

        generateDelayedReponseMethod(methodName, retInputType, retPart, newClass, binding, outputMessage);
    }
Example #17
0
	QList<QPair<QString, QVariant>> EntryBase::GetVCardRepresentation () const
	{
		Account_->GetClientConnection ()->FetchVCard (GetJID ());

		const auto vcard = GetVCard ();

		QList<QPair<QString, QVariant>> result
		{
			{ tr ("Photo"), QImage::fromData (vcard.photo ()) },
			{ "JID", vcard.from () },
			{ tr ("Real name"), vcard.fullName () },
			{ tr ("Birthday"), vcard.birthday () },
			{ "URL", vcard.url () },
			{ tr ("About"), vcard.description () }
		};

		for (const auto& phone : vcard.phones ())
		{
			if (phone.number ().isEmpty ())
				continue;

			QStringList attrs;
			if (phone.type () & QXmppVCardPhone::Preferred)
				attrs << tr ("preferred");
			if (phone.type () & QXmppVCardPhone::Home)
				attrs << tr ("home");
			if (phone.type () & QXmppVCardPhone::Work)
				attrs << tr ("work");
			if (phone.type () & QXmppVCardPhone::Cell)
				attrs << tr ("cell");

			result.append ({ tr ("Phone"), attrs.isEmpty () ?
						phone.number () :
						phone.number () + " (" + attrs.join (", ") + ")" });
		}

		for (const auto& email : vcard.emails ())
		{
			if (email.address ().isEmpty ())
				continue;

			QStringList attrs;
			if (email.type () == QXmppVCardEmail::Preferred)
				attrs << tr ("preferred");
			if (email.type () == QXmppVCardEmail::Home)
				attrs << tr ("home");
			if (email.type () == QXmppVCardEmail::Work)
				attrs << tr ("work");
			if (email.type () == QXmppVCardEmail::X400)
				attrs << "X400";

			result.append ({ "Email", attrs.isEmpty () ?
						email.address () :
						email.address () + " (" + attrs.join (", ") + ")" });
		}

		for (const auto& address : vcard.addresses ())
		{
			if ((address.country () + address.locality () + address.postcode () +
					address.region () + address.street ()).isEmpty ())
				continue;

			QStringList attrs;
			if (address.type () & QXmppVCardAddress::Home)
				attrs << tr ("home");
			if (address.type () & QXmppVCardAddress::Work)
				attrs << tr ("work");
			if (address.type () & QXmppVCardAddress::Postal)
				attrs << tr ("postal");
			if (address.type () & QXmppVCardAddress::Preferred)
				attrs << tr ("preferred");

			QString str;
			QStringList fields;
			auto addField = [&fields] (const QString& label, const QString& val)
			{
				if (!val.isEmpty ())
					fields << label.arg (val);
			};
			addField (tr ("Country: %1"), address.country ());
			addField (tr ("Region: %1"), address.region ());
			addField (tr ("Locality: %1", "User's locality"), address.locality ());
			addField (tr ("Street: %1"), address.street ());
			addField (tr ("Postal code: %1"), address.postcode ());

			result.append ({ tr ("Address"), fields });
		}

#if QXMPP_VERSION >= 0x000800
		const auto& orgInfo = vcard.organization ();
		result.append ({ tr ("Organization"), orgInfo.organization () });
		result.append ({ tr ("Organization unit"), orgInfo.unit () });
		result.append ({ tr ("Job title"), orgInfo.title () });
		result.append ({ tr ("Job role"), orgInfo.role () });
#endif
		return result;
	}
Example #18
0
int main(int argc, char *argv[])
{
    QScopedPointer<QGuiApplication> app(new QGuiApplication(argc, argv));

    qDebug() << app->arguments();
    if (app->arguments().size() < 2)
        return EXIT_FAILURE;

    auto defaultFont = app->font();
    defaultFont.setPointSize(10);
    app->setFont(defaultFont);

    Mode mode = Unknown;

    QScopedPointer<QQmlApplicationEngine> engine(new QQmlApplicationEngine);
    engine->rootContext()->setContextProperty("abort_editor", QVariant::fromValue(false));
    QScopedPointer<CommitModel> commitModel(new CommitModel);
    engine->rootContext()->setContextProperty("commits", commitModel.data());

    if (app->arguments()[1].endsWith("COMMIT_EDITMSG")
            || app->arguments()[1].endsWith("addp-hunk-edit.diff")) {
        mode = Edit;
        QFile file(app->arguments()[1]);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
            return EXIT_FAILURE;

        engine->rootContext()->setContextProperty("value", file.readAll());
        engine->load(QUrl(QStringLiteral("qrc:/qml/git_editor/edit.qml")));
    }

    if (app->arguments()[1].endsWith("git-rebase-todo")) {
        mode = Rebase;
        QFile file(app->arguments()[1]);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
            return EXIT_FAILURE;

        QTextStream in(&file);
        QStringList comments;
        while (!in.atEnd()) {
            QString line = in.readLine().trimmed();
            if (line.startsWith('|')) {
                comments += line;
            } else if (!line.isEmpty()) {
                QSharedPointer<DataObject> data(new DataObject);
                data->operation = line.section(' ', 0, 0);
                data->sha = line.section(' ', 1, 1);
                data->description = line.section(' ', 2);
                commitModel->appendRow(data);
            }
        }
        file.close();

        engine->rootContext()->setContextProperty("comments", comments.join("\n"));
        engine->load(QUrl(QStringLiteral("qrc:/qml/git_editor/main.qml")));
    }

    if (mode == Unknown) {
        return EXIT_FAILURE;
    }

    auto result = app->exec();

    if (commitModel->abort()) {
        qDebug() << "Aborting";
        return EXIT_FAILURE;
    }

    if (mode == Rebase) {
        QFile file(app->arguments()[1]);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            qDebug() << "Unable to open for write" << app->arguments()[1];
            return EXIT_FAILURE;
        }

        QTextStream out(&file);
        for (int row = 0; row < commitModel->rowCount(); ++row) {
            QModelIndex index = commitModel->index(row);
            QString operation = commitModel->data(index, CommitModel::Operation).toString();
            QString sha = commitModel->data(index, CommitModel::Sha).toString();
            QString description = commitModel->data(index, CommitModel::Description).toString();
            qDebug() << operation << sha << description;
            if (operation == "DELETE")
                continue;
            out << operation << ' ' << sha << ' ' << description << '\n';
        }
    } else if (mode == Edit) {
        QFile file(app->arguments()[1]);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            qDebug() << "Unable to open for write" << app->arguments()[1];
            return EXIT_FAILURE;
        }

        QTextStream out(&file);
        auto rootObject = engine->rootObjects()[0];
        auto textEdit = rootObject->findChild<QObject*>("textEdit");
        out << QQmlProperty::read(textEdit, "text").toString();
    }

    return result;
}
Example #19
0
QPair<QString, QVector<QVariant>> SelectBuilder::buildRaw(QSqlDatabase &db)
{
	auto fullField = [this](const QString &field) {
		if (field.contains(QLatin1Char('.')) || field.contains(QLatin1Char('('))) {
			return field;
		} else {
			return m_mainTable + QLatin1Char('.') + field;
		}
	};

	QString str = QStringLiteral("SELECT");
	QVector<QVariant> values;

	if (m_fields.isEmpty()) {
		str += QLatin1Char(' ') + m_mainTable + QStringLiteral(".*");
	} else {
		QStringList fields;
		for (const QString &field : m_fields) {
			fields.append(fullField(field));
		}
		str += fields.join(QLatin1Char(','));
	}

	str += QStringLiteral(" FROM ") + m_mainTable;

	if (!m_where.isEmpty()) {
		const auto built = m_where.build();
		str += QStringLiteral(" WHERE ") + built.first;
		values.append(built.second);
	}

	for (const Join &join : m_joins) {
		switch (join.type) {
		case JoinType::InnerJoin: str += QStringLiteral(" INNER JOIN"); break;
		case JoinType::LeftOuterJoin: str += QStringLiteral(" LEFT OUTER JOIN"); break;
		case JoinType::FullJoin: str += QStringLiteral(" FULL JOIN"); break;
		}
		str + QStringLiteral(" %1 ON %3.%4 = %1.%2").arg(join.tableA, join.fieldA, join.tableB, join.fieldB);
	}

	if (!m_groupBy.isEmpty()) {
		str += QStringLiteral(" GROUP BY ") + fullField(m_groupBy);

		if (!m_having.isEmpty()) {
			const auto built = m_having.build();
			str += QStringLiteral(" HAVING (") + built.first + QLatin1Char(')');
			values.append(built.second);
		}
	}

	if (!m_order.first.isEmpty()) {
		str += QStringLiteral(" ORDER BY ") + Functional::collection(m_order.first).map(fullField).join(QLatin1Char(','));
		if (m_order.second == Qt::AscendingOrder) {
			str += QStringLiteral(" ASC");
		} else {
			str += QStringLiteral(" DESC");
		}
	}

	return qMakePair(str, values);
}
Example #20
0
void OrganisationWidget::openFiles(const QStringList &pFileNames) const
{
    // Ask OpenCOR to open the files

    static_cast<SharedTools::QtSingleApplication *>(qApp)->handleAction("gui://openFiles/"+pFileNames.join("|"));
}
Example #21
0
bool Application::sendParams(const QStringList &params)
{
    return sendMessage(params.join(QLatin1String(PARAMS_SEPARATOR)));
}
Example #22
0
void RetrieveUrlsDialog::setUrls(const QStringList &u) {
    setText(u.join("\n") + "\n");
}
Example #23
0
QByteArray* QgsWCSServer::getCoverage()
{
  QStringList wcsLayersId = mConfigParser->wcsLayers();

  QList<QgsMapLayer*> layerList;

  QStringList mErrors = QStringList();

  //defining coverage name
  QString coveName = "";
  //read COVERAGE
  QMap<QString, QString>::const_iterator cove_name_it = mParameters.find( "COVERAGE" );
  if ( cove_name_it != mParameters.end() )
  {
    coveName = cove_name_it.value();
  }
  if ( coveName == "" )
  {
    QMap<QString, QString>::const_iterator cove_name_it = mParameters.find( "IDENTIFIER" );
    if ( cove_name_it != mParameters.end() )
    {
      coveName = cove_name_it.value();
    }
  }

  if ( coveName == "" )
  {
    mErrors << QString( "COVERAGE is mandatory" );
  }

  layerList = mConfigParser->mapLayerFromCoverage( coveName );
  if ( layerList.size() < 1 )
  {
    mErrors << QString( "The layer for the COVERAGE '%1' is not found" ).arg( coveName );
  }

  bool conversionSuccess;
  // BBOX
  bool bboxOk = false;
  double minx = 0.0, miny = 0.0, maxx = 0.0, maxy = 0.0;
  // WIDTh and HEIGHT
  int width = 0, height = 0;
  // CRS
  QString crs = "";

  // read BBOX
  QMap<QString, QString>::const_iterator bbIt = mParameters.find( "BBOX" );
  if ( bbIt == mParameters.end() )
  {
    minx = 0; miny = 0; maxx = 0; maxy = 0;
  }
  else
  {
    bboxOk = true;
    QString bbString = bbIt.value();
    minx = bbString.section( ",", 0, 0 ).toDouble( &conversionSuccess );
    if ( !conversionSuccess ) {bboxOk = false;}
    miny = bbString.section( ",", 1, 1 ).toDouble( &conversionSuccess );
    if ( !conversionSuccess ) {bboxOk = false;}
    maxx = bbString.section( ",", 2, 2 ).toDouble( &conversionSuccess );
    if ( !conversionSuccess ) {bboxOk = false;}
    maxy = bbString.section( ",", 3, 3 ).toDouble( &conversionSuccess );
    if ( !conversionSuccess ) {bboxOk = false;}
  }
  if ( !bboxOk )
  {
    mErrors << QString( "The BBOX is mandatory and has to be xx.xxx,yy.yyy,xx.xxx,yy.yyy" );
  }

  // read WIDTH
  width = mParameters.value( "WIDTH", "0" ).toInt( &conversionSuccess );
  if ( !conversionSuccess )
    width = 0;
  // read HEIGHT
  height = mParameters.value( "HEIGHT", "0" ).toInt( &conversionSuccess );
  if ( !conversionSuccess )
  {
    height = 0;
  }

  if ( width < 0 || height < 0 )
  {
    mErrors << QString( "The WIDTH and HEIGHT are mandatory and have to be integer" );
  }

  crs = mParameters.value( "CRS", "" );
  if ( crs == "" )
  {
    mErrors << QString( "The CRS is mandatory" );
  }

  if ( mErrors.count() != 0 )
  {
    throw QgsMapServiceException( "RequestNotWellFormed", mErrors.join( ". " ) );
  }

  QgsCoordinateReferenceSystem requestCRS = QgsCRSCache::instance()->crsByAuthId( crs );
  if ( !requestCRS.isValid() )
  {
    mErrors << QString( "Could not create request CRS" );
    throw QgsMapServiceException( "RequestNotWellFormed", mErrors.join( ". " ) );
  }

  QgsRectangle rect( minx, miny, maxx, maxy );

  QgsMapLayer* layer = layerList.at( 0 );
  QgsRasterLayer* rLayer = dynamic_cast<QgsRasterLayer*>( layer );
  if ( rLayer && wcsLayersId.contains( rLayer->id() ) )
  {
    // RESPONSE_CRS
    QgsCoordinateReferenceSystem responseCRS = rLayer->crs();
    crs = mParameters.value( "RESPONSE_CRS", "" );
    if ( crs != "" )
    {
      responseCRS = QgsCRSCache::instance()->crsByAuthId( crs );
      if ( !responseCRS.isValid() )
      {
        responseCRS = rLayer->crs();
      }
    }

    // transform rect
    if ( requestCRS != rLayer->crs() )
    {
      QgsCoordinateTransform t( requestCRS, rLayer->crs() );
      rect = t.transformBoundingBox( rect );
    }

    QTemporaryFile tempFile;
    tempFile.open();
    QgsRasterFileWriter fileWriter( tempFile.fileName() );

    // clone pipe/provider
    QgsRasterPipe* pipe = new QgsRasterPipe();
    if ( !pipe->set( rLayer->dataProvider()->clone() ) )
    {
      mErrors << QString( "Cannot set pipe provider" );
      throw QgsMapServiceException( "RequestNotWellFormed", mErrors.join( ". " ) );
    }

    // add projector if necessary
    if ( responseCRS != rLayer->crs() )
    {
      QgsRasterProjector * projector = new QgsRasterProjector;
      projector->setCRS( rLayer->crs(), responseCRS );
      if ( !pipe->insert( 2, projector ) )
      {
        mErrors << QString( "Cannot set pipe projector" );
        throw QgsMapServiceException( "RequestNotWellFormed", mErrors.join( ". " ) );
      }
    }

    QgsRasterFileWriter::WriterError err = fileWriter.writeRaster( pipe, width, height, rect, responseCRS );
    if ( err != QgsRasterFileWriter::NoError )
    {
      mErrors << QString( "Cannot write raster error code: %1" ).arg( err );
      throw QgsMapServiceException( "RequestNotWellFormed", mErrors.join( ". " ) );
    }
    delete pipe;
    QByteArray* ba = 0;
    ba = new QByteArray();
    *ba = tempFile.readAll();

    return ba;
  }
  return 0;
}
Example #24
0
static void load(IOAdapter* io, const U2DbiRef& dbiRef, const QVariantMap& fs, QList<GObject*>& objects,
                 int gapSize, QString& writeLockReason, U2OpStatus& os)
{
    DbiOperationsBlock opBlock(dbiRef, os);
    CHECK_OP(os, );
    Q_UNUSED(opBlock);

    static char fastaCommentStartChar = FastaFormat::FASTA_COMMENT_START_SYMBOL;

    MemoryLocker memoryLocker(os, 1);
    CHECK_OP(os, );

    writeLockReason.clear();
    QByteArray readBuff(DocumentFormat::READ_BUFF_SIZE + 1, 0);
    char* buff = readBuff.data();
    qint64 len = 0;

    bool merge = gapSize != -1;
    QStringList headers;
    QSet<QString> uniqueNames;
    QVector<U2Region> mergedMapping;

    // for lower case annotations
    GObjectReference sequenceRef;

    //skip leading whites if present
    bool lineOk = true;
    static QBitArray nonWhites = ~TextUtils::WHITES;
    io->readUntil(buff, DocumentFormat::READ_BUFF_SIZE, nonWhites, IOAdapter::Term_Exclude, &lineOk);
    CHECK_EXT(!io->hasError(), os.setError(io->errorString()), );

    U2SequenceImporter seqImporter(fs, true);
    const QString folder = fs.value(DocumentFormat::DBI_FOLDER_HINT, U2ObjectDbi::ROOT_FOLDER).toString();

    qint64 sequenceStart = 0;
    int sequenceNumber = 0;
    DbiConnection con(dbiRef, os);
    bool headerReaded = false;
    QStringList emptySeqNames;

    const int objectsCountLimit = fs.contains(DocumentReadingMode_MaxObjectsInDoc) ? fs[DocumentReadingMode_MaxObjectsInDoc].toInt() : -1;
    const bool settingsMakeUniqueName = !fs.value(DocumentReadingMode_DontMakeUniqueNames, false).toBool();
    while (!os.isCoR()) {
        //skip start comments and read header
        if(!headerReaded){
            do{
                len = io->readLine(buff, DocumentFormat::READ_BUFF_SIZE);
                CHECK_EXT(!io->hasError(), os.setError(io->errorString()), );
            }while(buff[0] == fastaCommentStartChar && len > 0);
        }

        if (len == 0 && io->isEof()) { //end if stream
            break;
        }
        CHECK_EXT(!io->hasError(), os.setError(io->errorString()), );
        CHECK_EXT_BREAK(lineOk, os.setError(FastaFormat::tr("Line is too long")));

        QString headerLine = QString(QByteArray(buff+1, len-1)).trimmed();
        CHECK_EXT_BREAK(buff[0] == FastaFormat::FASTA_HEADER_START_SYMBOL, os.setError(FastaFormat::tr("First line is not a FASTA header")));

        //read sequence
        if (sequenceNumber == 0 || !merge) {
            QString objName = headerLine;
            if(objName.isEmpty()){
                objName = "Sequence";
            }
            if (settingsMakeUniqueName) {
                objName = (merge) ? "Sequence" : TextUtils::variate(objName, "_", uniqueNames);
                objName.squeeze();
                memoryLocker.tryAcquire(2*objName.size());
                CHECK_OP_BREAK(os);
                uniqueNames.insert(objName);
            }
            seqImporter.startSequence(os, dbiRef, folder, objName, false);
            CHECK_OP_BREAK(os);

            sequenceRef = GObjectReference(io->getURL().getURLString(), objName, GObjectTypes::SEQUENCE);
        }
        if (sequenceNumber >= 1 && merge) {
            seqImporter.addDefaultSymbolsBlock(gapSize, os);
            sequenceStart += gapSize;
            CHECK_OP_BREAK(os);
        }
        int sequenceLen = 0;
        while (!os.isCoR()) {
            do {
                len = io->readLine(buff, DocumentFormat::READ_BUFF_SIZE);
                CHECK_EXT(!io->hasError(), os.setError(io->errorString()), );
            } while (len <= 0 && !io->isEof());
            CHECK_EXT(!io->hasError(), os.setError(io->errorString()), );

            if (len <= 0 && io->isEof()) {
                break;
            }
            CHECK_EXT(!io->hasError(), os.setError(io->errorString()), );

            buff[len] = 0;

            if(buff[0] != fastaCommentStartChar && buff[0] != FastaFormat::FASTA_HEADER_START_SYMBOL){
                len = TextUtils::remove(buff, len, TextUtils::WHITES);
                if(len > 0){
                    seqImporter.addBlock(buff, len, os);
                    sequenceLen += len;
                }
            }else if( buff[0] == FastaFormat::FASTA_HEADER_START_SYMBOL){
                headerReaded = true;
                break;
            }

            CHECK_OP_BREAK(os);
            os.setProgress(io->getProgress());
        }

        if (merge) {
            memoryLocker.tryAcquire(headerLine.size());
            CHECK_OP_BREAK(os);
            headers.append(headerLine);
            mergedMapping.append(U2Region(sequenceStart, sequenceLen));
        } else {
            if (objectsCountLimit > 0 && objects.size() >= objectsCountLimit) {
                os.setError(FastaFormat::tr("File \"%1\" contains too many sequences to be displayed. "
                    "However, you can process these data using instruments from the menu <i>Tools -> NGS data analysis</i> "
                    "or pipelines built with Workflow Designer.")
                    .arg(io->getURL().getURLString()));
                break;
            }
            memoryLocker.tryAcquire(800);
            CHECK_OP_BREAK(os);
            U2Sequence seq = seqImporter.finalizeSequenceAndValidate(os);
            if (os.hasError() && os.getError() == U2SequenceImporter::EMPTY_SEQUENCE_ERROR) {
                os.setError("");
                emptySeqNames << headerLine;
                continue;
            }
            sequenceRef.entityRef = U2EntityRef(dbiRef, seq.id);

            //TODO parse header
            U2StringAttribute attr(seq.id, DNAInfo::FASTA_HDR, headerLine);
            con.dbi->getAttributeDbi()->createStringAttribute(attr, os);
            CHECK_OP_BREAK(os);

            objects << new U2SequenceObject(seq.visualName, U2EntityRef(dbiRef, seq.id));
            CHECK_OP_BREAK(os);

            U1AnnotationUtils::addAnnotations(objects, seqImporter.getCaseAnnotations(), sequenceRef, NULL, fs);
        }
        sequenceStart += sequenceLen;
        sequenceNumber++;
        ioLog.trace(QString("Sequence #%1 is processed").arg(sequenceNumber));
    }

    CHECK_OP_EXT(os, qDeleteAll(objects); objects.clear(), );
    CHECK_EXT(!objects.isEmpty() || merge, os.setError(Document::tr("Document is empty.")), );
    SAFE_POINT(headers.size() == mergedMapping.size(), "headers <-> regions mapping failed!", );
    ioLog.trace("All sequences are processed");

    if (!emptySeqNames.isEmpty()) {
        QString warningMessage;
        warningMessage.append(FastaFormat::tr("Loaded sequences: %1.\n").arg(sequenceNumber));
        warningMessage.append(FastaFormat::tr("Skipped sequences: %1.\n").arg(emptySeqNames.size()));
        warningMessage.append(FastaFormat::tr("The following sequences are empty:\n%1").arg(emptySeqNames.join(",\n")));
        os.addWarning(warningMessage);
    }

    if (!merge) {
        return;
    }

    U2Sequence seq = seqImporter.finalizeSequenceAndValidate(os);
    CHECK_OP(os, );
    sequenceRef.entityRef = U2EntityRef(dbiRef, seq.id);

    U1AnnotationUtils::addAnnotations(objects, seqImporter.getCaseAnnotations(), sequenceRef, NULL, fs);
    objects << new U2SequenceObject(seq.visualName, U2EntityRef(dbiRef, seq.id));
    objects << DocumentFormatUtils::addAnnotationsForMergedU2Sequence( sequenceRef, dbiRef, headers, mergedMapping, fs );
    if (headers.size() > 1) {
        writeLockReason = QObject::tr("Document sequences were merged");
    }
}
// ------------ Messages
static inline QString msgStartFailed(const QString &binary, QStringList arguments)
{
    arguments.push_front(binary);
    return ExternalQtEditor::tr("Unable to start \"%1\"").arg(arguments.join(QLatin1Char(' ')));
}
LocalListingNetworkReply::LocalListingNetworkReply(QObject *parent, const QNetworkRequest &request) : QNetworkReply(parent),
	m_offset(0)
{
	setRequest(request);

	open(QIODevice::ReadOnly | QIODevice::Unbuffered);

	QFile file(QLatin1String(":/files/listing.html"));
	file.open(QIODevice::ReadOnly | QIODevice::Text);

	QTextStream stream(&file);
	stream.setCodec("UTF-8");

	QDir directory(request.url().toLocalFile());
	const QFileInfoList entries = directory.entryInfoList((QDir::AllEntries | QDir::Hidden), (QDir::Name | QDir::DirsFirst));
	const QRegularExpression expression(QLatin1String("^/+"));
	QStringList navigation;

	do
	{
		navigation.prepend(QStringLiteral("<a href=\"file:///%1\">%2</a>%3").arg(directory.canonicalPath().remove(expression)).arg(directory.dirName().isEmpty() ? QString('/') : directory.dirName()).arg(directory.dirName().isEmpty() ? QString() : QString('/')));
	}
	while (directory.cdUp());

	QHash<QString, QString> variables;
	variables[QLatin1String("title")] = QFileInfo(request.url().toLocalFile()).canonicalFilePath();
	variables[QLatin1String("description")] = tr("Directory Contents");
	variables[QLatin1String("dir")] = (QGuiApplication::isLeftToRight() ? QLatin1String("ltr") : QLatin1String("rtl"));
	variables[QLatin1String("navigation")] = navigation.join(QString());
	variables[QLatin1String("header_name")] = tr("Name");
	variables[QLatin1String("header_type")] = tr("Type");
	variables[QLatin1String("header_size")] = tr("Size");
	variables[QLatin1String("header_date")] = tr("Date");
	variables[QLatin1String("body")] = QString();

	const QMimeDatabase database;

	for (int i = 0; i < entries.count(); ++i)
	{
		const QMimeType mimeType = database.mimeTypeForFile(entries.at(i).canonicalFilePath());
		QByteArray byteArray;
		QBuffer buffer(&byteArray);
		QIcon::fromTheme(mimeType.iconName(), Utils::getIcon(entries.at(i).isDir() ? QLatin1String("inode-directory") : QLatin1String("unknown"))).pixmap(16, 16).save(&buffer, "PNG");

		variables[QLatin1String("body")].append(QStringLiteral("<tr>\n<td><a href=\"file:///%1\"><img src=\"data:image/png;base64,%2\" alt=\"\"> %3</a></td>\n<td>%4</td>\n<td>%5</td>\n<td>%6</td>\n</tr>\n").arg(entries.at(i).filePath().remove(expression)).arg(QString(byteArray.toBase64())).arg(entries.at(i).fileName()).arg(mimeType.comment()).arg(entries.at(i).isDir() ? QString() : Utils::formatUnit(entries.at(i).size(), false, 2)).arg(QLocale().toString(entries.at(i).lastModified())));
	}

	QString html = stream.readAll();
	QHash<QString, QString>::iterator iterator;

	for (iterator = variables.begin(); iterator != variables.end(); ++iterator)
	{
		html.replace(QStringLiteral("{%1}").arg(iterator.key()), iterator.value());
	}

	m_content = html.toUtf8();

	setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/html; charset=UTF-8"));
	setHeader(QNetworkRequest::ContentLengthHeader, QVariant(m_content.size()));

	QTimer::singleShot(0, this, SIGNAL(readyRead()));
	QTimer::singleShot(0, this, SIGNAL(finished()));
}
Example #27
0
QString htmlRow( QStringList columns ){
	return QString("<tr>%1</tr>").arg("<td>" + columns.join("</td><td>") + "</td>" );
}
Example #28
0
/*
 * Message Puller
 */
void TelegramBot::startMessagePulling(uint timeout, uint limit, TelegramPollMessageTypes messageTypes, long offset)
{
    // remove webhook
    this->deleteWebhookResult();

    // build url params
    this->pullParams.clear();
    if(offset) this->pullParams.addQueryItem("offset", QString::number(offset));
    else if(this->updateId) this->pullParams.addQueryItem("offset", QString::number(this->updateId));
    this->pullParams.addQueryItem("limit",   QString::number(limit));
    this->pullParams.addQueryItem("timeout", QString::number(timeout));

    // allowed updates
    QStringList allowedUpdates;
    if(static_cast<int>(messageTypes) > 0) {
        if(messageTypes && TelegramPollMessageTypes::Message) allowedUpdates += "message";
        if(messageTypes && TelegramPollMessageTypes::EditedMessage) allowedUpdates += "edited_message";
        if(messageTypes && TelegramPollMessageTypes::ChannelPost) allowedUpdates += "channel_post";
        if(messageTypes && TelegramPollMessageTypes::EditedChannelPost) allowedUpdates += "edited_channel_post";
        if(messageTypes && TelegramPollMessageTypes::InlineQuery) allowedUpdates += "inline_query";
        if(messageTypes && TelegramPollMessageTypes::ChoosenInlineQuery) allowedUpdates += "chosen_inline_result";
        if(messageTypes && TelegramPollMessageTypes::CallbackQuery) allowedUpdates += "callback_query";
    }
    if(!allowedUpdates.isEmpty()) this->pullParams.addQueryItem("allowed_updates", "[\"" + allowedUpdates.join("\",\"") + "\"]");

    // start pulling
    this->pull();
}
Example #29
0
void TabletWidget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    QStringList eventInfo;

    QString typeString("Event type: ");
    switch (mType) {
    case QEvent::TabletEnterProximity:
        typeString += "QEvent::TabletEnterProximity";
        break;
    case QEvent::TabletLeaveProximity:
        typeString += "QEvent::TabletLeaveProximity";
        break;
    case QEvent::TabletMove:
        typeString += "QEvent::TabletMove";
        break;
    case QEvent::TabletPress:
        typeString += "QEvent::TabletPress";
        break;
    case QEvent::TabletRelease:
        typeString += "QEvent::TabletRelease";
        break;
    case QEvent::MouseMove:
        typeString += "QEvent::MouseMove";
        break;
    }
    eventInfo << typeString;

    eventInfo << QString("Global position: %1 %2").arg(QString::number(mGPos.x()), QString::number(mGPos.y()));
    eventInfo << QString("Local position: %1 %2").arg(QString::number(mPos.x()), QString::number(mPos.y()));
    if (mType == QEvent::TabletEnterProximity || mType == QEvent::TabletLeaveProximity
        || mType == QEvent::TabletMove || mType == QEvent::TabletPress
        || mType == QEvent::TabletRelease) {

        eventInfo << QString("Hight res global position: %1 %2").arg(QString::number(mHiResGlobalPos.x()), QString::number(mHiResGlobalPos.y()));

        QString pointerType("Pointer type: ");
        switch (mPointerType) {
        case QTabletEvent::UnknownPointer:
            pointerType += "QTabletEvent::UnknownPointer";
            break;
        case QTabletEvent::Pen:
            pointerType += "QTabletEvent::Pen";
            break;
        case QTabletEvent::Cursor:
            pointerType += "QTabletEvent::Cursor";
            break;
        case QTabletEvent::Eraser:
            pointerType += "QTabletEvent::Eraser";
            break;
        }
        eventInfo << pointerType;


        QString deviceString = "Device type: ";
        switch (mDev) {
        case QTabletEvent::NoDevice:
            deviceString += "QTabletEvent::NoDevice";
            break;
        case QTabletEvent::Puck:
            deviceString += "QTabletEvent::Puck";
            break;
        case QTabletEvent::Stylus:
            deviceString += "QTabletEvent::Stylus";
            break;
        case QTabletEvent::Airbrush:
            deviceString += "QTabletEvent::Airbrush";
            break;
        case QTabletEvent::FourDMouse:
            deviceString += "QTabletEvent::FourDMouse";
            break;
        case QTabletEvent::RotationStylus:
            deviceString += "QTabletEvent::RotationStylus";
            break;
        }
        eventInfo << deviceString;

        eventInfo << QString("Pressure: %1").arg(QString::number(mPress));
        eventInfo << QString("Tangential pressure: %1").arg(QString::number(mTangential));
        eventInfo << QString("Rotation: %1").arg(QString::number(mRot));
        eventInfo << QString("xTilt: %1").arg(QString::number(mXT));
        eventInfo << QString("yTilt: %1").arg(QString::number(mYT));
        eventInfo << QString("z: %1").arg(QString::number(mZ));

        eventInfo << QString("Unique Id: %1").arg(QString::number(mUnique));
    }

    painter.drawText(rect(), eventInfo.join("\n"));
}
Example #30
0
void CDlgBulkRegister::SaveValueData( QStringList &lstDuplication, QStringList& lstTotalSql )
{
    int nRows = ui->tabRecord->rowCount( );
    QStringList lstSql;
    QString strTrue = "1";
    QString strFalse = "0";
    QString strQuotation = "'";
    bool bChecked = false;
    QComboBox* pCB = NULL;
    QString strText = "";
    QStringList lstExist;
    QStringList lstCardNo;

    for ( int nRow = 0; nRow < nRows; nRow++ ) {
        lstSql.clear( );
        strText = ui->tabRecord->item( nRow, 0 )->text( );

        CLogicInterface::GetInterface( )->ExistCardNumber(strText, lstExist );
        if ( 0 < lstExist.count( ) ) {
            lstDuplication << lstExist;
            continue;
        }

        QList< QTableWidgetItem* > lstItems = tabWidget->findItems( strText, Qt::MatchFixedString );
        if ( 0 < lstItems.count( ) ) {
            lstDuplication << strText;
            continue;
        }

        tabWidget->insertRow( 0 );
        lstCardNo << "'" + strText + "'";

        for ( int nCol = 0; nCol < ui->tabRecord->columnCount( ); nCol++ ) {
            switch ( nCol ) {
                case 0 :
                case 5 :
                case 7 :
                case 8 :
                case 9 :
                    strText = ui->tabRecord->item( nRow, nCol )->text( );
                    lstSql  << ( strQuotation + strText + strQuotation );
                    AddItem( strText, 0, nCol, tabWidget );
                    break;

                case 3 :
                case 4 :
                case 6 :
                    pCB = ( QComboBox* ) ui->tabRecord->cellWidget( nRow, nCol );
                    strText = pCB->currentText( );
                    lstSql << ( strQuotation + strText + strQuotation );
                    AddItem( strText, 0, nCol, tabWidget );
                    break;

                case 1 :
                case 2 :
                    bChecked = Qt::Checked == ui->tabRecord->item( nRow, nCol )->checkState( );
                    lstSql << ( bChecked ? strTrue : strFalse );
                    AddCheckBoxItem( 0, nCol, tabWidget, bChecked );
                    break;
            }
        }

        lstTotalSql << ( "(" + lstSql.join( "," ) + " )" );
    }

    emit BroadcastCardNo( lstCardNo );
}