Example #1
0
Morphos::Morphos (QString mo)
{
    // éclater en sous-chaînes
    if (!mo.isEmpty ()) mo = mo.simplified ();
    if (mo.isEmpty ())
    {
        graphie = "";
        return;
    }

    elements = mo.split (QRegExp ("\\W+"));
    QStringList eclats = elements;
    QStringList gr;
    QString el;
    foreach (el, eclats)
       if (k.contains (el)) 
          {
              gr << el;
              eclats.replace(eclats.indexOf (el), "");
          }
    foreach (el, eclats)
       if (g.contains (el))
          {
              gr << el;
              eclats.replace(eclats.indexOf (el), "");
          }
    foreach (el, eclats)
       if (n.contains (el))
          {
              gr << el;
              eclats.replace(eclats.indexOf (el), "");
          }
    foreach (el, eclats)
       if (d.contains (el)) 
          {
              gr << el;
              eclats.replace(eclats.indexOf (el), "");
          }
    foreach (el, eclats)
       if (p.contains (el)) 
          {
              gr << el;
              eclats.replace(eclats.indexOf (el), "");
          }
    foreach (el, eclats)
       if (t.contains (el)) 
          {
              gr << el;
              eclats.replace(eclats.indexOf (el), "");
          }
    foreach (el, eclats)
       if (m.contains (el))
          {
              gr << el;
              eclats.replace(eclats.indexOf (el), "");
          }
    foreach (el, eclats)
       if (v.contains (el)) 
          {
              gr << el;
              eclats.replace(eclats.indexOf (el), "");
          }
    graphie = gr.join (" ").simplified ();
}
Example #2
0
/** Check if a process with a given name is running
 *  @param names list of names to check
 *  @return list of detected processes.
 */
QStringList Utils::findRunningProcess(QStringList names)
{
    QStringList processlist;
    QStringList found;
#if defined(Q_OS_WIN32)
    HANDLE hdl;
    PROCESSENTRY32 entry;
    bool result;

    hdl = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if(hdl == INVALID_HANDLE_VALUE) {
        qDebug() << "[Utils] CreateToolhelp32Snapshot failed.";
        return found;
    }
    entry.dwSize = sizeof(PROCESSENTRY32);
    entry.szExeFile[0] = '\0';
    if(!Process32First(hdl, &entry)) {
        qDebug() << "[Utils] Process32First failed.";
        return found;
    }

    processlist.append(QString::fromWCharArray(entry.szExeFile));
    do {
        entry.dwSize = sizeof(PROCESSENTRY32);
        entry.szExeFile[0] = '\0';
        result = Process32Next(hdl, &entry);
        if(result) {
            processlist.append(QString::fromWCharArray(entry.szExeFile));
        }
    } while(result);
    CloseHandle(hdl);
#endif
#if defined(Q_OS_MACX)
    ProcessSerialNumber psn = { 0, kNoProcess };
    OSErr err;
    do {
        pid_t pid;
        err = GetNextProcess(&psn);
        err = GetProcessPID(&psn, &pid);
        if(err == noErr) {
            char buf[32] = {0};
            ProcessInfoRec info;
            memset(&info, 0, sizeof(ProcessInfoRec));
            info.processName = (unsigned char*)buf;
            info.processInfoLength = sizeof(ProcessInfoRec);
            err = GetProcessInformation(&psn, &info);
            if(err == noErr) {
                // some processes start with nonprintable characters. Skip those.
                int i;
                for(i = 0; i < 32; i++) {
                    if(isprint(buf[i])) break;
                }
                // avoid adding duplicates.
                QString process = QString::fromUtf8(&buf[i]);
                if(!processlist.contains(process)) {
                    processlist.append(process);
                }

            }
        }
    } while(err == noErr);
#endif
    // check for given names in list of processes
    for(int i = 0; i < names.size(); ++i) {
#if defined(Q_OS_WIN32)
        // the process name might be truncated. Allow the extension to be partial.
        int index = processlist.indexOf(QRegExp(names.at(i) + "(\\.(e(x(e?)?)?)?)?"));
#else
        int index = processlist.indexOf(names.at(i));
#endif
        if(index != -1) {
            found.append(processlist.at(index));
        }
    }
    qDebug() << "[Utils] Found listed processes running:" << found;
    return found;
}
Example #3
0
QStringList QgsStyleV2::findSymbols( QString qword )
{
  if ( !mCurrentDB )
  {
    QgsDebugMsg( "Sorry! Cannot open database to search" );
    return QStringList();
  }

  char *query = sqlite3_mprintf( "SELECT name FROM symbol WHERE xml LIKE '%%%q%%'", qword.toUtf8().constData() );

  sqlite3_stmt *ppStmt;
  int nErr = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, NULL );

  QStringList symbols;
  while ( nErr == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW )
  {
    symbols << QString::fromUtf8(( const char * ) sqlite3_column_text( ppStmt, 0 ) );
  }

  sqlite3_finalize( ppStmt );


  query = sqlite3_mprintf( "SELECT id FROM tag WHERE name LIKE '%%%q%%'", qword.toUtf8().constData() );
  nErr = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, NULL );

  QStringList tagids;
  while ( nErr == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW )
  {
    tagids << QString::fromUtf8(( const char * ) sqlite3_column_text( ppStmt, 0 ) );
  }

  sqlite3_finalize( ppStmt );


  QString dummy = tagids.join( ", " );

  query = sqlite3_mprintf( "SELECT symbol_id FROM tagmap WHERE tag_id IN (%q)", dummy.toUtf8().constData() );
  nErr = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, NULL );

  QStringList symbolids;
  while ( nErr == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW )
  {
    symbolids << QString::fromUtf8(( const char * ) sqlite3_column_text( ppStmt, 0 ) );
  }

  sqlite3_finalize( ppStmt );


  dummy = symbolids.join( ", " );
  query = sqlite3_mprintf( "SELECT name FROM symbol WHERE id IN (%q)", dummy.toUtf8().constData() );
  nErr = sqlite3_prepare_v2( mCurrentDB, query, -1, &ppStmt, NULL );
  while ( nErr == SQLITE_OK && sqlite3_step( ppStmt ) == SQLITE_ROW )
  {
    QString symbolName = QString::fromUtf8(( const char * ) sqlite3_column_text( ppStmt, 0 ) );
    if ( !symbols.contains( symbolName ) )
      symbols << symbolName;
  }

  sqlite3_finalize( ppStmt );

  return symbols;
}
void tst_QScriptExtensionPlugin::importSimplePlugin()
{
    QScriptEngine eng;
    QCoreApplication::addLibraryPath("plugins");

    QVERIFY(eng.importedExtensions().isEmpty());

    QStringList available = eng.availableExtensions();
    QVERIFY(available.contains("simple"));
    QVERIFY(available.contains("simple.foo"));
    QVERIFY(available.contains("simple.foo.bar"));

    QScriptValue extensionObject;
    {
        QVERIFY(eng.importExtension("simple").isUndefined());
        QCOMPARE(eng.importedExtensions().size(), 1);
        QCOMPARE(eng.importedExtensions().at(0), QString::fromLatin1("simple"));
        QVERIFY(eng.availableExtensions().contains("simple"));
        QVERIFY(eng.globalObject().property("pluginKey").equals("simple"));
        QVERIFY(eng.globalObject().property("package").isObject());
        extensionObject = eng.globalObject().property("simple");
        QVERIFY(extensionObject.isObject());
        QVERIFY(extensionObject.equals(eng.globalObject().property("package")));
    }

    {
        QVERIFY(eng.importExtension("simple.foo").isUndefined());
        QCOMPARE(eng.importedExtensions().size(), 2);
        QCOMPARE(eng.importedExtensions().at(1), QString::fromLatin1("simple.foo"));
        QVERIFY(eng.availableExtensions().contains("simple.foo"));
        QVERIFY(eng.globalObject().property("pluginKey").equals("simple.foo"));
        QVERIFY(eng.globalObject().property("package").isObject());
        QVERIFY(!extensionObject.equals(eng.globalObject().property("package")));
        QVERIFY(extensionObject.equals(eng.globalObject().property("simple")));
        QVERIFY(extensionObject.property("foo").isObject());
        QVERIFY(extensionObject.property("foo").equals(eng.globalObject().property("package")));
    }

    {
        QVERIFY(eng.importExtension("simple.foo.bar").isUndefined());
        QCOMPARE(eng.importedExtensions().size(), 3);
        QCOMPARE(eng.importedExtensions().at(2), QString::fromLatin1("simple.foo.bar"));
        QVERIFY(eng.availableExtensions().contains("simple.foo.bar"));
        QVERIFY(eng.globalObject().property("pluginKey").equals("simple.foo.bar"));
        QVERIFY(eng.globalObject().property("package").isObject());
        QVERIFY(!extensionObject.equals(eng.globalObject().property("package")));
        QVERIFY(extensionObject.equals(eng.globalObject().property("simple")));
        QVERIFY(extensionObject.property("foo").property("bar").isObject());
        QVERIFY(extensionObject.property("foo").property("bar").equals(eng.globalObject().property("package")));
    }

    // Extensions can't be imported multiple times.
    eng.globalObject().setProperty("pluginKey", QScriptValue());
    QVERIFY(eng.importExtension("simple").isUndefined());
    QCOMPARE(eng.importedExtensions().size(), 3);
    QVERIFY(!eng.globalObject().property("pluginKey").isValid());

    QVERIFY(eng.importExtension("simple.foo").isUndefined());
    QCOMPARE(eng.importedExtensions().size(), 3);
    QVERIFY(!eng.globalObject().property("pluginKey").isValid());

    QVERIFY(eng.importExtension("simple.foo.bar").isUndefined());
    QCOMPARE(eng.importedExtensions().size(), 3);
    QVERIFY(!eng.globalObject().property("pluginKey").isValid());
}
/**
 * Write log and parameter values to the table for the case of multiple fits.
 * @param table :: [input, output] Table to write to
 * @param paramsByLabel :: [input] Map of <label name, <workspace name,
 * <parameter, value>>>
 * @param paramsToDisplay :: [input] List of parameters to display in table
 */
void MuonAnalysisResultTableCreator::writeDataForMultipleFits(
    ITableWorkspace_sptr &table,
    const QMap<QString, WSParameterList> &paramsByLabel,
    const QStringList &paramsToDisplay) const {
  assert(m_multiple);
  assert(m_logValues);

  // Add data to table
  for (const auto &labelName : m_items) {
    Mantid::API::TableRow row = table->appendRow();
    size_t columnIndex(0); // Which column we are writing to

    row << labelName.toStdString();
    columnIndex++;

    // Get log values for this row and write in table
    for (const auto &log : m_logs) {
      QStringList valuesPerWorkspace;
      for (const auto &wsName : paramsByLabel[labelName].keys()) {
        const auto &logValues = m_logValues->value(wsName);
        const auto &val = logValues[log];

        auto dashIndex = val.toString().indexOf("-");
        // Special case: if log is time in sec, subtract the first start time
        if (log.endsWith(" (s)")) {
          auto seconds =
              val.toDouble() - static_cast<double>(m_firstStart_ns) * 1.e-9;
          valuesPerWorkspace.append(QString::number(seconds));
        } else if (dashIndex != 0 && dashIndex != -1) {
          valuesPerWorkspace.append(logValues[log].toString());
        } else if (MuonAnalysisHelper::isNumber(val.toString()) &&
                   !log.endsWith(" (text)")) {

          valuesPerWorkspace.append(QString::number(val.toDouble()));

        } else {
          valuesPerWorkspace.append(logValues[log].toString());
        }
      }

      // Range of values - use string comparison as works for numbers too
      // Why not use std::minmax_element? To avoid MSVC warning: QT bug 41092
      // (https://bugreports.qt.io/browse/QTBUG-41092)
      valuesPerWorkspace.sort();

      auto dashIndex =
          valuesPerWorkspace.front().toStdString().find_first_of("-");
      if (dashIndex != std::string::npos && dashIndex != 0) {
        std::ostringstream oss;
        auto dad = valuesPerWorkspace.front().toStdString();
        oss << valuesPerWorkspace.front().toStdString();
        row << oss.str();

      } else {
        if (MuonAnalysisHelper::isNumber(valuesPerWorkspace.front())) {
          const auto &min = valuesPerWorkspace.front().toDouble();
          const auto &max = valuesPerWorkspace.back().toDouble();
          if (min == max) {
            row << min;
          } else {
            std::ostringstream oss;
            oss << valuesPerWorkspace.front().toStdString() << "-"
                << valuesPerWorkspace.back().toStdString();
            row << oss.str();
          }
        } else {
          const auto &front = valuesPerWorkspace.front().toStdString();
          const auto &back = valuesPerWorkspace.back().toStdString();
          if (front == back) {
            row << front;
          } else {
            std::ostringstream oss;
            oss << valuesPerWorkspace[0].toStdString();

            for (int k = 1; k < valuesPerWorkspace.size(); k++) {
              oss << ", " << valuesPerWorkspace[k].toStdString();
              row << oss.str();
            }
          }
        }
      }
      columnIndex++;
    }

    // Parse column name - could be param name or f[n].param
    const auto parseColumnName =
        [&paramsToDisplay](
            const std::string &columnName) -> std::pair<int, std::string> {
      if (paramsToDisplay.contains(QString::fromStdString(columnName))) {
        return {0, columnName};
      } else {
        // column name is f[n].param
        size_t pos = columnName.find_first_of('.');
        if (pos != std::string::npos) {
          try {
            const auto &paramName = columnName.substr(pos + 1);
            const auto wsIndex = std::stoi(columnName.substr(1, pos));
            return {wsIndex, paramName};
          } catch (const std::exception &ex) {
            throw std::runtime_error("Failed to parse column name " +
                                     columnName + ": " + ex.what());
          }
        } else {
          throw std::runtime_error("Failed to parse column name " + columnName);
        }
      }
    };

    // Add param values
    const auto &params = paramsByLabel[labelName];
    while (columnIndex < table->columnCount()) {
      const auto &parsedColName =
          parseColumnName(table->getColumn(columnIndex)->name());
      const QString wsName = params.keys().at(parsedColName.first);
      const QString &paramName = QString::fromStdString(parsedColName.second);
      row << params[wsName].value(paramName);
      columnIndex++;
    }
  }
}
Example #6
0
InviteWidget::InviteWidget(QStringList items,
                           QString gd, QWidget *parent)
    : THWidgetBase(parent)
{
    setAttribute(Qt::WA_DeleteOnClose);
    setFixedSize(250, 180);
    setTitleBarWidth(250);
    setWindowFlags(Qt::FramelessWindowHint | Qt::Tool);
    setWindowModality(Qt::ApplicationModal);
    bar->setBarButtons(HappyTitleBar::MinButtonHint);
    bar->setBarButtons(HappyTitleBar::MaxButtonHint);
    bar->setExtraButtonVisible(false);
    bar->setBarIcon(":res/happy.png");
    bar->setBarContent(cn("邀请成员列表"));
    connect(bar, &HappyTitleBar::signalClose, this, [=] () {
            this->close();
    });
    members = items;
    gdm = gd;
    QLabel *lab = new QLabel(cn("选择邀请对象(未筛选)"));
    lab->setFixedWidth(120);
    lab->setStyleSheet(QStringLiteral("font-family:微软雅黑;font:12px;color:white;"));
    QPushButton *pb = new QPushButton(cn("筛选"), this);
    pb->setFixedWidth(50);
    pb->setCheckable(true);
    QHBoxLayout *h1 = new QHBoxLayout();
    h1->setContentsMargins(0, 0, 0, 0);
    h1->addStretch(1);
    h1->addWidget(lab, 0, Qt::AlignCenter);
    h1->addWidget(pb, 0, Qt::AlignCenter);
    h1->addStretch(1);
    CheckList *list = new CheckList(this);
    QPushButton *confrim = new QPushButton(cn("确认"), this);
    confrim->setFixedWidth(50);
    QVBoxLayout *v = new QVBoxLayout(this);
    v->setContentsMargins(10, 35, 10, 15);
    v->addLayout(h1, 1);
    v->addWidget(list, 5);
    v->addWidget(confrim, 1, Qt::AlignCenter);

    QFile file;
    file.setFileName(":res/css/button2.css");
    if (file.open(QIODevice::ReadOnly))
    {
        QByteArray ba = file.readAll();
        pb->setStyleSheet(QTextCodec::codecForLocale()->toUnicode(ba));
        confrim->setStyleSheet(QTextCodec::codecForLocale()->toUnicode(ba));
    }
    file.close();
    file.setFileName(":res/css/list2.css");
    if (file.open(QIODevice::ReadOnly))
    {
        QByteArray ba = file.readAll();
        list->setStyleSheet(QTextCodec::codecForLocale()->toUnicode(ba));
    }
    file.close();

    // load data
    ConfigureData *conf = ConfigureData::getInstance();
    updateColor(conf->getColorIni("color1"), conf->getColorIni("color2"));
    list->setmyuid(conf->getUuid());

    connect(pb, &QPushButton::toggled,
            this, [=] (bool b) {
        QString str = cn("选择邀请对象(%1)");
        if (b)
        {
            QStringList selectList;
            QStringList items = gdm.split(";");
            for (QString str : members)
            {
                QStringList temp = str.split(":");
                if (temp.size() == 2)
                {
                    if (!items.contains(temp.last()))
                    {
                        selectList << str;
                    }
                }
            }
            list->addCheckItems(selectList);
            str = str.arg(cn("筛选"));
        }
        else
        {
            list->addCheckItems(members);
            str = str.arg(cn("未筛选"));
        }
        lab->setText(str);
    });
    connect(confrim, &QPushButton::clicked,
            this, [=] () {
        QString uids = list->checkedids();
        QStringList lst = uids.split(";");
        if (lst.size() <= 1)
        {
            MsgBox::ShowMsgBox(cn("提示"),
                               cn("没有选择"),
                               cn("确定"));
                return;
        }
        emit confrimInvite(lst);
        this->close();
    });

    list->addCheckItems(items);
}
Example #7
0
  QDomDocument createTransactionDocument( QgsServerInterface* serverIface, const QString& version,
                                          const QgsServerRequest& request )
  {
    Q_UNUSED( version );

    QDomDocument doc;

    QgsWfsProjectParser* configParser = getConfigParser( serverIface );
#ifdef HAVE_SERVER_PYTHON_PLUGINS
    QgsAccessControl* accessControl = serverIface->accessControls();
#endif
    const QString requestBody = request.getParameter( QStringLiteral( "REQUEST_BODY" ) );

    QString errorMsg;
    if ( !doc.setContent( requestBody, true, &errorMsg ) )
    {
      throw QgsRequestNotWellFormedException( errorMsg );
    }

    QDomElement docElem = doc.documentElement();
    QDomNodeList docChildNodes = docElem.childNodes();

    // Re-organize the transaction document
    QDomDocument mDoc;
    QDomElement mDocElem = mDoc.createElement( QStringLiteral( "myTransactionDocument" ) );
    mDocElem.setAttribute( QStringLiteral( "xmlns" ), QGS_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:wfs" ), WFS_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:gml" ), GML_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:ogc" ), OGC_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:qgs" ), QGS_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) );
    mDoc.appendChild( mDocElem );

    QDomElement actionElem;
    QString actionName;
    QDomElement typeNameElem;
    QString typeName;

    for ( int i = docChildNodes.count(); 0 < i; --i )
    {
      actionElem = docChildNodes.at( i - 1 ).toElement();
      actionName = actionElem.localName();

      if ( actionName == QLatin1String( "Insert" ) )
      {
        QDomElement featureElem = actionElem.firstChild().toElement();
        typeName = featureElem.localName();
      }
      else if ( actionName == QLatin1String( "Update" ) )
      {
        typeName = actionElem.attribute( QStringLiteral( "typeName" ) );
      }
      else if ( actionName == QLatin1String( "Delete" ) )
      {
        typeName = actionElem.attribute( QStringLiteral( "typeName" ) );
      }

      if ( typeName.contains( QLatin1String( ":" ) ) )
        typeName = typeName.section( QStringLiteral( ":" ), 1, 1 );

      QDomNodeList typeNameList = mDocElem.elementsByTagName( typeName );
      if ( typeNameList.count() == 0 )
      {
        typeNameElem = mDoc.createElement( typeName );
        mDocElem.appendChild( typeNameElem );
      }
      else
        typeNameElem = typeNameList.at( 0 ).toElement();

      typeNameElem.appendChild( actionElem );
    }

    // It's time to make the transaction
    // Create the response document
    QDomDocument resp;
    //wfs:WFS_TransactionRespone element
    QDomElement respElem = resp.createElement( QStringLiteral( "WFS_TransactionResponse" )/*wfs:WFS_TransactionResponse*/ );
    respElem.setAttribute( QStringLiteral( "xmlns" ), WFS_NAMESPACE );
    respElem.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) );
    respElem.setAttribute( QStringLiteral( "xsi:schemaLocation" ), WFS_NAMESPACE + " http://schemas.opengis.net/wfs/1.0.0/wfs.xsd" );
    respElem.setAttribute( QStringLiteral( "xmlns:ogc" ), OGC_NAMESPACE );
    respElem.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0.0" ) );
    resp.appendChild( respElem );

    // Store the created feature id for WFS
    QStringList insertResults;
    // Get the WFS layers id
    QStringList wfsLayersId = configParser->wfsLayers();;

    QList<QgsMapLayer*> layerList;
    QgsMapLayer* currentLayer = nullptr;

    // Loop through the layer transaction elements
    docChildNodes = mDocElem.childNodes();
    for ( int i = 0; i < docChildNodes.count(); ++i )
    {
      // Get the vector layer
      typeNameElem = docChildNodes.at( i ).toElement();
      typeName = typeNameElem.tagName();

      layerList = configParser->mapLayerFromTypeName( typeName );
      // Could be empty!
      if ( layerList.count() > 0 )
      {
        currentLayer = layerList.at( 0 );
      }
      else
      {
        throw QgsRequestNotWellFormedException( QStringLiteral( "Wrong TypeName: %1" ).arg( typeName ) );
      }

      QgsVectorLayer* layer = qobject_cast<QgsVectorLayer*>( currentLayer );
      // it's a vectorlayer and defined by the administrator as a WFS layer
      if ( layer && wfsLayersId.contains( layer->id() ) )
      {
#ifdef HAVE_SERVER_PYTHON_PLUGINS
        if ( actionName == QLatin1String( "Insert" ) )
        {
          if ( !accessControl->layerInsertPermission( layer ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature insert permission denied" ) );
          }
        }
        else if ( actionName == QLatin1String( "Update" ) )
        {
          if ( !accessControl->layerUpdatePermission( layer ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature update permission denied" ) );
          }
        }
        else if ( actionName == QLatin1String( "Delete" ) )
        {
          if ( !accessControl->layerDeletePermission( layer ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature delete permission denied" ) );
          }
        }
#endif

        // Get the provider and it's capabilities
        QgsVectorDataProvider* provider = layer->dataProvider();
        if ( !provider )
        {
          continue;
        }

        int cap = provider->capabilities();

        // Start the update transaction
        layer->startEditing();
        if (( cap & QgsVectorDataProvider::ChangeAttributeValues ) && ( cap & QgsVectorDataProvider::ChangeGeometries ) )
        {
          // Loop through the update elements for this layer
          QDomNodeList upNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, QStringLiteral( "Update" ) );
          for ( int j = 0; j < upNodeList.count(); ++j )
          {
            if ( !configParser->wfstUpdateLayers().contains( layer->id() ) )
            {
              //no wfs permissions to do updates
              QString errorMsg = "No permissions to do WFS updates on layer '" + layer->name() + "'";
              QgsMessageLog::logMessage( errorMsg, QStringLiteral( "Server" ), QgsMessageLog::CRITICAL );
              addTransactionResult( resp, respElem, QStringLiteral( "FAILED" ), QStringLiteral( "Update" ), errorMsg );
              return resp;
            }

            actionElem = upNodeList.at( j ).toElement();

            // Get the Feature Ids for this filter on the layer
            QDomElement filterElem = actionElem.elementsByTagName( QStringLiteral( "Filter" ) ).at( 0 ).toElement();
            QgsFeatureIds fids = getFeatureIdsFromFilter( filterElem, layer );

            // Loop through the property elements
            // Store properties and the geometry element
            QDomNodeList propertyNodeList = actionElem.elementsByTagName( QStringLiteral( "Property" ) );
            QMap<QString, QString> propertyMap;
            QDomElement propertyElem;
            QDomElement nameElem;
            QDomElement valueElem;
            QDomElement geometryElem;

            for ( int l = 0; l < propertyNodeList.count(); ++l )
            {
              propertyElem = propertyNodeList.at( l ).toElement();
              nameElem = propertyElem.elementsByTagName( QStringLiteral( "Name" ) ).at( 0 ).toElement();
              valueElem = propertyElem.elementsByTagName( QStringLiteral( "Value" ) ).at( 0 ).toElement();
              if ( nameElem.text() != QLatin1String( "geometry" ) )
              {
                propertyMap.insert( nameElem.text(), valueElem.text() );
              }
              else
              {
                geometryElem = valueElem;
              }
            }

            // Update the features
            QgsFields fields = provider->fields();
            QMap<QString, int> fieldMap = provider->fieldNameMap();
            QMap<QString, int>::const_iterator fieldMapIt;
            QString fieldName;
            bool conversionSuccess;

            QgsFeatureIds::const_iterator fidIt = fids.constBegin();
            for ( ; fidIt != fids.constEnd(); ++fidIt )
            {
#ifdef HAVE_SERVER_PYTHON_PLUGINS
              QgsFeatureIterator fit = layer->getFeatures( QgsFeatureRequest( *fidIt ) );
              QgsFeature feature;
              while ( fit.nextFeature( feature ) )
              {
                if ( !accessControl->allowToEdit( layer, feature ) )
                {
                  throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
                }
              }
#endif

              QMap< QString, QString >::const_iterator it = propertyMap.constBegin();
              for ( ; it != propertyMap.constEnd(); ++it )
              {
                fieldName = it.key();
                fieldMapIt = fieldMap.find( fieldName );
                if ( fieldMapIt == fieldMap.constEnd() )
                {
                  continue;
                }
                QgsField field = fields.at( fieldMapIt.value() );
                if ( field.type() == 2 )
                  layer->changeAttributeValue( *fidIt, fieldMapIt.value(), it.value().toInt( &conversionSuccess ) );
                else if ( field.type() == 6 )
                  layer->changeAttributeValue( *fidIt, fieldMapIt.value(), it.value().toDouble( &conversionSuccess ) );
                else
                  layer->changeAttributeValue( *fidIt, fieldMapIt.value(), it.value() );
              }

              if ( !geometryElem.isNull() )
              {
                QgsGeometry g = QgsOgcUtils::geometryFromGML( geometryElem );
                if ( !layer->changeGeometry( *fidIt, g ) )
                {
                  throw QgsRequestNotWellFormedException( QStringLiteral( "Error in change geometry" ) );
                }
              }

#ifdef HAVE_SERVER_PYTHON_PLUGINS
              fit = layer->getFeatures( QgsFeatureRequest( *fidIt ) );
              while ( fit.nextFeature( feature ) )
              {
                if ( !accessControl->allowToEdit( layer, feature ) )
                {
                  layer->rollBack();
                  throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
                }
              }
#endif
            }
          }
        }
        // Commit the changes of the update elements
        if ( !layer->commitChanges() )
        {
          addTransactionResult( resp, respElem, QStringLiteral( "PARTIAL" ), QStringLiteral( "Update" ), layer->commitErrors().join( QStringLiteral( "\n  " ) ) );
          return resp;
        }
        // Start the delete transaction
        layer->startEditing();
        if (( cap & QgsVectorDataProvider::DeleteFeatures ) )
        {
          // Loop through the delete elements
          QDomNodeList delNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, QStringLiteral( "Delete" ) );
          for ( int j = 0; j < delNodeList.count(); ++j )
          {
            if ( !configParser->wfstDeleteLayers().contains( layer->id() ) )
            {
              //no wfs permissions to do updates
              QString errorMsg = "No permissions to do WFS deletes on layer '" + layer->name() + "'";
              QgsMessageLog::logMessage( errorMsg, QStringLiteral( "Server" ), QgsMessageLog::CRITICAL );
              addTransactionResult( resp, respElem, QStringLiteral( "FAILED" ), QStringLiteral( "Delete" ), errorMsg );
              return resp;
            }

            actionElem = delNodeList.at( j ).toElement();
            QDomElement filterElem = actionElem.firstChild().toElement();
            // Get Feature Ids for the Filter element
            QgsFeatureIds fids = getFeatureIdsFromFilter( filterElem, layer );

#ifdef HAVE_SERVER_PYTHON_PLUGINS
            QgsFeatureIds::const_iterator fidIt = fids.constBegin();
            for ( ; fidIt != fids.constEnd(); ++fidIt )
            {
              QgsFeatureIterator fit = layer->getFeatures( QgsFeatureRequest( *fidIt ) );
              QgsFeature feature;
              while ( fit.nextFeature( feature ) )
              {
                if ( !accessControl->allowToEdit( layer, feature ) )
                {
                  throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
                }
              }
            }
#endif

            layer->selectByIds( fids );
            layer->deleteSelectedFeatures();
          }
        }
        // Commit the changes of the delete elements
        if ( !layer->commitChanges() )
        {
          addTransactionResult( resp, respElem, QStringLiteral( "PARTIAL" ), QStringLiteral( "Delete" ), layer->commitErrors().join( QStringLiteral( "\n  " ) ) );
          return resp;
        }

        // Store the inserted features
        QgsFeatureList inFeatList;
        if ( cap & QgsVectorDataProvider::AddFeatures )
        {
          // Get Layer Field Information
          QgsFields fields = provider->fields();
          QMap<QString, int> fieldMap = provider->fieldNameMap();
          QMap<QString, int>::const_iterator fieldMapIt;

          // Loop through the insert elements
          QDomNodeList inNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, QStringLiteral( "Insert" ) );
          for ( int j = 0; j < inNodeList.count(); ++j )
          {
            if ( !configParser->wfstInsertLayers().contains( layer->id() ) )
            {
              //no wfs permissions to do updates
              QString errorMsg = "No permissions to do WFS inserts on layer '" + layer->name() + "'";
              QgsMessageLog::logMessage( errorMsg, QStringLiteral( "Server" ), QgsMessageLog::CRITICAL );
              addTransactionResult( resp, respElem, QStringLiteral( "FAILED" ), QStringLiteral( "Insert" ), errorMsg );
              return resp;
            }

            actionElem = inNodeList.at( j ).toElement();
            // Loop through the feature element
            QDomNodeList featNodes = actionElem.childNodes();
            for ( int l = 0; l < featNodes.count(); l++ )
            {
              // Add the feature to the layer
              // and store it to put it's Feature Id in the response
              inFeatList << QgsFeature( fields );

              // Create feature for this layer
              QDomElement featureElem = featNodes.at( l ).toElement();

              QDomNode currentAttributeChild = featureElem.firstChild();

              while ( !currentAttributeChild.isNull() )
              {
                QDomElement currentAttributeElement = currentAttributeChild.toElement();
                QString attrName = currentAttributeElement.localName();

                if ( attrName != QLatin1String( "boundedBy" ) )
                {
                  if ( attrName != QLatin1String( "geometry" ) ) //a normal attribute
                  {
                    fieldMapIt = fieldMap.find( attrName );
                    if ( fieldMapIt == fieldMap.constEnd() )
                    {
                      continue;
                    }
                    QgsField field = fields.at( fieldMapIt.value() );
                    QString attrValue = currentAttributeElement.text();
                    int attrType = field.type();
                    QgsMessageLog::logMessage( QStringLiteral( "attr: name=%1 idx=%2 value=%3" ).arg( attrName ).arg( fieldMapIt.value() ).arg( attrValue ) );
                    if ( attrType == QVariant::Int )
                      inFeatList.last().setAttribute( fieldMapIt.value(), attrValue.toInt() );
                    else if ( attrType == QVariant::Double )
                      inFeatList.last().setAttribute( fieldMapIt.value(), attrValue.toDouble() );
                    else
                      inFeatList.last().setAttribute( fieldMapIt.value(), attrValue );
                  }
                  else //a geometry attribute
                  {
                    QgsGeometry g = QgsOgcUtils::geometryFromGML( currentAttributeElement );
                    inFeatList.last().setGeometry( g );
                  }
                }
                currentAttributeChild = currentAttributeChild.nextSibling();
              }
            }
          }
        }
#ifdef HAVE_SERVER_PYTHON_PLUGINS
        QgsFeatureList::iterator featureIt = inFeatList.begin();
        while ( featureIt != inFeatList.end() )
        {
          if ( !accessControl->allowToEdit( layer, *featureIt ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
          }
          featureIt++;
        }
#endif

        // add the features
        if ( !provider->addFeatures( inFeatList ) )
        {
          addTransactionResult( resp, respElem, QStringLiteral( "Partial" ), QStringLiteral( "Insert" ), layer->commitErrors().join( QStringLiteral( "\n  " ) ) );
          if ( provider->hasErrors() )
          {
            provider->clearErrors();
          }
          return resp;
        }
        // Get the Feature Ids of the inserted feature
        for ( int j = 0; j < inFeatList.size(); j++ )
        {
          insertResults << typeName + "." + QString::number( inFeatList[j].id() );
        }
      }
    }

    // Put the Feature Ids of the inserted feature
    if ( !insertResults.isEmpty() )
    {
      Q_FOREACH ( const QString &fidStr, insertResults )
      {
        QDomElement irElem = doc.createElement( QStringLiteral( "InsertResult" ) );
        QDomElement fiElem = doc.createElement( QStringLiteral( "ogc:FeatureId" ) );
        fiElem.setAttribute( QStringLiteral( "fid" ), fidStr );
        irElem.appendChild( fiElem );
        respElem.appendChild( irElem );
      }
Example #8
0
QQuickTransition *QQuickStateGroupPrivate::findTransition(const QString &from, const QString &to)
{
    QQuickTransition *highest = 0;
    int score = 0;
    bool reversed = false;
    bool done = false;

    for (int ii = 0; !done && ii < transitions.count(); ++ii) {
        QQuickTransition *t = transitions.at(ii);
        if (!t->enabled())
            continue;
        for (int ii = 0; ii < 2; ++ii)
        {
            if (ii && (!t->reversible() ||
                       (t->fromState() == QLatin1String("*") &&
                        t->toState() == QLatin1String("*"))))
                break;
            QStringList fromState;
            QStringList toState;

            fromState = t->fromState().split(QLatin1Char(','));
            for (int jj = 0; jj < fromState.count(); ++jj)
                fromState[jj] = fromState.at(jj).trimmed();
            toState = t->toState().split(QLatin1Char(','));
            for (int jj = 0; jj < toState.count(); ++jj)
                toState[jj] = toState.at(jj).trimmed();
            if (ii == 1)
                qSwap(fromState, toState);
            int tScore = 0;
            if (fromState.contains(from))
                tScore += 2;
            else if (fromState.contains(QLatin1String("*")))
                tScore += 1;
            else
                continue;

            if (toState.contains(to))
                tScore += 2;
            else if (toState.contains(QLatin1String("*")))
                tScore += 1;
            else
                continue;

            if (ii == 1)
                reversed = true;
            else
                reversed = false;

            if (tScore == 4) {
                highest = t;
                done = true;
                break;
            } else if (tScore > score) {
                score = tScore;
                highest = t;
            }
        }
    }

    if (highest)
        highest->setReversed(reversed);

    return highest;
}
/*!
    Returns the list of valid keys, i.e. the keys this factory can
    create styles for.

    \sa create()
*/
QStringList QStyleFactory::keys()
{
#if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
    QStringList list = loader()->keys();
#else
    QStringList list;
#endif
#ifndef QT_NO_STYLE_WINDOWS
    if (!list.contains(QLatin1String("Windows")))
        list << QLatin1String("Windows");
#endif
#ifndef QT_NO_STYLE_WINDOWSCE
    if (!list.contains(QLatin1String("WindowsCE")))
        list << QLatin1String("WindowsCE");
#endif
#ifndef QT_NO_STYLE_WINDOWSMOBILE
    if (!list.contains(QLatin1String("WindowsMobile")))
        list << QLatin1String("WindowsMobile");
#endif
#ifndef QT_NO_STYLE_WINDOWSXP
    if (!list.contains(QLatin1String("WindowsXP")) &&
        (QSysInfo::WindowsVersion >= QSysInfo::WV_XP && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based))
        list << QLatin1String("WindowsXP");
#endif
#ifndef QT_NO_STYLE_WINDOWSVISTA
    if (!list.contains(QLatin1String("WindowsVista")) &&
        (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based))
        list << QLatin1String("WindowsVista");
#endif
#ifndef QT_NO_STYLE_MOTIF
    if (!list.contains(QLatin1String("Motif")))
        list << QLatin1String("Motif");
#endif
#ifndef QT_NO_STYLE_CDE
    if (!list.contains(QLatin1String("CDE")))
        list << QLatin1String("CDE");
#endif
#ifndef QT_NO_STYLE_S60
    if (!list.contains(QLatin1String("S60")))
        list << QLatin1String("S60");
#endif
#ifndef QT_NO_STYLE_PLASTIQUE
    if (!list.contains(QLatin1String("Plastique")))
        list << QLatin1String("Plastique");
#endif
#ifndef QT_NO_STYLE_GTK
    if (!list.contains(QLatin1String("GTK+")))
        list << QLatin1String("GTK+");
#endif
#ifndef QT_NO_STYLE_CLEANLOOKS
    if (!list.contains(QLatin1String("Cleanlooks")))
        list << QLatin1String("Cleanlooks");
#endif
#ifndef QT_NO_STYLE_MAC
    QString mstyle = QLatin1String("Macintosh");
# ifdef Q_WS_MAC
    mstyle += QLatin1String(" (aqua)");
# endif
    if (!list.contains(mstyle))
        list << mstyle;
#endif
    return list;
}
Example #10
0
bool QLinuxFbScreen::connect(const QString &displaySpec)
{
    d_ptr->displaySpec = displaySpec;

    const QStringList args = displaySpec.split(QLatin1Char(':'));

    if (args.contains(QLatin1String("nographicsmodeswitch")))
        d_ptr->doGraphicsMode = false;

#ifdef QT_QWS_DEPTH_GENERIC
    if (args.contains(QLatin1String("genericcolors")))
        d_ptr->doGenericColors = true;
#endif

    QRegExp ttyRegExp(QLatin1String("tty=(.*)"));
    if (args.indexOf(ttyRegExp) != -1)
        d_ptr->ttyDevice = ttyRegExp.cap(1);

#if Q_BYTE_ORDER == Q_BIG_ENDIAN
#ifndef QT_QWS_FRAMEBUFFER_LITTLE_ENDIAN
    if (args.contains(QLatin1String("littleendian")))
#endif
        QScreen::setFrameBufferLittleEndian(true);
#endif

    // Check for explicitly specified device
    const int len = 8; // "/dev/fbx"
    int m = displaySpec.indexOf(QLatin1String("/dev/fb"));

    QString dev;
    if (m > 0)
        dev = displaySpec.mid(m, len);
    else
        dev = QLatin1String("/dev/fb0");

    if (access(dev.toLatin1().constData(), R_OK|W_OK) == 0)
        d_ptr->fd = open(dev.toLatin1().constData(), O_RDWR);
    if (d_ptr->fd == -1) {
        if (QApplication::type() == QApplication::GuiServer) {
            perror("QScreenLinuxFb::connect");
            qCritical("Error opening framebuffer device %s", qPrintable(dev));
            return false;
        }
        if (access(dev.toLatin1().constData(), R_OK) == 0)
            d_ptr->fd = open(dev.toLatin1().constData(), O_RDONLY);
    }

    fb_fix_screeninfo finfo;
    fb_var_screeninfo vinfo;
    //#######################
    // Shut up Valgrind
    memset(&vinfo, 0, sizeof(vinfo));
    memset(&finfo, 0, sizeof(finfo));
    //#######################

    /* Get fixed screen information */
    if (d_ptr->fd != -1 && ioctl(d_ptr->fd, FBIOGET_FSCREENINFO, &finfo)) {
        perror("QLinuxFbScreen::connect");
        qWarning("Error reading fixed information");
        return false;
    }

    if (finfo.type == FB_TYPE_VGA_PLANES) {
        qWarning("VGA16 video mode not supported");
        return false;
    }

    /* Get variable screen information */
    if (d_ptr->fd != -1 && ioctl(d_ptr->fd, FBIOGET_VSCREENINFO, &vinfo)) {
        perror("QLinuxFbScreen::connect");
        qWarning("Error reading variable information");
        return false;
    }

    grayscale = vinfo.grayscale;
    d = vinfo.bits_per_pixel;
    if (d == 24) {
        d = vinfo.red.length + vinfo.green.length + vinfo.blue.length;
        if (d <= 0)
            d = 24; // reset if color component lengths are not reported
    } else if (d == 16) {
        d = vinfo.red.length + vinfo.green.length + vinfo.blue.length;
        if (d <= 0)
            d = 16;
    }
    lstep = finfo.line_length;

    int xoff = vinfo.xoffset;
    int yoff = vinfo.yoffset;
    const char* qwssize;
    if((qwssize=::getenv("QWS_SIZE")) && sscanf(qwssize,"%dx%d",&w,&h)==2) {
        if (d_ptr->fd != -1) {
            if ((uint)w > vinfo.xres) w = vinfo.xres;
            if ((uint)h > vinfo.yres) h = vinfo.yres;
        }
        dw=w;
        dh=h;
        int xxoff, yyoff;
        if (sscanf(qwssize, "%*dx%*d+%d+%d", &xxoff, &yyoff) == 2) {
            if (xxoff < 0 || xxoff + w > vinfo.xres)
                xxoff = vinfo.xres - w;
            if (yyoff < 0 || yyoff + h > vinfo.yres)
                yyoff = vinfo.yres - h;
            xoff += xxoff;
            yoff += yyoff;
        } else {
            xoff += (vinfo.xres - w)/2;
            yoff += (vinfo.yres - h)/2;
        }
    } else {
        dw=w=vinfo.xres;
        dh=h=vinfo.yres;
    }

    if (w == 0 || h == 0) {
        qWarning("QScreenLinuxFb::connect(): Unable to find screen geometry, "
                 "will use 320x240.");
        dw = w = 320;
        dh = h = 240;
    }

    setPixelFormat(vinfo);

    // Handle display physical size spec.
    QStringList displayArgs = displaySpec.split(QLatin1Char(':'));
    QRegExp mmWidthRx(QLatin1String("mmWidth=?(\\d+)"));
    int dimIdxW = displayArgs.indexOf(mmWidthRx);
    QRegExp mmHeightRx(QLatin1String("mmHeight=?(\\d+)"));
    int dimIdxH = displayArgs.indexOf(mmHeightRx);
    if (dimIdxW >= 0) {
        mmWidthRx.exactMatch(displayArgs.at(dimIdxW));
        physWidth = mmWidthRx.cap(1).toInt();
        if (dimIdxH < 0)
            physHeight = dh*physWidth/dw;
    }
    if (dimIdxH >= 0) {
        mmHeightRx.exactMatch(displayArgs.at(dimIdxH));
        physHeight = mmHeightRx.cap(1).toInt();
        if (dimIdxW < 0)
            physWidth = dw*physHeight/dh;
    }
    if (dimIdxW < 0 && dimIdxH < 0) {
        if (vinfo.width != 0 && vinfo.height != 0
            && vinfo.width != UINT_MAX && vinfo.height != UINT_MAX) {
            physWidth = vinfo.width;
            physHeight = vinfo.height;
        } else {
            const int dpi = 72;
            physWidth = qRound(dw * 25.4 / dpi);
            physHeight = qRound(dh * 25.4 / dpi);
        }
    }

    dataoffset = yoff * lstep + xoff * d / 8;
    //qDebug("Using %dx%dx%d screen",w,h,d);

    /* Figure out the size of the screen in bytes */
    size = h * lstep;

    mapsize = finfo.smem_len;

    data = (unsigned char *)-1;
    if (d_ptr->fd != -1)
        data = (unsigned char *)mmap(0, mapsize, PROT_READ | PROT_WRITE,
                                     MAP_SHARED, d_ptr->fd, 0);

    if ((long)data == -1) {
        if (QApplication::type() == QApplication::GuiServer) {
            perror("QLinuxFbScreen::connect");
            qWarning("Error: failed to map framebuffer device to memory.");
            return false;
        }
        data = 0;
    } else {
        data += dataoffset;
    }

    canaccel = useOffscreen();
    if(canaccel)
        setupOffScreen();

    // Now read in palette
    if((vinfo.bits_per_pixel==8) || (vinfo.bits_per_pixel==4)) {
        screencols= (vinfo.bits_per_pixel==8) ? 256 : 16;
        int loopc;
        fb_cmap startcmap;
        startcmap.start=0;
        startcmap.len=screencols;
        startcmap.red=(unsigned short int *)
                 malloc(sizeof(unsigned short int)*screencols);
        startcmap.green=(unsigned short int *)
                   malloc(sizeof(unsigned short int)*screencols);
        startcmap.blue=(unsigned short int *)
                  malloc(sizeof(unsigned short int)*screencols);
        startcmap.transp=(unsigned short int *)
                    malloc(sizeof(unsigned short int)*screencols);
        if (d_ptr->fd == -1 || ioctl(d_ptr->fd, FBIOGETCMAP, &startcmap)) {
            perror("QLinuxFbScreen::connect");
            qWarning("Error reading palette from framebuffer, using default palette");
            createPalette(startcmap, vinfo, finfo);
        }
        int bits_used = 0;
        for(loopc=0;loopc<screencols;loopc++) {
            screenclut[loopc]=qRgb(startcmap.red[loopc] >> 8,
                                   startcmap.green[loopc] >> 8,
                                   startcmap.blue[loopc] >> 8);
            bits_used |= startcmap.red[loopc]
                         | startcmap.green[loopc]
                         | startcmap.blue[loopc];
        }
        // WORKAROUND: Some framebuffer drivers only return 8 bit
        // color values, so we need to not bit shift them..
        if ((bits_used & 0x00ff) && !(bits_used & 0xff00)) {
            for(loopc=0;loopc<screencols;loopc++) {
                screenclut[loopc] = qRgb(startcmap.red[loopc],
                                         startcmap.green[loopc],
                                         startcmap.blue[loopc]);
            }
            qWarning("8 bits cmap returned due to faulty FB driver, colors corrected");
        }
        free(startcmap.red);
        free(startcmap.green);
        free(startcmap.blue);
        free(startcmap.transp);
    } else {
Example #11
0
const std::tuple<MapFVTables, MapOCRanges> dXorg::parseOcTable() {
    MapFVTables tables;
    MapOCRanges ocRanges;

    QStringList sl = getValueFromSysFsFile(driverFiles.sysFs.pp_od_clk_voltage).remove(' ')
            .replace(QRegularExpression(":|MHz|mV", QRegularExpression::CaseInsensitiveOption), "|").split('\n');

    // OD_VDDC_CURVE only in Vega20+
    bool vega20Mode = sl.contains(QString(OD_VDDC_CURVE).append('|'));

    for (auto i = 0; i < sl.length(); ++i) {

        if (vega20Mode) {
            if (sl.at(i).contains(OD_SCLK)) {
                QStringList stateMin = sl[++i].split("|", QString::SkipEmptyParts);
                QStringList stateMax = sl[++i].split("|", QString::SkipEmptyParts);
                ocRanges.insert(OD_SCLK, OCRange(stateMin[1].toUInt(), stateMax[1].toUInt()));
                continue;
            }

            if (sl.at(i).contains(OD_MCLK)) {
                QStringList stateMax = sl[++i].split("|", QString::SkipEmptyParts);
                ocRanges.insert(OD_MCLK, OCRange(0, stateMax[1].toUInt()));
                continue;
            }
        }

        QString tableKey;
        for (; i < sl.length(); ++i) {
            auto tableItems = sl[i].split("|", QString::SkipEmptyParts);

            if (tableItems.length() == 1) {

                if (tableItems[0] == OD_RANGE) {
                    for (++i; i < sl.length(); ++i) {

                        auto state = sl[i].split("|", QString::SkipEmptyParts);
                        if (state.length() == 1)
                            break;

                        ocRanges.insert(state[0], OCRange(state[1].toUInt(), state[2].toUInt()));
                    }
                } else
                    tableKey = tableItems[0]; // next table key

            } else {

                FVTable fvt;
                for (; i < sl.length(); ++i) {
                    auto state = sl[i].split("|", QString::SkipEmptyParts);

                    if (state.length() == 1) {
                        --i; // go back to next table start
                        break;
                    }

                    fvt.insert(state[0].toUInt(), FreqVoltPair(state[1].toUInt(), state[2].toUInt()));
                }

                tables.insert(tableKey, fvt);
            }
        }
    }

    return std::make_tuple(tables, ocRanges);
}
QStringList Attribute::listValuesFromNode(const QDomElement &m_node)
{
    QStringList result;
    if (m_references.size() == 0) {
        // Parse the content of the attribute
        QDomElement content = m_node.firstChildElement();
        if ((content.tagName() == "choice") && (m_name != "style:text-emphasize")) {
            QDomElement valueChild = content.firstChildElement();
            do {
                if (valueChild.tagName() == "value") {
                    result << valueChild.text();
                } else if (valueChild.tagName() == "ref") {
                    m_references << valueChild.attribute("name");
                } else if (valueChild.tagName() == "list") {
                    // Parse that sublist
                    if (valueChild.childNodes().length() != 1) {
                        kFatal() << "Unrecognized list element in " << m_name;
                    }
                    QDomElement subElement = valueChild.firstChildElement();
                    if (subElement.nodeName() == "oneOrMore") {
                        // Build a list of each sub item
                        QStringList allowedValues;
                        QDomElement subChoices = subElement.firstChildElement();
                        if (subChoices.nodeName() != "choice") {
                            kFatal() << "Unrecognized oneOrMore element in " << m_name;
                        }
                        QDomElement subValueChild = subChoices.firstChildElement();
                        do {
                            if (subValueChild.nodeName() == "value") {
                                allowedValues << subValueChild.text();
                            } else {
                                kFatal() << "Unrecognized oneOrMore element in " << m_name;
                            }
                            subValueChild = subValueChild.nextSiblingElement();
                        } while (!subValueChild.isNull());
                        QStringList mergedAllowedValues;
                        while (mergedAllowedValues.length() != (pow((double) allowedValues.length(), allowedValues.length()))) {
                            foreach (QString baseValue, allowedValues) {
                                if (!mergedAllowedValues.contains(baseValue))
                                    mergedAllowedValues << baseValue;
                                foreach (QString knownValue, mergedAllowedValues) {
                                    if ((knownValue == baseValue) || (knownValue.contains(baseValue + ' ')) || (knownValue.contains(' ' + baseValue))) {
                                        continue;
                                    }
                                    QString builtValue = knownValue + ' ' + baseValue;
                                    if (!mergedAllowedValues.contains(builtValue))
                                        mergedAllowedValues << builtValue;
                                }
                            }
                        }
                        foreach (QString allowedValue, mergedAllowedValues) {
                            QStringList equivalenceList;
                            equivalenceList << allowedValue;
                            
                            QStringList currentList = allowedValue.split(' ');
                            currentList.sort();
                            
                            foreach (QString otherAllowedValue, mergedAllowedValues) {
                                if (otherAllowedValue == allowedValue)
                                    continue;
                                
                                QStringList otherList = otherAllowedValue.split(' ');
                                otherList.sort();
                                if (otherList == currentList)
                                    equivalenceList << otherAllowedValue;
                            }
                            equivalenceList.sort();
                            if (!m_equivalences.contains(equivalenceList))
                                m_equivalences << equivalenceList;
                        }
                        result << mergedAllowedValues;
                    }
                } else {
Example #13
0
QStringList KStandardDirs::resourceDirs(const char *type) const
{
    QStringList *candidates = dircache.find(type);

    if(!candidates)
    { // filling cache
        if(strcmp(type, "socket") == 0)
            const_cast< KStandardDirs * >(this)->createSpecialResource(type);
        else if(strcmp(type, "tmp") == 0)
            const_cast< KStandardDirs * >(this)->createSpecialResource(type);
        else if(strcmp(type, "cache") == 0)
            const_cast< KStandardDirs * >(this)->createSpecialResource(type);

        QDir testdir;

        candidates = new QStringList();
        QStringList *dirs;

        bool restrictionActive = false;
        if(d && d->restrictionsActive)
        {
            if(d->dataRestrictionActive)
                restrictionActive = true;
            else if(d->restrictions["all"])
                restrictionActive = true;
            else if(d->restrictions[type])
                restrictionActive = true;
            d->dataRestrictionActive = false; // Reset
        }

        dirs = relatives.find(type);
        if(dirs)
        {
            bool local = true;
            const QStringList *prefixList = 0;
            if(strncmp(type, "xdgdata-", 8) == 0)
                prefixList = &(d->xdgdata_prefixes);
            else if(strncmp(type, "xdgconf-", 8) == 0)
                prefixList = &(d->xdgconf_prefixes);
            else
                prefixList = &prefixes;

            for(QStringList::ConstIterator pit = prefixList->begin(); pit != prefixList->end(); ++pit)
            {
                for(QStringList::ConstIterator it = dirs->begin(); it != dirs->end(); ++it)
                {
                    QString path = realPath(*pit + *it);
                    testdir.setPath(path);
                    if(local && restrictionActive)
                        continue;
                    if((local || testdir.exists()) && !candidates->contains(path))
                        candidates->append(path);
                }
                local = false;
            }
        }
        dirs = absolutes.find(type);
        if(dirs)
            for(QStringList::ConstIterator it = dirs->begin(); it != dirs->end(); ++it)
            {
                testdir.setPath(*it);
                if(testdir.exists())
                {
                    QString filename = realPath(*it);
                    if(!candidates->contains(filename))
                        candidates->append(filename);
                }
            }
        dircache.insert(type, candidates);
    }

#if 0
    kdDebug() << "found dirs for resource " << type << ":" << endl;
    for (QStringList::ConstIterator pit = candidates->begin();
	 pit != candidates->end();
	 pit++)
    {
	fprintf(stderr, "%s\n", (*pit).latin1());
    }
#endif


    return *candidates;
}
Example #14
0
static void lookupDirectory(const QString &path, const QString &relPart, const QRegExp &regexp, QStringList &list, QStringList &relList,
                            bool recursive, bool unique)
{
    QString pattern = regexp.pattern();
    if(recursive || pattern.contains('?') || pattern.contains('*'))
    {
        if(path.isEmpty()) // for sanity
            return;
        // We look for a set of files.
        DIR *dp = opendir(QFile::encodeName(path));
        if(!dp)
            return;

        assert(path.at(path.length() - 1) == '/');

        struct dirent *ep;
        KDE_struct_stat buff;

        QString _dot(".");
        QString _dotdot("..");

        while((ep = readdir(dp)) != 0L)
        {
            QString fn(QFile::decodeName(ep->d_name));
            if(fn == _dot || fn == _dotdot || fn.at(fn.length() - 1).latin1() == '~')
                continue;

            if(!recursive && !regexp.exactMatch(fn))
                continue; // No match

            QString pathfn = path + fn;
            if(KDE_stat(QFile::encodeName(pathfn), &buff) != 0)
            {
                kdDebug() << "Error stat'ing " << pathfn << " : " << perror << endl;
                continue; // Couldn't stat (e.g. no read permissions)
            }
            if(recursive)
            {
                if(S_ISDIR(buff.st_mode))
                {
                    lookupDirectory(pathfn + '/', relPart + fn + '/', regexp, list, relList, recursive, unique);
                }
                if(!regexp.exactMatch(fn))
                    continue; // No match
            }
            if(S_ISREG(buff.st_mode))
            {
                if(!unique || !relList.contains(relPart + fn))
                {
                    list.append(pathfn);
                    relList.append(relPart + fn);
                }
            }
        }
        closedir(dp);
    }
    else
    {
        // We look for a single file.
        QString fn = pattern;
        QString pathfn = path + fn;
        KDE_struct_stat buff;
        if(KDE_stat(QFile::encodeName(pathfn), &buff) != 0)
            return; // File not found
        if(S_ISREG(buff.st_mode))
        {
            if(!unique || !relList.contains(relPart + fn))
            {
                list.append(pathfn);
                relList.append(relPart + fn);
            }
        }
    }
}
Example #15
0
void PICComponent::slotUpdateFileList()
{
	QStringList preFileList = KTechlab::self()->recentFiles();
	
	QStringList fileList;
	 
	if ( ProjectInfo * info = ProjectManager::self()->currentProject() )
	{
		const KUrl::List urls = info->childOutputURLs( ProjectItem::AllTypes, ProjectItem::ProgramOutput );
		KUrl::List::const_iterator urlsEnd = urls.end();
		for ( KUrl::List::const_iterator it = urls.begin(); it != urlsEnd; ++it )
			fileList << (*it).path();
	}
	
	const QStringList::iterator end = preFileList.end();
	for ( QStringList::iterator it = preFileList.begin(); it != end; ++it )
	{
		QString file = KUrl(*it).path();
		if ( (file.endsWith(".flowcode") || file.endsWith(".asm") || file.endsWith(".cod") || file.endsWith(".basic") || file.endsWith(".microbe") ) && !fileList.contains(file) ) {
			fileList.append(file);
		}
	}
	
	QString fileName = dataString("program");
	
	property("program")->setAllowed(fileList);
	property("program")->setValue( fileName.isEmpty() ? _def_PICComponent_fileName : fileName );
}
Example #16
0
static void loadIndexFiles(Config& config)
{
    QDocDatabase* qdb = QDocDatabase::qdocDB();
    /*
      Read some XML indexes containing definitions from other documentation sets.
     */
    QStringList indexFiles = config.getStringList(CONFIG_INDEXES);

    dependModules += config.getStringList(CONFIG_DEPENDS);

    // Allow modules and third-party application/libraries to link
    // to the Qt docs without having to explicitly pass --indexdir.
    if (!indexDirs.contains(documentationPath))
        indexDirs.append(documentationPath);

    if (dependModules.size() > 0) {
        if (indexDirs.size() > 0) {
            for (int i = 0; i < indexDirs.size(); i++) {
                if (indexDirs[i].startsWith("..")) {
                    const QString prefix(QDir(currentDir).relativeFilePath(prevCurrentDir));
                    if (!prefix.isEmpty())
                        indexDirs[i].prepend(prefix + QLatin1Char('/'));
                }
            }
            /*
              Add all subdirectories of the indexdirs as dependModules,
              when an asterisk is used in the 'depends' list.
            */
            if (dependModules.contains("*")) {
                dependModules.removeOne("*");
                for (int i = 0; i < indexDirs.size(); i++) {
                    QDir scanDir = QDir(indexDirs[i]);
                    scanDir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
                    QFileInfoList dirList = scanDir.entryInfoList();
                    for (int j = 0; j < dirList.size(); j++) {
                        if (dirList[j].fileName().toLower() != config.getString(CONFIG_PROJECT).toLower())
                            dependModules.append(dirList[j].fileName());
                    }
                }
            }
            for (int i = 0; i < dependModules.size(); i++) {
                QString indexToAdd;
                QList<QFileInfo> foundIndices;
                for (int j = 0; j < indexDirs.size(); j++) {
                    QString fileToLookFor = indexDirs[j] + QLatin1Char('/') + dependModules[i] +
                            QLatin1Char('/') + dependModules[i] + QLatin1String(".index");
                    if (QFile::exists(fileToLookFor)) {
                        QFileInfo tempFileInfo(fileToLookFor);
                        if (!foundIndices.contains(tempFileInfo))
                            foundIndices.append(tempFileInfo);
                    }
                }
                qSort(foundIndices.begin(), foundIndices.end(), creationTimeBefore);
                if (foundIndices.size() > 1) {
                    /*
                        QDoc should always use the last entry in the multimap when there are
                        multiple index files for a module, since the last modified file has the
                        highest UNIX timestamp.
                    */
                    qDebug() << "Multiple indices found for dependency:" << dependModules[i] << "\nFound:";
                    for (int k = 0; k < foundIndices.size(); k++)
                        qDebug() << foundIndices[k].absoluteFilePath();
                    qDebug() << "Using" << foundIndices[foundIndices.size() - 1].absoluteFilePath()
                            << "as index for" << dependModules[i];
                    indexToAdd = foundIndices[foundIndices.size() - 1].absoluteFilePath();
                }
                else if (foundIndices.size() == 1) {
                    indexToAdd = foundIndices[0].absoluteFilePath();
                }
                if (!indexToAdd.isEmpty() && !indexFiles.contains(indexToAdd))
                    indexFiles << indexToAdd;
            }
        }
        else {
            qDebug() << "Dependant modules specified, but no index directories or "
                     << "install directory were set."
                     << "There will probably be errors for missing links.";
        }
    }
    qdb->readIndexes(indexFiles);
}
Example #17
0
QString
Track::socialActionDescription( const QString& action, DescriptionMode mode ) const
{
    QString desc;
    QList< Tomahawk::SocialAction > socialActions = allSocialActions();

    QStringList actionSources;
    int loveTotal = 0;
    foreach ( const Tomahawk::SocialAction& sa, socialActions )
    {
        if ( sa.action == action )
        {
            if ( actionSources.contains( sa.source->friendlyName() ) )
                continue;
            actionSources << sa.source->friendlyName();
            loveTotal++;
        }
    }

    QDateTime earliestTimestamp = QDateTime::currentDateTime();
    actionSources.clear();
    int loveCounter = 0;
    foreach ( const Tomahawk::SocialAction& sa, socialActions )
    {
        if ( sa.action == action )
        {
            if ( actionSources.contains( sa.source->friendlyName() ) )
                continue;
            actionSources << sa.source->friendlyName();

            if ( ++loveCounter > 3 )
                continue;
            else if ( loveCounter > 1 )
            {
                if ( loveCounter == loveTotal )
                    desc += tr( " and " );
                else
                    desc += ", ";
            }

            if ( sa.source->isLocal() )
            {
                if ( loveCounter == 1 )
                    desc += "<b>" + tr( "You" ) + "</b>";
                else
                    desc += "<b>" + tr( "you" ) + "</b>";
            }
            else
                desc += "<b>" + sa.source->friendlyName() + "</b>";

            QDateTime saTimestamp = QDateTime::fromTime_t( sa.timestamp.toInt() );
            if ( saTimestamp < earliestTimestamp && saTimestamp.toTime_t() > 0 )
                earliestTimestamp = saTimestamp;
        }
    }
    if ( loveCounter > 0 )
    {
        if ( loveCounter > 3 )
            desc += " " + tr( "and" ) + " <b>" + tr( "%n other(s)", "", loveCounter - 3 ) + "</b>";

        if ( mode == Short )
            desc = "<b>" + tr( "%n people", "", loveCounter ) + "</b>";

         //FIXME: more action descs required
        if ( action == "Love" )
            desc += " " + tr( "loved this track" );
        else if ( action == "Inbox" )
            desc += " " + tr( "sent you this track %1" )
                    .arg( TomahawkUtils::ageToString( earliestTimestamp, true ) );
    }

    return desc;
}
Example #18
0
void Smb4KConfigPageMounting::slotAdditionalCIFSOptions()
{
#if defined (Q_OS_LINUX)
  KLineEdit *cifs_opts = findChild<KLineEdit *>("kcfg_CustomCIFSOptions");
  
  if (cifs_opts)
  {
    QString options = cifs_opts->originalText();
    
    bool ok = false;
    options = QInputDialog::getText(this, i18n("Additional CIFS Options"), 
                                    i18n("<qt>Enter the desired options as a comma separated list:</qt>"), 
                                    QLineEdit::Normal, 
                                    options,
                                    &ok);
    
    if (ok)
    {
      if(!options.trimmed().isEmpty())
      {
        // SECURITY: Only pass those arguments to mount.cifs that do not pose
        // a potential security risk and that have not already been defined.
        //
        // This is, among others, the proper fix to the security issue reported
        // by Heiner Markert (aka CVE-2014-2581).
        QStringList whitelist = whitelistedMountArguments();
        QStringList denied_args;
        QStringList list = options.split(',', QString::SkipEmptyParts);
        QMutableStringListIterator it(list);
        
        while (it.hasNext())
        {
          QString arg = it.next().section("=", 0, 0);
          
          if (!whitelist.contains(arg))
          {
            denied_args << arg;
            it.remove();
          }
          else
          {
            // Do nothing
          }
        }
        
        if (!denied_args.isEmpty())
        {
          QString msg = i18np("<qt>The following entry is going to be removed from the additional options: %2. Please read the handbook for details.</qt>", "<qt>The following %1 entries are going to be removed from the additional options: %2. Please read the handbook for details.</qt>", denied_args.size(), denied_args.join(", "));
          KMessageBox::sorry(this, msg);
        }
        else
        {
          // Do nothing
        }
        
        cifs_opts->setText(list.join(",").trimmed());
      }
      else
      {
        cifs_opts->clear();
      }
    }
    else
    {
      // Do nothing
    }
  }
  else
  {
    // Do nothing
  }
#endif
}
Example #19
0
FiffCov FiffCov::regularize(const FiffInfo& p_info, double p_fRegMag, double p_fRegGrad, double p_fRegEeg, bool p_bProj, QStringList p_exclude) const
{
    FiffCov cov(*this);

    if(p_exclude.size() == 0)
    {
        p_exclude = p_info.bads;
        for(qint32 i = 0; i < cov.bads.size(); ++i)
            if(!p_exclude.contains(cov.bads[i]))
                p_exclude << cov.bads[i];
    }

    //Allways exclude all STI channels from covariance computation
    for(int i=0; i<p_info.chs.size(); i++)
        if(p_info.chs[i].kind == FIFFV_STIM_CH)
            p_exclude << p_info.chs[i].ch_name;

    RowVectorXi sel_eeg = p_info.pick_types(false, true, false, defaultQStringList, p_exclude);
    RowVectorXi sel_mag = p_info.pick_types(QString("mag"), false, false, defaultQStringList, p_exclude);
    RowVectorXi sel_grad = p_info.pick_types(QString("grad"), false, false, defaultQStringList, p_exclude);

    QStringList info_ch_names = p_info.ch_names;
    QStringList ch_names_eeg, ch_names_mag, ch_names_grad;
    for(qint32 i = 0; i < sel_eeg.size(); ++i)
        ch_names_eeg << info_ch_names[sel_eeg(i)];
    for(qint32 i = 0; i < sel_mag.size(); ++i)
        ch_names_mag << info_ch_names[sel_mag(i)];
    for(qint32 i = 0; i < sel_grad.size(); ++i)
        ch_names_grad << info_ch_names[sel_grad(i)];

    // This actually removes bad channels from the cov, which is not backward
    // compatible, so let's leave all channels in
    FiffCov cov_good = cov.pick_channels(info_ch_names, p_exclude);
    QStringList ch_names = cov_good.names;

    std::vector<qint32> idx_eeg, idx_mag, idx_grad;
    for(qint32 i = 0; i < ch_names.size(); ++i)
    {
        if(ch_names_eeg.contains(ch_names[i]))
            idx_eeg.push_back(i);
        else if(ch_names_mag.contains(ch_names[i]))
            idx_mag.push_back(i);
        else if(ch_names_grad.contains(ch_names[i]))
            idx_grad.push_back(i);
    }

    MatrixXd C(cov_good.data);

    if((unsigned) C.rows() != idx_eeg.size() + idx_mag.size() + idx_grad.size())
        printf("Error in FiffCov::regularize: Channel dimensions do not fit.\n");//ToDo Throw

    QList<FiffProj> t_listProjs;
    if(p_bProj)
    {
        t_listProjs = p_info.projs + cov_good.projs;
        FiffProj::activate_projs(t_listProjs);
    }

    //Build regularization MAP
    QMap<QString, QPair<double, std::vector<qint32> > > regData;
    regData.insert("EEG", QPair<double, std::vector<qint32> >(p_fRegEeg, idx_eeg));
    regData.insert("MAG", QPair<double, std::vector<qint32> >(p_fRegMag, idx_mag));
    regData.insert("GRAD", QPair<double, std::vector<qint32> >(p_fRegGrad, idx_grad));

    //
    //Regularize
    //
    QMap<QString, QPair<double, std::vector<qint32> > >::Iterator it;
    for(it = regData.begin(); it != regData.end(); ++it)
    {
        QString desc(it.key());
        double reg = it.value().first;
        std::vector<qint32> idx = it.value().second;

        if(idx.size() == 0 || reg == 0.0)
            printf("\tNothing to regularize within %s data.\n", desc.toLatin1().constData());
        else
        {
            printf("\tRegularize %s: %f\n", desc.toLatin1().constData(), reg);
            MatrixXd this_C(idx.size(), idx.size());
            for(quint32 i = 0; i < idx.size(); ++i)
                for(quint32 j = 0; j < idx.size(); ++j)
                    this_C(i,j) = cov_good.data(idx[i], idx[j]);

            MatrixXd U;
            qint32 ncomp;
            if(p_bProj)
            {
                QStringList this_ch_names;
                for(quint32 k = 0; k < idx.size(); ++k)
                    this_ch_names << ch_names[idx[k]];

                MatrixXd P;
                ncomp = FiffProj::make_projector(t_listProjs, this_ch_names, P); //ToDo: Synchronize with mne-python and debug

                JacobiSVD<MatrixXd> svd(P, ComputeFullU);
                //Sort singular values and singular vectors
                VectorXd t_s = svd.singularValues();
                MatrixXd t_U = svd.matrixU();
                MNEMath::sort<double>(t_s, t_U);

                U = t_U.block(0,0, t_U.rows(), t_U.cols()-ncomp);

                if (ncomp > 0)
                {
                    printf("\tCreated an SSP operator for %s (dimension = %d).\n", desc.toLatin1().constData(), ncomp);
                    this_C = U.transpose() * (this_C * U);
                }
            }

            double sigma = this_C.diagonal().mean();
            this_C.diagonal() = this_C.diagonal().array() + reg * sigma;  // modify diag inplace
            if(p_bProj && ncomp > 0)
                this_C = U * (this_C * U.transpose());

            for(qint32 i = 0; i < this_C.rows(); ++i)
                for(qint32 j = 0; j < this_C.cols(); ++j)
                    C(idx[i],idx[j]) = this_C(i,j);
        }
    }

    // Put data back in correct locations
    RowVectorXi idx = FiffInfo::pick_channels(cov.names, info_ch_names, p_exclude);
    for(qint32 i = 0; i < idx.size(); ++i)
        for(qint32 j = 0; j < idx.size(); ++j)
            cov.data(idx[i], idx[j]) = C(i, j);

    return cov;
}
Example #20
0
bool SeekOption::identify(const QString &str) const
{
    QStringList opts;
    opts << "--seek" << "--seek-fwd" << "--seek-bwd";
    return opts.contains(str);
}
Example #21
0
File: main.cpp Project: darcyg/pi
/*----------------------------------------------------------------------
|    main
+---------------------------------------------------------------------*/
int main(int argc, char* argv[])
{
	QGuiApplication::setAttribute(Qt::AA_ShareOpenGLContexts, true);
	QGuiApplication app(argc, argv);

	// Utility.
	QStringList args = app.arguments();
	POC_Mode currentMode;
	if (args.contains("--animations"))
		currentMode = MODE_ANIMATIONS;
	else if (args.contains("--loop"))
		currentMode = MODE_LOOP;
	else if (args.contains("--seektest"))
		currentMode = MODE_SEEK;
	else if (args.contains("--multipletest"))
		currentMode = MODE_MULTIPLE;
	else if (args.contains("--multipleanimtest"))
		currentMode = MODE_MULTIPLEANIM;
	else if (args.contains("--overlaystest"))
		currentMode = MODE_OVERLAYS;
	else
		currentMode = MODE_PLAYER;

	POC_QMLUtils qmlUtils;
	POC_Uptime uptime;

	QQuickView view;

	// Set EGL to 24bit color depth.
	QSurfaceFormat curSurface = view.format();
	curSurface.setRedBufferSize(8);
	curSurface.setGreenBufferSize(8);
	curSurface.setBlueBufferSize(8);
	curSurface.setAlphaBufferSize(0);
	view.setFormat(curSurface);

	view.engine()->rootContext()->setContextProperty("utils", &qmlUtils);
	view.engine()->rootContext()->setContextProperty("uptime", &uptime);

	switch (currentMode) {
	case MODE_ANIMATIONS:
		view.setSource(QUrl(QStringLiteral("qrc:///qml/main_animations.qml")));
		break;
	case MODE_LOOP:
		view.setSource(QUrl(QStringLiteral("qrc:///qml/main_loop.qml")));
		break;
	case MODE_SEEK:
		view.setSource(QUrl(QStringLiteral("qrc:///qml/main_seektest.qml")));
		break;
	case MODE_MULTIPLE:
		view.setSource(QUrl(QStringLiteral("qrc:///qml/main_multiple.qml")));
		break;
	case MODE_OVERLAYS:
		view.setSource(QUrl(QStringLiteral("qrc:///qml/main_overlays.qml")));
		break;
	case MODE_MULTIPLEANIM:
		view.setSource(QUrl(QStringLiteral("qrc:///qml/main_multipleanim.qml")));
		break;
	default:
		view.setSource(QUrl(QStringLiteral("qrc:///qml/main.qml")));
		break;
	}

	qInstallMessageHandler(&log_handler);
	LC_QMLLogger::registerObject(view.rootContext());

	view.setResizeMode(QQuickView::SizeRootObjectToView);
#ifdef RASPBERRY
	view.showFullScreen();
#else
	view.resize(800, 400);
	view.show();
#endif // RASPBERRY
	qApp->connect(view.engine(), SIGNAL(quit()), qApp, SLOT(quit()));

	// If file path is provided from the command line, I start the player
	// immediately.
	switch (currentMode) {
	case MODE_MULTIPLEANIM:
	case MODE_LOOP: {
		QStringList list;
		for (int i = 2; i < args.size(); i++)
			list << args.at(i);
		if (list.size() < 1)
			return log_warn("No items to play.");
      if (!show_media(&view, list))
			return 1;
		break;
	}
	case MODE_PLAYER:
		if (args.size() > 1)
			if (!show_media(&view, args.at(1)))
				return 1;
		break;
	case MODE_MULTIPLE:
		break;
	default:
		if (args.size() > 2)
			if (!show_media(&view, args.at(2)))
				return 1;
		break;
	}

	return app.exec();
}
Example #22
0
int main(int argc, char *argv[])
{
  QCoreApplication app_core(argc, argv);
  QStringList arguments = QCoreApplication::arguments();
  QString programName = arguments.at(0);

  if (arguments.count() == 1) {
    qWarning() << "No args given.";
    return -1;
  }

  if ((arguments.contains("-h")) || (arguments.contains("--help"))) {
    qWarning() << "Call:";
    qWarning() << programName << "<filename>";
    return 0;
  }

  QString inputFileName;
  QString argument;

  for (int i=0; i<arguments.count(); i++) {
      argument = arguments[i];

      if (argument.startsWith('-')) {
        argument = argument.toLower();
        if (argument == "--md5")
          ;
      }
  }

  inputFileName = arguments[1];

  if (inputFileName.length() <= 0) {
    qDebug() << "No input file name given.";
    return -2;
  }

  inputFileName  = QFileInfo(inputFileName).absoluteFilePath();
  qDebug() << "File:" << inputFileName;

  QFile file(inputFileName);
  QByteArray result, input;
  int size;

  if (! file.open(QIODevice::ReadOnly)) {
    qDebug() << "File not found.";
    return -2;
  }

  size = file.size();
  //QDataStream in(&file);
  input = file.readAll();
  file.close();

  result = QCryptographicHash::hash(input, QCryptographicHash::Md4);
  qDebug() << "MD4" << result.toHex();
  result = QCryptographicHash::hash(input, QCryptographicHash::Md5);
  qDebug() << "MD5" << result.toHex();
  result = QCryptographicHash::hash(input, QCryptographicHash::Sha1);
  qDebug() << "SHA-1" << result.toHex();

  qDebug() << "Adler-32" << Adler32::calcHash(input);
  qDebug() << "CRC32" << CRC32::calcHash(input);
  qDebug() << "SHA-1" << SHA1::calcHash(input);
  qDebug() << "SHA-256" << SHA256::calcHash(input);
  qDebug() << "SHA-512" << SHA512::calcHash(input);
  qDebug() << "MD5" << MD5::calcHash(input);
  qDebug() << "Tiger" << Tiger::calcHash(input);
  qDebug() << "Tiger2" << Tiger2::calcHash(input);

  return 0;
}
void LoadCoreWindow::initCoreList(const QStringList &extensionFilters)
{
   core_info_list_t *cores = NULL;
   QStringList horizontal_header_labels;
   QDesktopWidget *desktop = qApp->desktop();
   QRect desktopRect = desktop->availableGeometry();
   unsigned i = 0;
   int j = 0;

   horizontal_header_labels << msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_NAME);
   horizontal_header_labels << msg_hash_to_str(MENU_ENUM_LABEL_VALUE_QT_CORE_VERSION);

   core_info_get_list(&cores);

   m_table->clear();
   m_table->setColumnCount(0);
   m_table->setRowCount(0);
   m_table->setSelectionBehavior(QAbstractItemView::SelectRows);
   m_table->setSelectionMode(QAbstractItemView::SingleSelection);
   m_table->setSortingEnabled(false);
   m_table->setRowCount(cores->count);
   m_table->setColumnCount(2);
   m_table->setHorizontalHeaderLabels(horizontal_header_labels);

   for (i = 0; i < cores->count; i++)
   {
      core_info_t *core = core_info_get(cores, i);
      QTableWidgetItem *name_item = NULL;
      QTableWidgetItem *version_item = new QTableWidgetItem(core->display_version);
      QVariantHash hash;
      const char *name = core->display_name;

      if (string_is_empty(name))
         name = path_basename(core->path);

      name_item = new QTableWidgetItem(name);

      hash["path"] = core->path;
      hash["extensions"] = QString(core->supported_extensions).split("|");

      name_item->setData(Qt::UserRole, hash);
      name_item->setFlags(name_item->flags() & ~Qt::ItemIsEditable);
      version_item->setFlags(version_item->flags() & ~Qt::ItemIsEditable);

      m_table->setItem(i, CORE_NAME_COLUMN, name_item);
      m_table->setItem(i, CORE_VERSION_COLUMN, version_item);
   }

   if (!extensionFilters.isEmpty())
   {
      QVector<int> rowsToHide;

      for (j = 0; j < m_table->rowCount(); j++)
      {
         bool found = false;
         QTableWidgetItem *item = m_table->item(j, CORE_NAME_COLUMN);
         QVariantHash hash;
         QStringList extensions;
         int k = 0;

         if (!item)
            continue;

         hash = item->data(Qt::UserRole).toHash();
         extensions = hash["extensions"].toStringList();

         if (!extensions.isEmpty())
         {
            for (k = 0; k < extensions.size(); k++)
            {
               QString ext = extensions.at(k).toLower();

               if (extensionFilters.contains(ext, Qt::CaseInsensitive))
               {
                  found = true;
                  break;
               }
            }

            if (!found)
               rowsToHide.append(j);
         }
      }

      if (rowsToHide.size() != m_table->rowCount())
      {
         int i = 0;

         for (i = 0; i < rowsToHide.count() && rowsToHide.count() > 0; i++)
         {
            const int &row = rowsToHide.at(i);
            m_table->setRowHidden(row, true);
         }
      }
   }

   m_table->setSortingEnabled(true);
   m_table->resizeColumnsToContents();
   m_table->sortByColumn(0, Qt::AscendingOrder);
   m_table->selectRow(0);
   m_table->setAlternatingRowColors(true);

   resize(qMin(desktopRect.width(), contentsMargins().left() + m_table->horizontalHeader()->length() + contentsMargins().right()), height());
}
Example #24
0
static Utils::Environment msvcReadEnvironmentSetting(const QString &varsBat,
                                                     const QString &args,
                                                     const Utils::Environment &env)
{
    // Run the setup script and extract the variables
    Utils::Environment result = env;
    if (!QFileInfo(varsBat).exists())
        return result;

    const QString tempOutputFileName = QDir::tempPath() + QLatin1String("\\qtcreator-msvc-environment.txt");
    Utils::TempFileSaver saver(QDir::tempPath() + "\\XXXXXX.bat");
    QByteArray call = "call ";
    call += Utils::QtcProcess::quoteArg(varsBat).toLocal8Bit();
    if (!args.isEmpty()) {
        call += ' ';
        call += args.toLocal8Bit();
    }
    call += "\r\n";
    saver.write(call);
    const QByteArray redirect = "set > " + Utils::QtcProcess::quoteArg(
                QDir::toNativeSeparators(tempOutputFileName)).toLocal8Bit() + "\r\n";
    saver.write(redirect);
    if (!saver.finalize()) {
        qWarning("%s: %s", Q_FUNC_INFO, qPrintable(saver.errorString()));
        return result;
    }

    Utils::QtcProcess run;
    run.setEnvironment(env);
    const QString cmdPath = QString::fromLocal8Bit(qgetenv("COMSPEC"));
    // Windows SDK setup scripts require command line switches for environment expansion.
    QString cmdArguments = QLatin1String(" /E:ON /V:ON /c \"");
    cmdArguments += QDir::toNativeSeparators(saver.fileName());
    cmdArguments += QLatin1Char('"');
    run.setCommand(cmdPath, cmdArguments);
    if (debug)
        qDebug() << "msvcReadEnvironmentSetting: " << call << cmdPath << cmdArguments
                 << " Env: " << env.size();
    run.start();

    if (!run.waitForStarted()) {
        qWarning("%s: Unable to run '%s': %s", Q_FUNC_INFO, qPrintable(varsBat),
            qPrintable(run.errorString()));
        return result;
    }
    if (!run.waitForFinished()) {
        qWarning("%s: Timeout running '%s'", Q_FUNC_INFO, qPrintable(varsBat));
        Utils::SynchronousProcess::stopProcess(run);
        return result;
    }

    QFile varsFile(tempOutputFileName);
    if (!varsFile.open(QIODevice::ReadOnly|QIODevice::Text))
        return result;

    QRegExp regexp(QLatin1String("(\\w*)=(.*)"));
    while (!varsFile.atEnd()) {
        const QString line = QString::fromLocal8Bit(varsFile.readLine()).trimmed();
        if (regexp.exactMatch(line)) {
            const QString varName = regexp.cap(1);
            const QString expandedValue = winExpandDelayedEnvReferences(regexp.cap(2), env);
            if (!expandedValue.isEmpty())
                result.set(varName, expandedValue);
        }
    }
    varsFile.close();
    varsFile.remove();
    if (debug) {
        const QStringList newVars = result.toStringList();
        const QStringList oldVars = env.toStringList();
        QDebug nsp = qDebug().nospace();
        foreach (const QString &n, newVars) {
            if (!oldVars.contains(n))
                nsp << n << '\n';
        }
    }
    return result;
}
Example #25
0
QStringList Utils::mountpoints(enum MountpointsFilter type)
{
    QStringList supported;
    QStringList tempList;
#if defined(Q_OS_WIN32)
    supported << "FAT32" << "FAT16" << "FAT12" << "FAT" << "HFS";
    QFileInfoList list = QDir::drives();
    for(int i=0; i<list.size();i++)
    {
        wchar_t t[32];
        memset(t, 0, 32);
        if(GetVolumeInformationW((LPCWSTR)list.at(i).absolutePath().utf16(),
                NULL, 0, NULL, NULL, NULL, t, 32) == 0) {
            // on error empty retrieved type -- don't rely on
            // GetVolumeInformation not changing it.
            memset(t, 0, sizeof(t));
        }

        QString fstype = QString::fromWCharArray(t);
        if(type == MountpointsAll || supported.contains(fstype)) {
            tempList << list.at(i).absolutePath();
            qDebug() << "[Utils] Added:" << list.at(i).absolutePath()
                     << "type" << fstype;
        }
        else {
            qDebug() << "[Utils] Ignored:" << list.at(i).absolutePath()
                     << "type" << fstype;
        }
    }

#elif defined(Q_OS_MACX) || defined(Q_OS_OPENBSD)
    supported << "vfat" << "msdos" << "hfs";
    int num;
    struct statfs *mntinf;

    num = getmntinfo(&mntinf, MNT_WAIT);
    while(num--) {
        if(type == MountpointsAll || supported.contains(mntinf->f_fstypename)) {
            tempList << QString(mntinf->f_mntonname);
            qDebug() << "[Utils] Added:" << mntinf->f_mntonname
                     << "is" << mntinf->f_mntfromname << "type" << mntinf->f_fstypename;
        }
        else {
            qDebug() << "[Utils] Ignored:" << mntinf->f_mntonname
                     << "is" << mntinf->f_mntfromname << "type" << mntinf->f_fstypename;
        }
        mntinf++;
    }
#elif defined(Q_OS_LINUX)
    supported << "vfat" << "msdos" << "hfsplus";
    FILE *mn = setmntent("/etc/mtab", "r");
    if(!mn)
        return QStringList("");

    struct mntent *ent;
    while((ent = getmntent(mn))) {
        if(type == MountpointsAll || supported.contains(ent->mnt_type)) {
            tempList << QString(ent->mnt_dir);
            qDebug() << "[Utils] Added:" << ent->mnt_dir
                     << "is" << ent->mnt_fsname << "type" << ent->mnt_type;
        }
        else {
            qDebug() << "[Utils] Ignored:" << ent->mnt_dir
                     << "is" << ent->mnt_fsname << "type" << ent->mnt_type;
        }
    }
    endmntent(mn);

#else
#error Unknown Platform
#endif
    return tempList;
}
int PaymentechProcessor::handleResponse(const QString &presponse, const int pccardid, const QString &ptype, const double pamount, const int pcurrid, QString &pneworder, QString &preforder, int &pccpayid, ParameterList &pparams)
{
  if (DEBUG)
    qDebug("Paymentech::handleResponse(%s, %d, %s, %f, %d, %s, %d, pparams)",
	   presponse.toAscii().data(), pccardid,
	   ptype.toAscii().data(), pamount, pcurrid,
	   preforder.toAscii().data(), pccpayid);

  int returnValue = 0;

  QString r_approved;
  QString r_avs;
  QString r_code;
  QString r_cvv;
  QString r_error;
  QString r_message;
  QString r_ordernum;
  QString r_reason;     // not stored
  QString r_ref;
  QString r_shipping;
  QString r_tax;
  QString r_date;

  QString status;

  QString r_response;
  r_response = presponse.mid(26, 3).trimmed();
  int i_response = r_response.toInt();
  if ((i_response >= 100 && i_response < 200) || i_response == 704)
    r_approved = "APPROVED";
  else if((i_response >= 200 && i_response < 300 && i_response != 260) || (i_response >= 740 && i_response <= 768))
    r_approved = "ERROR"; // REJECTED
  else
    r_approved = "DECLINED";

  r_reason = r_response;

  r_message = r_response;

  r_date = presponse.mid(29, 6).trimmed();
  r_code = presponse.mid(35, 6).trimmed();
  r_avs = presponse.mid(41, 2).trimmed();
  r_ordernum = presponse.mid(4, 22).trimmed();
  r_cvv = presponse.mid(43, 1).trimmed();

  if (r_approved == "APPROVED")
  {
    _errorMsg = errorMsg(0).arg(r_code);
    if (ptype == "A")
      status = "A";	// Authorized
    else if (ptype == "V")
      status = "V";	// Voided
    else
      status = "C";	// Completed/Charged
  }
  else if (r_approved == "DECLINED")
  {
    _errorMsg = errorMsg(-92).arg(r_message);
    returnValue = -92;
    status = "D";
  }
  else if (r_approved == "ERROR")
  {
    r_error = r_message;
    _errorMsg = errorMsg(-12).arg(r_error);
    returnValue = -12;
    status = "X";
  }

  else if (r_approved.isEmpty() && ! r_message.isEmpty())
  {
    _errorMsg = errorMsg(-95).arg(r_message);
    returnValue = -95;
    status = "X";
  }

  else if (r_approved.isEmpty())
  {
    _errorMsg = errorMsg(-100).arg(r_error).arg(r_message).arg(presponse);
    returnValue = -100;
    status = "X";
  }

  QStringList validAvs;
  // TODO: is this list correct?
  validAvs << "N1" << "N2" << "  " << "IG" << "IU" << "ID" << "IA" << "IB" << "IP" << "A1" << "A3" << "A4" << "A7" << "I3" << "I4";
  _passedAvs = validAvs.contains(r_avs);

  // always use the CVV checking configured on the gateway
  QString validCvv("MPU ");
  _passedCvv = validCvv.contains(r_cvv);

  if (DEBUG)
    qDebug("Paymentech:%s _passedAvs %d\t%s _passedCvv %d",
	    r_avs.toAscii().data(), _passedAvs, 
	    r_cvv.toAscii().data(), _passedCvv);

  pparams.append("ccard_id",    pccardid);
  pparams.append("currid",      pcurrid);
  pparams.append("auth_charge", ptype);
  pparams.append("type",        ptype);
  pparams.append("reforder",    (preforder.isEmpty()) ? pneworder : preforder);
  pparams.append("status",      status);
  pparams.append("avs",         r_avs);
  pparams.append("ordernum",    pneworder);
  pparams.append("xactionid",   r_ordernum);
  pparams.append("error",       r_error);
  pparams.append("approved",    r_approved);
  pparams.append("code",        r_code);
  pparams.append("shipping",    r_shipping);
  pparams.append("tax",         r_tax);
  pparams.append("ref",         r_ref);
  pparams.append("message",     r_message);
  pparams.append("tdate",       r_date);

  pparams.append("auth", (ptype == "A"));

  if (DEBUG)
    qDebug("Paymentech:r_error.isEmpty() = %d", r_error.isEmpty());

  if (returnValue == 0)
    pparams.append("amount",   pamount);
  else
    pparams.append("amount",   0);	// no money changed hands this attempt

  if (DEBUG)
    qDebug("Paymentech::handleResponse returning %d %s",
           returnValue, errorMsg().toAscii().data());
  return returnValue;
}
void fill_computer_list()
{
	dc_iterator_t *iterator = NULL;
	dc_descriptor_t *descriptor = NULL;

	unsigned int transportMask = get_supported_transports(NULL);

	fill_supported_mobile_list();

	dc_descriptor_iterator(&iterator);
	while (dc_iterator_next(iterator, &descriptor) == DC_STATUS_SUCCESS) {
		// mask out the transports that aren't supported
		unsigned int transports = dc_descriptor_get_transports(descriptor) & transportMask;
		if (transports == 0)
			// none of the transports are available, skip
			continue;

		const char *vendor = dc_descriptor_get_vendor(descriptor);
		const char *product = dc_descriptor_get_product(descriptor);
#if defined(Q_OS_ANDROID)
		if ((transports & ~(DC_TRANSPORT_SERIAL | DC_TRANSPORT_USB | DC_TRANSPORT_USBHID)) == 0)
			// if the only available transports are serial/USB, then check against
			// the ones that we explicitly support on Android
			if (!mobileProductList.contains(vendor) || !mobileProductList[vendor].contains(product))
				continue;
#endif
		if (!vendorList.contains(vendor))
			vendorList.append(vendor);
		if (!productList[vendor].contains(product))
			productList[vendor].append(product);

		descriptorLookup[QString(vendor) + QString(product)] = descriptor;
	}
	dc_iterator_free(iterator);
	Q_FOREACH (QString vendor, vendorList)
		qSort(productList[vendor]);

#if !defined(Q_OS_ANDROID) && !defined(Q_OS_IOS)
	/* currently suppress the Uemis Zurich on Q_OS_ANDROID and Q_OS_IOS,
	 * as it is no BT device */

	/* and add the Uemis Zurich which we are handling internally
	  THIS IS A HACK as we magically have a data structure here that
	  happens to match a data structure that is internal to libdivecomputer;
	  this WILL BREAK if libdivecomputer changes the dc_descriptor struct...
	  eventually the UEMIS code needs to move into libdivecomputer, I guess */
	struct mydescriptor *mydescriptor = (struct mydescriptor *)malloc(sizeof(struct mydescriptor));
	mydescriptor->vendor = "Uemis";
	mydescriptor->product = "Zurich";
	mydescriptor->type = DC_FAMILY_NULL;
	mydescriptor->model = 0;
	mydescriptor->transports = DC_TRANSPORT_USBSTORAGE;

	if (!vendorList.contains("Uemis"))
		vendorList.append("Uemis");

	if (!productList["Uemis"].contains("Zurich"))
		productList["Uemis"].push_back("Zurich");

	descriptorLookup["UemisZurich"] = (dc_descriptor_t *)mydescriptor;
#endif

	qSort(vendorList);
}
Example #28
0
void PICComponent::initPackage( MicroInfo * microInfo )
{
	MicroPackage * microPackage = microInfo ? microInfo->package() : 0l;
	
	if ( microPackage )
	{
		m_bCreatedInitialPackage = true;
		
		//BEGIN Get pin IDs
		QStringList allPinIDs = microPackage->pinIDs();
		QStringList ioPinIDs = microPackage->pinIDs( PicPin::type_bidir | PicPin::type_input | PicPin::type_open );
	
		// Now, we make the unwanted pin ids blank, so a pin is not created for them
		const QStringList::iterator allPinIDsEnd = allPinIDs.end();
		for ( QStringList::iterator it = allPinIDs.begin(); it != allPinIDsEnd; ++it )
		{
			if ( !ioPinIDs.contains(*it) )
				*it = "";
		}
		//END Get pin IDs
	
	
		//BEGIN Remove old stuff
		// Remove old text
		TextMap textMapCopy = m_textMap;
		const TextMap::iterator textMapEnd = textMapCopy.end();
		for ( TextMap::iterator it = textMapCopy.begin(); it != textMapEnd; ++it )
			removeDisplayText(it.key());
	
		// Remove the old pins
		deletePICComponentPins();
	
		// Remove old nodes
		NodeInfoMap nodeMapCopy = m_nodeMap;
		const NodeInfoMap::iterator nodeMapEnd = nodeMapCopy.end();
		for ( NodeInfoMap::iterator it = nodeMapCopy.begin(); it != nodeMapEnd; ++it )
		{
			if ( !ioPinIDs.contains(it.key()) )
				removeNode( it.key() );
		}
	
		removeElements();
		//END Remove old stuff
	
	
	
		//BEGIN Create new stuff
		initDIPSymbol( allPinIDs, 80 );
		initDIP(allPinIDs);
	
		PicPinMap picPinMap = microPackage->pins( PicPin::type_bidir | PicPin::type_input | PicPin::type_open );
		const PicPinMap::iterator picPinMapEnd = picPinMap.end();
		for ( PicPinMap::iterator it = picPinMap.begin(); it != picPinMapEnd; ++it )
			m_picComponentPinMap[it.key()] = new PICComponentPin( this, it.value() );
		//END Create new stuff
	
	
		removeDisplayText( "no_file" );
		addDisplayText( "picid", QRect(offsetX(), offsetY()-16, width(), 16), microInfo->id() );
	}
	else
	{
		setSize( -48, -72, 96, 144 );
		removeDisplayText( "picid" );
		addDisplayText( "no_file", sizeRect(), i18n("(No\nprogram\nloaded)") );
	}
	
	
	//BEGIN Update button positions
	int leftpos = (width()-88)/2+offsetX();
	button("run")->setOriginalRect( QRect( leftpos, height()+4+offsetY(), 20, 20 ) );
	button("pause")->setOriginalRect( QRect( leftpos+23, height()+4+offsetY(), 20, 20 ) );
	button("reset")->setOriginalRect( QRect( leftpos+46, height()+4+offsetY(), 20, 20 ) );
	button("reload")->setOriginalRect( QRect( leftpos+69, height()+4+offsetY(), 20, 20 ) );
	updateAttachedPositioning();
	//END Update button positions
}
Example #29
0
/**
 *  \brief Creates MythMedia instances for sysfs removable media devices.
 *
 *   Block devices are represented as directories in sysfs with directories
 *   for each partition underneath the parent device directory.
 *
 *   This function recursively calls itself to find all partitions on a block
 *   device and creates a MythHDD instance for each partition found.  If no
 *   partitions are found and the device is a CD or DVD device a MythCDROM
 *   instance is created.  Otherwise a MythHDD instance is created for the
 *   entire block device.
 *
 *  \param dev path to sysfs block device.
 *  \param checkPartitions check for partitions on block device.
 *  \return true if MythMedia instances are created.
 */
bool MediaMonitorUnix::FindPartitions(const QString &dev, bool checkPartitions)
{
    LOG(VB_MEDIA, LOG_DEBUG, 
             LOC + ":FindPartitions(" + dev + 
             QString(",%1").arg(checkPartitions ? " true" : " false" ) + ")");
    MythMediaDevice* pDevice = NULL;

    if (checkPartitions)
    {
        // check for partitions
        QDir sysfs(dev);
        sysfs.setFilter(QDir::Dirs);

        bool found_partitions = false;
        QStringList parts = sysfs.entryList();
        for (QStringList::iterator pit = parts.begin();
             pit != parts.end(); ++pit)
        {
            if (*pit == "." || *pit == "..")
                continue;

            // skip some sysfs dirs that are _not_ sub-partitions
            if (*pit == "device" || *pit == "holders" || *pit == "queue"
                                 || *pit == "slaves"  || *pit == "subsystem"
                                 || *pit == "bdi"     || *pit == "power")
                continue;

            found_partitions |= FindPartitions(
                sysfs.absoluteFilePath(*pit), false);
        }

        // no partitions on block device, use main device
        if (!found_partitions)
            found_partitions |= FindPartitions(sysfs.absolutePath(), false);

        return found_partitions;
    }

    QString device_file = GetDeviceFile(dev);

    if (device_file.isEmpty())
        return false;

    QStringList cdroms = GetCDROMBlockDevices();

    if (cdroms.contains(dev.section('/', -1)))
    {
        // found cdrom device
            pDevice = MythCDROM::get(
                this, device_file.toAscii().constData(), false, m_AllowEject);
    }
    else
    {
        // found block or partition device
            pDevice = MythHDD::Get(
                this, device_file.toAscii().constData(), false, false);
    }

    if (AddDevice(pDevice))
        return true;

    if (pDevice)
        pDevice->deleteLater();

    return false;
}
CppToolsSettings::CppToolsSettings(QObject *parent)
    : QObject(parent)
    , d(new Internal::CppToolsSettingsPrivate)
{
    QTC_ASSERT(!m_instance, return);
    m_instance = this;

    qRegisterMetaType<CppTools::CppCodeStyleSettings>("CppTools::CppCodeStyleSettings");

    d->m_completionSettingsPage = new CompletionSettingsPage(this);
    ExtensionSystem::PluginManager::addObject(d->m_completionSettingsPage);

    connect(d->m_completionSettingsPage,
            SIGNAL(commentsSettingsChanged(CppTools::CommentsSettings)),
            this,
            SIGNAL(commentsSettingsChanged(CppTools::CommentsSettings)));

    TextEditor::TextEditorSettings *textEditorSettings = TextEditor::TextEditorSettings::instance();

    // code style factory
    TextEditor::ICodeStylePreferencesFactory *factory = new CppTools::CppCodeStylePreferencesFactory();
    textEditorSettings->registerCodeStyleFactory(factory);

    // code style pool
    TextEditor::CodeStylePool *pool = new TextEditor::CodeStylePool(factory, this);
    textEditorSettings->registerCodeStylePool(Constants::CPP_SETTINGS_ID, pool);

    // global code style settings
    d->m_globalCodeStyle = new CppCodeStylePreferences(this);
    d->m_globalCodeStyle->setDelegatingPool(pool);
    d->m_globalCodeStyle->setDisplayName(tr("Global", "Settings"));
    d->m_globalCodeStyle->setId(idKey);
    pool->addCodeStyle(d->m_globalCodeStyle);
    textEditorSettings->registerCodeStyle(CppTools::Constants::CPP_SETTINGS_ID, d->m_globalCodeStyle);

    /*
    For every language we have exactly 1 pool. The pool contains:
    1) All built-in code styles (Qt/GNU)
    2) All custom code styles (which will be added dynamically)
    3) A global code style

    If the code style gets a pool (setCodeStylePool()) it means it can behave
    like a proxy to one of the code styles from that pool
    (ICodeStylePreferences::setCurrentDelegate()).
    That's why the global code style gets a pool (it can point to any code style
    from the pool), while built-in and custom code styles don't get a pool
    (they can't point to any other code style).

    The instance of the language pool is shared. The same instance of the pool
    is used for all project code style settings and for global one.
    Project code style can point to one of built-in or custom code styles
    or to the global one as well. That's why the global code style is added
    to the pool. The proxy chain can look like:
    ProjectCodeStyle -> GlobalCodeStyle -> BuildInCodeStyle (e.g. Qt).

    With the global pool there is an exception - it gets a pool
    in which it exists itself. The case in which a code style point to itself
    is disallowed and is handled in ICodeStylePreferences::setCurrentDelegate().
    */

    // built-in settings
    // Qt style
    CppCodeStylePreferences *qtCodeStyle = new CppCodeStylePreferences();
    qtCodeStyle->setId(QLatin1String("qt"));
    qtCodeStyle->setDisplayName(tr("Qt"));
    qtCodeStyle->setReadOnly(true);
    TabSettings qtTabSettings;
    qtTabSettings.m_tabPolicy = TabSettings::SpacesOnlyTabPolicy;
    qtTabSettings.m_tabSize = 4;
    qtTabSettings.m_indentSize = 4;
    qtTabSettings.m_continuationAlignBehavior = TabSettings::ContinuationAlignWithIndent;
    qtCodeStyle->setTabSettings(qtTabSettings);
    pool->addCodeStyle(qtCodeStyle);

    // GNU style
    CppCodeStylePreferences *gnuCodeStyle = new CppCodeStylePreferences();
    gnuCodeStyle->setId(QLatin1String("gnu"));
    gnuCodeStyle->setDisplayName(tr("GNU"));
    gnuCodeStyle->setReadOnly(true);
    TabSettings gnuTabSettings;
    gnuTabSettings.m_tabPolicy = TabSettings::MixedTabPolicy;
    gnuTabSettings.m_tabSize = 8;
    gnuTabSettings.m_indentSize = 2;
    gnuTabSettings.m_continuationAlignBehavior = TabSettings::ContinuationAlignWithIndent;
    gnuCodeStyle->setTabSettings(gnuTabSettings);
    CppCodeStyleSettings gnuCodeStyleSettings;
    gnuCodeStyleSettings.indentNamespaceBody = true;
    gnuCodeStyleSettings.indentBlockBraces = true;
    gnuCodeStyleSettings.indentSwitchLabels = true;
    gnuCodeStyleSettings.indentBlocksRelativeToSwitchLabels = true;
    gnuCodeStyle->setCodeStyleSettings(gnuCodeStyleSettings);
    pool->addCodeStyle(gnuCodeStyle);

    // default delegate for global preferences
    d->m_globalCodeStyle->setCurrentDelegate(qtCodeStyle);

    pool->loadCustomCodeStyles();

    // load global settings (after built-in settings are added to the pool)
    if (QSettings *s = Core::ICore::settings()) {
        d->m_globalCodeStyle->fromSettings(CppTools::Constants::CPP_SETTINGS_ID, s);

        // legacy handling start (Qt Creator Version < 2.4)
        const bool legacyTransformed =
                    s->value(QLatin1String("CppCodeStyleSettings/LegacyTransformed"), false).toBool();

        if (!legacyTransformed) {
            // creator 2.4 didn't mark yet the transformation (first run of creator 2.4)

            // we need to transform the settings only if at least one from
            // below settings was already written - otherwise we use
            // defaults like it would be the first run of creator 2.4 without stored settings
            const QStringList groups = s->childGroups();
            const bool needTransform = groups.contains(QLatin1String("textTabPreferences")) ||
                                       groups.contains(QLatin1String("CppTabPreferences")) ||
                                       groups.contains(QLatin1String("CppCodeStyleSettings"));
            if (needTransform) {
                CppCodeStyleSettings legacyCodeStyleSettings;
                if (groups.contains(QLatin1String("CppCodeStyleSettings"))) {
                    Utils::fromSettings(QLatin1String("CppCodeStyleSettings"),
                                        QString(), s, &legacyCodeStyleSettings);
                }

                const QString currentFallback = s->value(QLatin1String("CppTabPreferences/CurrentFallback")).toString();
                TabSettings legacyTabSettings;
                if (currentFallback == QLatin1String("CppGlobal")) {
                    // no delegate, global overwritten
                    Utils::fromSettings(QLatin1String("CppTabPreferences"),
                                        QString(), s, &legacyTabSettings);
                } else {
                    // delegating to global
                    legacyTabSettings = textEditorSettings->codeStyle()->currentTabSettings();
                }

                // create custom code style out of old settings
                QVariant v;
                v.setValue(legacyCodeStyleSettings);
                TextEditor::ICodeStylePreferences *oldCreator = pool->createCodeStyle(
                         QLatin1String("legacy"), legacyTabSettings,
                         v, tr("Old Creator"));

                // change the current delegate and save
                d->m_globalCodeStyle->setCurrentDelegate(oldCreator);
                d->m_globalCodeStyle->toSettings(CppTools::Constants::CPP_SETTINGS_ID, s);
            }
            // mark old settings as transformed
            s->setValue(QLatin1String("CppCodeStyleSettings/LegacyTransformed"), true);
        }
        // legacy handling stop
    }


    // mimetypes to be handled
    textEditorSettings->registerMimeTypeForLanguageId(
                QLatin1String(Constants::C_SOURCE_MIMETYPE),
                Constants::CPP_SETTINGS_ID);
    textEditorSettings->registerMimeTypeForLanguageId(
                QLatin1String(Constants::C_HEADER_MIMETYPE),
                Constants::CPP_SETTINGS_ID);
    textEditorSettings->registerMimeTypeForLanguageId(
                QLatin1String(Constants::CPP_SOURCE_MIMETYPE),
                Constants::CPP_SETTINGS_ID);
    textEditorSettings->registerMimeTypeForLanguageId(
                QLatin1String(Constants::CPP_HEADER_MIMETYPE),
                Constants::CPP_SETTINGS_ID);
}