void Ut_NotificationPreviewPresenter::testNotificationNotShownIfNoSummaryOrBody()
{
    QFETCH(QString, previewSummary);
    QFETCH(QString, previewBody);
    QFETCH(int, changedSignalCount);
    QFETCH(int, presentedSignalCount);
    QFETCH(bool, windowVisible);

    NotificationPreviewPresenter presenter;
    QSignalSpy changedSpy(&presenter, SIGNAL(notificationChanged()));
    QSignalSpy presentedSpy(&presenter, SIGNAL(notificationPresented(uint)));

    // Create notification
    LipstickNotification *notification = new LipstickNotification;
    QVariantHash hints;
    hints.insert(NotificationManager::HINT_PREVIEW_SUMMARY, previewSummary);
    hints.insert(NotificationManager::HINT_PREVIEW_BODY, previewBody);
    notification->setHints(hints);
    notificationManagerNotification.insert(1, notification);
    presenter.updateNotification(1);

    // Check whether the expected notification is signaled onwards
    QCOMPARE(changedSpy.count(), changedSignalCount);
    QCOMPARE(presentedSpy.count(), presentedSignalCount);

    QCOMPARE(homeWindowVisible.isEmpty(), !windowVisible);
    if (windowVisible) {
        // Check whether the window was shown
        QCOMPARE(homeWindowVisible[homeWindows.first()], windowVisible);
    }
}
Example #2
0
  void RepeatingBulkRound::IncomingData(const Request &notification)
  {
    if(Stopped()) {
      qWarning() << "Received a message on a closed session:" << ToString();
      return;
    }

    QSharedPointer<Connections::IOverlaySender> sender =
      notification.GetFrom().dynamicCast<Connections::IOverlaySender>();
    if(!sender) {
      qDebug() << ToString() << " received wayward message from: " <<
        notification.GetFrom()->ToString();
      return;
    }

    const Id &id = sender->GetRemoteId();
    if(!GetGroup().Contains(id)) {
      qDebug() << ToString() << " received wayward message from: " << 
        notification.GetFrom()->ToString();
      return;
    }

    QVariantHash msg = notification.GetData().toHash();

    bool bulk = msg.value("bulk").toBool();
    if(bulk) {
      ProcessData(id, msg.value("data").toByteArray());
    } else {
      _shuffle_round->IncomingData(notification);
    }
  }
/*!
  \~english
  Returns the rendering data of the partial template given by \a templateName.

  \~japanese
  部分テンプレート \a templateName に変数 \a vars を設定した描画データを返す
*/
QString TActionController::getRenderingData(const QString &templateName, const QVariantHash &vars)
{
    T_TRACEFUNC("templateName: %s", qPrintable(templateName));

    // Creates view-object
    QStringList names = templateName.split("/");
    if (names.count() != 2) {
        tError("Invalid patameter: %s", qPrintable(templateName));
        return QString();
    }

    TDispatcher<TActionView> viewDispatcher(viewClassName(names[0], names[1]));
    TActionView *view = viewDispatcher.object();
    if (!view) {
        return QString();
    }

    QVariantHash hash = allVariants();
    for (QHashIterator<QString, QVariant> i(vars); i.hasNext(); ) {
        i.next();
        hash.insert(i.key(), i.value()); // item's value of same key is replaced
    }

    view->setController(this);
    view->setVariantHash(hash);
    return view->toString();  
}
Example #4
0
void JMUCUser::setMUCAffiliationAndRole(MUCRoom::Affiliation affiliation, MUCRoom::Role role)
{
	int oldPriority = priority();
	d_func()->affiliation = affiliation;
	d_func()->role = role;
	int newPriority = priority();
	emit priorityChanged(oldPriority, newPriority);
	
	QString iconName;
	if (affiliation == MUCRoom::AffiliationOwner)
		iconName = QStringLiteral("user-role-owner");
	else if (affiliation == MUCRoom::AffiliationAdmin)
		iconName = QStringLiteral("user-role-admin");
	else if (role == MUCRoom::RoleModerator)
		iconName = QStringLiteral("user-role-moderator");
	else if (role == MUCRoom::RoleVisitor)
		iconName = QStringLiteral("user-role-visitor");
	else if (affiliation == MUCRoom::AffiliationMember)
		iconName = QStringLiteral("user-role-member");
	else
		iconName = QStringLiteral("user-role-participant");
	
	QVariantHash clientInfo;
	ExtensionIcon extIcon(iconName);
	clientInfo.insert("id", "mucRole");
	clientInfo.insert("icon", QVariant::fromValue(extIcon));
	clientInfo.insert("priorityInContactList", 30);
	setExtendedInfo("mucRole", clientInfo);
}
Example #5
0
void Keyboard::handleInfo(QVariant const& properties)
{
    bool ok = false;
    QVariantHash items = properties.toHash();
    QString newSize = items[QString::fromLatin1("size")].toString();
    QVariantHash locale = items[QString::fromLatin1("locale")].toHash();

    int intSize = newSize.toInt(&ok);

    if (!locale.isEmpty())
    {
        QString languageId = locale[QString::fromLatin1("languageId")].toString();
        QString countryId = locale[QString::fromLatin1("countryId")].toString();

        if (!languageId.isEmpty())
            mLanguageId = languageId;

        if (!countryId.isEmpty())
            mCountryId = countryId;
    }

    if (ok && intSize != mKeyboardHeight) {
        mKeyboardHeight = intSize;
        emit notifyHeightChanged(mKeyboardHeight);
    }

#ifdef PPS_KEYBOARD_DEBUG
    qDebug() << "Keyboard: height:" << mKeyboardHeight << " languageId:" << mLanguageId
             << " countryId:" << mCountryId;
#endif

}
Example #6
0
void SessionPrivate::_q_saveSession(Context *c)
{
    // fix cookie before we send headers
    saveSessionExpires(c);

    // Force extension of session_expires before finalizing headers, so a pos
    // up to date. First call to session_expires will extend the expiry, methods
    // just return the previously extended value.
    Session::expires(c);

    // Persist data
    static Session *session = c->plugin<Session*>();
    if (!session) {
        qCCritical(C_SESSION) << "Session plugin not registered";
        return;
    }
    saveSessionExpires(c);

    if (!c->property(SESSION_UPDATED).toBool()) {
        return;
    }
    SessionStore *store = session->d_ptr->store;
    QVariantHash sessionData = c->property(SESSION_VALUES).toHash();
    sessionData.insert(QStringLiteral("__updated"), QDateTime::currentMSecsSinceEpoch() / 1000);

    const QString sid = c->property(SESSION_ID).toString();
    store->storeSessionData(c, sid,  QStringLiteral("session"), sessionData);
}
/**
 * @fn editTaskPrivate
 */
QueuedResult<bool> QueuedCorePrivateHelper::editTaskPrivate(QueuedProcess *_process,
                                                            const QVariantHash &_taskData,
                                                            const int _userId)
{
    qCDebug(LOG_LIB) << "Edit task with ID" << _process->index() << "from" << _userId;

    // modify record in database first
    bool status = database()->modify(QueuedDB::TASKS_TABLE, _process->index(), _taskData);
    if (!status) {
        qCWarning(LOG_LIB) << "Could not modify task record" << _process->index()
                           << "in database, do not edit it in memory";
        return QueuedError("", QueuedEnums::ReturnStatus::Error);
    }
    // store modification
    for (auto &field : _taskData.keys())
        database()->add(QueuedDB::TASKS_MODS_TABLE,
                        {{"task", _process->index()},
                         {"time", QDateTime::currentDateTimeUtc().toString(Qt::ISODateWithMs)},
                         {"user", _userId},
                         {"field", field},
                         {"value", _taskData[field]}});

    // modify values stored in memory
    for (auto &property : _taskData.keys())
        _process->setProperty(qPrintable(property), _taskData[property]);
    // notify plugins
    if (plugins())
        emit(plugins()->interface()->onEditTask(_process->index(), _taskData));

    return true;
}
Example #8
0
void BookWindow::renderBooks() const
{
    int rows = model->rowCount();
    QVariantHash mapping;
    QVariantList bookList;
    for (int row = 0; row < rows; ++row)
    {
      QString title = model->index(row, 1).data().toString();
      QString author = model->index(row, 2).data().toString();
      QString genre = model->index(row, 3).data().toString();
      int rating = model->index(row, 5).data().toInt();
      QObject *book = new BookWrapper(author, title, genre, rating, this);
      QVariant var = QVariant::fromValue(book);
      bookList.append(var);
    }
    mapping.insert("books", bookList);

    QString themeName = ui.exportTheme->currentText();

    Grantlee::Context c(mapping);

    Grantlee::Template t = m_engine->loadByName( themeName + ".html" );
    if (!t)
    {
      QMessageBox::critical(this, "Unable to load template",
                QString( "Error loading template: %1" ).arg( themeName + ".html" ) );
      return;
    }

    if ( t->error() )
    {
      QMessageBox::critical(this, "Unable to load template",
                QString( "Error loading template: %1" ).arg( t->errorString() ) );
      return;
    }

    bool ok;
    QString text = QInputDialog::getText(this, tr("Export Location"),
                                         tr("file name:"), QLineEdit::Normal,
                                         QDir::home().absolutePath() + "/book_export.html", &ok);
    if (!ok || text.isEmpty())
      return;

    QFile file( text );
    if ( !file.open( QIODevice::WriteOnly | QIODevice::Text ) )
      return;

    QString content = t->render(&c);

    if ( t->error() )
    {
      QMessageBox::critical(this, "Unable render template",
                QString( "Error rendering template: %1" ).arg( t->errorString() ) );
      return;
    }

    file.write(content.toLocal8Bit());
    file.close();

}
bool ZrpcResponsePacket::fromVariant(const QVariant &in)
{
	if(in.type() != QVariant::Hash)
		return false;

	QVariantHash obj = in.toHash();

	if(!obj.contains("id") || obj["id"].type() != QVariant::ByteArray)
		return false;
	id = obj["id"].toByteArray();

	if(!obj.contains("success") || obj["success"].type() != QVariant::Bool)
		return false;
	success = obj["success"].toBool();

	value.clear();
	condition.clear();
	if(success)
	{
		if(!obj.contains("value"))
			return false;
		value = obj["value"];
	}
	else
	{
		if(!obj.contains("condition") || obj["condition"].type() != QVariant::ByteArray)
			return false;
		condition = obj["condition"].toByteArray();
	}

	return true;
}
Example #10
0
void Tohkbd::notificationSend(QString summary, QString body)
{

    QDBusInterface notifyCall("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "");

    QVariantHash hints;
    hints.insert("x-nemo-preview-summary", summary);

    QList<QVariant> args;
    args.append("tohkbd2");
    args.append(ssNotifyReplacesId);
    args.append("icon-m-notifications");
    args.append(summary);
    args.append(body);
    args.append((QStringList() << "default" << ""));
    args.append(hints);
    args.append(-1);

    QDBusMessage notifyCallReply = notifyCall.callWithArgumentList(QDBus::AutoDetect, "Notify", args);

    QList<QVariant> outArgs = notifyCallReply.arguments();

    ssNotifyReplacesId = outArgs.at(0).toInt();

    printf("Notification sent, got id %d\n", ssNotifyReplacesId);
}
Example #11
0
QByteArray FSTReader::writeMapping(const QVariantHash& mapping) {
    static const QStringList PREFERED_ORDER = QStringList() << NAME_FIELD << TYPE_FIELD << SCALE_FIELD << FILENAME_FIELD
    << TEXDIR_FIELD << JOINT_FIELD << FREE_JOINT_FIELD
    << BLENDSHAPE_FIELD << JOINT_INDEX_FIELD;
    QBuffer buffer;
    buffer.open(QIODevice::WriteOnly);
    
    for (auto key : PREFERED_ORDER) {
        auto it = mapping.find(key);
        if (it != mapping.constEnd()) {
            if (key == FREE_JOINT_FIELD) { // writeVariant does not handle strings added using insertMulti.
                for (auto multi : mapping.values(key)) {
                    buffer.write(key.toUtf8());
                    buffer.write(" = ");
                    buffer.write(multi.toByteArray());
                    buffer.write("\n");
                }
            } else {
                writeVariant(buffer, it);
            }
        }
    }
    
    for (auto it = mapping.constBegin(); it != mapping.constEnd(); it++) {
        if (!PREFERED_ORDER.contains(it.key())) {
            writeVariant(buffer, it);
        }
    }
    return buffer.data();
}
void SymbianIDeviceConfigurationWidget::getRomInfoResult(const Coda::CodaCommandResult &result)
{
    codaIncreaseProgress();
    if (result.type == Coda::CodaCommandResult::SuccessReply && result.values.count()) {
        startTable(m_deviceInfo);
        QTextStream str(&m_deviceInfo);

        QVariantHash obj = result.values[0].toVariant().toHash();
        QString romVersion = obj.value(QLatin1String("romVersion"), tr("unknown")).toString();
        romVersion.replace(QLatin1Char('\n'), QLatin1Char(' ')); // The ROM string is split across multiple lines, for some reason.
        addToTable(str, tr("ROM version:"), romVersion);

        QString pr = obj.value(QLatin1String("prInfo")).toString();
        if (pr.length())
            addToTable(str, tr("Release:"), pr);
        finishTable(m_deviceInfo);
    }

    QList<quint32> packagesOfInterest;
    packagesOfInterest.append(CODA_UID);
    packagesOfInterest.append(QTMOBILITY_UID);
    packagesOfInterest.append(QTCOMPONENTS_UID);
    packagesOfInterest.append(QMLVIEWER_UID);
    if (m_codaInfoDevice)
        m_codaInfoDevice->sendSymbianInstallGetPackageInfoCommand(Coda::CodaCallback(this, &SymbianIDeviceConfigurationWidget::getInstalledPackagesResult), packagesOfInterest);
}
Example #13
0
bool ModelPackager::editProperties() {
    // open the dialog to configure the rest
    ModelPropertiesDialog properties(_mapping, _modelFile.path(), *_hfmModel);
    if (properties.exec() == QDialog::Rejected) {
        return false;
    }
    _mapping = properties.getMapping();

    // Make sure that a mapping for the root joint has been specified
    QVariantHash joints = _mapping.value(JOINT_FIELD).toHash();
    if (!joints.contains("jointRoot")) {
        qWarning() << "root joint not configured for skeleton.";
        
        QString message = "Your did not configure a root joint for your skeleton model.\n\nPackaging will be canceled.";
        QMessageBox msgBox;
        msgBox.setWindowTitle("Model Packager");
        msgBox.setText(message);
        msgBox.setStandardButtons(QMessageBox::Ok);
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.exec();
        
        return false;
    }
    
    return true;
}
void
HatchetAccountConfig::login()
{
    tLog() << Q_FUNC_INFO;
    const ButtonAction action = static_cast< ButtonAction>( m_ui->loginButton->property( "action" ).toInt() );

    if ( action == Login )
    {
        // Log in mode
        tLog() << Q_FUNC_INFO << "Logging in...";
        m_account->loginWithPassword( m_ui->usernameEdit->text(), m_ui->passwordEdit->text(), m_ui->otpEdit->text() );
    }
    else if ( action == Logout )
    {
        // TODO
        m_ui->usernameEdit->clear();
        m_ui->passwordEdit->clear();
        m_ui->otpEdit->clear();

        QVariantHash creds = m_account->credentials();
        creds.clear();
        m_account->setCredentials( creds );
        m_account->sync();
        m_account->deauthenticate();
    }
}
Example #15
0
Menu *FileEnginePrivate::createMenu(const QString &id, QObject *parent)
{
    settings->beginGroup(id);

    Menu *menu = new Menu(id);

    menu->setName(settings->value(QStringLiteral("Name")).toString());
    menu->setLocations(settings->value(QStringLiteral("Locations")).toStringList());
    menu->setAutoAddPages(settings->value(QStringLiteral("AutoAddPages")).toBool());

    QList<QVariantHash> urls;

    int size = settings->beginReadArray(QStringLiteral("urls"));
    for (int i = 0; i < size; ++i) {
        settings->setArrayIndex(i);
        QVariantHash data;
        // TODO read all data
        data.insert(QStringLiteral("id"), i);
        data.insert(QStringLiteral("text"), settings->value(QStringLiteral("text")));
        data.insert(QStringLiteral("url"), settings->value(QStringLiteral("url")));
        data.insert(QStringLiteral("attr"), settings->value(QStringLiteral("attr")));
        urls.append(data);
    }
    settings->endArray();

    menu->setEntries(urls);

    settings->endGroup(); // menu name

    return menu;
}
FormGenAcceptResult FormGenRecordComposition::acceptsValueImpl(const QVariant &val) const
{
    if( variantType(val) != QMetaType::QVariantHash )
        return FormGenAcceptResult::reject({}, val);

    QVariantHash hash = val.toHash();
    QStringList valueStringList;
    QSet<QString> processedTags;

    for( const auto &elm : mElements ) {
        auto elementAccepts = elm.element->acceptsValue(hash.value(elm.tag));
        if( ! elementAccepts.acceptable ) {
            QString path = elm.tag;
            if( ! elementAccepts.path.isEmpty() )
                path += QString("/%1").arg(elementAccepts.path);
            return FormGenAcceptResult::reject(path, elementAccepts.value);
        }
        valueStringList.append(FormGenElement::keyStringValuePair(elm.tag, elementAccepts.valueString));
        processedTags.insert(elm.tag);
    }

    QSet<QString> remainingTags = hash.keys().toSet() - processedTags;
    if( ! remainingTags.isEmpty() )
        return FormGenAcceptResult::reject(*remainingTags.cbegin(),
                                           hash.value(*remainingTags.cbegin()));

    return FormGenAcceptResult::accept(val, FormGenElement::objectString(valueStringList));
}
QVariantHash WeatherWidget::getCurrentData()
{
    QVariantHash data;
    data.insert("weatherCurrent", weatherDataWidget->getCurrentData());
    data.insert("weatherForecast", forecastDataWidget->getCurrentData());
    return data;
}
Example #18
0
  void TabEdit::changePOTCAR(QListWidgetItem *item)
  {
    QSettings settings; // Already set up in avogadro/src/main.cpp

    // Get symbol and filename
    QStringList strl = item->text().split(":");
    QString symbol   = strl.at(0).trimmed();
    QString filename = strl.at(1).trimmed();

    QStringList files;
    QString path = settings.value("xtalopt/templates/potcarPath", "").toString();
    QFileDialog dialog (NULL, QString("Select pot file for atom %1").arg(symbol), path);
    dialog.selectFile(filename);
    dialog.setFileMode(QFileDialog::ExistingFile);
    if (dialog.exec()) {
      files = dialog.selectedFiles();
      if (files.size() != 1) { return;} // Only one file per element
      filename = files.first();
      settings.setValue("xtalopt/templates/potcarPath", dialog.directory().absolutePath());
    }
    else { return;} // User cancel file selection.
    // "POTCAR info" is of type
    // QList<QHash<QString, QString> >
    // e.g. a list of hashes containing
    // [atomic symbol : pseudopotential file] pairs
    QVariantList potcarInfo = m_opt->optimizer()->getData("POTCAR info").toList();
    QVariantHash hash = potcarInfo.at(ui_list_optStep->currentRow()).toHash();
    hash.insert(symbol,QVariant(filename));
    potcarInfo.replace(ui_list_optStep->currentRow(), hash);
    m_opt->optimizer()->setData("POTCAR info", potcarInfo);
    qobject_cast<VASPOptimizer*>(m_opt->optimizer())->buildPOTCARs();
    updateEditWidget();
  }
  void Session::HandlePrepare(const Request &notification)
  {
    if(_prepare_waiting) {
      _prepare_waiting = false;
    }

    QVariantHash msg = notification.GetData().toHash();

    if(_current_round && !_current_round->Stopped() && _current_round->Started()) {
      _prepare_waiting = true;
      _prepare_notification = notification;
      if(msg.value("interrupt").toBool()) {
        _current_round->Stop("Round interrupted.");
      }
      return;
    }

    QByteArray brid = msg.value("round_id").toByteArray();
    if(brid.isEmpty()) {
      qDebug() << "HandlePrepare: Invalid round id";
      return;
    }

    Id round_id(brid);

    if(msg.contains("group")) {
      QDataStream stream(msg.value("group").toByteArray());
      Group group;
      stream >> group;
      qDebug() << "Prepare contains new group. I am present:" <<
        group.Contains(GetPrivateIdentity().GetLocalId());
      _group_holder->UpdateGroup(group);
    }
Example #20
0
QVariantHash FSTReader::parseMapping(QIODevice* device) {
    QVariantHash properties;
    
    QByteArray line;
    while (!(line = device->readLine()).isEmpty()) {
        if ((line = line.trimmed()).startsWith('#')) {
            continue; // comment
        }
        QList<QByteArray> sections = line.split('=');
        if (sections.size() < 2) {
            continue;
        }
        QByteArray name = sections.at(0).trimmed();
        if (sections.size() == 2) {
            properties.insertMulti(name, sections.at(1).trimmed());
            
        } else if (sections.size() == 3) {
            QVariantHash heading = properties.value(name).toHash();
            heading.insertMulti(sections.at(1).trimmed(), sections.at(2).trimmed());
            properties.insert(name, heading);
            
        } else if (sections.size() >= 4) {
            QVariantHash heading = properties.value(name).toHash();
            QVariantList contents;
            for (int i = 2; i < sections.size(); i++) {
                contents.append(sections.at(i).trimmed());
            }
            heading.insertMulti(sections.at(1).trimmed(), contents);
            properties.insert(name, heading);
        }
    }
    
    return properties;
}
QString TemplateLayout::generate()
{
	int progress = 0;
	int totalWork = getTotalWork(PrintOptions);
	QString templateName;

	QString htmlContent;
	m_engine = new Grantlee::Engine(this);

	QSharedPointer<Grantlee::FileSystemTemplateLoader> m_templateLoader =
		QSharedPointer<Grantlee::FileSystemTemplateLoader>(new Grantlee::FileSystemTemplateLoader());
	m_templateLoader->setTemplateDirs(QStringList() << getSubsurfaceDataPath("printing_templates"));
	m_engine->addTemplateLoader(m_templateLoader);

	Grantlee::registerMetaType<Dive>();
	Grantlee::registerMetaType<template_options>();
	Grantlee::registerMetaType<print_options>();

	QVariantHash mapping;
	QVariantList diveList;

	struct dive *dive;
	int i;
	for_each_dive (i, dive) {
		//TODO check for exporting selected dives only
		if (!dive->selected && PrintOptions->print_selected)
			continue;
		Dive d(dive);
		diveList.append(QVariant::fromValue(d));
		progress++;
		emit progressUpdated(progress * 100.0 / totalWork);
	}
	mapping.insert("dives", diveList);
	mapping.insert("template_options", QVariant::fromValue(*templateOptions));
	mapping.insert("print_options", QVariant::fromValue(*PrintOptions));

	Grantlee::Context c(mapping);

	if (PrintOptions->p_template == print_options::ONE_DIVE) {
		templateName = "one_dive.html";
	} else if (PrintOptions->p_template == print_options::TWO_DIVE) {
		templateName = "two_dives.html";
	} else if (PrintOptions->p_template == print_options::CUSTOM) {
		templateName = "custom.html";
	}
	Grantlee::Template t = m_engine->loadByName(templateName);
	if (!t || t->error()) {
		qDebug() << "Can't load template";
		return htmlContent;
	}

	htmlContent = t->render(&c);

	if (t->error()) {
		qDebug() << "Can't render template";
		return htmlContent;
	}
	return htmlContent;
}
Example #22
0
void ShutdownScreen::createAndPublishNotification(const QString &category, const QString &body)
{
    NotificationManager *manager = NotificationManager::instance();
    QVariantHash hints;
    hints.insert(NotificationManager::HINT_CATEGORY, category);
    hints.insert(NotificationManager::HINT_PREVIEW_BODY, body);
    manager->Notify(qApp->applicationName(), 0, QString(), QString(), QString(), QStringList(), hints, -1);
}
Example #23
0
static QString
variantHashToString( const QVariantHash& variantHash )
{
    QStringList result;
    for ( auto it = variantHash.constBegin(); it != variantHash.constEnd(); ++it )
        result.append( it.key() + '=' + variantToString( it.value() ) );
    return '<' + result.join(',') + '>';
}
/*!
  Use the validate(const QVariantHash &) function instead.
  Obsolete function. 
 */
bool TFormValidator::validate(const QHash<QString, QString> &hash)
{
    QVariantHash vhash;
    for (QHashIterator<QString, QString> it(hash); it.hasNext(); ) {
        it.next();
        vhash.insert(it.key(), it.value());
    }
    return validate(vhash);
}
Example #25
0
const QVariantHash AbstractParam::attributes() const {
    QVariantHash a;
    const QMetaObject *mo = metaObject();
    for (int k = AbstractParam::staticMetaObject.propertyOffset(); k < mo->propertyCount(); ++k) {
        const QMetaProperty mp = mo->property(k);
        a.insert(mp.name(), this->property(mp.name()));
    }
    return a;
}
Example #26
0
void
CredentialsManager::keychainJobFinished( QKeychain::Job* j )
{
    tDebug() << Q_FUNC_INFO;
    if ( QKeychain::ReadPasswordJob* readJob = qobject_cast< QKeychain::ReadPasswordJob* >( j ) )
    {
        if ( readJob->error() == QKeychain::NoError )
        {
            tDebug() << "QtKeychain readJob for" << readJob->service() << "/"
                     << readJob->key() << "finished without errors";

            QVariant creds;
            QJson::Parser parser;
            bool ok;

            creds = parser.parse( readJob->textData().toLatin1(), &ok );

            QVariantMap map = creds.toMap();
            QVariantHash hash;
            for ( QVariantMap::const_iterator it = map.constBegin();
                  it != map.constEnd(); ++it )
            {
                hash.insert( it.key(), it.value() );
            }
            creds = QVariant( hash );

            if ( !ok || creds.toHash().isEmpty() )
            {
                creds = QVariant( readJob->textData() );
            }

            m_credentials.insert( CredentialsStorageKey( readJob->service(), readJob->key() ), creds );
        }
        else
        {
            tDebug() << "QtKeychain readJob for" << readJob->service() << "/" << readJob->key() << "finished with error:" << j->error() << j->errorString();
        }

        m_readJobs[ readJob->service() ].removeOne( readJob );

        if ( m_readJobs[ readJob->service() ].isEmpty() )
        {
            emit serviceReady( readJob->service() );
        }
    }
    else if ( QKeychain::WritePasswordJob* writeJob = qobject_cast< QKeychain::WritePasswordJob* >( j ) )
    {
        tLog() << Q_FUNC_INFO << "QtKeychain writeJob for" << writeJob->service() << "/" << writeJob->key() << "finished"
               << ( ( j->error() == QKeychain::NoError ) ? "without error" : j->errorString() );
    }
    else if ( QKeychain::DeletePasswordJob* deleteJob = qobject_cast< QKeychain::DeletePasswordJob* >( j ) )
    {
        tLog() << Q_FUNC_INFO << "QtKeychain deleteJob for" << deleteJob->service() << "/" << deleteJob->key() << "finished"
               << ( ( j->error() == QKeychain::NoError ) ? "without error" : j->errorString() );
    }
    j->deleteLater();
}
void TestMustache::testHelpers()
{
	QVariantHash args;
	args.insert("name", "Jim Smith");
	args.insert("age", 42);

	QString output = Mustache::renderTemplate("Hello {{name}}, you are {{age}}", args);
	QCOMPARE(output, QString("Hello Jim Smith, you are 42"));
}
Example #28
0
/*!
    Converts the variant hash \a hash to a QJsonObject.
    \since 5.5

    The keys in \a hash will be used as the keys in the JSON object,
    and the QVariant values will be converted to JSON values.

    \sa fromVariantMap(), toVariantHash(), QJsonValue::fromVariant()
 */
QJsonObject QJsonObject::fromVariantHash(const QVariantHash &hash)
{
    // ### this is implemented the trivial way, not the most efficient way

    QJsonObject object;
    for (QVariantHash::const_iterator it = hash.constBegin(); it != hash.constEnd(); ++it)
        object.insert(it.key(), QJsonValue::fromVariant(it.value()));
    return object;
}
Example #29
0
void BatteryNotifier::sendNotification(const QString &category, const QString &text, const QString &icon)
{
    NotificationManager *manager = NotificationManager::instance();
    QVariantHash hints;
    hints.insert(NotificationManager::HINT_CATEGORY, category);
    hints.insert(NotificationManager::HINT_PREVIEW_BODY, text);
    notificationId = manager->Notify(qApp->applicationName(), 0, icon, QString(), QString(), QStringList(), hints, -1);
    notificationCategory = category;
    notificationTimer.start();
}
void Ut_NotificationListModel::testNotificationIsNotAddedIfUrgencyIsCritical()
{
    QVariantHash hints;
    hints.insert(NotificationManager::HINT_URGENCY, 2);
    LipstickNotification notification("appName", 1, "appIcon", "summary", "body", QStringList() << "action", hints, 1);
    gNotificationManagerStub->stubSetReturnValue("notificationIds", QList<uint>() << 1);
    gNotificationManagerStub->stubSetReturnValue("notification", &notification);
    NotificationListModel model;
    QCOMPARE(model.itemCount(), 0);
}