//@Override
 /*protected*/ /*synchronized*/ void SmlBeanTableDataModel::updateNameList()
{
 // first, remove listeners from the individual objects
 if (act->signalMastLogicList != NULL)
 {
     for (int i = 0; i < act->signalMastLogicList->size(); i++) {
         // if object has been deleted, it's not here; ignore it
         QHash<SignalMastLogic*, SignalMast*>* b = act->signalMastLogicList->at(i);
         QListIterator<SignalMastLogic*> en = b->keys();
         while (en.hasNext()) {
             SignalMastLogic* sm = en.next();
             SignalMast* dest = b->value(sm);
             //sm.removePropertyChangeListener(this);
             disconnect(sm->pcs, SIGNAL(propertyChange(PropertyChangeEvent*)), this, SLOT(propertyChange(PropertyChangeEvent*)));
             //sm.getSourceMast().removePropertyChangeListener(this);
             disconnect(sm->getSourceMast()->pcs, SIGNAL(propertyChange(PropertyChangeEvent*)), this, SLOT(propertyChange(PropertyChangeEvent*)));
             //dest.removePropertyChangeListener(this);
             disconnect(dest, SIGNAL(propertyChange(PropertyChangeEvent*)), this, SLOT(propertyChange(PropertyChangeEvent*)));
         }
     }
 }
 for (int i = 0; i < source.size(); i++) {
     QList<SignalMast*> destList = source.at(i)->getDestinationList();
     //source.at(i).addPropertyChangeListener(this);
     connect(source.at(i)->pcs, SIGNAL(propertyChange(PropertyChangeEvent*)), this, SLOT(propertyChange(PropertyChangeEvent*)));
     //source.get(i).getSourceMast().addPropertyChangeListener(this);
     connect(source.at(i)->pcs, SIGNAL(propertyChange(PropertyChangeEvent*)), this, SLOT(propertyChange(PropertyChangeEvent*)));
     for (int j = 0; j < destList.size(); j++) {
         QHash<SignalMastLogic*, SignalMast*>* hash = new QHash<SignalMastLogic*, SignalMast*>(/*1*/);
         hash->insert(source.at(i), destList.at(j));
         //destList.a(j).addPropertyChangeListener(this);
         connect(destList.at(i), SIGNAL(propertyChange(PropertyChangeEvent*)), this, SLOT(propertyChange(PropertyChangeEvent*)));
         act->signalMastLogicList->append(hash);
     }
  }
 }
double dist_pt_to_swc(const XYZ & pt, const NeuronTree * p_tree)
{
	//first find all the edge end point distances
	if (!p_tree) return -1;
	V3DLONG p_tree_sz = p_tree->listNeuron.size();

	NeuronSWC *tp1, *tp2;
	if (p_tree_sz<2)
	{
		tp1 = (NeuronSWC *)(&(p_tree->listNeuron.at(0)));
		return norm(pt - XYZ(tp1->x, tp1->y, tp1->z));
	}

	QHash<int, int> h = generate_neuron_swc_hash(p_tree); //generate a hash lookup table from a neuron swc graph

	V3DLONG i;
	double min_dist;
	bool b_first=false;
	for (i=0;i<p_tree->listNeuron.size();i++)
	{
		//first find the two ends of a line seg
		tp1 = (NeuronSWC *)(&(p_tree->listNeuron.at(i)));
		if (tp1->pn < 0 || tp1->pn >= p_tree_sz)
			continue;
		tp2 = (NeuronSWC *)(&(p_tree->listNeuron.at(h.value(tp1->pn)))); //use hash table

		//now compute the distance between the pt and the current segment
		double cur_d = dist_pt_to_line_seg(pt, XYZ(tp1->x,tp1->y,tp1->z), XYZ(tp2->x,tp2->y,tp2->z));

		//now find the min distance
		if (b_first==false) {min_dist = cur_d; b_first=true;}
		else min_dist = (min_dist>cur_d) ? cur_d : min_dist;
	}

	return min_dist;
}
示例#3
0
static QScriptValue js_label(QScriptContext *context, QScriptEngine *engine)
{
	QString label = context->argument(0).toString();
	QScriptValue ret = engine->newObject();
	if (labels.contains(label))
	{
		labeltype p = labels.value(label);
		if (p.type == AREA || p.type == POSITION)
		{
			ret.setProperty("x", map_coord(p.p1.x), QScriptValue::ReadOnly);
			ret.setProperty("y", map_coord(p.p1.y), QScriptValue::ReadOnly);
		}
		if (p.type == AREA)
		{
			ret.setProperty("x2", map_coord(p.p2.x), QScriptValue::ReadOnly);
			ret.setProperty("xy", map_coord(p.p2.y), QScriptValue::ReadOnly);
		}
		else if (p.type == OBJ_DROID)
		{
			DROID *psDroid = IdToDroid(p.id, p.player);
			if (psDroid) ret = convDroid(psDroid, engine);
		}
		else if (p.type == OBJ_STRUCTURE)
		{
			STRUCTURE *psStruct = IdToStruct(p.id, p.player);
			if (psStruct) ret = convStructure(psStruct, engine);
		}
		else if (p.type == OBJ_FEATURE)
		{
			FEATURE *psFeature = IdToFeature(p.id, p.player);
			if (psFeature) ret = convFeature(psFeature, engine);
		}
	}
	else debug(LOG_ERROR, "label %s not found!", label.toUtf8().constData());
	return ret;
}
void KStandardItemModel::changeItem(int index, KStandardItem* item)
{
    if (index < 0 || index >= count() || !item) {
        delete item;
        return;
    }

    item->m_model = this;

    QSet<QByteArray> changedRoles;

    KStandardItem* oldItem = m_items[index];
    const QHash<QByteArray, QVariant> oldData = oldItem->data();
    const QHash<QByteArray, QVariant> newData = item->data();

    // Determine which roles have been changed
    QHashIterator<QByteArray, QVariant> it(oldData);
    while (it.hasNext()) {
        it.next();
        const QByteArray role = it.key();
        const QVariant oldValue = it.value();
        if (newData.contains(role) && newData.value(role) != oldValue) {
            changedRoles.insert(role);
        }
    }

    m_indexesForItems.remove(oldItem);
    delete oldItem;
    oldItem = 0;

    m_items[index] = item;
    m_indexesForItems.insert(item, index);

    onItemChanged(index, changedRoles);
    emit itemsChanged(KItemRangeList() << KItemRange(index, 1), changedRoles);
}
示例#5
0
QByteArray convertToId(const QMetaObject *mo)
{
    QByteArray className(mo->className());
    if (!className.isEmpty())
        return convertToId(className);

    // likely a metaobject generated for an extended qml object
    if (mo->superClass()) {
        className = convertToId(mo->superClass());
        className.append("_extended");
        return className;
    }

    static QHash<const QMetaObject *, QByteArray> generatedNames;
    className = generatedNames.value(mo);
    if (!className.isEmpty())
        return className;

    std::cerr << "Found a QMetaObject without a className, generating a random name" << std::endl;
    className = QByteArray("error-unknown-name-");
    className.append(QByteArray::number(generatedNames.size()));
    generatedNames.insert(mo, className);
    return className;
}
示例#6
0
    HRESULT STDMETHODCALLTYPE DirectWriteFontFileLoader::CreateStreamFromKey(
        void const *fontFileReferenceKey,
        UINT32 fontFileReferenceKeySize,
        IDWriteFontFileStream **fontFileStream)
    {
        Q_UNUSED(fontFileReferenceKeySize);

        if (fontFileReferenceKeySize != sizeof(const void *)) {
            qWarning("DirectWriteFontFileLoader::CreateStreamFromKey: Wrong key size");
            return E_FAIL;
        }

        const void *key = *reinterpret_cast<void * const *>(fontFileReferenceKey);
        *fontFileStream = NULL;
        if (!m_fontDatas.contains(key))
            return E_FAIL;

        QByteArray fontData = m_fontDatas.value(key);
        DirectWriteFontFileStream *stream = new DirectWriteFontFileStream(fontData);
        stream->AddRef();
        *fontFileStream = stream;

        return S_OK;
    }
static bool x11EventFilter(void *message, long *result)
{
#ifdef HAVE_XDAMAGE
    XEvent *event = (XEvent *)message;

    if (event->type == xDamageEventBase + XDamageNotify) {
        XDamageNotifyEvent *xevent = (XDamageNotifyEvent *) event;

        // notify status bar
        MDeclarativeStatusBar *statusBar = damageMap.value(xevent->damage);
        if (statusBar) {
            statusBar->update();
            return true;
        }
    }
#else
    Q_UNUSED(message);
#endif

    if (oldEventFilter) {
        return oldEventFilter(message, result);
    } else
        return false;
}
static bool saveUids(const QHash<QString, int> &drugs_uids)
{
    QString content;
    content += "// /***************************************************************************\n"
               "//  *   FreeMedicalForms                                                      *\n"
               "//  *   (C) 2008-2015 by Eric MAEKER, MD                                      *\n"
               "//  *   [email protected]                                                   *\n"
               "//  *   All rights reserved.                                                  *\n"
               "//  ***************************************************************************/\n"
               "// /***************************************************************************\n"
               "//  *   Owner :  Eric MAEKER, MD <*****@*****.**>                      *\n"
               "//  ***************************************************************************/\n"
               "// /***************************************************************************\n"
               "//  * - Autogenerated file for the Portuguese drugs database                  *\n"
               "//  *    This file presents all known drugs and their                         *\n"
               "//  *    FreeDiams autogenerated UID                                          *\n"
               "//  *    !!!! The content MUST NOT be changed by hand !!!!                    *\n"
               "//  ***************************************************************************/\n"
               "// \n";
    QStringList names = drugs_uids.keys();
    qSort(names);
    foreach(const QString &drug, names) {
        content += drug + ";" + QString::number(drugs_uids.value(drug)) + "\n";
    }
示例#9
0
void SatellitesPlugin::setSettings( const QHash<QString, QVariant> &settings )
{
    RenderPlugin::setSettings( settings );

    // add default data sources
    if( !settings.contains( "dataSources" ) ) {
        QStringList dsList;
        dsList << "http://www.celestrak.com/NORAD/elements/visual.txt";
        m_settings.insert( "dataSources", dsList );
        m_settings.insert( "idList", dsList );
    }
    else {
        // HACK: KConfig can't guess the type of the settings, when we use
        // KConfigGroup::readEntry() in marble_part it returns a QString which
        // is then wrapped into a QVariant when added to the settings hash.
        // QVariant can handle the conversion for some types, like toDateTime()
        // but when calling toStringList() on a QVariant::String, it will
        // return a one element list
        if( settings.value( "dataSources" ).type() == QVariant::String ) {
            m_settings.insert( "dataSources",
                settings.value( "dataSources" ).toString().split(QLatin1Char( ',' ) ) );
        }
        if( settings.value( "idList" ).type() == QVariant::String ) {
            m_settings.insert( "idList",
                settings.value( "idList" ).toString().split(QLatin1Char( ',' ) ) );
        }
    }

    // add default user data source
    if( !settings.contains( "userDataSources" ) ) {
        QStringList udsList;
        udsList << "http://files.kde.org/marble/satellites/PlanetarySatellites.msc";
        m_settings.insert( "userDataSources", udsList );
        userDataSourceAdded( udsList[0] );
    }
    else if( settings.value( "userDataSources" ).type() == QVariant::String ) {
        // same HACK as above
        m_settings.insert( "userDataSources",
            settings.value( "userDataSources" ).toString().split(QLatin1Char( ',' ) ) );
    }

    emit settingsChanged( nameId() );
}
示例#10
0
void QGraphicsHelperGL4::bindFragDataLocation(GLuint shader, const QHash<QString, int> &outputs)
{
    Q_FOREACH (const QString &name, outputs.keys())
        m_funcs->glBindFragDataLocation(shader, outputs.value(name), name.toStdString().c_str());
}
 QString SqlRelationalTableModel::selectStatement() const
  {
      QString query;

      if (tableName().isEmpty())
          return query;

      QString tList;
      QString jList;
      QString fList;
      QString where;

      QSqlRecord rec = record();
      QStringList tables;

      // Count how many times each field name occurs in the record
      QHash<QString, int> fieldNames;
      QStringList fieldList;
      for (int i = 0; i < rec.count(); ++i) {
          SqlRelation relation = this->relation(i);

          QString name;
          if (relation.isValid())
          {
              // Count the display column name, not the original foreign key
              name = relation.displayColumn();
              if (database().driver()->isIdentifierEscaped(name, QSqlDriver::FieldName))
                  name = database().driver()->stripDelimiters(name, QSqlDriver::FieldName);

              QSqlRecord rec = database().record(relation.tableName());
              for (int i = 0; i < rec.count(); ++i) {
                  if (name.compare(rec.fieldName(i), Qt::CaseInsensitive) == 0) {
                      name = rec.fieldName(i);
                      break;
                  }
              }
          }
          else
              name = rec.fieldName(i);
          fieldNames.insert(name, fieldNames.value(name, 0) + 1);
          fieldList.append(name);
      }

      for (int i = 0; i < rec.count(); ++i) {
          SqlRelation relation = this->relation(i);

          if (relation.isValid()) {
              QString relTableAlias = QString::fromLatin1("relTblAl_%1").arg(i);
              if (!fList.isEmpty())
                  fList.append(QLatin1String(", "));
              fList.append(relationField(relTableAlias,relation.displayColumn()));

              // If there are duplicate field names they must be aliased
              if (fieldNames.value(fieldList[i]) > 1) {
                  QString relTableName = relation.tableName().section(QChar::fromLatin1('.'), -1, -1);
                  if (database().driver()->isIdentifierEscaped(relTableName, QSqlDriver::TableName))
                      relTableName = database().driver()->stripDelimiters(relTableName, QSqlDriver::TableName);
                  QString displayColumn = relation.displayColumn();
                  if (database().driver()->isIdentifierEscaped(displayColumn, QSqlDriver::FieldName))
                      displayColumn = database().driver()->stripDelimiters(displayColumn, QSqlDriver::FieldName);
                  fList.append(QString::fromLatin1(" AS %1_%2_%3").arg(relTableName).arg(displayColumn).arg(fieldNames.value(fieldList[i])));
                  fieldNames.insert(fieldList[i], fieldNames.value(fieldList[i])-1);

                 }

              // this needs fixing!! the below if is borken.
              //tables.append(relation.tableName().append(QLatin1Char(' ')).append(relTableAlias));
              //if(!where.isEmpty())
                  //where.append(QLatin1String(" AND "));

              switch(relation.getJoinKind()){
              case SqlRelation::RIGHT:
                  jList.append(QLatin1String(" RIGHT JOIN "));
                  break;
              case SqlRelation::LEFT:
                  jList.append(QLatin1String(" LEFT JOIN "));
                  break;
              case SqlRelation::OUTER:
                  jList.append(QLatin1String(" FULL OUTER JOIN "));
                  break;
              case SqlRelation::INNER:
                  jList.append(QLatin1String(" INNER JOIN "));
                  break;
              default:
                  jList.append(QLatin1String(" JOIN "));
                  break;
                  }
              jList.append(relation.tableName().append(QLatin1Char(' ')).append(relTableAlias));
              jList.append(QLatin1String(" ON "));
              jList.append(relationField(tableName(), database().driver()->escapeIdentifier(rec.fieldName(i), QSqlDriver::FieldName)));
              jList.append(QLatin1String(" = "));
              jList.append(relationField(relTableAlias, relation.indexColumn()));
          } else {
              if (!fList.isEmpty())
                  fList.append(QLatin1String(", "));
              fList.append(relationField(tableName(), database().driver()->escapeIdentifier(rec.fieldName(i), QSqlDriver::FieldName)));
          }
      }

      for(int i = 0; i < rec.count(); ++i)
      {
          SqlRelation relation = this->relation(i);
          if(relation.isValid()){
              fList.append(QLatin1String(", "));
              fList.append(relationField(QString::fromLatin1("relTblAl_%1").arg(i),relation.indexColumn()));
              fList.append(QString::fromLatin1(" AS %1_%2").arg(relation.tableName().section(QChar::fromLatin1('.'), -1, -1)).arg(relation.indexColumn()));
          }
      }

      if(!additionalField.isEmpty())
          fList.append(additionalField+" ");

      if (!tables.isEmpty())
          tList.append(tables.join(QLatin1String(", ")));
      if (fList.isEmpty())
          return query;
      if(!tList.isEmpty())
          tList.prepend(QLatin1String(", "));
      tList.prepend(tableName());
      query.append(QLatin1String("SELECT "));
      query.append(fList).append(QLatin1String(" FROM ")).append(tList);
      query.append(jList);
      query = qAppendWhereClause(query, where, filter());
      query.append(groupByClause);

      QString orderBy = orderByClause();
      if (!orderBy.isEmpty())
          query.append(QLatin1Char(' ')).append(orderBy);

      return query;
  }
示例#12
0
void QWebSettingsPrivate::apply()
{
    if (settings) {
        settings->setTextAreasAreResizable(true);

        QWebSettingsPrivate* global = QWebSettings::globalSettings()->d;

        QString family = fontFamilies.value(QWebSettings::StandardFont,
                                            global->fontFamilies.value(QWebSettings::StandardFont));
        settings->setStandardFontFamily(family);

        family = fontFamilies.value(QWebSettings::FixedFont,
                                    global->fontFamilies.value(QWebSettings::FixedFont));
        settings->setFixedFontFamily(family);

        family = fontFamilies.value(QWebSettings::SerifFont,
                                    global->fontFamilies.value(QWebSettings::SerifFont));
        settings->setSerifFontFamily(family);

        family = fontFamilies.value(QWebSettings::SansSerifFont,
                                    global->fontFamilies.value(QWebSettings::SansSerifFont));
        settings->setSansSerifFontFamily(family);

        family = fontFamilies.value(QWebSettings::CursiveFont,
                                    global->fontFamilies.value(QWebSettings::CursiveFont));
        settings->setCursiveFontFamily(family);

        family = fontFamilies.value(QWebSettings::FantasyFont,
                                    global->fontFamilies.value(QWebSettings::FantasyFont));
        settings->setFantasyFontFamily(family);

        int size = fontSizes.value(QWebSettings::MinimumFontSize,
                                   global->fontSizes.value(QWebSettings::MinimumFontSize));
        settings->setMinimumFontSize(size);

        size = fontSizes.value(QWebSettings::MinimumLogicalFontSize,
                                   global->fontSizes.value(QWebSettings::MinimumLogicalFontSize));
        settings->setMinimumLogicalFontSize(size);

        size = fontSizes.value(QWebSettings::DefaultFontSize,
                                   global->fontSizes.value(QWebSettings::DefaultFontSize));
        settings->setDefaultFontSize(size);

        size = fontSizes.value(QWebSettings::DefaultFixedFontSize,
                                   global->fontSizes.value(QWebSettings::DefaultFixedFontSize));
        settings->setDefaultFixedFontSize(size);

        bool value = attributes.value(QWebSettings::AutoLoadImages,
                                      global->attributes.value(QWebSettings::AutoLoadImages));
        settings->setLoadsImagesAutomatically(value);

        value = attributes.value(QWebSettings::DnsPrefetchEnabled,
                                 global->attributes.value(QWebSettings::DnsPrefetchEnabled));
        settings->setDNSPrefetchingEnabled(value);

        value = attributes.value(QWebSettings::JavascriptEnabled,
                                      global->attributes.value(QWebSettings::JavascriptEnabled));
        settings->setScriptEnabled(value);
#if USE(ACCELERATED_COMPOSITING)
        value = attributes.value(QWebSettings::AcceleratedCompositingEnabled,
                                      global->attributes.value(QWebSettings::AcceleratedCompositingEnabled));

        settings->setAcceleratedCompositingEnabled(value);
        settings->setAcceleratedCompositingFor3DTransformsEnabled(value);
        settings->setAcceleratedCompositingForAnimationEnabled(value);
#if USE(TEXTURE_MAPPER)
        settings->setAcceleratedCompositingForVideoEnabled(false);
        settings->setAcceleratedCompositingForPluginsEnabled(false);
#endif
#endif
#if ENABLE(WEBGL)
        value = attributes.value(QWebSettings::WebGLEnabled,
                                 global->attributes.value(QWebSettings::WebGLEnabled));

        settings->setWebGLEnabled(value);
#if USE(ACCELERATED_COMPOSITING)
        settings->setAcceleratedCompositingForCanvasEnabled(value);
#endif
#endif

        value = attributes.value(QWebSettings::HyperlinkAuditingEnabled,
                                 global->attributes.value(QWebSettings::HyperlinkAuditingEnabled));

        settings->setHyperlinkAuditingEnabled(value);
 
        value = attributes.value(QWebSettings::JavascriptCanOpenWindows,
                                      global->attributes.value(QWebSettings::JavascriptCanOpenWindows));
        settings->setJavaScriptCanOpenWindowsAutomatically(value);

        value = attributes.value(QWebSettings::JavascriptCanCloseWindows,
                                      global->attributes.value(QWebSettings::JavascriptCanCloseWindows));
        settings->setAllowScriptsToCloseWindows(value);

        value = attributes.value(QWebSettings::JavaEnabled,
                                      global->attributes.value(QWebSettings::JavaEnabled));
        settings->setJavaEnabled(value);

        value = attributes.value(QWebSettings::PluginsEnabled,
                                      global->attributes.value(QWebSettings::PluginsEnabled));
        settings->setPluginsEnabled(value);

        value = attributes.value(QWebSettings::PrivateBrowsingEnabled,
                                      global->attributes.value(QWebSettings::PrivateBrowsingEnabled));
        settings->setPrivateBrowsingEnabled(value);

        value = attributes.value(QWebSettings::SpatialNavigationEnabled,
                                      global->attributes.value(QWebSettings::SpatialNavigationEnabled));
        settings->setSpatialNavigationEnabled(value);

        value = attributes.value(QWebSettings::JavascriptCanAccessClipboard,
                                      global->attributes.value(QWebSettings::JavascriptCanAccessClipboard));
        settings->setDOMPasteAllowed(value);
        settings->setJavaScriptCanAccessClipboard(value);

        value = attributes.value(QWebSettings::DeveloperExtrasEnabled,
                                      global->attributes.value(QWebSettings::DeveloperExtrasEnabled));
        settings->setDeveloperExtrasEnabled(value);

        value = attributes.value(QWebSettings::FrameFlatteningEnabled,
                                      global->attributes.value(QWebSettings::FrameFlatteningEnabled));
        settings->setFrameFlatteningEnabled(value);

        QUrl location = !userStyleSheetLocation.isEmpty() ? userStyleSheetLocation : global->userStyleSheetLocation;
        settings->setUserStyleSheetLocation(WebCore::KURL(location));

        QString encoding = !defaultTextEncoding.isEmpty() ? defaultTextEncoding: global->defaultTextEncoding;
        settings->setDefaultTextEncodingName(encoding);

        QString storagePath = !localStoragePath.isEmpty() ? localStoragePath : global->localStoragePath;
        settings->setLocalStorageDatabasePath(storagePath);

        QString path = !pluginSupplementalPath.isEmpty() ? pluginSupplementalPath : global->pluginSupplementalPath;
        settings->setPluginSupplementalPath(path);

        value = attributes.value(QWebSettings::PrintElementBackgrounds,
                                      global->attributes.value(QWebSettings::PrintElementBackgrounds));
        settings->setShouldPrintBackgrounds(value);

#if ENABLE(SQL_DATABASE)
        value = attributes.value(QWebSettings::OfflineStorageDatabaseEnabled,
                                      global->attributes.value(QWebSettings::OfflineStorageDatabaseEnabled));
        WebCore::AbstractDatabase::setIsAvailable(value);
#endif

        value = attributes.value(QWebSettings::OfflineWebApplicationCacheEnabled,
                                      global->attributes.value(QWebSettings::OfflineWebApplicationCacheEnabled));
        settings->setOfflineWebApplicationCacheEnabled(value);

        value = attributes.value(QWebSettings::LocalStorageEnabled,
                                      global->attributes.value(QWebSettings::LocalStorageEnabled));
        settings->setLocalStorageEnabled(value);

        value = attributes.value(QWebSettings::LocalContentCanAccessRemoteUrls,
                                      global->attributes.value(QWebSettings::LocalContentCanAccessRemoteUrls));
        settings->setAllowUniversalAccessFromFileURLs(value);

        value = attributes.value(QWebSettings::LocalContentCanAccessFileUrls,
                                      global->attributes.value(QWebSettings::LocalContentCanAccessFileUrls));
        settings->setAllowFileAccessFromFileURLs(value);

        value = attributes.value(QWebSettings::XSSAuditingEnabled,
                                      global->attributes.value(QWebSettings::XSSAuditingEnabled));
        settings->setXSSAuditorEnabled(value);

#if USE(TILED_BACKING_STORE)
        value = attributes.value(QWebSettings::TiledBackingStoreEnabled,
                                      global->attributes.value(QWebSettings::TiledBackingStoreEnabled));
        settings->setTiledBackingStoreEnabled(value);
#endif

        value = attributes.value(QWebSettings::SiteSpecificQuirksEnabled,
                                      global->attributes.value(QWebSettings::SiteSpecificQuirksEnabled));
        settings->setNeedsSiteSpecificQuirks(value);

        settings->setUsesPageCache(WebCore::pageCache()->capacity());

#if ENABLE(VIDEO) && USE(WEBOS_MULTIMEDIA)
        QString moptions = !mediaPipelineOptions.isEmpty() ? mediaPipelineOptions: global->mediaPipelineOptions;
        settings->setMediaPipelineOptions( moptions );
#endif

    } else {
        QList<QWebSettingsPrivate*> settings = *::allSettings();
        for (int i = 0; i < settings.count(); ++i)
            settings[i]->apply();
    }
}
示例#13
0
ConnectionPointer<Connection> ConnectionManager2::getConnWithConfig(quint8 type, const QHash<QString, QVariant> &cfg)
{
    this->refresh();

#ifdef HAVE_LIBYB
    // We want to receive first USB enumeration events,
    // so that connections created here can be opened
    QApplication::processEvents();
#endif

    Connection *enumCon = NULL;
    for(int i = 0; i < m_conns.size(); ++i)
    {
        if(m_conns[i]->getType() != type)
            continue;

        switch(type)
        {
            case CONNECTION_SERIAL_PORT:
            {
                SerialPort *sp = (SerialPort*)m_conns[i];
                if(sp->deviceName() == cfg["device_name"])
                {
                    if(!sp->removable())
                        enumCon = sp;
                    else if(sp->baudRate() == cfg["baud_rate"])
                        return ConnectionPointer<Connection>::fromPtr(sp);
                }
                break;
            }
            case CONNECTION_TCP_SOCKET:
            {
                TcpSocket *socket = (TcpSocket*)m_conns[i];
                if(socket->host() == cfg["host"] && socket->port() == cfg["port"])
                    return ConnectionPointer<Connection>::fromPtr(socket);
                break;
            }
            case CONNECTION_UDP_SOCKET:
            {
                UdpSocket *socket = (UdpSocket*)m_conns[i];
                if (socket->name() == cfg["name"] &&
                    socket->host() == cfg["host"] && socket->port() == cfg["port"])
                    return ConnectionPointer<Connection>::fromPtr(socket);
                break;
            }
            case CONNECTION_PROXY_TUNNEL:
            {
                ProxyTunnel *tunnel = (ProxyTunnel*)m_conns[i];
                if(tunnel->name() == cfg["name"])
                    return ConnectionPointer<Connection>::fromPtr(tunnel);
                break;
            }
            case CONNECTION_SHUPITO_TUNNEL:
            {
                QHash<QString, QVariant> c = cfg.value("companions").toHash();
                QHash<QString, QVariant>::iterator itr = c.find(ShupitoTunnel::getCompanionName());
                if(itr == c.end())
                    return ConnectionPointer<Connection>();

                qint64 id = itr.value().toLongLong();
                if(id != 0 && id == m_conns[i]->getCompanionId(ShupitoTunnel::getCompanionName()))
                    return ConnectionPointer<Connection>::fromPtr((ShupitoTunnel*)m_conns[i]);
                break;
            }
            case CONNECTION_SHUPITO_SPI_TUNNEL:
            {
                QHash<QString, QVariant> c = cfg.value("companions").toHash();
                QHash<QString, QVariant>::iterator itr = c.find(ShupitoSpiTunnelConn::getCompanionName());
                if(itr == c.end())
                    return ConnectionPointer<Connection>();

                qint64 id = itr.value().toLongLong();
                if(id != 0 && id == m_conns[i]->getCompanionId(ShupitoSpiTunnelConn::getCompanionName()))
                    return ConnectionPointer<Connection>::fromPtr((ShupitoSpiTunnelConn*)m_conns[i]);
                break;
            }
#ifdef HAVE_LIBYB
            case CONNECTION_USB_ACM2:
            {
                UsbAcmConnection2 *usb = (UsbAcmConnection2*)m_conns[i];
                if (usb->vid() == cfg.value("vid", 0).toInt() &&
                    usb->pid() == cfg.value("pid", 0).toInt() &&
                    usb->serialNumber() == cfg.value("serial_number").toString() &&
                    usb->intfName() == cfg.value("intf_name").toString() &&
                    usb->baudRate() == cfg.value("baud_rate", 115200).toInt() &&
                    usb->stopBits() == cfg.value("stop_bits", 0).toInt() &&
                    usb->parity() == (UsbAcmConnection2::parity_t)cfg.value("parity", 0).toInt() &&
                    usb->dataBits() == cfg.value("data_bits", 8).toInt())
                {
                    usb->applyConfig(cfg);
                    return ConnectionPointer<Connection>::fromPtr(usb);
                }
                break;
            }
            case CONNECTION_SHUPITO23:
            {
                UsbShupito23Connection *usb = (UsbShupito23Connection*)m_conns[i];
                if (usb->vid() == cfg.value("vid", 0).toInt() &&
                    usb->pid() == cfg.value("pid", 0).toInt() &&
                    usb->serialNumber() == cfg.value("serial_number").toString() &&
                    usb->intfName() == cfg.value("intf_name").toString())
                {
                    usb->applyConfig(cfg);
                    return ConnectionPointer<Connection>::fromPtr(usb);
                }
                break;
            }
            case CONNECTION_STM32:
            {
                STM32Connection *stm32 = (STM32Connection*)m_conns[i];
                if (stm32->vid() == cfg.value("vid", 0).toInt() &&
                    stm32->pid() == cfg.value("pid", 0).toInt() &&
                    stm32->serialNumber() == cfg.value("serial_number").toString() &&
                    stm32->intfName() == cfg.value("intf_name").toString())
                {
                    return ConnectionPointer<Connection>::fromPtr(stm32);
                }
                break;
            }
#endif
            default:
                return ConnectionPointer<Connection>();
        }
    }

    if(enumCon)
    {
        enumCon->applyConfig(cfg);
        return ConnectionPointer<Connection>::fromPtr(enumCon);
    }

    if(type == CONNECTION_SHUPITO_TUNNEL)
    {
        QHash<QString, QVariant> c = cfg.value("companions").toHash();
        QHash<QString, QVariant>::iterator itr = c.find(ShupitoTunnel::getCompanionName());
        if(itr == c.end())
            return ConnectionPointer<Connection>();

        qint64 id = itr.value().toLongLong();
        if(id == 0)
            return ConnectionPointer<Connection>();

        ConnectionPointer<Connection> tunnel(new ShupitoTunnel());
        tunnel->applyConfig(cfg);
        tunnel->setRemovable(false);
        this->addConnection(tunnel.data());
        return tunnel;
    }
    else if(type == CONNECTION_SHUPITO_SPI_TUNNEL)
    {
        QHash<QString, QVariant> c = cfg.value("companions").toHash();
        QHash<QString, QVariant>::iterator itr = c.find(ShupitoSpiTunnelConn::getCompanionName());
        if(itr == c.end())
            return ConnectionPointer<Connection>();

        qint64 id = itr.value().toLongLong();
        if(id == 0)
            return ConnectionPointer<Connection>();

        ConnectionPointer<Connection> tunnel(new ShupitoSpiTunnelConn());
        tunnel->applyConfig(cfg);
        tunnel->setRemovable(false);
        this->addConnection(tunnel.data());
        return tunnel;
    }
#ifdef HAVE_LIBYB
    else if(type == CONNECTION_USB_ACM2)
    {
        ConnectionPointer<Connection> usb(createUsbAcmConn());
        usb->applyConfig(cfg);
        return usb;
    }
    else if(type == CONNECTION_STM32)
    {
        ConnectionPointer<Connection> stm32(createSTM32Conn());
        stm32->applyConfig(cfg);
        return stm32;
    }
#endif

    return ConnectionPointer<Connection>();
}
示例#14
0
PwDatabaseV3::ErrorCode PwDatabaseV3::readContent(QDataStream& stream) {

    setPhaseProgressRawTarget(header.getGroupCount() + header.getEntryCount());

    QList<PwGroupV3*> groups;
    ErrorCode err = readAllGroups(stream, groups);
    if (err != SUCCESS)
        return err;

    QList<PwEntryV3*> entries;
    err = readAllEntries(stream, entries);
    if (err != SUCCESS)
        return err;

    // make a group-by-ID lookup hashtable;
    // also find the maximum group level
    int maxLevel = 0;
    quint16 level;
    PwGroupV3* group;
    QHash<qint32, PwGroupV3*> groupById;
    for (int i = 0; i < groups.size(); i++) {
        group = groups.at(i);
        groupById.insert(group->getId(), group);
        level = group->getLevel();
        if (level > maxLevel)
            maxLevel = level;
    }

    // restore group hierarchy
    PwGroupV3* rootGroupV3 = new PwGroupV3();
    rootGroupV3->setDatabase(this);
    rootGroupV3->setLevel(-1); // because its children should have level 0
    rootGroupV3->setIconId(PwGroup::DEFAULT_ICON_ID); // created subgroups will use this icon
    // give the "virtual" root group some meaningful name
    rootGroupV3->setName(getDatabaseFileName());
    _rootGroup = rootGroupV3;
    PwGroupV3* parentGroup = (PwGroupV3*)_rootGroup;
    for (quint16 level = 0; level <= maxLevel; level++) {
        quint16 prevLevel = level - 1;
        for (int i = 0; i < groups.size(); i++) {
            PwGroupV3* group = groups.at(i);
            quint16 curLevel = group->getLevel();
            if (curLevel == level) {
                parentGroup->addSubGroup(group);
            } else if (curLevel == prevLevel) {
                parentGroup = group;
            }
        }
    }

    // put entries to their groups
    PwEntryV3* entry;
    for (int i = 0; i < entries.size(); i++) {
        entry = entries.at(i);
        if (entry->isMetaStream()) {
            // meta streams are kept in their own list, invisibly for the user
            metaStreamEntries.append(entry);
        } else {
            qint32 groupId = entry->getGroupId();
            if (!groupById.contains(groupId)) {
                LOG("There is an entry %s with unknown groupId: %d", entry->toString().toUtf8().constData(), groupId);
                return ORPHANED_ENTRY_ERROR;
            }
            PwGroupV3* group = groupById.value(groupId);
            entry->setDeleted(group->isDeleted());
            group->addEntry(entry);
        }
    }
    return SUCCESS;
}
示例#15
0
void ChessProtocol::receiveMessage(const QString &msg)
{
    QHash<QString, QString> hash = analyse(msg);
    qDebug() << hash;
    if(!hash.contains("TYPE"))
    {
        Chess_Error("has no message type: "+msg);
        return;
    }
    QString type = hash.value("TYPE");
    QString body = hash.value("BODY");
    if(type == "CHAT")
    {
        emit receiveChatMessage(body);
    }
    else if(type == "CHESS")
    {
        int fid = -1;
        int fx = -1;
        int fy = -1;
        int tid = -1;
        int tx = -1;
        int ty = -1;
        if(body.size() == 8)
        {
        fid = body.mid(0, 2).toInt();
        fx = body.mid(2, 1).toInt();
        fy = body.mid(3, 1).toInt();
        tid = body.mid(4, 2).toInt();
        tx = body.mid(6, 1).toInt();
        ty = body.mid(7, 1).toInt();

        }
        else if(body.size() == 4)
        {
            body = body.toLower();

//            fx = body.at(0).toAscii() - 'a';
//            fy = 9 - (body.at(1).toAscii() - '0');
//            fid = ChessData::instance()->isWho(QPoint(fx, fy));
//            tx = body.at(2).toAscii() - 'a';
//            ty = 9 - (body.at(3).toAscii() - '0');

            fx = body.at(0).toLatin1() - 'a';
            fy = 9 - (body.at(1).toLatin1() - '0');
            fid = ChessData::instance()->isWho(QPoint(fx, fy));
            tx = body.at(2).toLatin1() - 'a';
            ty = 9 - (body.at(3).toLatin1() - '0');

            tid = ChessData::instance()->isWho(QPoint(tx, ty));
        }
        emit receiveChessMessage(fid, tid, QPoint(fx, fy), QPoint(tx, ty));
    }
    else if(type == "START")
    {
        emit receiveStartMessage();
    }
    else
    {
        Chess_Error("unknown message type: "+type);
    }
}
示例#16
0
void QAuthenticatorPrivate::parseHttpResponse(const QList<QPair<QByteArray, QByteArray> > &values, bool isProxy)
{
    const char *search = isProxy ? "proxy-authenticate" : "www-authenticate";

    method = None;
    /*
      Fun from the HTTP 1.1 specs, that we currently ignore:

      User agents are advised to take special care in parsing the WWW-
      Authenticate field value as it might contain more than one challenge,
      or if more than one WWW-Authenticate header field is provided, the
      contents of a challenge itself can contain a comma-separated list of
      authentication parameters.
    */

    QByteArray headerVal;
    for (int i = 0; i < values.size(); ++i) {
        const QPair<QByteArray, QByteArray> &current = values.at(i);
        if (current.first.toLower() != search)
            continue;
        QByteArray str = current.second.toLower();
        if (method < Basic && str.startsWith("basic")) {
            method = Basic;
            headerVal = current.second.mid(6);
        } else if (method < Ntlm && str.startsWith("ntlm")) {
            method = Ntlm;
            headerVal = current.second.mid(5);
        } else if (method < DigestMd5 && str.startsWith("digest")) {
            method = DigestMd5;
            headerVal = current.second.mid(7);
        }
    }

    challenge = headerVal.trimmed();
    QHash<QByteArray, QByteArray> options = parseDigestAuthenticationChallenge(challenge);

    switch(method) {
    case Basic:
        this->options[QLatin1String("realm")] = realm = QString::fromLatin1(options.value("realm"));
        if (user.isEmpty() && password.isEmpty())
            phase = Done;
        break;
    case Ntlm:
        // #### extract from header
        if (user.isEmpty() && password.isEmpty())
            phase = Done;
        break;
    case DigestMd5: {
        this->options[QLatin1String("realm")] = realm = QString::fromLatin1(options.value("realm"));
        if (options.value("stale").toLower() == "true")
            phase = Start;
        if (user.isEmpty() && password.isEmpty())
            phase = Done;
        break;
    }
    default:
        realm.clear();
        challenge = QByteArray();
        phase = Invalid;
    }
}
示例#17
0
QHash<QByteArray, QByteArray> QAuthenticatorPrivate::parseDigestAuthenticationChallenge(const QByteArray &challenge)
{
    QHash<QByteArray, QByteArray> options;
    // parse the challenge
    const char *d = challenge.constData();
    const char *end = d + challenge.length();
    while (d < end) {
        while (d < end && (*d == ' ' || *d == '\n' || *d == '\r'))
            ++d;
        const char *start = d;
        while (d < end && *d != '=')
            ++d;
        QByteArray key = QByteArray(start, d - start);
        ++d;
        if (d >= end)
            break;
        bool quote = (*d == '"');
        if (quote)
            ++d;
        if (d >= end)
            break;
        start = d;
        QByteArray value;
        while (d < end) {
            bool backslash = false;
            if (*d == '\\' && d < end - 1) {
                ++d;
                backslash = true;
            }
            if (!backslash) {
                if (quote) {
                    if (*d == '"')
                        break;
                } else {
                    if (*d == ',')
                        break;
                }
            }
            value += *d;
            ++d;
        }
        while (d < end && *d != ',')
            ++d;
        ++d;
        options[key] = value;
    }

    QByteArray qop = options.value("qop");
    if (!qop.isEmpty()) {
        QList<QByteArray> qopoptions = qop.split(',');
        if (!qopoptions.contains("auth"))
            return QHash<QByteArray, QByteArray>();
        // #### can't do auth-int currently
//         if (qop.contains("auth-int"))
//             qop = "auth-int";
//         else if (qop.contains("auth"))
//             qop = "auth";
//         else
//             qop = QByteArray();
        options["qop"] = "auth";
    }

    return options;
}
KNMusicPlaylistModel *KNMusicPlaylistiTunesXMLParser::read(
        const QString &filePath)
{
    //Get the plist file.
    QFile plistFile(filePath);
    //Open the playlist file first.
    if(!plistFile.open(QIODevice::ReadOnly))
    {
        return nullptr;
    }
    //Generate a dom document to parse the file.
    QDomDocument plistDocument;
    //Use QDomDocument to parse the file.
    if(!plistDocument.setContent(&plistFile, true))
    {
        //If there's any error, return nullptr.
        return nullptr;
    }
    //Close the playlist file.
    plistFile.close();
    //Get the 'plist' element from the document.
    QDomElement plistRoot=plistDocument.documentElement();
    //Check the 'plist' element.
    if(plistRoot.nodeName()!="plist" ||
                !plistRoot.hasAttribute("version") ||
                plistRoot.attribute("version")!="1.0")
    {
        return nullptr;
    }
    //Get the dict elements from the 'plist'.
    QDomNodeList root=plistRoot.elementsByTagName("dict");
    //Check the list data.
    if(root.isEmpty())
    {
        return nullptr;
    }
    //Pick out the 'dict' element.
    QDomNodeList dictElement=root.at(0).toElement().childNodes();
    //Check 'dict' childe nodes size.
    if(dictElement.isEmpty())
    {
        return nullptr;
    }
    //Initial the track info hash.
    QHash<QString, QString> musicLocateHash;
    QStringList playlistIndexList;
    //Prepare the playlist.
    KNMusicPlaylistModel *model=new KNMusicPlaylistModel(thread());
    //Get the first node.
    QDomElement keyNode=dictElement.at(0).toElement(),
                valueNode=keyNode.nextSiblingElement();
    //Check the current key node.
    while(!keyNode.isNull() && !keyNode.isNull())
    {
        //Check the name of the node.
        //For 'tracks':
        if(keyNode.text()=="Tracks")
        {
            //Check whether the child nodes is empty.
            if(!valueNode.childNodes().isEmpty())
            {
                //Get all the tracks information.
                QDomElement trackKeyNode=
                                valueNode.childNodes().at(0).toElement(),
                            trackValueNode=
                                trackKeyNode.nextSiblingElement();
                //Pick out all the tracks.
                while(!trackKeyNode.isNull() && !trackValueNode.isNull())
                {
                    //Parse the track dict information.
                    QDomElement songKeyNode=
                                  trackValueNode.childNodes().at(0).toElement(),
                                songValueNode=
                                  songKeyNode.nextSiblingElement();
                    //If all the information is valid.
                    while(!songKeyNode.isNull() && !songValueNode.isNull())
                    {
                        //Get the location of the song.
                        if(songKeyNode.text()=="Location")
                        {
                            //Get the url from the file.
                            //Use QUrl to translate it to a readable string.
                            QString rawUrlText=
                                    QUrl::fromPercentEncoding(
                                        songValueNode.text().toUtf8());
                            //Remove the protocol name.
                            if(rawUrlText.length()>17 &&
                                    rawUrlText.left(17)=="file://localhost/")
                            {
                                rawUrlText.remove(0, 17);
                            }
                            else
                            {
                                rawUrlText=QUrl(rawUrlText).path();
                            }
                            //Set the hash.
                            musicLocateHash.insert(
                                        trackKeyNode.text(),
                                        QFileInfo(rawUrlText).absoluteFilePath()
                                        );
                            break;
                        }
                        //Switch to the next song elements.
                        songKeyNode=songValueNode.nextSiblingElement();
                        songValueNode=songKeyNode.nextSiblingElement();
                    }
                    //Switch to the track elements.
                    trackKeyNode=trackValueNode.nextSiblingElement();
                    trackValueNode=trackKeyNode.nextSiblingElement();
                }
            }
        }
        //For 'Playlists'.
        else if(keyNode.text()=="Playlists")
        {
            //Check the node size.
            if(valueNode.childNodes().size()!=0)
            {
                //Get the dict of the playlist.
                QDomElement playlistDict=
                        valueNode.childNodes().at(0).toElement();
                //Check the size of playlist dict.
                if(playlistDict.childNodes().size()!=0)
                {
                    //Get the playlist keys.
                    QDomElement playlistKey=
                            playlistDict.childNodes().at(0).toElement(),
                                playlistValue=
                            playlistKey.nextSiblingElement();
                    //Read the playlist information.
                    while(!playlistKey.isNull() && !playlistValue.isNull())
                    {
                        //For 'Name' element, it stored the name of the
                        //playlist.
                        if(playlistKey.text()=="Name")
                        {
                            //Set the title to model.
                            model->setTitle(playlistValue.text());
                        }
                        //For 'Playlist Items' element, it stored the file path
                        //information of the songs.
                        else if(playlistKey.text()=="Playlist Items")
                        {
                            //Check the array is empty or not.
                            QDomNodeList itemsArray=playlistValue.childNodes();
                            if(!itemsArray.isEmpty())
                            {
                                //Get all the information from the items array.
                                for(int i=0; i<itemsArray.size(); i++)
                                {
                                    QDomElement currentTrack=
                                            itemsArray.at(i).toElement();
                                    if(currentTrack.childNodes().size()==2)
                                    {
                                        QDomElement trackElement=
                                                        currentTrack.
                                                        childNodes().
                                                        at(0).toElement(),
                                                    trackIndex=
                                                        trackElement.
                                                        nextSiblingElement();
                                        //Check if the track element is
                                        //'Track ID' we will save track info.
                                        if(trackElement.text()=="Track ID")
                                        {
                                            //Insert the track.
                                            playlistIndexList.append(
                                                        trackIndex.text());
                                        }
                                    }
                                }
                            }
                        }
                        //Switch to the next playlist key.
                        playlistKey=playlistValue.nextSiblingElement();
                        playlistValue=playlistKey.nextSiblingElement();
                    }
                }
            }
        }
        //Switch to the next elements.
        keyNode=valueNode.nextSiblingElement();
        valueNode=keyNode.nextSiblingElement();
    }
    //Prepare the file list.
    QStringList fileList;
    //Translate the index list to file list.
    for(auto i=playlistIndexList.constBegin();
        i!=playlistIndexList.constEnd();
        ++i)
    {
        //Get the file path according to the hash table.
        QString filePath=musicLocateHash.value((*i), QString());
        //If the file is not empty,
        if(!filePath.isEmpty())
        {
            //Add to file list.
            fileList.append(filePath);
        }
    }
    //Add the file list to model.
    model->appendFiles(fileList);
    //Set the changed flag.
    model->setChanged(true);
    //Give back the model.
    return model;
}
示例#19
0
bool
TcxFileReader::writeRideFile(MainWindow *mainWindow, const RideFile *ride, QFile &file) const
{
    QDomText text;
    QDomDocument doc;
    QDomProcessingInstruction hdr = doc.createProcessingInstruction("xml","version=\"1.0\"");
    doc.appendChild(hdr);

    // pwx
    QDomElement tcx = doc.createElementNS("http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2", "TrainingCenterDatabase");
    tcx.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    tcx.setAttribute("xsi:schemaLocation", "http://www.garmin.com/xmlschemas/ActivityExtension/v2 http://www.garmin.com/xmlschemas/ActivityExtensionv2.xsd http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd");
    //tcx.setAttribute("version", "2.0");
    doc.appendChild(tcx);

    // activities, we just serialise one ride
    QString sport = ride->getTag("Sport", "Biking");
    if (sport == QObject::tr("Biking") || sport == QObject::tr("Cycling") || sport == QObject::tr("Cycle") || sport == QObject::tr("Bike")) {
        sport = "Biking";
    }
    QDomElement activities = doc.createElement("Activities");
    tcx.appendChild(activities);
    QDomElement activity = doc.createElement("Activity");
    activity.setAttribute("Sport", sport); // was ride->getTag("Sport", "Biking") but must be Biking, Running or Other
    activities.appendChild(activity);

    // time
    QDomElement id = doc.createElement("Id");
    text = doc.createTextNode(ride->startTime().toUTC().toString(Qt::ISODate));
    id.appendChild(text);
    activity.appendChild(id);

    QDomElement lap = doc.createElement("Lap");
    lap.setAttribute("StartTime", ride->startTime().toUTC().toString(Qt::ISODate));
    activity.appendChild(lap);

    const char *metrics[] = {
        "total_distance",
        "workout_time",
        "total_work",
        "average_hr",
        "max_heartrate",
        "average_cad",
        "max_cadence",
        "average_power",
        "max_power",
        "max_speed",
        "average_speed",
        NULL
    };

    QStringList worklist = QStringList();
    for (int i=0; metrics[i];i++) worklist << metrics[i];

    QHash<QString, RideMetricPtr> computed = RideMetric::computeMetrics(mainWindow, ride, mainWindow->zones(), mainWindow->hrZones(), worklist);

    QDomElement lap_time = doc.createElement("TotalTimeSeconds");
    text = doc.createTextNode(QString("%1").arg(computed.value("workout_time")->value(true)));
    //text = doc.createTextNode(ride->dataPoints().last()->secs);
    lap_time.appendChild(text);
    lap.appendChild(lap_time);

    QDomElement lap_distance = doc.createElement("DistanceMeters");
    text = doc.createTextNode(QString("%1").arg(1000*computed.value("total_distance")->value(true)));
    //text = doc.createTextNode(ride->dataPoints().last()->km);
    lap_distance.appendChild(text);
    lap.appendChild(lap_distance);

    QDomElement max_speed = doc.createElement("MaximumSpeed");
    text = doc.createTextNode(QString("%1").arg(computed.value("max_speed")->value(true)));
    max_speed.appendChild(text);
    lap.appendChild(max_speed);

    QDomElement lap_calories = doc.createElement("Calories");
    text = doc.createTextNode(QString("%1").arg((int)computed.value("total_work")->value(true)));
    lap_calories.appendChild(text);
    lap.appendChild(lap_calories);

    QDomElement avg_heartrate = doc.createElement("AverageHeartRateBpm");
    QDomElement value = doc.createElement("Value");
    text = doc.createTextNode(QString("%1").arg((int)computed.value("average_hr")->value(true)));
    value.appendChild(text);
    avg_heartrate.appendChild(value);
    lap.appendChild(avg_heartrate);

    QDomElement max_heartrate = doc.createElement("MaximumHeartRateBpm");
    value = doc.createElement("Value");
    text = doc.createTextNode(QString("%1").arg((int)computed.value("max_heartrate")->value(true)));
    value.appendChild(text);
    max_heartrate.appendChild(value);
    lap.appendChild(max_heartrate);

    QDomElement lap_intensity = doc.createElement("Intensity");
    text = doc.createTextNode("Active");
    lap_intensity.appendChild(text);
    lap.appendChild(lap_intensity);

    QDomElement lap_triggerMethod = doc.createElement("TriggerMethod");
    text = doc.createTextNode("Manual");
    lap_triggerMethod.appendChild(text);
    lap.appendChild(lap_triggerMethod);

    // samples
    // data points: timeoffset, dist, hr, spd, pwr, torq, cad, lat, lon, alt
    if (!ride->dataPoints().empty()) {
        QDomElement track = doc.createElement("Track");
        lap.appendChild(track);

        foreach (const RideFilePoint *point, ride->dataPoints()) {
            QDomElement trackpoint = doc.createElement("Trackpoint");
            track.appendChild(trackpoint);

            // time
            QDomElement time = doc.createElement("Time");
            text = doc.createTextNode(ride->startTime().toUTC().addSecs(point->secs).toString(Qt::ISODate));
            time.appendChild(text);
            trackpoint.appendChild(time);

            // position
            if (ride->areDataPresent()->lat && point->lat > -90.0 && point->lat < 90.0 && point->lat != 0.0 &&
                ride->areDataPresent()->lon && point->lon > -180.00 && point->lon < 180.00 && point->lon != 0.0 ) {
                QDomElement position = doc.createElement("Position");
                trackpoint.appendChild(position);

                // lat
                QDomElement lat = doc.createElement("LatitudeDegrees");
                text = doc.createTextNode(QString("%1").arg(point->lat, 0, 'g', 11));
                lat.appendChild(text);
                position.appendChild(lat);

                // lon
                QDomElement lon = doc.createElement("LongitudeDegrees");
                text = doc.createTextNode(QString("%1").arg(point->lon, 0, 'g', 11));
                lon.appendChild(text);
                position.appendChild(lon);
            }

            // alt
            if (ride->areDataPresent()->alt && point->alt != 0.0) {
                QDomElement alt = doc.createElement("AltitudeMeters");
                text = doc.createTextNode(QString("%1").arg(point->alt));
                alt.appendChild(text);
                trackpoint.appendChild(alt);
            }

            // distance - meters
            if (ride->areDataPresent()->km) {
                QDomElement dist = doc.createElement("DistanceMeters");
                text = doc.createTextNode(QString("%1").arg((int)(point->km*1000)));
                dist.appendChild(text);
                trackpoint.appendChild(dist);
            }

            // HeartRate hack for Garmin Training Center
            // It needs an hr datapoint for every trackpoint or else the 
            // hr graph in TC won't display. Schema defines the datapoint
            // as a positive int (> 0)

            int tHr = 1;
            if (ride->areDataPresent()->hr && point->hr >0.00) {
                tHr = (int)point->hr;
            }
            QDomElement hr = doc.createElement("HeartRateBpm");
            hr.setAttribute("xsi:type", "HeartRateInBeatsPerMinute_t");
            QDomElement value = doc.createElement("Value");
            text = doc.createTextNode(QString("%1").arg(tHr));
            value.appendChild(text);
            hr.appendChild(value);
            trackpoint.appendChild(hr);

            // cad
            if (ride->areDataPresent()->cad && point->cad < 255) { //xsd maxInclusive value="254"
                QDomElement cad = doc.createElement("Cadence");
                text = doc.createTextNode(QString("%1").arg((int)(point->cad)));
                cad.appendChild(text);
                trackpoint.appendChild(cad);
            }

            if (ride->areDataPresent()->kph || ride->areDataPresent()->watts) {
                QDomElement extension = doc.createElement("Extensions");
                trackpoint.appendChild(extension);
                QDomElement tpx = doc.createElement("TPX");
                tpx.setAttribute("xmlns", "http://www.garmin.com/xmlschemas/ActivityExtension/v2");
                extension.appendChild(tpx);

                // spd - meters per second
                if (ride->areDataPresent()->kph) {
                    QDomElement spd = doc.createElement("Speed");
                    text = doc.createTextNode(QString("%1").arg(point->kph / 3.6));
                    spd.appendChild(text);
                    tpx.appendChild(spd);
                }
                // pwr
                if (ride->areDataPresent()->watts) {
                    QDomElement pwr = doc.createElement("Watts");
                    text = doc.createTextNode(QString("%1").arg((int)point->watts));
                    pwr.appendChild(text);
                    tpx.appendChild(pwr);
                }
            }
        }
    }
示例#20
0
    m_serialPortMenu = new QMenu(tr("Select port"), this);
    currentMenu->addMenu(m_serialPortMenu);

    m_serialPortActionGroup = new QActionGroup(this);
	updateSerialPorts();

    connect(m_serialPortMenu, SIGNAL(triggered(QAction*)), this, SLOT(setPort(QAction*)));
	connect(m_serialPortMenu, SIGNAL(aboutToShow()), this, SLOT(updateSerialPorts()), Qt::DirectConnection);

	m_programmerMenu = new QMenu(tr("Select programmer"), this);
    currentMenu->addMenu(m_programmerMenu);

	m_programmerActionGroup = new QActionGroup(this);
	QHash<QString, QString> programmerNames = getProgrammerNames();
	foreach (QString name, programmerNames.keys()) {
		addProgrammer(name, programmerNames.value(name));
	}
	
    connect(m_programmerMenu, SIGNAL(triggered(QAction*)), this, SLOT(setProgrammer(QAction*)));

    currentMenu->addSeparator();

    m_programAction = new QAction(tr("Program"), this);
    m_programAction->setStatusTip(tr("Load the current program onto a microcontroller"));
    m_programAction->setEnabled(false);
    connect(m_programAction, SIGNAL(triggered()), this, SLOT(sendProgram()));
    currentMenu->addAction(m_programAction);

    if (!linkedFiles.isEmpty()) {
        bool firstTime = true;
        foreach (LinkedFile * linkedFile, linkedFiles) {
/*!
    Sets the item's transient state using given \a state data.
*/
void HbAbstractViewItem::setTransientState(const QHash<QString, QVariant> &state)
{
    Q_D( HbAbstractViewItem );
    d->mFocused = state.value("focused").toBool();
    d->mCheckState = (Qt::CheckState)state.value("checkState").toInt();
}
示例#22
0
 bool Metadata::containsType(const QHash<QString,QVariant>& data) const
 {
     return data.contains(otp::storage::Storage::OTP_TOKEN_TYPE) &&
         !data.value(otp::storage::Storage::OTP_TOKEN_TYPE).isNull();
 }
示例#23
0
void AutoProfileWatcher::runAppCheck()
{
    //qDebug() << qApp->applicationFilePath();
    QString appLocation;
    QString baseAppFileName;
    guidSet.clear();

    // Check whether program path needs to be parsed. Removes processing time
    // and need to run Linux specific code searching /proc.
#ifdef Q_OS_LINUX
    if (!appProfileAssignments.isEmpty())
    {
        appLocation = findAppLocation();
    }
#else
    // In Windows, get program location no matter what.
    appLocation = findAppLocation();
    if (!appLocation.isEmpty())
    {
        baseAppFileName = QFileInfo(appLocation).fileName();
    }
#endif

    // More portable check for whether antimicro is the current application
    // with focus.
    QWidget *focusedWidget = qApp->activeWindow();

    QString nowWindow;
    QString nowWindowClass;
    QString nowWindowName;

#ifdef Q_OS_WIN
    nowWindowName = WinExtras::getCurrentWindowText();
#else
    unsigned long currentWindow = X11Extras::getInstance()->getWindowInFocus();
    if (currentWindow > 0)
    {
        unsigned long tempWindow = X11Extras::getInstance()->findParentClient(currentWindow);
        if (tempWindow > 0)
        {
            currentWindow = tempWindow;
        }
        nowWindow = QString::number(currentWindow);
        nowWindowClass = X11Extras::getInstance()->getWindowClass(currentWindow);
        nowWindowName = X11Extras::getInstance()->getWindowTitle(currentWindow);
        //qDebug() << nowWindowClass;
        //qDebug() << nowWindowName;
    }
#endif

    bool checkForTitleChange = windowNameProfileAssignments.size() > 0;

#ifdef Q_OS_WIN
    if (!focusedWidget && ((!appLocation.isEmpty() && appLocation != currentApplication) ||
        (checkForTitleChange && nowWindowName != currentAppWindowTitle)))

#else
    if (!focusedWidget && ((!nowWindow.isEmpty() && nowWindow != currentApplication) ||
        (checkForTitleChange && nowWindowName != currentAppWindowTitle)))

#endif
    {

#ifdef Q_OS_WIN
        currentApplication = appLocation;
#else
        currentApplication = nowWindow;
#endif

        currentAppWindowTitle = nowWindowName;
        //currentApplication = appLocation;

        QSet<AutoProfileInfo*> fullSet;

        if (!appLocation.isEmpty() && appProfileAssignments.contains(appLocation))
        {
            QSet<AutoProfileInfo*> tempSet;
            tempSet = appProfileAssignments.value(appLocation).toSet();
            fullSet.unite(tempSet);
        }
        else if (!baseAppFileName.isEmpty() && appProfileAssignments.contains(baseAppFileName))
        {
            QSet<AutoProfileInfo*> tempSet;
            tempSet = appProfileAssignments.value(baseAppFileName).toSet();
            fullSet.unite(tempSet);
        }

        if (!nowWindowClass.isEmpty() && windowClassProfileAssignments.contains(nowWindowClass))
        {
            QSet<AutoProfileInfo*> tempSet;
            tempSet = windowClassProfileAssignments.value(nowWindowClass).toSet();
            fullSet.unite(tempSet);
        }

        if (!nowWindowName.isEmpty() && windowNameProfileAssignments.contains(nowWindowName))
        {
            QSet<AutoProfileInfo*> tempSet;
            tempSet = windowNameProfileAssignments.value(nowWindowName).toSet();
            fullSet = fullSet.unite(tempSet);
        }

        QHash<QString, int> highestMatchCount;
        QHash<QString, AutoProfileInfo*> highestMatches;

        QSetIterator<AutoProfileInfo*> fullSetIter(fullSet);
        while (fullSetIter.hasNext())
        {
            AutoProfileInfo *info = fullSetIter.next();
            if (info->isActive())
            {
                int numProps = 0;
                numProps += !info->getExe().isEmpty() ? 1 : 0;
                numProps += !info->getWindowClass().isEmpty() ? 1 : 0;
                numProps += !info->getWindowName().isEmpty() ? 1 : 0;

                int numMatched = 0;
                numMatched += info->getExe() == appLocation ? 1 : 0;
                numMatched += info->getWindowClass() == nowWindowClass ? 1 : 0;
                numMatched += info->getWindowName() == nowWindowName ? 1 : 0;

                if (numProps == numMatched)
                {
                    if (highestMatchCount.contains(info->getGUID()))
                    {
                        int currentHigh = highestMatchCount.value(info->getGUID());
                        if (numMatched > currentHigh)
                        {
                            highestMatchCount.insert(info->getGUID(), numMatched);
                            highestMatches.insert(info->getGUID(), info);
                        }
                    }
                    else
                    {
                        highestMatchCount.insert(info->getGUID(), numMatched);
                        highestMatches.insert(info->getGUID(), info);
                    }
                }
            }
        }

        QHashIterator<QString, AutoProfileInfo*> highIter(highestMatches);
        while (highIter.hasNext())
        {
            AutoProfileInfo *info = highIter.next().value();
            guidSet.insert(info->getGUID());
            emit foundApplicableProfile(info);
        }

        if ((!defaultProfileAssignments.isEmpty() || allDefaultInfo) && !focusedWidget)
             //antiProgramLocation != appLocation)
        {
            if (allDefaultInfo)
            {
                if (allDefaultInfo->isActive() && !guidSet.contains("all"))
                {
                    emit foundApplicableProfile(allDefaultInfo);
                }
            }

            QHashIterator<QString, AutoProfileInfo*> iter(defaultProfileAssignments);
            while (iter.hasNext())
            {
                iter.next();
                AutoProfileInfo *info = iter.value();
                if (info->isActive() && !guidSet.contains(info->getGUID()))
                {
                    emit foundApplicableProfile(info);
                }
            }
        }
    }
}
bool QQmlListModelWorkerAgent::event(QEvent *e)
{
    if (e->type() == QEvent::User) {
        bool cc = false;
        QMutexLocker locker(&mutex);
        if (m_orig) {
            Sync *s = static_cast<Sync *>(e);
            const QList<Change> &changes = s->data.changes;

            cc = m_orig->count() != s->list->count();

            QHash<int, QQmlListModel *> targetModelDynamicHash;
            QHash<int, ListModel *> targetModelStaticHash;

            Q_ASSERT(m_orig->m_dynamicRoles == s->list->m_dynamicRoles);
            if (m_orig->m_dynamicRoles)
                QQmlListModel::sync(s->list, m_orig, &targetModelDynamicHash);
            else
                ListModel::sync(s->list->m_listModel, m_orig->m_listModel, &targetModelStaticHash);

            for (int ii = 0; ii < changes.count(); ++ii) {
                const Change &change = changes.at(ii);

                QQmlListModel *model = 0;
                if (m_orig->m_dynamicRoles) {
                    model = targetModelDynamicHash.value(change.modelUid);
                } else {
                    ListModel *lm = targetModelStaticHash.value(change.modelUid);
                    if (lm)
                        model = lm->m_modelCache;
                }

                if (model) {
                    switch (change.type) {
                    case Change::Inserted:
                        model->beginInsertRows(
                                    QModelIndex(), change.index, change.index + change.count - 1);
                        model->endInsertRows();
                        break;
                    case Change::Removed:
                        model->beginRemoveRows(
                                    QModelIndex(), change.index, change.index + change.count - 1);
                        model->endRemoveRows();
                        break;
                    case Change::Moved:
                        model->beginMoveRows(
                                    QModelIndex(),
                                    change.index,
                                    change.index + change.count - 1,
                                    QModelIndex(),
                                    change.to > change.index ? change.to + change.count : change.to);
                        model->endMoveRows();
                        break;
                    case Change::Changed:
                        emit model->dataChanged(
                                    model->createIndex(change.index, 0),
                                    model->createIndex(change.index + change.count - 1, 0),
                                    change.roles);
                        break;
                    }
                }
            }
        }

        syncDone.wakeAll();
        locker.unlock();

        if (cc)
            emit m_orig->countChanged();
        return true;
    }

    return QObject::event(e);
}
示例#25
0
文件: main.cpp 项目: Fale/qtmoko
int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);
    QStringList args = app.arguments();
    QTranslator translator;
    if (translator.load(QLatin1String("lrelease_") + QLocale::system().name()))
        app.installTranslator(&translator);

    bool verbose = true; // the default is true starting with Qt 4.2
    bool ignoreUnfinished = false;
    // the default mode is SaveEverything starting with Qt 4.2
    TranslatorSaveMode mode = SaveEverything;
    bool removeIdentical = false;
    Translator tor;
    QString outputFile;
    int numFiles = 0;

    for (int i = 1; i < argc; ++i) {
        if (args[i] == QLatin1String("-compress")) {
            mode = SaveStripped;
            continue;
        } else if (args[i] == QLatin1String("-nocompress")) {
            mode = SaveEverything;
            continue;
        } else if (args[i] == QLatin1String("-removeidentical")) {
            removeIdentical = true;
            continue;
        } else if (args[i] == QLatin1String("-nounfinished")) {
            ignoreUnfinished = true;
            continue;
        } else if (args[i] == QLatin1String("-silent")) {
            verbose = false;
            continue;
        } else if (args[i] == QLatin1String("-verbose")) {
            verbose = true;
            continue;
        } else if (args[i] == QLatin1String("-version")) {
            printOut(QCoreApplication::tr( "lrelease version %1\n").arg(QLatin1String(QT_VERSION_STR)) );
            return 0;
        } else if (args[i] == QLatin1String("-qm")) {
            if (i == argc - 1) {
                printUsage();
                return 1;
            }
            i++;
            outputFile = args[i];
        } else if (args[i] == QLatin1String("-help")) {
            printUsage();
            return 0;
        } else if (args[i][0] == QLatin1Char('-')) {
            printUsage();
            return 1;
        } else {
            numFiles++;
        }
    }

    if (numFiles == 0) {
        printUsage();
        return 1;
    }

    for (int i = 1; i < argc; ++i) {
        if (args[i][0] == QLatin1Char('-') || args[i] == outputFile)
            continue;

        if (args[i].endsWith(QLatin1String(".pro"), Qt::CaseInsensitive)
            || args[i].endsWith(QLatin1String(".pri"), Qt::CaseInsensitive)) {
            QHash<QByteArray, QStringList> varMap;
            bool ok = evaluateProFile(args[i], verbose, &varMap );
            if (ok) {
                QStringList translations = varMap.value("TRANSLATIONS");
                if (translations.isEmpty()) {
                    qWarning("lrelease warning: Met no 'TRANSLATIONS' entry in"
                             " project file '%s'\n",
                             qPrintable(args[i]));
                } else {
                    foreach (const QString &trans, translations)
                        if (!releaseTsFile(trans, verbose, ignoreUnfinished, removeIdentical, mode))
                            return 1;
                }
            } else {
                qWarning("error: lrelease encountered project file functionality that is currently not supported.\n"
                    "You might want to consider using .ts files as input instead of a project file.\n"
                    "Try the following syntax:\n"
                    "    lrelease [options] ts-files [-qm qm-file]\n");
            }
        } else {
示例#26
0
static void syncId(ModelNode &outputNode, const ModelNode &inputNode, const QHash<QString, QString> &idRenamingHash)
{
    if (!inputNode.id().isEmpty()) {
        outputNode.setId(idRenamingHash.value(inputNode.id()));
    }
}
示例#27
0
void AutoProfileWatcher::syncProfileAssignment()
{
    QListIterator<QList<AutoProfileInfo*> > iterDelete(appProfileAssignments.values());
    while (iterDelete.hasNext())
    {
        QList<AutoProfileInfo*> templist = iterDelete.next();
        QListIterator<AutoProfileInfo*> iterAuto(templist);
        while (iterAuto.hasNext())
        {
            AutoProfileInfo *info = iterAuto.next();
            if (info)
            {
                delete info;
                info = 0;
            }
        }
    }
    appProfileAssignments.clear();

    QListIterator<AutoProfileInfo*> iterDefaultsDelete(defaultProfileAssignments.values());
    while (iterDefaultsDelete.hasNext())
    {
        AutoProfileInfo *info = iterDefaultsDelete.next();
        if (info)
        {
            delete info;
            info = 0;
        }
    }
    defaultProfileAssignments.clear();

    allDefaultInfo = 0;
    currentApplication = "";

    //QStringList assignments = settings->allKeys();
    //QStringListIterator iter(assignments);

    settings->beginGroup("DefaultAutoProfiles");
    QString exe;
    QString guid;
    QString profile;
    QString active;

    QStringList defaultkeys = settings->allKeys();
    settings->endGroup();

    QString allProfile = settings->value(QString("DefaultAutoProfileAll/Profile"), "").toString();
    QString allActive = settings->value(QString("DefaultAutoProfileAll/Active"), "0").toString();

    if (!allProfile.isEmpty())
    {
        bool defaultActive = allActive == "1" ? true : false;
        allDefaultInfo = new AutoProfileInfo("all", profile, defaultActive, this);
        allDefaultInfo->setDefaultState(true);
    }

    QStringListIterator iter(defaultkeys);
    while (iter.hasNext())
    {
        QString tempkey = iter.next();
        QString guid = QString(tempkey).replace("GUID", "");

        QString profile = settings->value(QString("DefaultAutoProfile-%1/Profile").arg(guid), "").toString();
        QString active = settings->value(QString("DefaultAutoProfile-%1/Active").arg(guid), "").toString();

        if (!guid.isEmpty() && !profile.isEmpty())
        {
            bool profileActive = active == "1" ? true : false;
            if (guid != "all")
            {
                AutoProfileInfo *info = new AutoProfileInfo(guid, profile, profileActive, this);
                info->setDefaultState(true);
                defaultProfileAssignments.insert(guid, info);
            }
        }
    }

    settings->beginGroup("AutoProfiles");
    bool quitSearch = false;

    QHash<QString, QList<QString> > tempAssociation;
    for (int i = 1; !quitSearch; i++)
    {
        exe = settings->value(QString("AutoProfile%1Exe").arg(i), "").toString();
        guid = settings->value(QString("AutoProfile%1GUID").arg(i), "").toString();
        profile = settings->value(QString("AutoProfile%1Profile").arg(i), "").toString();
        active = settings->value(QString("AutoProfile%1Active").arg(i), 0).toString();

        // Check if all required elements exist. If not, assume that the end of the
        // list has been reached.
        if (!exe.isEmpty() && !guid.isEmpty() && !profile.isEmpty())
        {
            bool profileActive = active == "1" ? true : false;
            QList<AutoProfileInfo*> templist;
            if (appProfileAssignments.contains(exe))
            {
                templist = appProfileAssignments.value(exe);
            }

            QList<QString> tempguids;
            if (tempAssociation.contains(exe))
            {
                tempguids = tempAssociation.value(exe);
            }

            if (!tempguids.contains(guid))
            {
                AutoProfileInfo *info = new AutoProfileInfo(guid, profile, profileActive, this);
                tempguids.append(guid);
                tempAssociation.insert(exe, tempguids);
                templist.append(info);
                appProfileAssignments.insert(exe, templist);
            }
        }
        else
        {
            quitSearch = true;
        }
    }

    settings->endGroup();
}
void IntervalSummaryWindow::calcInterval(IntervalItem* interval, QString& html)
{
	const RideFile* ride = context->currentRide();

    bool metricUnits = context->athlete->useMetricUnits;

    RideFile f(ride->startTime(), ride->recIntSecs());
    f.context = context;
    int start = ride->timeIndex(interval->start);
    int end = ride->timeIndex(interval->stop);
    for (int i = start; i <= end; ++i) {
        const RideFilePoint *p = ride->dataPoints()[i];
        f.appendPoint(p->secs, p->cad, p->hr, p->km, p->kph, p->nm,
                      p->watts, p->alt, p->lon, p->lat, p->headwind, p->slope, p->temp, p->lrbalance, 
                      p->lte, p->rte, p->lps, p->rps, p->smo2, p->thb, 0);

        // derived data
        RideFilePoint *l = f.dataPoints().last();
        l->np = p->np;
        l->xp = p->xp;
        l->apower = p->apower;
    }
    if (f.dataPoints().size() == 0) {
        // Interval empty, do not compute any metrics
        html += "<i>" + tr("empty interval") + "</tr>";
    }

    QString s;
    if (appsettings->contains(GC_SETTINGS_INTERVAL_METRICS))
        s = appsettings->value(this, GC_SETTINGS_INTERVAL_METRICS).toString();
    else
        s = GC_SETTINGS_INTERVAL_METRICS_DEFAULT;
    QStringList intervalMetrics = s.split(",");

    QHash<QString,RideMetricPtr> metrics =
        RideMetric::computeMetrics(context, &f, context->athlete->zones(), context->athlete->hrZones(), intervalMetrics);

    html += "<b>" + interval->text(0) + "</b>";
    html += "<table align=\"center\" width=\"90%\" ";
    html += "cellspacing=0 border=0>";

    foreach (QString symbol, intervalMetrics) {
        RideMetricPtr m = metrics.value(symbol);
        if (!m) continue;

        html += "<tr>";
        // left column (names)
        html += "<td align=\"right\" valign=\"bottom\">" + m->name() + "</td>";

        // right column (values)
        QString s("<td align=\"center\">%1</td>");
        if (m->units(metricUnits) == "seconds" ||
            m->units(metricUnits) == tr("seconds"))
            html += s.arg(time_to_string(m->value(metricUnits)));
        else if (m->internalName() == "Pace") {
            html += s.arg(QTime(0,0,0,0).addSecs(m->value(metricUnits)*60).toString("mm:ss"));
        } else
            html += s.arg(m->value(metricUnits), 0, 'f', m->precision());

        html += "<td align=\"left\" valign=\"bottom\">";
        if (m->units(metricUnits) == "seconds" ||
            m->units(metricUnits) == tr("seconds"))
            ; // don't do anything
        else if (m->units(metricUnits).size() > 0)
            html += m->units(metricUnits);
        html += "</td>";

        html += "</tr>";

    }
示例#29
0
void GLC_Mesh::copyIndex(int lodIndex, GLC_Mesh* pLodMesh, QHash<GLuint, GLuint>& sourceToTargetIndexMap, QHash<GLuint, GLuint>& tagetToSourceIndexMap, int& maxIndex, int targetLod)
{
	//! The list of LOD material ID
	QList<GLuint> materialId= m_PrimitiveGroups.value(lodIndex)->keys();

	const int materialCount= materialId.size();
	for (int i= 0; i < materialCount; ++i)
	{
		GLuint currentMaterialId= materialId.at(i);
		GLC_Material* pCurrentMaterial= GLC_Geometry::material(currentMaterialId);

		// Triangles
		if (containsTriangles(lodIndex, currentMaterialId))
		{
			QVector<GLuint> sourceTriangleIndex= getTrianglesIndex(lodIndex, currentMaterialId);
			QList<GLuint> targetTriangleIndex;
			const int triangleIndexCount= sourceTriangleIndex.size();
			for (int i= 0; i < triangleIndexCount; ++i)
			{
				const GLuint currentIndex= sourceTriangleIndex.at(i);
				if (!sourceToTargetIndexMap.contains(currentIndex))
				{
					sourceToTargetIndexMap.insert(currentIndex, ++maxIndex);
					tagetToSourceIndexMap.insert(maxIndex, currentIndex);
					targetTriangleIndex.append(maxIndex);
				}
				else
				{
					targetTriangleIndex.append(sourceToTargetIndexMap.value(currentIndex));
				}
			}
			pLodMesh->addTriangles(pCurrentMaterial, targetTriangleIndex, targetLod, m_MeshData.getLod(lodIndex)->accuracy());
		}

		//Triangles strips
		if (containsStrips(lodIndex, currentMaterialId))
		{
			QList<QVector<GLuint> > sourceStripIndex= getStripsIndex(lodIndex, currentMaterialId);
			const int stripCount= sourceStripIndex.size();
			for (int stripIndex= 0; stripIndex < stripCount; ++stripIndex)
			{

				QVector<GLuint> sourceTriangleStripIndex= sourceStripIndex.at(stripIndex);
				QList<GLuint> targetTriangleStripIndex;
				const int triangleStripIndexCount= sourceTriangleStripIndex.size();
				for (int i= 0; i < triangleStripIndexCount; ++i)
				{
					const GLuint currentIndex= sourceTriangleStripIndex.at(i);
					if (!sourceToTargetIndexMap.contains(currentIndex))
					{
						sourceToTargetIndexMap.insert(currentIndex, ++maxIndex);
						tagetToSourceIndexMap.insert(maxIndex, currentIndex);
						targetTriangleStripIndex.append(maxIndex);
					}
					else
					{
						targetTriangleStripIndex.append(sourceToTargetIndexMap.value(currentIndex));
					}
				}
				pLodMesh->addTrianglesStrip(pCurrentMaterial, targetTriangleStripIndex, targetLod, m_MeshData.getLod(lodIndex)->accuracy());
			}
		}
		//Triangles fans
		if (containsFans(lodIndex, currentMaterialId))
		{
			QList<QVector<GLuint> > sourceFanIndex= getFansIndex(lodIndex, currentMaterialId);
			const int fanCount= sourceFanIndex.size();
			for (int fanIndex= 0; fanIndex < fanCount; ++fanIndex)
			{

				QVector<GLuint> sourceTriangleFanIndex= sourceFanIndex.at(fanIndex);
				QList<GLuint> targetTriangleFanIndex;
				const int triangleFanIndexCount= sourceTriangleFanIndex.size();
				for (int i= 0; i < triangleFanIndexCount; ++i)
				{
					const GLuint currentIndex= sourceTriangleFanIndex.at(i);
					if (!sourceToTargetIndexMap.contains(currentIndex))
					{
						sourceToTargetIndexMap.insert(currentIndex, ++maxIndex);
						tagetToSourceIndexMap.insert(maxIndex, currentIndex);
						targetTriangleFanIndex.append(maxIndex);
					}
					else
					{
						targetTriangleFanIndex.append(sourceToTargetIndexMap.value(currentIndex));
					}
				}
				pLodMesh->addTrianglesFan(pCurrentMaterial, targetTriangleFanIndex, targetLod, m_MeshData.getLod(lodIndex)->accuracy());
			}
		}
	}
}
示例#30
0
void GraphUtils::minCut(QList<ConnectorItem *> & connectorItems, QList<SketchWidget *> & foreignSketchWidgets, ConnectorItem * source, ConnectorItem * sink, QList<ConnectorEdge *> & minCut) 
{
	// this helped:  http://boost.2283326.n4.nabble.com/graph-edmund-karp-max-flow-vs-kolmogorov-max-flow-color-map-td2565611.html
	
	using namespace boost;

	typedef adjacency_list_traits < vecS, vecS, directedS > Traits;
    typedef property < vertex_color_t, boost::default_color_type > COLOR;
	typedef property < vertex_index_t, long, COLOR > VERTEX;
    typedef property < edge_reverse_t, Traits::edge_descriptor > REVERSE;
    typedef property < edge_residual_capacity_t, long, REVERSE > RESIDUAL;
	typedef property < edge_capacity_t, long, RESIDUAL > EDGE;
	typedef adjacency_list < listS, vecS, directedS, VERTEX, EDGE > Graph;

	Graph g;

	property_map < Graph, edge_capacity_t >::type capacity = get(edge_capacity, g);
	property_map < Graph, edge_residual_capacity_t >::type residual_capacity = get(edge_residual_capacity, g);
	property_map < Graph, edge_reverse_t >::type reverse = get(edge_reverse, g);

	property_map < Graph, vertex_color_t >::type color = get(vertex_color, g);
	property_map < Graph, vertex_index_t >::type index = get(vertex_index, g);

	Traits::vertex_descriptor s, t;

	QList<Wire *> visitedWires;
	QList<int> indexes;
	QHash<ConnectorItem *, int> vertices;
	QList<ConnectorEdge *> edges;
	QVector<Traits::vertex_descriptor> verts;

	vertices.insert(source, 0);
	vertices.insert(sink, 1);
	verts.append(s = add_vertex(g));
	verts.append(t = add_vertex(g));

	foreach (ConnectorItem * connectorItem, connectorItems) {
		//connectorItem->debugInfo("input");
		if (connectorItem->attachedToItemType() == ModelPart::Wire) {
			Wire * wire = qobject_cast<Wire *>(connectorItem->attachedTo());
			if (visitedWires.contains(wire)) continue;

			QList<Wire *> wires;
			QList<ConnectorItem *> ends;
			wire->collectChained(wires, ends);
			visitedWires.append(wires);
			if (ends.count() < 2) continue;

			foreach (ConnectorItem * end, ends) {
				appendVertIf(end, vertices, verts);
			}

			for (int i = 0; i < ends.count(); i++) {
				ConnectorItem * end = ends[i];
				for (int j = i + 1; j < ends.count(); j++) {
					ConnectorEdge * connectorEdge = makeConnectorEdge(edges, end, ends[j], 1000, wire);
					connectorEdge->setHeadTail(vertices.value(connectorEdge->c0), vertices.value(connectorEdge->c1));
				}
			}
			continue;
		}