Example #1
0
bool Player::removeTracksFromSavedQueue(const QString& SQid, const QVariantList& indexes, int containerUpdateID)
{
  if (m_player)
  {
    QString trackList;
    for (QVariantList::const_iterator it = indexes.begin(); it != indexes.end(); ++it)
    {
      if (it != indexes.begin())
        trackList.append(",");
      trackList.append(QString::number(it->value<int>()));
    }
    return m_player->ReorderTracksInSavedQueue(SQid.toUtf8().constData(), trackList.toUtf8().constData(), "", containerUpdateID);
  }
  return false;
}
Example #2
0
QMap<QUrl,QUrl>* Fetcher::parseJson(QByteArray json)
{
    QMap<QUrl,QUrl>* urls = new QMap<QUrl,QUrl>();
    QJsonDocument jsonDoc = QJsonDocument::fromJson(json);

    QVariantMap  result = jsonDoc.toVariant().toMap();
    QVariantMap  responseData = (*result.find("responseData")).toMap();
    QVariantList resultList = (*responseData.find("results")).toList();
    QVariantMap  tmp;
    QVariant     tbUrl,imgUrl;
    QString      tbUrlString,imgUrlString;

    QVariantList::iterator it;
    for(it = resultList.begin() ; it != resultList.end() ; ++it)
    {
        tmp = (*it).toMap();

        tbUrl = (*tmp.find("tbUrl"));
        imgUrl = (*tmp.find("unescapedUrl"));
        tbUrlString = tbUrl.toString();
        imgUrlString = imgUrl.toString();
        urls->insert(QUrl(imgUrlString),QUrl(tbUrlString));
    }

    return urls;
}
Example #3
0
/**
 * Returns all the torrents in JSON format.
 *
 * The return value is a JSON-formatted list of dictionaries.
 * The dictionary keys are:
 *   - "hash": Torrent hash
 *   - "name": Torrent name
 *   - "size": Torrent size
 *   - "progress: Torrent progress
 *   - "dlspeed": Torrent download speed
 *   - "upspeed": Torrent upload speed
 *   - "priority": Torrent priority (-1 if queuing is disabled)
 *   - "num_seeds": Torrent seeds connected to
 *   - "num_complete": Torrent seeds in the swarm
 *   - "num_leechs": Torrent leechers connected to
 *   - "num_incomplete": Torrent leechers in the swarm
 *   - "ratio": Torrent share ratio
 *   - "eta": Torrent ETA
 *   - "state": Torrent state
 *   - "seq_dl": Torrent sequential download state
 *   - "f_l_piece_prio": Torrent first last piece priority state
 *   - "force_start": Torrent force start state
 *   - "category": Torrent category
 */
QByteArray btjson::getTorrents(QString filter, QString category,
                               QString sortedColumn, bool reverse, int limit, int offset)
{
    QVariantList torrentList;
    TorrentFilter torrentFilter(filter, TorrentFilter::AnyHash, category);
    foreach (BitTorrent::TorrentHandle *const torrent, BitTorrent::Session::instance()->torrents()) {
        if (torrentFilter.match(torrent))
            torrentList.append(toMap(torrent));
    }

    std::sort(torrentList.begin(), torrentList.end(), QTorrentCompare(sortedColumn, reverse));
    int size = torrentList.size();
    // normalize offset
    if (offset < 0)
        offset = size + offset;
    if ((offset >= size) || (offset < 0))
        offset = 0;
    // normalize limit
    if (limit <= 0)
        limit = -1; // unlimited

    if ((limit > 0) || (offset > 0))
        return json::toJson(torrentList.mid(offset, limit));
    else
        return json::toJson(torrentList);
}
void QmlProfilerEventsModelProxy::notesChanged(int typeIndex)
{
    const QmlProfilerNotesModel *notesModel = d->modelManager->notesModel();
    if (typeIndex == -1) {
        d->notes.clear();
        for (int noteId = 0; noteId < notesModel->count(); ++noteId) {
            int noteType = notesModel->typeId(noteId);
            if (noteType != -1) {
                QString &note = d->notes[noteType];
                if (note.isEmpty()) {
                    note = notesModel->text(noteId);
                } else {
                    note.append(QStringLiteral("\n")).append(notesModel->text(noteId));
                }
            }
        }
    } else {
        d->notes.remove(typeIndex);
        QVariantList changedNotes = notesModel->byTypeId(typeIndex);
        if (!changedNotes.isEmpty()) {
            QStringList newNotes;
            for (QVariantList::ConstIterator it = changedNotes.begin(); it !=  changedNotes.end();
                 ++it) {
                newNotes << notesModel->text(it->toInt());
            }
            d->notes[typeIndex] = newNotes.join(QStringLiteral("\n"));
        }
    }

    emit notesAvailable(typeIndex);
}
void WeatherDataSource::loadNetworkReplyDataIntoDataBase(QVariantList weatherData)
{
    // Iterate over all the items in the received data.
    QVariantList::Iterator item = weatherData.begin();

    // ValuesTable is a list of lists for adding a batch of data to the database.
    QVariantList valuesTable;

    // Update the data revision since we are adding new data to the data base.
    int revision = incrementRevision();

    while (item != weatherData.end()) {
        QVariantList entryValues;
        QVariantMap itemMap = (*item).toMap();
        QDate itemDate = QDate::fromString(itemMap["date"].toString(), "yyyy M d");
        itemMap["date"] = QVariant(itemDate.toString("yyyy-MM-dd"));

        // Store the retrieved values for adding to data base.
        entryValues << itemMap["city"];
        entryValues << itemMap["region"];
        entryValues << itemMap["templo"].toInt();
        entryValues << itemMap["temphi"].toInt();
        entryValues << itemMap["tempaverage"].toInt();
        entryValues << itemMap["icon"].toInt();
        entryValues << itemMap["date"].toString();
        entryValues << revision;
        valuesTable << QVariant::fromValue(entryValues);
        ++item;
    }

    // Insert the data into the data base here.
    QString query = "INSERT INTO weather (city, region, templo, temphi, tempaverage, icon, date, revision_id) VALUES (:city, :region, :templo, :temphi, :tempaverage, :icon, :date, :revision_id)";
    mSqlConnector->executeBatch(query, valuesTable);
}
void QgsRelationReferenceWidget::init()
{
  if ( !mReadOnlySelector && mComboBox->count() == 0 && mReferencedLayer )
  {
    QApplication::setOverrideCursor( Qt::WaitCursor );

    QSet<QString> requestedAttrs;

    QgsVectorLayerCache* layerCache = new QgsVectorLayerCache( mReferencedLayer, 100000, this );

    if ( !mFilterFields.isEmpty() )
    {
      Q_FOREACH ( const QString& fieldName, mFilterFields )
      {
        QVariantList uniqueValues;
        int idx = mReferencedLayer->fields().lookupField( fieldName );
        QComboBox* cb = new QComboBox();
        cb->setProperty( "Field", fieldName );
        cb->setProperty( "FieldAlias", mReferencedLayer->attributeDisplayName( idx ) );
        mFilterComboBoxes << cb;
        mReferencedLayer->uniqueValues( idx, uniqueValues );
        cb->addItem( mReferencedLayer->attributeDisplayName( idx ) );
        QVariant nullValue = QSettings().value( QStringLiteral( "qgis/nullValue" ), "NULL" );
        cb->addItem( nullValue.toString(), QVariant( mReferencedLayer->fields().at( idx ).type() ) );

        qSort( uniqueValues.begin(), uniqueValues.end(), qgsVariantLessThan );
        Q_FOREACH ( const QVariant& v, uniqueValues )
        {
          cb->addItem( v.toString(), v );
        }
int RatingsProcessor::getId(QString title, QString response) {
	int id;
	bool flagIn = false;
	bb::data::JsonDataAccess jda;
	QVariant vlist =  jda.loadFromBuffer(response);

	QVariantList list = vlist.toList();

	for (QList<QVariant>::iterator it = list.begin(); it != list.end(); it++) {
		QVariantMap map = it->toMap();
		QMapIterator<QString, QVariant> iw(map);
		while (iw.hasNext()) {
			iw.next();
			QVariantMap tw = iw.value().toMap();
			if (tw["title"] == title) {
				flagIn = true;
				id = tw["id"].toInt();
			}
		}
	}
	if (jda.hasError()) {
		id = 0;
		bb::data::DataAccessError error = jda.error();
		qDebug() << "JSON loading error: " << error.errorType() << ": "
				<< error.errorMessage();
	}
	if (!flagIn) {
		return 0;
	}
	return id;
}
Example #8
0
QVariantList Nuria::RestfulHttpNode::deepConvertList (QVariantList list) {
	for (auto it = list.begin (), end = list.end (); it != end; ++it) {
		*it = serializeVariant (*it);
	}
	
	return list;
	
}
Example #9
0
    /**
     * Load settings from the map. Existings settings will be overwritten.
     */
    void SettingsManager::loadFromMap(QVariantMap &map)
    {
        // 1. Load version
        _version = map.value("version").toString();

        // 2. Load UUID encoding
        int encoding = map.value("uuidEncoding").toInt();
        if (encoding > 3 || encoding < 0)
            encoding = 0;

        _uuidEncoding = (UUIDEncoding) encoding;


        // 3. Load view mode
        if (map.contains("viewMode")) {
            int viewMode = map.value("viewMode").toInt();
            if (viewMode > 2 || encoding < 0)
                viewMode = Custom; // Default View Mode
            _viewMode = (ViewMode) viewMode;
        } else {
            _viewMode = Custom; // Default View Mode
        }

        _autoExpand = map.contains("autoExpand") ?
            map.value("autoExpand").toBool() : true;

        _lineNumbers = map.contains("lineNumbers") ?
            map.value("lineNumbers").toBool() : true;

        // 4. Load TimeZone
        int timeZone = map.value("timeZone").toInt();
        if (timeZone > 1 || timeZone < 0)
            timeZone = 0;

        _timeZone = (SupportedTimes) timeZone;
        _loadMongoRcJs = map.value("loadMongoRcJs").toBool();
        _disableConnectionShortcuts = map.value("disableConnectionShortcuts").toBool();

        // Load Batch Size
        _batchSize = map.value("batchSize").toInt();
        if (_batchSize == 0)
            _batchSize = 50;
        _currentStyle = map.value("style").toString();
        if (_currentStyle.isEmpty()) {
            _currentStyle = AppStyle::StyleName;
        }

        // 5. Load connections
        _connections.clear();

        QVariantList list = map.value("connections").toList();
        for (QVariantList::iterator it = list.begin(); it != list.end(); ++it) {
            ConnectionSettings *record = new ConnectionSettings((*it).toMap());
            _connections.push_back(record);
        }
    }
Example #10
0
int Player::addMultipleItemsToQueue(const QVariantList& payloads)
{
  if (m_player)
  {
    std::vector<SONOS::DigitalItemPtr> items;
    for (QVariantList::const_iterator it = payloads.begin(); it != payloads.end(); ++it)
      items.push_back(it->value<SONOS::DigitalItemPtr>());
    return m_player->AddMultipleURIsToQueue(items);
  }
  return 0;
}
// For QML
QVariantList
RuleConditionNFC::getUidsQml() const {
    QVariantList uids;
    for (QSet<QByteArray>::const_iterator i = _uids.constBegin(); i != _uids.constEnd(); ++i) {
        QString uidHex(i->toHex());
        uids << uidHex; // QVariant::fromValue(*i);
    }
    qSort(uids.begin(), uids.end(), variantQStringLessThan);
    return uids;

}
Example #12
0
void jpush_setTags(QVariantList tags)
{
    QString st;
    for(auto it = tags.begin(); it != tags.end(); ++it){
        st += (*it).toString() + ",";
    }
    st.remove(st.length()-1, 1);
    qDebug() << "******************* st=" << st;
    QAndroidJniObject jst = QAndroidJniObject::fromString(st);
    QAndroidJniObject::callStaticMethod<void>("qkit/KJPush","setTags","(Ljava/lang/String;)V", jst.object<jstring>());
}
Example #13
0
void QueueResourcesList::fromQVariantList(QVariantList const& list)
{
   QVariantList::const_iterator iter;
   for (iter = list.begin(); iter != list.end(); ++iter) {
       QueueResources* queue(new QueueResources());
       if (queue->fromQVariant(*iter)) {
          append(queue);
       } else {
          delete queue;
       }
   }
}
Example #14
0
QString MailAddress::prettyList(const QVariantList &list, FormattingMode mode)
{
    QStringList buf;
    for (QVariantList::const_iterator it = list.begin(); it != list.end(); ++it) {
        Q_ASSERT(it->type() == QVariant::StringList);
        QStringList item = it->toStringList();
        Q_ASSERT(item.size() == 4);
        MailAddress a(item[0], item[1], item[2], item[3]);
        buf << a.prettyName(mode);
    }
    return buf.join(QLatin1String(", "));
}
Example #15
0
void SimpleClient::load(const QVariant& settings)
{
    const QVariantMap map = settings.toMap();

    if (map.contains("dialogs"))
    {
        const QVariantList list = map.value("dialogs").toList();

        for (QVariantList::const_iterator it = list.begin();
                it != list.end(); ++it)
        {
            const QVariantMap map = it->toMap();
            const QString operation = map["operation"].toString();

            if (!operation.isEmpty() && map.contains("value"))
            {
                // find the index
                unsigned int i = 0;
                const unsigned int count =
                    m_objref->interface()->operation_count();

                for (; i < count; i++)
                {
                    const char * current =
                            m_objref->interface()->get_reflective_by_index(
                                    i)->get_name();

                    if (operation == current) break;
                }

                // load its saved value
                if (i < count)
                {
                    getRequestDialog(i)->load(map.value("value"));
                }
            }
        }
    }

    if (map.contains("filtered_log"))
    {
        m_filteredLog->load(map["filtered_log"]);
    }

    if (map.contains("operations"))
    {
        // ensure created
        showOperationSequenceTool();

        m_seqTool->load(map["operations"]);
    }
}
Example #16
0
void AudioPlayer::audioStateChanged(const QVariantMap &data)
{
    QVariantList players = data["audio_players"].toList();
    QVariantList::iterator it = players.begin();
    for (;it != players.end();it++)
    {
        QVariantMap r = it->toMap();
        if (r["player_id"].toString() == playerData["id"].toString())
        {
            load(r);
            break;
        }
    }
}
Example #17
0
void FilterModel::load(const QVariant& settings)
{
    const QVariantList list = settings.toList();

    for (QVariantList::const_iterator it = list.begin(); 
            it != list.end(); ++it) 
    {
        const QVariantMap map = it->toMap();

        if (!map.contains("instance") || !map.contains("operations"))
            continue;

        // Name to ID conversion
        const QString instance = map["instance"].toString();

        if (instance.isEmpty()) continue;

        Objref_ptr objref = m_instances.find(instance);

        if (!objref) continue;

        FirstLevelItems_t::iterator fit =  m_items.find(objref->id());

        if (fit == m_items.end()) continue;

        // End Name to ID conversion
        
        const QVariantMap operations = map["operations"].toMap();

        for (unsigned int j = 0; 
                j < objref->interface()->operation_count(); j++) 
        {
            OperationDescriptor_ptr op = 
                objref->interface()->get_reflective_by_index(j);
            tag_t tag = op->get_tag();

            OperationsMap_t::iterator opit = 
                fit.value().operations.find(tag);

            if(operations.contains(op->get_name()) && 
                    opit != fit.value().operations.end())
            {
                bool state = operations[op->get_name()].toBool();

                opit.value()->setCheckState((state)?
                        Qt::Checked: Qt::Unchecked);
            }
        }
    }
}
Example #18
0
bool SearchPattern::check(const QVariantList& other)
{
    if (m_conditions.size() != other.size())
        return false;

    QList<Condition>::iterator cond_it = m_conditions.begin();
    QList<QVariant>::const_iterator data_it = other.begin();

    for (; cond_it != m_conditions.end(); ++cond_it, ++data_it) {
        if (!cond_it->check(*data_it))
            return false;
    }

    return true;
}
Example #19
0
QList<Notification> parseNotificationJson(const QVariantList &json)
{
    QList<Notification> item_list;

    for(QVariantList::const_iterator it = json.begin(); it != json.end(); ++it)
    {
        QVariantMap notification = it->toMap();
        Notification notif;
        notif.contentID = notification["contentId"].toString();
        notif.status = notification["status"].toString();
        item_list.append(notif);
    }

    return item_list;
}
QVariantMap
YTVideoUrlFetcher::parseResponse(QJsonDocument doc)
{
    Q_ASSERT(doc.isObject());
    QVariantMap map = doc.object().toVariantMap();

    if (!map.contains("formats")) {
        qCritical() << "Output JSON does not contain formats array";
        return QVariantMap();
    }

    QVariant formats = map["formats"];
    if (formats.type() != QVariant::List) {
        qCritical() << "Formats is not an array!" << formats.type();
        return QVariantMap();
    }

    QVariantMap response;
    QVariantList lst = formats.toList();
    QVariantList::iterator it = lst.begin();
    for (;it != lst.end(); ++it) {
        QVariantMap entry = it->toMap();
        if (entry.isEmpty())
            continue;
        if (!entry.contains("format_id") || !entry.contains("url"))
            continue;

        QVariantMap details;
        details["url"] = entry["url"];

        int itag = entry["format_id"].toInt();
        switch (itag) {
        case 18:
            response.insert("360p", details);
            break;
        case 22:
            response.insert("720p", details);
            break;
        case 37:
            response.insert(("1080p"), details);
            break;
        }
    }

    return response;
}
Example #21
0
QVariant AccessClass::callMethod(ForeignObject *obj, size_t id, const QVariantList &args)
{
    auto self = static_cast<AccessWrapper *>(obj)->wrappedValue();
    QVariant ret;
    withGvl([&] {
        std::vector<VALUE> values(args.size());
        std::transform(args.begin(), args.end(), values.begin(), &RubyValue::from<QVariant>);
        RubyValue retValue;
        protect([&] {
            rescueNotify([&] {
                retValue = rb_funcall2(self, id, values.size(), values.data());
            });
        });
        ret = retValue.to<QVariant>();
    });
    return ret;
}
Example #22
0
void JSONSerializer::serialize(const QVariant &variant) {
	if (!variant.isValid()) { // Case of JSON null/undefined
		// TODO:find a way to differenciate null/undefined
		m_stream << JSON_NULL;
	} else if (variant.type() == QVariant::Bool) { // Case of JSON boolean
		m_stream << (variant.toBool() ? JSON_TRUE: JSON_FALSE);
	} else if (variant.type() == QVariant::Map) { // Case of JSON object
		m_stream << JSON_OBJECT_BEGIN;
		const QVariantMap elements = variant.toMap();
		auto it = elements.begin();
		if (it != elements.end()) {
			m_stream << sanitizeString(it.key()) << JSON_MEMBER_SEP;
			serialize(it.value());
			it++;
		}
		while (it != elements.end()) {
			m_stream << JSON_ELEMENT_SEP << sanitizeString(it.key()) << JSON_MEMBER_SEP;
			serialize(it.value());
			it++;
		}
		m_stream << JSON_OBJECT_END;
	} else if (variant.type() == QVariant::List) { // Case of JSON array
		m_stream << JSON_ARRAY_BEGIN;
		const QVariantList elements = variant.toList();
		auto it = elements.begin();
		if (it != elements.end()) {
			serialize(*it);
			it++;
		}
		while (it != elements.end()) {
			m_stream << JSON_MEMBER_SEP;
			serialize(*it);
			it++;
		}
		m_stream << JSON_ARRAY_END;
	} else if ((variant.type() == QVariant::String) 
		|| (variant.type() == QVariant::ByteArray)) { // Case of JSON string
		m_stream << sanitizeString(variant.toString());
	} else if ((variant.type() == QVariant::Double) || variant.canConvert<double>()) {
		m_stream << QString::number(variant.toDouble()).replace("inf", "infinity");
	} else if ((variant.type() == QVariant::String) || variant.canConvert<QString>()) {
		m_stream << variant.toString();
	} else {
		throw JSONSerializerException("Fatal: QVariant type not managed.");
	}
}
Example #23
0
    /**
     * Load settings from config file.
     * @return true if success, false otherwise
     */
    bool SettingsManager::load()
    {
        bool result = false;
        if(QFile::exists(_configPath))
        {
            QFile f(_configPath);
            if(f.open(QIODevice::ReadOnly))
            {
                QJson::Parser parser;
                bool ok;
                QVariantMap map = parser.parse(f.readAll(), &ok).toMap();
                if(ok)
                {
                    // 1. Load version
                    _version = map.value("version").toString();

                    // 2. Load UUID encoding
                    int encoding = map.value("uuidEncoding").toInt();
                    if (encoding > 3 || encoding < 0)
                        encoding = 0;

                    _uuidEncoding = (UUIDEncoding) encoding;

                    // 3. Load view mode
                    int viewMode = map.value("viewMode").toInt();
                    if (viewMode > 2 || encoding < 0)
                        viewMode = 0;

                    _viewMode = (ViewMode) viewMode;

                    // 4. Load connections
                    _connections.clear();

                    QVariantList list = map.value("connections").toList();
                    for(QVariantList::iterator it = list.begin();it!=list.end();++it) {
                        ConnectionSettings *record = new ConnectionSettings((*it).toMap());
                        _connections.append(record);
                    }
                    result = true;
                }
            }
        }
        return result;
    }
Example #24
0
 bool TabRow::update(const QVariantList& args) const
 {
   if (args.length() == 0)
   {
     return true;  // nothing to do
   }
   
   if ((args.length() % 2) != 0)
   {
     throw std::invalid_argument("Update row: Need an even number of arguments (column / value pairs)");
   }
   
   // create the SQL statement
   QString sql = "UPDATE " + tabName + " SET ";
   
   // split the combined column/values list in "args" into a separate list of values
   QVariantList vals;
   QVariantList::const_iterator i = args.begin();
   while (i != args.end())
   {
     QString colName = (*i).toString();
     if (colName == "id")
     {
       throw std::invalid_argument("Update row: can't alter value of the ID column!");
     }
     sql += colName + " = ?, ";
     i++;
     vals << (*i);
     i++;
   }
   
   // remove the trailing ", "
   sql = sql.left(sql.length() - 2);
   
   // complete the statement
   sql += " WHERE id = ?";
   vals << rowId;
   
   int result = db->execNonQuery(sql, vals);
   
   return (result == 1);
 }
Example #25
0
void AudioModel::load(const QVariantMap &homeData)
{
    clear();

    if (!homeData.contains("audio"))
    {
        qDebug() << "no audio entry";
        return;
    }

    QVariantList players = homeData["audio"].toList();
    QVariantList::iterator it = players.begin();
    for (;it != players.end();it++)
    {
        QVariantMap r = it->toMap();
        AudioPlayer *p = new AudioPlayer(connection);
        p->load(r);
        appendRow(p);
    }
}
Example #26
0
void CameraModel::load(const QVariantMap &homeData)
{
    clear();

    if (!homeData.contains("cameras"))
    {
        qDebug() << "no camera entry";
        return;
    }

    QVariantList cameras = homeData["cameras"].toList();
    QVariantList::iterator it = cameras.begin();
    for (int i = 0;it != cameras.end();it++, i++)
    {
        QVariantMap r = it->toMap();
        CameraItem *p = new CameraItem(connection);
        p->load(r, i);
        appendRow(p);
    }
}
Example #27
0
QVariantList SettingsUi::getApplications()
{
    QVariantList tmp;
    QVariantMap map;
    QFileInfoList list;
    QDir dir;

    dir.setPath("/usr/share/applications/");
    dir.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
    dir.setNameFilters(QStringList() << "*.desktop");
    dir.setSorting(QDir::Name);

    list = dir.entryInfoList();

    for (int i=0 ; i<list.size() ; i++)
    {
        MDesktopEntry app(list.at(i).absoluteFilePath());

        if (!app.hidden() && !app.icon().isEmpty() && !app.noDisplay() && !app.notShowIn().contains("X-Meego"))
        {
            map.clear();
            map.insert("filePath", list.at(i).absoluteFilePath());
            map.insert("name", app.name());
            if (app.icon().startsWith("icon-launcher-") || app.icon().startsWith("icon-l-") || app.icon().startsWith("icons-Applications"))
                map.insert("iconId", QString("image://theme/%1").arg(app.icon()));
            else if (app.icon().startsWith("/"))
                map.insert("iconId", QString("%1").arg(app.icon()));
            else
                map.insert("iconId", QString("/usr/share/icons/hicolor/86x86/apps/%1.png").arg(app.icon()));

            map.insert("isAndroid", app.exec().contains("apkd-launcher"));

            tmp.append(map);
        }
    }

    // sort them by application name
    std::sort(tmp.begin(), tmp.end(), appNameLessThan);

    return tmp;
}
void Actor::setShapes(const QVariantList& shapes)
{
    _shapes = shapes;
    _geode->removeDrawables(0, _geode->getNumDrawables());

    for(auto i = shapes.begin(); i != shapes.end(); ++i)
    {
        QVariantMap entry = i->toMap();
        if(!entry.contains("prototype"))
        {
            qDebug() << "Shape contains no prototype name!?!";
            continue;
        }
        QString prototype = entry["prototype"].toString();
        QVariantMap val = entry["value"].toMap();

        osg::ref_ptr<osg::ShapeDrawable> sd = new osg::ShapeDrawable();
        
        using namespace QtEntity;

        if(prototype == "Box")
        {
            osg::Vec3 hl = toVec(val["HalfLengths"]);
            osg::Vec3 c = toVec(val["Center"]);
            sd->setShape(new osg::Box(c, hl[0],hl[1],hl[2]));
            
        }
        else if(prototype == "Sphere")
        {
            osg::Vec3 c = toVec(val["Center"]);
            float radius = val["Radius"].toFloat();
            sd->setShape(new osg::Sphere(c, radius));
        }
        QColor co = val["Color"].value<QColor>();
        sd->setColor(osg::Vec4(co.redF(), co.greenF(), co.blueF(), co.alphaF()));
        _geode->addDrawable(sd);

    }
}
Example #29
0
Pelatihan::Pelatihan(bb::cascades::Application *app) :
		QObject(app) {
	// create scene document from main.qml asset
	// set parent to created document to ensure it exists for the whole application lifetime


	qmlRegisterType<WebImageView>("WebImageView", 1, 0, "WebImageView");
	QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);


	// create root object for the UI
	AbstractPane *root = qml->createRootObject<AbstractPane>();
	ListView *lv= root->findChild<ListView*>("listdata");

	bb::data::JsonDataAccess jda;

	QVariant data = jda.load(
			QDir::currentPath() + "/app/native/assets/db.json");

	QVariantList dataList = data.toList();

	qDebug()<< dataList.size();
	GroupDataModel *dm = new GroupDataModel(QStringList() << "id");
	dm->setGrouping(ItemGrouping::None);

	for (QList<QVariant>::iterator it = dataList.begin(); it != dataList.end();
			it++) {
		QVariantMap post = it->toMap();
		dm->insert(post);
	}


	lv->setDataModel(dm);


	// set created root object as a scene
	app->setScene(root);
}
Example #30
0
    void ConnectionSettings::fromVariant(const QVariantMap &map) {
        setConnectionName(QtUtils::toStdString(map.value("connectionName").toString()));
        setServerHost(QtUtils::toStdString(map.value("serverHost").toString().left(maxLength)));
        setServerPort(map.value("serverPort").toInt());
        setDefaultDatabase(QtUtils::toStdString(map.value("defaultDatabase").toString()));
        setReplicaSet(map.value("isReplicaSet").toBool());       
        
        QVariantList list = map.value("credentials").toList();
        for (QVariantList::const_iterator it = list.begin(); it != list.end(); ++it) {
            QVariant var = *it;
            CredentialSettings *credential = new CredentialSettings(var.toMap());
            addCredential(credential);
        }

        if (map.contains("ssh")) {
            _sshSettings->fromVariant(map.value("ssh").toMap());
        }

        if (map.contains("ssl")) {
            _sslSettings->fromVariant(map.value("ssl").toMap());
        }

        if (isReplicaSet()) {
            _replicaSetSettings->fromVariant(map.value("replicaSet").toMap());
        }

        // If UUID has never been created or is empty, create a new one. Otherwise load the existing.
        if (!map.contains("uuid") || map.value("uuid").toString().isEmpty())
            _uuid = QUuid::createUuid().toString();
        else
            _uuid = map.value("uuid").toString();


//#ifdef MONGO_SSL
//      ,SSLInfo(map.value("sslEnabled").toBool(),QtUtils::toStdString(map.value("sslPemKeyFile").toString()))
//#endif
    }