Exemple #1
0
QVariantMap authActionQueryPerms(int i, QIODevice *connection,
	const QSqlDatabase& db, const QSqlDatabase& user_db,
	const QVariantMap& action, const QString& email)
{
	Q_UNUSED(i);
	Q_UNUSED(db);
	Q_UNUSED(user_db);
	Q_UNUSED(connection);

	if( action.contains("email") )
	{
		QVariantMap perms = auth->queryPerms(
			action.value("email").toString() ).toMap();
		perms.remove("any");

		QVariantMap map;
		map["email"] = action.value("email");
		map["perms"] = perms;

		return map;
	}
	else
	{
		QVariantMap perms = auth->queryPerms(email).toMap();
		perms.remove("any");

		QVariantMap map;
		map["email"] = email;
		map["perms"] = perms;

		return map;
	}
}
/**
 * @brief FilePersistence::modifyAccountObject
 * @param modifications
 * @return
 */
bool FilePersistence::modifyAccountObject(const OptionTable &modifications)
{
    int index = findAccountObj(modifications);
    if (index < 0) {
        m_error.append(QString("Could not modify Account object !\n"));
        m_error.append(QString("There is no such an Account object.\n"));
        return false;
    }
    QVariantMap modifyValues = variantMapFromOptionTable(modifications);
    if (modifications.contains('i')) {
        modifyValues.remove(optionToRealName('i'));
    } else {
        modifyValues.remove(optionToRealName('p'));
        modifyValues.remove(optionToRealName('u'));
    }
    QVariantMap originObject = m_fileContent[index];
    QStringList keyList = modifyValues.keys();
    for (int index=0; index<keyList.size(); ++index) {
        QVariant value = modifyValues.value(keyList[index]);
        originObject.insert(keyList[index], value);
    }
    m_isModified = true;

    return true;
}
void BoneLimitsMutation::mutate(QVariantMap &lowerLimits, QVariantMap &upperLimits)
{
    // foreach axis...
    QString allAxis[] = {"x","y","z"};
    for(int i=0;i<3;i++){

        QString axis = allAxis[i];
        btScalar loValue = lowerLimits[axis].toDouble();
        btScalar upValue = upperLimits[axis].toDouble();

        loValue = axisMutation->mutate(loValue);
        upValue = axisMutation->mutate(upValue);

        // Y axis limited between -SIMD_PI/2..SIMD_PI/2
        if(axis == "y") {
            if(loValue < -SIMD_HALF_PI+0.1)
                loValue = -SIMD_HALF_PI+0.1;

            if(upValue > SIMD_HALF_PI-0.1)
                upValue = SIMD_HALF_PI-0.1;
        }

        // 0 must be included between lo and up
        if(loValue > 0)
            loValue = 0;

        if(upValue < 0)
            upValue = 0;

        lowerLimits.remove(axis);
        upperLimits.remove(axis);
        lowerLimits.insert(axis,QVariant((double)loValue));
        upperLimits.insert(axis,QVariant((double)upValue));
    }
}
Exemple #4
0
std::shared_ptr<StartEndRenderState> ParabolaPointer::buildRenderState(const QVariantMap& propMap) {
    QUuid startID;
    if (propMap["start"].isValid()) {
        QVariantMap startMap = propMap["start"].toMap();
        if (startMap["type"].isValid()) {
            startMap.remove("visible");
            startID = qApp->getOverlays().addOverlay(startMap["type"].toString(), startMap);
        }
    }

    glm::vec3 color = glm::vec3(RenderState::ParabolaRenderItem::DEFAULT_PARABOLA_COLOR);
    float alpha = RenderState::ParabolaRenderItem::DEFAULT_PARABOLA_COLOR.a;
    float width = RenderState::ParabolaRenderItem::DEFAULT_PARABOLA_WIDTH;
    bool isVisibleInSecondaryCamera = RenderState::ParabolaRenderItem::DEFAULT_PARABOLA_ISVISIBLEINSECONDARYCAMERA;
    bool drawInFront = RenderState::ParabolaRenderItem::DEFAULT_PARABOLA_DRAWINFRONT;
    bool enabled = false;
    if (propMap["path"].isValid()) {
        enabled = true;
        QVariantMap pathMap = propMap["path"].toMap();
        if (pathMap["color"].isValid()) {
            color = toGlm(u8vec3FromVariant(pathMap["color"]));
        }

        if (pathMap["alpha"].isValid()) {
            alpha = pathMap["alpha"].toFloat();
        }

        if (pathMap["width"].isValid()) {
            width = pathMap["width"].toFloat();
        }

        if (pathMap["isVisibleInSecondaryCamera"].isValid()) {
            isVisibleInSecondaryCamera = pathMap["isVisibleInSecondaryCamera"].toBool();
        }

        if (pathMap["drawInFront"].isValid()) {
            drawInFront = pathMap["drawInFront"].toBool();
        }
    }

    QUuid endID;
    if (propMap["end"].isValid()) {
        QVariantMap endMap = propMap["end"].toMap();
        if (endMap["type"].isValid()) {
            endMap.remove("visible");
            endID = qApp->getOverlays().addOverlay(endMap["type"].toString(), endMap);
        }
    }

    return std::make_shared<RenderState>(startID, endID, color, alpha, width, isVisibleInSecondaryCamera, drawInFront, enabled);
}
Exemple #5
0
/**
 * The function returns the changed data from the server to synchronize with the web client.
 * Return value is map in JSON format.
 * Map contain the key:
 *  - "Rid": ID response
 * Map can contain the keys:
 *  - "full_update": full data update flag
 *  - "torrents": dictionary contains information about torrents.
 *  - "torrents_removed": a list of hashes of removed torrents
 *  - "labels": list of labels
 *  - "labels_removed": list of removed labels
 *  - "server_state": map contains information about the state of the server
 * The keys of the 'torrents' dictionary are hashes of torrents.
 * Each value of the 'torrents' dictionary contains map. The map can contain following keys:
 *  - "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
 * Server state map may contain the following keys:
 *  - "connection_status": conection status
 *  - "dht_nodes": DHT nodes count
 *  - "dl_info_data": bytes downloaded
 *  - "dl_info_speed": download speed
 *  - "dl_rate_limit: downlaod rate limit
 *  - "up_info_data: bytes uploaded
 *  - "up_info_speed: upload speed
 *  - "up_rate_limit: upload speed limit
 *  - "queueing": priority system usage flag
 *  - "refresh_interval": torrents table refresh interval
 */
QByteArray btjson::getSyncMainData(int acceptedResponseId, QVariantMap &lastData, QVariantMap &lastAcceptedData)
{
    QVariantMap data;

    QVariantHash torrents;

    std::vector<torrent_handle> torrentsList = QBtSession::instance()->getTorrents();
    std::vector<torrent_handle>::const_iterator it = torrentsList.begin();
    std::vector<torrent_handle>::const_iterator end = torrentsList.end();

    for (; it != end; ++it) {
        QTorrentHandle torrent = QTorrentHandle(*it);
        QVariantMap map = toMap(torrent);
        map.remove(KEY_TORRENT_HASH);
        torrents[torrent.hash()] = map;
    }

    data["torrents"] = torrents;

    QVariantList labels;
    foreach (QString s, Preferences::instance()->getTorrentLabels())
        labels << s;

    data["labels"] = labels;

    QVariantMap serverState = getTranserInfoMap();
    serverState[KEY_SYNC_MAINDATA_QUEUEING] = QBtSession::instance()->isQueueingEnabled();
    serverState[KEY_SYNC_MAINDATA_USE_ALT_SPEED_LIMITS] = Preferences::instance()->isAltBandwidthEnabled();
    serverState[KEY_SYNC_MAINDATA_REFRESH_INTERVAL] = Preferences::instance()->getRefreshInterval();
    data["server_state"] = serverState;

    return json::toJson(generateSyncData(acceptedResponseId, data, lastAcceptedData, lastData));
}
    void PrefabSystem::updateComponentInPrefab(const QString& path, const QString& component, const QVariantMap& values, bool updateInstances)
    {
        EntitySystem* es = entityManager()->system(component);
        Q_ASSERT(es);

        auto i = _prefabs.find(path);
        if(i == _prefabs.end())
        {
            return;
        }
        Prefab* prefab = i.value().data();
        QVariantMap current = prefab->components()[component].toMap();
        for(QString param : values.keys())
        {
            current[param] = values[param];
        }

        for(QString param : prefab->parameters())
        {
            current.remove(param);
        }
        prefab->_components[component] = current;


        if(updateInstances)
        {
            for(auto k = this->begin(); k != this->end(); ++k)
            {
                if(es->component(k->first))
                {
                    es->fromVariantMap(k->first, values);
                }
            }
        }
    }
void EditAccountDialog::accept()
{
    if (!d->widget) {
        kWarning() << "missing d->widget, not saving parameters";
        return;
    }

    QVariantMap setParameters = d->widget->parametersSet();
    QStringList unsetParameters = d->widget->parametersUnset();

    // Check all pages of parameters pass validation.
    if (!d->widget->validateParameterValues()) {
        kDebug() << "A widget failed parameter validation. Not accepting wizard.";
        return;
    }

    //remove password from setParameters as this is now stored by kwallet instead
    setParameters.remove(QLatin1String("password"));
    unsetParameters.append(QLatin1String("password")); //remove the password from mission control

    Tp::PendingStringList *psl = d->account->updateParameters(setParameters, unsetParameters);

    kDebug() << "Set parameters:" << setParameters;
    kDebug() << "Unset parameters:" << unsetParameters;

    connect(psl,
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onParametersUpdated(Tp::PendingOperation*)));
}
	bool BookmarksManagerDialog::CheckSave (const QModelIndex& index)
	{
		if (!index.isValid ())
			return false;

		if (!CurrentEditor_)
			return false;

		QStandardItem *item = BMModel_->itemFromIndex (index);
		if (!item)
			return false;

		QVariantMap oldMap = item->data ().toMap ();
		const QVariantMap& ourMap = CurrentEditor_->GetIdentifyingData ();
		if (!ourMap.contains ("AccountID"))
			oldMap.remove ("AccountID");

		if (oldMap == ourMap)
			return false;

		if (QMessageBox::question (this,
					tr ("Save the bookmark?"),
					tr ("You've changed the bookmark. Do you want to save the changes?"),
					QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)
			return false;

		item->setData (ourMap);
		Save ();
		return true;
	}
Exemple #9
0
/**
 * The function returns the changed data from the server to synchronize with the web client.
 * Return value is map in JSON format.
 * Map contain the key:
 *  - "Rid": ID response
 * Map can contain the keys:
 *  - "full_update": full data update flag
 *  - "torrents": dictionary contains information about torrents.
 *  - "torrents_removed": a list of hashes of removed torrents
 *  - "categories": list of categories
 *  - "categories_removed": list of removed categories
 *  - "server_state": map contains information about the state of the server
 * The keys of the 'torrents' dictionary are hashes of torrents.
 * Each value of the 'torrents' dictionary contains map. The map can contain following keys:
 *  - "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
 * Server state map may contain the following keys:
 *  - "connection_status": connection status
 *  - "dht_nodes": DHT nodes count
 *  - "dl_info_data": bytes downloaded
 *  - "dl_info_speed": download speed
 *  - "dl_rate_limit: download rate limit
 *  - "up_info_data: bytes uploaded
 *  - "up_info_speed: upload speed
 *  - "up_rate_limit: upload speed limit
 *  - "queueing": priority system usage flag
 *  - "refresh_interval": torrents table refresh interval
 */
QByteArray btjson::getSyncMainData(int acceptedResponseId, QVariantMap &lastData, QVariantMap &lastAcceptedData)
{
    QVariantMap data;
    QVariantHash torrents;

    BitTorrent::Session *const session = BitTorrent::Session::instance();

    foreach (BitTorrent::TorrentHandle *const torrent, session->torrents()) {
        QVariantMap map = toMap(torrent);
        map.remove(KEY_TORRENT_HASH);
        torrents[torrent->hash()] = map;
    }

    data["torrents"] = torrents;

    QVariantList categories;
    foreach (const QString &category, session->categories())
        categories << category;

    data["categories"] = categories;

    QVariantMap serverState = getTranserInfoMap();
    serverState[KEY_SYNC_MAINDATA_QUEUEING] = session->isQueueingSystemEnabled();
    serverState[KEY_SYNC_MAINDATA_USE_ALT_SPEED_LIMITS] = session->isAltGlobalSpeedLimitEnabled();
    serverState[KEY_SYNC_MAINDATA_REFRESH_INTERVAL] = session->refreshInterval();
    data["server_state"] = serverState;

    return json::toJson(generateSyncData(acceptedResponseId, data, lastAcceptedData, lastData));
}
Exemple #10
0
// DeviceInterface
DeviceInterface::DeviceInterface(const QDBusObjectPath &path, const QVariantMap &properties, QObject *parent)
    : QDBusAbstractAdaptor(parent)
    , m_mediaPlayer(0)
{
    setPath(path);
    setObjectParent(parent);
    setProperties(properties);
    setName(QStringLiteral("org.bluez.Device1"));

    // Alias needs special handling
    setAlias(properties.value(QStringLiteral("Alias")).toString());

    // Create Input1
    if (properties.contains(QStringLiteral("Input"))) {
        const QVariantMap &inputProps = qdbus_cast<QVariantMap>(properties.value(QStringLiteral("Input")));
        InputInterface *input = new InputInterface(path, inputProps, parent);

        ObjectManager *manager = ObjectManager::self();
        manager->addObject(input);

        QVariantMap props = properties;
        props.remove(QStringLiteral("Input"));
        setProperties(props);
    }
}
void XmlToQtScript::SimplifyMouseMovementsPostProcessor::process(Item* iterator, QList<Item>* in)
{
	if(iterator->method == "moveMouse")
	{
		const QVariant target = iterator->target;
		const QString targetClass = iterator->targetClass;
		QVariantMap parameters = iterator->parameters.toMap();
		const QPoint origin = QPoint(
			parameters.value("x").toInt(),
			parameters.value("y").toInt()
		);
		int duration = 0;
		while(!in->isEmpty())
		{
			Item msec;
			msec = in->takeFirst(); // msec << pointing at
			duration += msec.parameters.toInt();

			if(in->isEmpty())
			{
				*iterator = msec;
				break;
			}

			*iterator = in->takeFirst(); // ? Unknown
			if(iterator->method != "moveMouse" || iterator->target != target)
			{
				in->prepend(*iterator);
				*iterator = msec;
				break;
			}
			parameters = iterator->parameters.toMap();
		}
		const QPoint destination = QPoint(
			parameters.value("x").toInt(),
			parameters.value("y").toInt()
		);
		parameters.remove("x");
		parameters.remove("y");
		parameters.insert("originX", origin.x());
		parameters.insert("originY", origin.y());
		parameters.insert("destinationX", destination.x());
		parameters.insert("destinationY", destination.y());
		parameters.insert("duration", duration);
		insertItem(
			Item(
				target,
				targetClass,
				"moveMouse",
				parameters
			),
			BeforeCurrentItem
		);
	}
}
// The function returns the changed data from the server to synchronize with the web client.
// Return value is map in JSON format.
// Map contain the key:
//  - "Rid": ID response
// Map can contain the keys:
//  - "full_update": full data update flag
//  - "torrents": dictionary contains information about torrents.
//  - "torrents_removed": a list of hashes of removed torrents
//  - "categories": map of categories info
//  - "categories_removed": list of removed categories
//  - "server_state": map contains information about the state of the server
// The keys of the 'torrents' dictionary are hashes of torrents.
// Each value of the 'torrents' dictionary contains map. The map can contain following keys:
//  - "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
//  - "completion_on": Torrent copletion time
//  - "tracker": Torrent tracker
//  - "dl_limit": Torrent download limit
//  - "up_limit": Torrent upload limit
//  - "downloaded": Amount of data downloaded
//  - "uploaded": Amount of data uploaded
//  - "downloaded_session": Amount of data downloaded since program open
//  - "uploaded_session": Amount of data uploaded since program open
//  - "amount_left": Amount of data left to download
//  - "save_path": Torrent save path
//  - "completed": Amount of data completed
//  - "max_ratio": Upload max share ratio
//  - "max_seeding_time": Upload max seeding time
//  - "ratio_limit": Upload share ratio limit
//  - "seeding_time_limit": Upload seeding time limit
//  - "seen_complete": Indicates the time when the torrent was last seen complete/whole
//  - "last_activity": Last time when a chunk was downloaded/uploaded
//  - "total_size": Size including unwanted data
// Server state map may contain the following keys:
//  - "connection_status": connection status
//  - "dht_nodes": DHT nodes count
//  - "dl_info_data": bytes downloaded
//  - "dl_info_speed": download speed
//  - "dl_rate_limit: download rate limit
//  - "up_info_data: bytes uploaded
//  - "up_info_speed: upload speed
//  - "up_rate_limit: upload speed limit
//  - "queueing": priority system usage flag
//  - "refresh_interval": torrents table refresh interval
//  - "free_space_on_disk": Free space on the default save path
// GET param:
//   - rid (int): last response id
void SyncController::maindataAction()
{
    auto lastResponse = sessionManager()->session()->getData(QLatin1String("syncMainDataLastResponse")).toMap();
    auto lastAcceptedResponse = sessionManager()->session()->getData(QLatin1String("syncMainDataLastAcceptedResponse")).toMap();

    QVariantMap data;
    QVariantHash torrents;

    BitTorrent::Session *const session = BitTorrent::Session::instance();

    for (BitTorrent::TorrentHandle *const torrent : asConst(session->torrents())) {
        QVariantMap map = serialize(*torrent);
        map.remove(KEY_TORRENT_HASH);

        // Calculated last activity time can differ from actual value by up to 10 seconds (this is a libtorrent issue).
        // So we don't need unnecessary updates of last activity time in response.
        if (lastResponse.contains("torrents") && lastResponse["torrents"].toHash().contains(torrent->hash()) &&
                lastResponse["torrents"].toHash()[torrent->hash()].toMap().contains(KEY_TORRENT_LAST_ACTIVITY_TIME)) {
            uint lastValue = lastResponse["torrents"].toHash()[torrent->hash()].toMap()[KEY_TORRENT_LAST_ACTIVITY_TIME].toUInt();
            if (qAbs(static_cast<int>(lastValue - map[KEY_TORRENT_LAST_ACTIVITY_TIME].toUInt())) < 15)
                map[KEY_TORRENT_LAST_ACTIVITY_TIME] = lastValue;
        }

        torrents[torrent->hash()] = map;
    }

    data["torrents"] = torrents;

    QVariantHash categories;
    const auto categoriesList = session->categories();
    for (auto it = categoriesList.cbegin(); it != categoriesList.cend(); ++it) {
        const auto key = it.key();
        categories[key] = QVariantMap {
            {"name", key},
            {"savePath", it.value()}
        };
    }

    data["categories"] = categories;

    QVariantMap serverState = getTranserInfo();
    serverState[KEY_TRANSFER_FREESPACEONDISK] = getFreeDiskSpace();
    serverState[KEY_SYNC_MAINDATA_QUEUEING] = session->isQueueingSystemEnabled();
    serverState[KEY_SYNC_MAINDATA_USE_ALT_SPEED_LIMITS] = session->isAltGlobalSpeedLimitEnabled();
    serverState[KEY_SYNC_MAINDATA_REFRESH_INTERVAL] = session->refreshInterval();
    data["server_state"] = serverState;

    const int acceptedResponseId {params()["rid"].toInt()};
    setResult(QJsonObject::fromVariantMap(generateSyncData(acceptedResponseId, data, lastAcceptedResponse, lastResponse)));

    sessionManager()->session()->setData(QLatin1String("syncMainDataLastResponse"), lastResponse);
    sessionManager()->session()->setData(QLatin1String("syncMainDataLastAcceptedResponse"), lastAcceptedResponse);
}
	void PsiPlusImportPage::SendImportAcc (QStandardItem *accItem)
	{
		Entity e = Util::MakeEntity (QVariant (),
				QString (),
				FromUserInitiated | OnlyHandle,
				"x-leechcraft/im-account-import");

		QVariantMap data = accItem->data (Roles::AccountData).toMap ();
		data.remove ("Contacts");
		e.Additional_ ["AccountData"] = data;

		emit gotEntity (e);
	}
bool FreyaPublicRegister::ConfigModifyRecursion(QVariantMap &varMap, const QStringList &configPath, const ConfModType &type, const QVariant &var)
{
    if(configPath.size() > 0)
    {
        const QString &key = configPath.at(0);

        if(configPath.size() == 1)
        {
            switch (type)
            {
            case eCMADD:
            {
                varMap.insert(key, var);
                return varMap.contains(key);
            }
            case eCMDEL:
            {
                varMap.remove(key);
                return !varMap.contains(key);
            }
            case eCMMOD:
            {
                if(varMap.contains(key))
                {
                    varMap.insert(key, var);
                    return (varMap.value(key) == var);
                }
            }
            default:
                return false;
            }
        }
        else
        {
            QVariant newVar = varMap.value(key);
            if(newVar.type() == QVariant::Map || eCMADD == type)
            {
                QStringList newConfigPath = configPath;
                newConfigPath.removeAt(0);
                QVariantMap tempVarMap = newVar.toMap();
                if(ConfigModifyRecursion(tempVarMap, newConfigPath, type, var))
                {
                    varMap.insert(key, tempVarMap);
                    return true;
                }
            }
        }
    }
    return false;
}
Exemple #15
0
Application::Application(int& argc, char* argv[]) : QApplication(argc, argv)
{
    setApplicationName("Communi");
    setOrganizationName("Communi");
    setApplicationVersion(Irc::version());
    setOrganizationDomain("communi.github.com");

    *originalPalette() = palette();

    QIcon icon;
    icon.addFile(":/resources/icons/16x16/communi.png");
    icon.addFile(":/resources/icons/24x24/communi.png");
    icon.addFile(":/resources/icons/32x32/communi.png");
    icon.addFile(":/resources/icons/48x48/communi.png");
    icon.addFile(":/resources/icons/64x64/communi.png");
    icon.addFile(":/resources/icons/128x128/communi.png");
    setWindowIcon(icon);

    qRegisterMetaTypeStreamOperators<ConnectionInfo>("ConnectionInfo");
    qRegisterMetaTypeStreamOperators<ConnectionInfos>("ConnectionInfos");

    QSettings settings;
    if (arguments().contains("-reset"))
        settings.clear();
    if (arguments().contains("-reset-settings"))
        settings.remove("settings");
    if (arguments().contains("-reset-connections"))
        settings.remove("connections");
    if (arguments().contains("-reset-state")) {
        settings.remove("list");
        settings.remove("tree");
        settings.remove("splitter");
        settings.remove("geometry");
    }

    bool appliedSettings = false;
    if (settings.contains("settings")) {
        QVariant value = settings.value("settings");
        if (value.canConvert<QVariantMap>()) {
            QVariantMap map = value.toMap();
            // cleanup obsolete theme bloat
            foreach (const QString& key, map.keys()) {
                if (key.startsWith("ui.theme") || key.startsWith("themes."))
                    map.remove(key);
            }
            applySettings(map);
            appliedSettings = true;
            Application::settings()->setValues(map);
        }
Exemple #16
0
void DeviceInterface::connectMediaPlayer()
{
    const QVariantMap &properties = qdbus_cast<QVariantMap>(Object::property(QStringLiteral("MediaPlayer")));
    const QDBusObjectPath &path = properties.value(QStringLiteral("Path")).value<QDBusObjectPath>();
    QVariantMap props = properties;
    props.remove(QStringLiteral("Path"));

    MediaPlayerObject *mediaPlayerObj = new MediaPlayerObject(path);
    m_mediaPlayer = new MediaPlayerInterface(path, props, mediaPlayerObj);

    ObjectManager *manager = ObjectManager::self();
    manager->addObject(m_mediaPlayer);
    manager->addAutoDeleteObject(mediaPlayerObj);

    m_connectedUuids.append(MediaPlayerUuid);
}
static bool decodeUri(QVariantMap &map, const QString& entry) {
    if (map.contains(entry)) {
        QString urlString = map.value(entry).toString();
        QUrl url = QUrl::fromEncoded(urlString.toAscii());
        if (!url.isValid()) {
            // try to be lenient
            url = QUrl(urlString);
        }
        if (url.isValid()) {
            map.insert(entry, QVariant(url));
            return true;
        } else {
            map.remove(entry);
            return false;
        }
    }
    // count it as a success if it doesn't exist
    return true;
}
void DeviceProperties::UpdateHardwareInfo() {
    // Hardware information
    QString id = index_.data(DeviceManager::Role_UniqueId).toString();
    if (DeviceLister* lister = manager_->GetLister(index_.row())) {
        QVariantMap info = lister->DeviceHardwareInfo(id);

        // Remove empty items
        for (const QString& key : info.keys()) {
            if (info[key].isNull() || info[key].toString().isEmpty())
                info.remove(key);
        }

        ui_->hardware_info_stack->setCurrentWidget(ui_->hardware_info_page);
        ui_->hardware_info->clear();
        ui_->hardware_info->setRowCount(2 + info.count());

        int row = 0;
        AddHardwareInfo(row++, tr("Model"), lister->DeviceModel(id));
        AddHardwareInfo(row++, tr("Manufacturer"), lister->DeviceManufacturer(id));
        for (const QString& key : info.keys()) {
            AddHardwareInfo(row++, tr(key.toAscii()), info[key].toString());
        }

        ui_->hardware_info->sortItems(0);
    } else {
        ui_->hardware_info_stack->setCurrentWidget(
            ui_->hardware_info_not_connected_page);
    }

    // Size
    quint64 total = index_.data(DeviceManager::Role_Capacity).toLongLong();

    QVariant free_var = index_.data(DeviceManager::Role_FreeSpace);
    if (free_var.isValid()) {
        quint64 free = free_var.toLongLong();

        ui_->free_space_bar->set_total_bytes(total);
        ui_->free_space_bar->set_free_bytes(free);
        ui_->free_space_bar->show();
    } else {
        ui_->free_space_bar->hide();
    }
}
Exemple #19
0
QString
JSAccount::serializeQVariantMap( const QVariantMap& map )
{
    QVariantMap localMap = map;

    foreach( const QString& key, localMap.keys() )
    {
        QVariant currentVariant = localMap[ key ];

        // strip unserializable types - at least QJson needs this, check with QtJson
        if( currentVariant.canConvert<QImage>() )
        {
            localMap.remove( key );
        }
    }

    QByteArray serialized = TomahawkUtils::toJson( localMap );

    return QString( "JSON.parse('%1')" ).arg( JSAccount::escape( QString::fromUtf8( serialized ) ) );
}
Exemple #20
0
bool unset(const QStringList & keys, QVariantMap & context){
    if(keys.size() == 1){
        return context.remove(keys.first()) > 0;
    }
    QVariant v = value_unsafe(keys.mid(0, keys.size() - 1), context);
    if(v.isNull())
        return false;
    if(v.type() == QVariant::Map) {
        QVariantMap & map = asMap(v);
        return map.remove(keys.last()) != 0;
    }
    if(v.type() == QVariant::List) {
        QVariantList & lst = asList(v);
        bool ok;
        int idx = keys.last().toInt(&ok);
        if(!ok || idx >= lst.size())
            return false;
        lst.removeAt(idx);
        return true;

    }
    return false;
}
void IdentityInfo::removeMethod(const MethodName &method)
{
    QVariantMap methods = impl->fields["methods"].toMap();
    methods.remove(method);
    impl->fields["methods"] = methods;
}
// Parameter List:
// Name - String displayed as name in Qt Creator
// qmake path - location of the qmake binary
// Type identifier - Desktop, Simulator, Symbian, ...
// SDK identifier - unique string to identify Qt version inside of the SDK (eg. desk473, simu11, ...)
// System Root Path
// sbs path
bool RegisterQtInCreatorV23Operation::performOperation()
{
    const QStringList args = arguments();

    if (args.count() < 4) {
        setError(InvalidArguments);
        setErrorString(tr("Invalid arguments in %0: %1 arguments given, minimum 4 expected.")
                        .arg(name()).arg(args.count()));
        return false;
    }

    PackageManagerCore *const core = qVariantValue<PackageManagerCore*>(value(QLatin1String("installer")));
    if (!core) {
        setError(UserDefinedError);
        setErrorString(tr("Needed installer object in \"%1\" operation is empty.").arg(name()));
        return false;
    }
    const QString &rootInstallPath = core->value(scTargetDir);
    if (rootInstallPath.isEmpty() || !QDir(rootInstallPath).exists()) {
        setError(UserDefinedError);
        setErrorString(tr("The given TargetDir %1 is not a valid/existing dir.").arg(rootInstallPath));
        return false;
    }

    const QString qtVersionsFileName = rootInstallPath
                                     + QLatin1String(QtVersionSettingsSuffixPath);
    int argCounter = 0;
    const QString &versionName = args.at(argCounter++);
    const QString &path = QDir::toNativeSeparators(args.value(argCounter++));
    const QString versionQmakePath = absoluteQmakePath(path);

    const QString &versionTypeIdentifier = args.at(argCounter++);
    const QString &versionSDKIdentifier = args.at(argCounter++);
    const QString &versionSystemRoot = fromNativeSeparatorsAllOS(args.value(argCounter++));
    const QString &versionSbsPath = fromNativeSeparatorsAllOS(args.value(argCounter++));

    ProjectExplorer::PersistentSettingsReader reader;
    int qtVersionCount = 0;
    QVariantMap map;
    if (reader.load(qtVersionsFileName)) {
        map = reader.restoreValues();
        qtVersionCount = map.value(QLatin1String("QtVersion.Count")).toInt();
        map.remove(QLatin1String("QtVersion.Count"));
        map.remove(QLatin1String("Version"));
    }

    ProjectExplorer::PersistentSettingsWriter writer;
    // Store old qt versions
    if (!map.isEmpty()) {
        for (int i = 0; i < qtVersionCount; ++i) {
            writer.saveValue(QString::fromLatin1("QtVersion.%1").arg(i)
                             , map[QLatin1String("QtVersion.") + QString::number(i)].toMap());
        }
        map.clear();
    }
    // Enter new version
    map.insert(QLatin1String("Id"), -1);
    map.insert(QLatin1String("Name"), versionName);
    map.insert(QLatin1String("QMakePath"), versionQmakePath);
    map.insert(QLatin1String("QtVersion.Type"),
               QLatin1String("Qt4ProjectManager.QtVersion.") + versionTypeIdentifier);
    map.insert(QLatin1String("isAutodetected"), true);
    map.insert(QLatin1String("autodetectionSource"),
               QLatin1String("SDK.") + versionSDKIdentifier);
    if (!versionSystemRoot.isEmpty())
        map.insert(QLatin1String("SystemRoot"), versionSystemRoot);
    if (!versionSbsPath.isEmpty())
        map.insert(QLatin1String("SBSv2Directory"), versionSbsPath);

    writer.saveValue(QLatin1String("QtVersion.") + QString::number(qtVersionCount), map);

    writer.saveValue(QLatin1String("Version"), 1);
    writer.saveValue(QLatin1String("QtVersion.Count"), qtVersionCount + 1);
    QDir().mkpath(QFileInfo(qtVersionsFileName).absolutePath());
    writer.save(qtVersionsFileName, QLatin1String("QtCreatorQtVersions"));

    return true;
}
void DomainServerSettingsManager::setupConfigMap(const QStringList& argumentList) {
    _configMap.loadMasterAndUserConfig(argumentList);

    // What settings version were we before and what are we using now?
    // Do we need to do any re-mapping?
    QSettings appSettings;
    const QString JSON_SETTINGS_VERSION_KEY = "json-settings/version";
    double oldVersion = appSettings.value(JSON_SETTINGS_VERSION_KEY, 0.0).toDouble();

    if (oldVersion != _descriptionVersion) {
        qDebug() << "Previous domain-server settings version was"
                 << QString::number(oldVersion, 'g', 8) << "and the new version is"
                 << QString::number(_descriptionVersion, 'g', 8) << "- checking if any re-mapping is required";

        // we have a version mismatch - for now handle custom behaviour here since there are not many remappings
        if (oldVersion < 1.0) {
            // This was prior to the introduction of security.restricted_access
            // If the user has a list of allowed users then set their value for security.restricted_access to true

            QVariant* allowedUsers = valueForKeyPath(_configMap.getMergedConfig(), ALLOWED_USERS_SETTINGS_KEYPATH);

            if (allowedUsers
                    && allowedUsers->canConvert(QMetaType::QVariantList)
                    && reinterpret_cast<QVariantList*>(allowedUsers)->size() > 0) {

                qDebug() << "Forcing security.restricted_access to TRUE since there was an"
                         << "existing list of allowed users.";

                // In the pre-toggle system the user had a list of allowed users, so
                // we need to set security.restricted_access to true
                QVariant* restrictedAccess = valueForKeyPath(_configMap.getUserConfig(),
                                             RESTRICTED_ACCESS_SETTINGS_KEYPATH,
                                             true);

                *restrictedAccess = QVariant(true);

                // write the new settings to the json file
                persistToFile();

                // reload the master and user config so that the merged config is right
                _configMap.loadMasterAndUserConfig(argumentList);
            }
        } else if (oldVersion < 1.1) {
            static const QString ENTITY_SERVER_SETTINGS_KEY = "entity_server_settings";
            static const QString ENTITY_FILE_NAME_KEY = "persistFilename";
            static const QString ENTITY_FILE_PATH_KEYPATH = ENTITY_SERVER_SETTINGS_KEY + ".persistFilePath";

            // this was prior to change of poorly named entitiesFileName to entitiesFilePath
            QVariant* persistFileNameVariant = valueForKeyPath(_configMap.getMergedConfig(),
                                               ENTITY_SERVER_SETTINGS_KEY + "." + ENTITY_FILE_NAME_KEY);
            if (persistFileNameVariant && persistFileNameVariant->canConvert(QMetaType::QString)) {
                QString persistFileName = persistFileNameVariant->toString();

                qDebug() << "Migrating persistFilename to persistFilePath for entity-server settings";

                // grab the persistFilePath option, create it if it doesn't exist
                QVariant* persistFilePath = valueForKeyPath(_configMap.getUserConfig(), ENTITY_FILE_PATH_KEYPATH, true);

                // write the migrated value
                *persistFilePath = persistFileName;

                // remove the old setting
                QVariant* entityServerVariant = valueForKeyPath(_configMap.getUserConfig(), ENTITY_SERVER_SETTINGS_KEY);
                if (entityServerVariant && entityServerVariant->canConvert(QMetaType::QVariantMap)) {
                    QVariantMap entityServerMap = entityServerVariant->toMap();
                    entityServerMap.remove(ENTITY_FILE_NAME_KEY);

                    *entityServerVariant = entityServerMap;
                }

                // write the new settings to the json file
                persistToFile();

                // reload the master and user config so that the merged config is right
                _configMap.loadMasterAndUserConfig(argumentList);
            }

        }
    }

    // write the current description version to our settings
    appSettings.setValue(JSON_SETTINGS_VERSION_KEY, _descriptionVersion);
}
 void IntegerMutation::mutate(QVariantMap &map, QString key){
     int newValue = this->mutate(map.value(key).toInt());
     map.remove(key);
     map.insert(key,QVariant((int)newValue));
 }
Exemple #25
0
void SlewDialog::loadPointsFromFile()
{
	QVariantMap result;
	QString pointsJsonPath = StelFileMgr::findFile("modules/TelescopeControl", (StelFileMgr::Flags)(StelFileMgr::Directory|StelFileMgr::Writable)) + "/points.json";

	if (pointsJsonPath.isEmpty())
	{
		qWarning() << "SlewDialog: Error loading points";
		return;
	}
	if(!QFileInfo(pointsJsonPath).exists())
	{
		qWarning() << "SlewDialog::loadPointsFromFile(): No pointss loaded. File is missing:"
			   << QDir::toNativeSeparators(pointsJsonPath);
		storedPointsDescriptions = result;
		return;
	}

	QFile pointsJsonFile(pointsJsonPath);

	QVariantMap map;

	if(!pointsJsonFile.open(QFile::ReadOnly))
	{
		qWarning() << "SlewDialog: No points loaded. Can't open for reading"
			   << QDir::toNativeSeparators(pointsJsonPath);
		storedPointsDescriptions = result;
		return;
	}
	else
	{
		map = StelJsonParser::parse(&pointsJsonFile).toMap();
		pointsJsonFile.close();
	}

	//File contains any points?
	if(map.isEmpty())
	{
		storedPointsDescriptions = result;
		return;
	}

	QString version = map.value("version", "0.0.0").toString();
	if(version < QString(TELESCOPE_CONTROL_VERSION))
	{
		QString newName = pointsJsonPath + ".backup." + QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss");
		if(pointsJsonFile.rename(newName))
		{
			qWarning() << "SlewDialog: The existing version of points.json is obsolete. Backing it up as "
				   << QDir::toNativeSeparators(newName);
			qWarning() << "SlewDialog: A blank points.json file will have to be created.";
			storedPointsDescriptions = result;
			return;
		}
		else
		{
			qWarning() << "SlewDialog: The existing version of points.json is obsolete. Unable to rename.";
			storedPointsDescriptions = result;
			return;
		}
	}
	map.remove("version");//Otherwise it will try to read it as a point

	//Read pointss, if any
	QMapIterator<QString, QVariant> node(map);

	if(node.hasNext())
	{
		ui->comboBoxStoredPoints->addItem(q_("Select one"));
		do
		{
			node.next();

			QVariantMap point = node.value().toMap();
			storedPoint sp;
			sp.name       = point.value("name").toString();
			sp.number     = point.value("number").toInt();
			sp.radiansRA  = point.value("radiansRA").toDouble();
			sp.radiansDec = point.value("radiansDec").toDouble();

			QVariant var;
			var.setValue(sp);
			ui->comboBoxStoredPoints->addItem(sp.name,var);
		} while (node.hasNext());
	}
}