void ImgurImagesList::slotAddImages(const QList<QUrl>& list)
{
    /* Replaces the KPImagesList::slotAddImages method, so that
     * ImgurImageListViewItems can be added instead of ImagesListViewItems */

    // Figure out which of the supplied URL's should actually be added and which
    // of them already exist.
    bool found;

    for (QList<QUrl>::ConstIterator it = list.constBegin(); it != list.constEnd(); ++it)
    {
        QUrl imageUrl = *it;
        found         = false;

        if (iface())
        {
            QPointer<MetadataProcessor> meta = iface()->createMetadataProcessor();

            if (meta && meta->load(imageUrl))
            {
                const QString sUrl       = meta->getXmpTagString(QLatin1String("Xmp.kipi.Imgur.Hash"));
                const QString sDeleteUrl = meta->getXmpTagString(QLatin1String("Xmp.kipi.Imgur.Delete"));

                for (int i = 0; i < listView()->topLevelItemCount(); ++i)
                {
                    ImgurImageListViewItem* const currItem = dynamic_cast<ImgurImageListViewItem*>(listView()->topLevelItem(i));

                    if (currItem && currItem->url() == imageUrl)
                    {
                        found = true;

                        if (!sUrl.isEmpty())
                        {
                            currItem->setUrl(sUrl);
                        }

                        if (!sDeleteUrl.isEmpty())
                        {
                            currItem->setDeleteUrl(sDeleteUrl);
                        }

                        break;
                    }
                }

                if (!found)
                {
                    new ImgurImageListViewItem(listView(), imageUrl);
                }
            }
        }
    }

    // Duplicate the signalImageListChanged of the ImageWindow, to enable the
    // upload button again.
    emit signalImageListChanged();
    emit signalAddItems(list);
}
Exemple #2
0
void ScanDialog::slotThreadDone(const KUrl& url, bool success)
{
    if (!success)
        KMessageBox::error(0, i18n("Cannot save \"%1\" file", url.fileName()));

    if (iface())
        iface()->refreshImages( KUrl::List(url) );

    unsetCursor();
    setEnabled(true);
}
bool SmugWindow::prepareImageForUpload(const QString& imgPath)
{
    QImage image;

    if (iface())
    {
        image = iface()->preview(QUrl::fromLocalFile(imgPath));
    }

    if (image.isNull())
    {
       image.load(imgPath);
    }

    if (image.isNull())
    {
        return false;
    }

    // get temporary file name
    m_tmpPath  = m_tmpDir + QFileInfo(imgPath).baseName().trimmed() + QString::fromLatin1(".jpg");

    // rescale image if requested
    int maxDim = m_widget->m_dimensionSpB->value();

    if (m_widget->m_resizeChB->isChecked() &&
        (image.width() > maxDim || image.height() > maxDim))
    {
        qCDebug(KIPIPLUGINS_LOG) << "Resizing to " << maxDim;
        image = image.scaled(maxDim, maxDim, Qt::KeepAspectRatio,
                                             Qt::SmoothTransformation);
    }

    qCDebug(KIPIPLUGINS_LOG) << "Saving to temp file: " << m_tmpPath;
    image.save(m_tmpPath, "JPEG", m_widget->m_imageQualitySpB->value());

    // copy meta-data to temporary image
    if (iface())
    {
        QPointer<MetadataProcessor> meta = iface()->createMetadataProcessor();

        if (meta && meta->load(QUrl::fromLocalFile(imgPath)))
        {
            meta->setImageDimensions(image.size());
            meta->setImageProgramId(QString::fromLatin1("Kipi-plugins"), kipipluginsVersion());
            meta->save(QUrl::fromLocalFile(m_tmpPath));
        }
    }

    return true;
}
const Face &StructuredGrid2D::face(const Cell &cell, Coordinates::Direction dir) const
{
    switch(dir)
    {
    case Coordinates::I_POS:
        return iface(cell.i() + 1, cell.j());
    case Coordinates::I_NEG:
        return iface(cell.i(), cell.j());
    case Coordinates::J_POS:
        return jface(cell.i(), cell.j() + 1);
    case Coordinates::J_NEG:
        return jface(cell.i(), cell.j());
    }
}
void UploadDialog::createIpodAlbum()
{
    QString helper;

#if KIPI_PLUGIN
    ImageCollection album = iface()->currentAlbum();
    if( album.isValid() )
        helper = album.name();
#endif

    bool ok = false;
    QString newAlbum = KInputDialog::getText( i18n("New iPod Photo Album"),
                                              i18n("Create a new album:"),
                                              helper, &ok, this );
    if( ok )
    {
        kDebug() << "creating album " << newAlbum ;

        Itdb_PhotoAlbum* photoAlbum = itdb_photodb_photoalbum_create( m_itdb, QFile::encodeName( newAlbum ), -1/*end*/ );
        // add the new album to the list view
        new IpodAlbumItem( m_ipodAlbumList, photoAlbum );
        m_ipodAlbumList->clearSelection();

        // commit the changes to the iPod
        GError* err = 0;
        itdb_photodb_write( m_itdb, &err );
    }
}
Exemple #6
0
const QString PBTreeNode::GetIntrospectXml(const QDBusObjectPath &object_path)
{
    // Connect to the introspectable interface
    QDBusInterface iface(PBBusName, \
                         object_path.path(), \
                         ofDIntrospectableName, \
                         QDBusConnection::sessionBus());

    // Lets see what we have - introspect this first
    QDBusMessage reply = iface.call("Introspect");
    if (reply.type() != QDBusMessage::ReplyMessage) {
        qDebug("Could not introspect this object");
        return NULL;
    }

    QList<QVariant> args = reply.arguments();

    QList<QVariant>::iterator iter = args.begin();

    QVariant variant = *iter;

    // The introspected string describing this object
    const QString intro_xml = variant.value<QString>();

    return intro_xml;
}
void CalWizard::print()
{
    calProgressUI.totalProgress->setMaximum(months_.count());
    calProgressUI.totalProgress->setValue(0);
    calProgressUI.totalProgress->progressScheduled(i18n("Making calendar"), false, true);
    calProgressUI.totalProgress->progressThumbnailChanged(QIcon::fromTheme(QStringLiteral("kipi")).pixmap(22, 22));

    if (printThread_)
    {
        printThread_->cancel();
        printThread_->wait();
        delete printThread_;
    }

    cSettings_->clearSpecial();
    cSettings_->loadSpecial(QUrl::fromLocalFile(calEventsUI.ohUrlRequester->lineEdit()->text()), Qt::red);
    cSettings_->loadSpecial(QUrl::fromLocalFile(calEventsUI.fhUrlRequester->lineEdit()->text()), Qt::darkGreen);

    printThread_ = new CalPrinter(printer_, months_, iface(), this);

    connect(printThread_, SIGNAL(pageChanged(int)),
            this,         SLOT(updatePage(int)));

    connect(printThread_, SIGNAL(pageChanged(int)),
            calProgressUI.totalProgress, SLOT(setValue(int)));

    connect(printThread_, SIGNAL(totalBlocks(int)),
            calProgressUI.currentProgress, SLOT(setMaximum(int)));

    connect(printThread_, SIGNAL(blocksFinished(int)),
            calProgressUI.currentProgress, SLOT(setValue(int)));

    calProgressUI.totalProgress->setMaximum(months_.count());
    printThread_->start();
}
bool QtBluezDiscoveryManager::registerDiscoveryInterest(const QString &adapterPath)
{
    if (adapterPath.isEmpty())
        return false;

    // already monitored adapter? -> increase ref count -> done
    if (d->references.contains(adapterPath)) {
        d->references[adapterPath]->reference++;
        return true;
    }

    AdapterData *data = new AdapterData();

    OrgFreedesktopDBusPropertiesInterface *propIface = new OrgFreedesktopDBusPropertiesInterface(
                QStringLiteral("org.bluez"), adapterPath, QDBusConnection::systemBus());
    connect(propIface, SIGNAL(PropertiesChanged(QString,QVariantMap,QStringList)),
            SLOT(PropertiesChanged(QString,QVariantMap,QStringList)));
    data->propteryListener = propIface;

    OrgBluezAdapter1Interface iface(QStringLiteral("org.bluez"), adapterPath,
                                    QDBusConnection::systemBus());
    data->wasListeningAlready = iface.discovering();

    d->references[adapterPath] = data;

    if (!data->wasListeningAlready)
        iface.StartDiscovery();

    return true;
}
Exemple #9
0
bool ListReaderH5::GetIface (T *a_) const
{
  std::pair<int, int> myPair(0, m_nRows);
  VEC_INT_PAIR indices(1, myPair);

  CStr str(m_path);
  str += "/";
  str += IFACE;

  int auxIdx(GetAuxIdx("iface"));
  if (auxIdx < 0)
  {
    auxIdx = 0;
  }
  int index;
  index = m_nFields - m_nAuxFields + auxIdx - m_nCbcFields;

  H5DataSetReader r(m_file, str, indices);
  std::vector<int> iface(m_nRows, 0);
  r.GetData(&iface[0], iface.size());
  for (size_t i=0; i<iface.size(); i++)
  {
    a_[i*m_nFields+index] = (T)iface.at(i);
  }
  return true;
} // ListReaderH5::GetIface
Exemple #10
0
bool NDBusDevice::activeNetwork(NDBusNetwork *net)
{
	if (!net)
		return false;

	if (NDBusStateTools::getInstance()->isSystemBusConnected() == false)
		return false;

	NDBusEncryption *enc = net->getEncryption();

	QDBusInterface iface(NM_DBUS_SERVICE, NM_DBUS_PATH, NM_DBUS_INTERFACE,
						 QDBusConnection::systemBus());

	if (iface.isValid()) {
		QDBusMessage msg;

		if (enc)
			enc->serialize(msg, net->getEssid());

		msg = iface.callWithArgumentList(QDBus::BlockWithGui, "setActiveDevice", msg.arguments());
	}

	fprintf(stderr, "%s\n",
			qPrintable(QDBusConnection::systemBus().lastError().message()));

	return false;
}
void listObjects(const QString &service, const QString &path)
{
    QDBusInterfacePtr iface(*connection, service, path.isEmpty() ? "/" : path,
                   "org.freedesktop.DBus.Introspectable");
    if (!iface->isValid()) {
        QDBusError err(iface->lastError());
        fprintf(stderr, "Cannot introspect object %s at %s:\n%s (%s)\n",
                qPrintable(path.isEmpty() ? "/" : path), qPrintable(service),
                qPrintable(err.name()), qPrintable(err.message()));
        exit(1);
    }
    QDBusReply<QString> xml = iface->call("Introspect");

    if (xml.isError())
        return;                 // silently

    QDomDocument doc;
    doc.setContent(xml);
    QDomElement node = doc.documentElement();
    QDomElement child = node.firstChildElement();
    while (!child.isNull()) {
        if (child.tagName() == QLatin1String("node")) {
            QString sub = path + '/' + child.attribute("name");
            printf("%s\n", qPrintable(sub));
            listObjects(service, sub);
        }
        child = child.nextSiblingElement();
    }
}
void GPSSyncDialog::setImages(const KUrl::List& images)
{
    for ( KUrl::List::ConstIterator it = images.begin(); it != images.end(); ++it )
    {
        KipiImageItem* const newItem = new KipiImageItem(iface(), *it);
        newItem->loadImageData(true, false);
        d->imageModel->addItem(newItem);
    }

    QList<QPersistentModelIndex> imagesToLoad;
    for (int i=0; i<d->imageModel->rowCount(); ++i)
    {
        imagesToLoad << d->imageModel->index(i, 0);
    }

    slotSetUIEnabled(false);
    slotProgressSetup(imagesToLoad.count(), i18n("Loading metadata - %p%"));

    // initiate the saving
    d->fileIOCountDone     = 0;
    d->fileIOCountTotal    = imagesToLoad.count();
    d->fileIOFutureWatcher = new QFutureWatcher<QPair<KUrl, QString> >(this);

    connect(d->fileIOFutureWatcher, SIGNAL(resultsReadyAt(int,int)),
            this, SLOT(slotFileMetadataLoaded(int,int)));

    d->fileIOFuture = QtConcurrent::mapped(imagesToLoad, LoadFileMetadataHelper(d->imageModel));
    d->fileIOFutureWatcher->setFuture(d->fileIOFuture);
}
void PowerDevilRunner::run(const Plasma::RunnerContext &context, const Plasma::QueryMatch &match)
{
    Q_UNUSED(context)

    QDBusInterface iface("org.kde.Solid.PowerManagement",
                         "/org/kde/Solid/PowerManagement",
                         "org.kde.Solid.PowerManagement");
    if (match.id().startsWith("PowerDevil_ProfileChange")) {
        iface.asyncCall("loadProfile", match.data().toString());
    } else if (match.id() == "PowerDevil_BrightnessChange") {
        iface.asyncCall("setBrightness", match.data().toInt());
    } else if (match.id() == "PowerDevil_DimTotal") {
        iface.asyncCall("setBrightness", 0);
    } else if (match.id() == "PowerDevil_DimHalf") {
        iface.asyncCall("setBrightness", -2);
    } else if (match.id() == "PowerDevil_TurnOffScreen") {
        // FIXME: Maybe this should be even removed
        // iface.asyncCall("turnOffScreen");
    } else if (match.id().startsWith("PowerDevil_Suspend")) {
        switch ((Solid::PowerManagement::SleepState)match.data().toInt()) {
            case Solid::PowerManagement::SuspendState:
            case Solid::PowerManagement::StandbyState:
                iface.asyncCall("suspendToRam");
                break;
            case Solid::PowerManagement::HibernateState:
                iface.asyncCall("suspendToDisk");
                break;
        }
    }
}
void WPASupplicantInstance::keepalive_thread()
{
    NL80211Iface iface(m_ifname);
    iface.connectVirtualIfaceTo(m_ifname,m_ssid,m_bssid);//La prima volta deve lanciare subito la connessione
    struct timeval now;
    struct timespec ts;
    gettimeofday(&now,NULL);
    ts.tv_sec = now.tv_sec;
    ts.tv_nsec = now.tv_usec *1000;
    ts.tv_sec += 10;

    pthread_cond_timedwait(&keepalive_cond,&keepalive_mutex,&ts);
    while ( keepalive_run)
    {
        if ( !iface.isConnected() )
        {
            L->warn(m_ifname+": Connection failed, retrying in 10 seconds...");
            iface.connectVirtualIfaceTo(m_ifname,m_ssid,m_bssid);
            
        }
        gettimeofday(&now,NULL);
        ts.tv_sec = now.tv_sec;
        ts.tv_nsec = now.tv_usec *1000;
        ts.tv_sec += 10;
        pthread_cond_timedwait(&keepalive_cond,&keepalive_mutex,&ts);
    }
}
void bluetoothDiscoverySDPCompleteCallback(void *userRefCon, IOBluetoothDeviceRef foundDevRef, IOReturn status)
{
	ConnectivityBluetooth *conn = (ConnectivityBluetooth *) userRefCon;
	IOBluetoothSDPUUIDRef uuid;
	unsigned char uuid_bytes[] = HAGGLE_BLUETOOTH_SDP_UUID;
	
	uuid = IOBluetoothSDPUUIDCreateWithBytes(uuid_bytes, sizeof(uuid_bytes));

	if (uuid == NULL) {
		CM_DBG("Failed to create UUID (%ld)\n", sizeof(uuid_bytes));
	}
	
	CFStringRef nameRef = IOBluetoothDeviceGetName(foundDevRef);

	const char *name = nameRef ? CFStringGetCStringPtr(nameRef, CFStringGetSystemEncoding()) : "PeerBluetoothInterface";
	//IOBluetoothObjectRetain(foundDevRef);
	//memcpy(macaddr, btAddr, BT_ALEN);
	
	const BluetoothDeviceAddress *btAddr = IOBluetoothDeviceGetAddress(foundDevRef);
	BluetoothAddress addr((unsigned char *)btAddr);
	
	BluetoothInterface iface((unsigned char *)btAddr, name, &addr, IFFLAG_UP);
	
	if (IOBluetoothDeviceGetServiceRecordForUUID(foundDevRef, uuid) != NULL) {
		CM_DBG("%s: Found Haggle device %s\n", conn->getName(), addr.getStr());
		
		conn->report_interface(&iface, conn->rootInterface, new ConnectivityInterfacePolicyTTL(2));
	} else {
		CM_DBG("%s: Found non-Haggle device [%s]\n", conn->getName(), addr.getStr());
	}

	IOBluetoothDeviceCloseConnection(foundDevRef);
	IOBluetoothObjectRelease(foundDevRef);
	IOBluetoothObjectRelease(uuid);
}
NotificationsListener::NotificationsListener(KdeConnectPlugin* aPlugin)
    : QDBusAbstractAdaptor(aPlugin),
      mPlugin(aPlugin)
{
    qRegisterMetaTypeStreamOperators<NotifyingApplication>("NotifyingApplication");

    bool ret = QDBusConnection::sessionBus()
                .registerObject(QStringLiteral("/org/freedesktop/Notifications"),
                                this,
                                QDBusConnection::ExportScriptableContents);
    if (!ret)
        qCWarning(KDECONNECT_PLUGIN_SENDNOTIFICATION)
                << "Error registering notifications listener for device"
                << mPlugin->device()->name() << ":"
                << QDBusConnection::sessionBus().lastError();
    else
        qCDebug(KDECONNECT_PLUGIN_SENDNOTIFICATION)
                << "Registered notifications listener for device"
                << mPlugin->device()->name();

    QDBusInterface iface(QStringLiteral("org.freedesktop.DBus"), QStringLiteral("/org/freedesktop/DBus"),
                         QStringLiteral("org.freedesktop.DBus"));
    iface.call(QStringLiteral("AddMatch"),
               "interface='org.freedesktop.Notifications',member='Notify',type='method_call',eavesdrop='true'");

    setTranslatedAppName();
    loadApplications();

    connect(mPlugin->config(), &KdeConnectPluginConfig::configChanged, this, &NotificationsListener::loadApplications);
}
Exemple #17
0
void StubBase::set_property(const char* name, std::function<void(DBusMessageIter&)>&& f)
{
    message_ptr_t msg = make_message(dbus_message_new_method_call(busname().c_str(), objectpath(), "org.freedesktop.DBus.Properties", "Set"));

    DBusMessageIter iter;
    dbus_message_iter_init_append(msg.get(), &iter);
   
    encode(iter, iface(), name);

    f(iter);   // and now serialize the variant

     DBusError err;
     dbus_error_init(&err);

     DBusMessage* reply = dbus_connection_send_with_reply_and_block(disp().conn_, msg.get(), DBUS_TIMEOUT_USE_DEFAULT, &err);

     // drop original message
     msg.reset(reply);

     // check for reponse
     if (dbus_error_is_set(&err))
     {
        // TODO make static function to throw from DBusError
        Error ex(err.name, err.message);

        dbus_error_free(&err);
        throw ex;
    }
}
void QDBusViewer::setProperty(const BusSignature &sig)
{
    QDBusInterface iface(sig.mService, sig.mPath, sig.mInterface, c);
    QMetaProperty prop = iface.metaObject()->property(iface.metaObject()->indexOfProperty(sig.mName.toLatin1()));

    bool ok;
    QString input = QInputDialog::getText(this, tr("Arguments"),
                    tr("Please enter the value of the property %1 (type %2)").arg(
                        sig.mName, QString::fromLatin1(prop.typeName())),
                    QLineEdit::Normal, QString(), &ok);
    if (!ok)
        return;

    QVariant value = input;
    if (!value.convert(prop.type())) {
        QMessageBox::warning(this, tr("Unable to marshall"),
                tr("Value conversion failed, unable to set property"));
        return;
    }

    QDBusMessage message = QDBusMessage::createMethodCall(sig.mService, sig.mPath, QLatin1String("org.freedesktop.DBus.Properties"), QLatin1String("Set"));
    QList<QVariant> arguments;
    arguments << sig.mInterface << sig.mName << qVariantFromValue(QDBusVariant(value));
    message.setArguments(arguments);
    c.callWithCallback(message, this, SLOT(dumpMessage(QDBusMessage)));

}
Exemple #19
0
QVariantMap PBTreeNode::GetObjectProperties(const QDBusObjectPath &object_path, \
                                            const QString interface)
{
    QVariantMap properties;

    // Connect to the freedesktop Properties interface
    QDBusInterface iface(PBBusName, \
                         object_path.path(), \
                         ofDPropertiesName, \
                         QDBusConnection::sessionBus());

    // GetAll properties
    QDBusMessage reply = iface.call("GetAll",interface);
    if (reply.type() != QDBusMessage::ReplyMessage) {
        // not worth complaining if they dont have properties, just return the empty
        return properties;
    }

    QList<QVariant> args = reply.arguments();

    if (args.empty()) {
        return properties;
    }

    QList<QVariant>::iterator p = args.begin();

    QVariant variant = *p;

    const QDBusArgument qda = variant.value<QDBusArgument>();

    qda >> properties;

    return properties;
}
QDomDocument QDBusModel::introspect(const QString &path)
{
    QDomDocument doc;

    QDBusInterface iface(service, path, QLatin1String("org.freedesktop.DBus.Introspectable"), c);
    if (!iface.isValid()) {
        QDBusError err(iface.lastError());
        emit busError(QString::fromLatin1("Cannot introspect object %1 at %2:\n  %3 (%4)\n").arg(path).arg(
                      service).arg(err.name()).arg(err.message()));
        return doc;
    }

    QDBusReply<QString> xml = iface.call(QLatin1String("Introspect"));

    if (!xml.isValid()) {
        QDBusError err(xml.error());
        if (err.isValid()) {
            emit busError(QString::fromLatin1("Call to object %1 at %2:\n  %3 (%4) failed\n").arg(
                        path).arg(service).arg(err.name()).arg(err.message()));
        } else {
            emit busError(QString::fromLatin1("Invalid XML received from object %1 at %2\n").arg(
                    path).arg(service));
        }
        return doc;
    }

    doc.setContent(xml);
    return doc;
}
Exemple #21
0
void MainDialog::saveConfig() {
  // ensure the existance of user config dir
  QString configDir = QFileInfo(userConfigFile_).dir().path();
  QDir().mkpath(configDir);
  qDebug() << userConfigFile_;
  // save the config file
  config_write_file(&config_, userConfigFile_.toLocal8Bit().constData());
  
  // ask compton to reload the config
  QString displayName = qgetenv("DISPLAY");
  for(int i = 0; i < displayName.length(); ++i) {
    if(!displayName[i].isNumber()) // replace non-numeric chars with _
      displayName[i] = '_';
  }
  QString comptonServiceName = COMPTON_SERVICE_PREFIX + displayName;
  QDBusInterface iface(comptonServiceName, COMPTON_PATH, COMPTON_INTERFACE);
  if(iface.isValid()) {
    iface.call("reset");
    // raise ourself to the top again (we'll loosing focus after reloading compton)
    activateWindow();
  }
  // FIXME: dbus interface of compton is not always available and reset() creates
  // much flickers. Maybe we should use internal dbus method set_opts().
  // Or, we can patch compton to do what we want.
}
Exemple #22
0
bool NDBusTools::update()
{
	if (NDBusStateTools::getInstance()->isSystemBusConnected() == false)
		return false;

	QDBusInterface iface(NM_DBUS_SERVICE, NM_DBUS_PATH, NM_DBUS_INTERFACE,
						 QDBusConnection::systemBus());

	if (iface.isValid()) {
		QDBusReply< QList< QDBusObjectPath > > reply = iface.call("getDevices");
		if (reply.isValid()) {

			_device_list.clear();

			NDBusDevice *dev;

			QList<QDBusObjectPath> list = reply.value();
			for (int i=0; i<list.count(); i++) {
				dev = new NDBusDevice(list.at(i));
				dev->update();
				_device_list << dev;
			}

			return true;

 		} else {
			fprintf(stderr, "Call failed: %s\n", qPrintable(reply.error().message()));
		}
	}

	fprintf(stderr, "%s\n",
			qPrintable(QDBusConnection::systemBus().lastError().message()));

	return false;
}
Exemple #23
0
void Mpris::checkConnection()
{
    if (m_valid) {
        QDBusConnection::sessionBus().disconnect(m_service, mprisPath, dbusPropertiesInterface,
                                                 QStringLiteral("PropertiesChanged"),
                                                 this, SLOT(propertiesChanged(QString, QMap<QString, QVariant>, QStringList)));
    }

    DBusInterface iface(dbusService, QStringLiteral("/"), dbusService);
    if (!iface.isValid()) {
        return;
    }
    QDBusPendingCall call = iface.asyncCall(QStringLiteral("ListNames"));
    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(call);
    watcher->connect(watcher, &QDBusPendingCallWatcher::finished, [this](QDBusPendingCallWatcher *watcher) {
        watcher->deleteLater();
        QDBusPendingReply<QStringList> reply = *watcher;

        if (reply.isError()) {
            qDebug("Failed to get the list of DBus services.");
        } else {
            QStringList services = reply.value();
            checkServices(services);
        }
    });
}
void RegisterExportFunctions(HDATA Data, tDWORD* pOut, tDWORD iMaxSize, tDWORD* result ) 
{
	tDWORD exp_count = 0;
	HDATA iface_data = GetStaticIface(Data);
	tUINT  mcount = 0;
	CFaceInfo iface( iface_data, false );
	CPubMethodInfo method( iface );

	exp_count = 0;

	if ( iface_data ) 
	{
		while( method ) 
		{
		  if ((pOut != 0) && (mcount*4 < iMaxSize))
			  pOut[mcount] = method.MethodID(); 

		  mcount++;
		  method.GoNext();
		}
	} //	if ( iface_data ) 


	if ( result )
		*result = mcount;
}
Exemple #25
0
/* PRBool enumerate (in nsIXPConnectWrappedNative wrapper, in JSContextPtr cx, in JSObjectPtr obj); */
NS_IMETHODIMP
nsJSIID::Enumerate(nsIXPConnectWrappedNative *wrapper,
                   JSContext * cx, JSObject * obj, PRBool *_retval)
{
    // In this case, let's just eagerly resolve...

    XPCCallContext ccx(JS_CALLER, cx);

    AutoMarkingNativeInterfacePtr iface(ccx);

    const nsIID* iid;
    mInfo->GetIIDShared(&iid);

    iface = XPCNativeInterface::GetNewOrUsed(ccx, iid);

    if(!iface)
        return NS_OK;

    PRUint16 count = iface->GetMemberCount();
    for(PRUint16 i = 0; i < count; i++)
    {
        XPCNativeMember* member = iface->GetMemberAt(i);
        if(member && member->IsConstant() &&
           !xpc_ForcePropertyResolve(cx, obj, member->GetName()))
        {
            return NS_ERROR_UNEXPECTED;
        }
    }
    return NS_OK;
}
Exemple #26
0
/* PRBool resolve (in nsIXPConnectWrappedNative wrapper, in JSContextPtr cx, in JSObjectPtr obj, in jsval id); */
NS_IMETHODIMP
nsJSIID::NewResolve(nsIXPConnectWrappedNative *wrapper,
                    JSContext * cx, JSObject * obj,
                    jsid id, PRUint32 flags,
                    JSObject * *objp, PRBool *_retval)
{
    XPCCallContext ccx(JS_CALLER, cx);

    AutoMarkingNativeInterfacePtr iface(ccx);

    const nsIID* iid;
    mInfo->GetIIDShared(&iid);

    iface = XPCNativeInterface::GetNewOrUsed(ccx, iid);

    if(!iface)
        return NS_OK;

    XPCNativeMember* member = iface->FindMember(id);
    if(member && member->IsConstant())
    {
        jsval val;
        if(!member->GetConstantValue(ccx, iface, &val))
            return NS_ERROR_OUT_OF_MEMORY;

        *objp = obj;
        *_retval = JS_DefinePropertyById(cx, obj, id, val, nsnull, nsnull,
                                         JSPROP_ENUMERATE | JSPROP_READONLY |
                                         JSPROP_PERMANENT);
    }

    return NS_OK;
}
void listAllInterfaces(const QString &service, const QString &path)
{
    QDBusInterfacePtr iface(*connection, service, path, "org.freedesktop.DBus.Introspectable");
    if (!iface->isValid()) {
        QDBusError err(iface->lastError());
        fprintf(stderr, "Cannot introspect object %s at %s:\n%s (%s)\n",
                qPrintable(path), qPrintable(service),
                qPrintable(err.name()), qPrintable(err.message()));
        exit(1);
    }
    QDBusReply<QString> xml = iface->call("Introspect");

    if (xml.isError())
        return;                 // silently

    QDomDocument doc;
    doc.setContent(xml);
    QDomElement node = doc.documentElement();
    QDomElement child = node.firstChildElement();
    while (!child.isNull()) {
        if (child.tagName() == QLatin1String("interface")) {
            QString ifaceName = child.attribute("name");
            if (QDBusUtil::isValidInterfaceName(ifaceName))
                listInterface(service, path, ifaceName);
            else {
                qWarning("Invalid D-BUS interface name '%s' found while parsing introspection",
                         qPrintable(ifaceName));
            }
        }
        child = child.nextSiblingElement();
    }
}
Exemple #28
0
int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);

    if (!QDBusConnection::sessionBus().isConnected()) {
        fprintf(stderr, "Cannot connect to the D-Bus session bus.\n"
                "To start it, run:\n"
                "\teval `dbus-launch --auto-syntax`\n");
        return 1;
    }

    QDBusInterface iface(SERVICE_NAME, "/", "", QDBusConnection::sessionBus());
    if (iface.isValid()) {
        QDBusReply<QString> reply = iface.call("ping", argc > 1 ? argv[1] : "");
        if (reply.isValid()) {
            printf("Reply was: %s\n", qPrintable(reply.value()));
            return 0;
        }

        fprintf(stderr, "Call failed: %s\n", qPrintable(reply.error().message()));
        return 1;
    }

    fprintf(stderr, "%s\n",
            qPrintable(QDBusConnection::sessionBus().lastError().message()));
    return 1;
}
//------------------------------------
// class MLCompDataToLayPerf
//------------------------------------
int MLCompDataToLayPerf::Process(const vector<string>& args)
	{
	if (args.size() != 6)
		throw MLCompDataToLayPerfArgsErr();

    int arg = 2;
	string cdlName = args[arg++];

	CCdlTkCdlFileParser parser(cdlName);
	auto_ptr<CCdlTkInterface> iface(parser.LoadAndParse(true));

	int numLayouts = args.size() - 4;
	if (numLayouts < 1)
		throw MLCompDataToLayPerfArgsErr();

	TMLCompData* mergedLayout = NULL;
	TMLAttributes* mergedAttribs = NULL;
    for(int ii = 0; ii < numLayouts; ii++)
        {
		string layoutName = args[arg++];
		string attribsName = CdlTkUtil::Replace(KCompDataFileNameSuffix, KAttributesFileNameSuffix, layoutName);

		auto_ptr<TMLCompDataParseLayout> layoutParse = TMLCompDataParseLayout::Parse(layoutName);
		auto_ptr<TMLCompData> layout(layoutParse.get());
		layoutParse.release();

		auto_ptr<TMLAttributesParse> attribsParse = TMLAttributesParse::Parse(attribsName);
		auto_ptr<TMLAttributes> attribs(attribsParse.get());
		attribsParse.release();

		if (mergedLayout || mergedAttribs)
			{
			// first we merge the components and the attributes
			mergedLayout->MergeComponents(*layout);
			mergedAttribs->Merge(*attribs);
			}
		else
			{
			// first time around
			mergedLayout = layout.get();
			mergedAttribs = attribs.get();
			}
        layout.release();
		attribs.release();
        }

	mergedLayout->iAttributes = mergedAttribs; // transfer ownership

	// once merged, we can compile the tables
    mergedLayout->Compile();


	string destLayout = args[arg++];
	MLCompDataToLayPerf layPerf(cdlName, *iface, *mergedLayout, destLayout);
	layPerf.WriteLayout();

	return 0;
	}
void QDBusViewer::callMethod(const BusSignature &sig)
{
    QDBusInterface iface(sig.mService, sig.mPath, sig.mInterface, c);
    const QMetaObject *mo = iface.metaObject();

    // find the method
    QMetaMethod method;
    for (int i = 0; i < mo->methodCount(); ++i) {
        const QString signature = QString::fromLatin1(mo->method(i).signature());
        if (signature.startsWith(sig.mName) && signature.at(sig.mName.length()) == QLatin1Char('('))
            if (getDbusSignature(mo->method(i)) == sig.mTypeSig)
                method = mo->method(i);
    }
    if (!method.signature()) {
        QMessageBox::warning(this, tr("Unable to find method"),
                tr("Unable to find method %1 on path %2 in interface %3").arg(
                    sig.mName).arg(sig.mPath).arg(sig.mInterface));
        return;
    }

    PropertyDialog dialog;
    QList<QVariant> args;

    const QList<QByteArray> paramTypes = method.parameterTypes();
    const QList<QByteArray> paramNames = method.parameterNames();
    QList<int> types; // remember the low-level D-Bus type
    for (int i = 0; i < paramTypes.count(); ++i) {
        const QByteArray paramType = paramTypes.at(i);
        if (paramType.endsWith('&'))
            continue; // ignore OUT parameters

        QVariant::Type type = QVariant::nameToType(paramType);
        dialog.addProperty(QString::fromLatin1(paramNames.value(i)), type);
        types.append(QMetaType::type(paramType));
    }

    if (!types.isEmpty()) {
        dialog.setInfo(tr("Please enter parameters for the method \"%1\"").arg(sig.mName));

        if (dialog.exec() != QDialog::Accepted)
            return;

        args = dialog.values();
    }

    // Special case - convert a value to a QDBusVariant if the
    // interface wants a variant
    for (int i = 0; i < args.count(); ++i) {
        if (types.at(i) == qMetaTypeId<QDBusVariant>())
            args[i] = qVariantFromValue(QDBusVariant(args.at(i)));
    }

    QDBusMessage message = QDBusMessage::createMethodCall(sig.mService, sig.mPath, sig.mInterface,
            sig.mName);
    message.setArguments(args);
    c.callWithCallback(message, this, SLOT(dumpMessage(QDBusMessage)));
}