Example #1
0
bool QBluetoothPasskeyAgent_Private::registerAgent(const QString &localAdapter,
        const QString &addr)
{
    QString bluezAdapter = "/org/bluez";

    if (!localAdapter.isNull()) {
        bluezAdapter.append("/");
        bluezAdapter.append(localAdapter);
    }

    QDBusInterface *iface = new QDBusInterface("org.bluez",
                                               bluezAdapter,
                                               "org.bluez.Security",
                                               QDBusConnection::systemBus());

    if (!iface->isValid())
        return false;

    QString bluezMethod;
    QVariantList args;

    QString path = m_name;
    path.prepend('/');
    args << path;

    if (addr.isNull()) {
        bluezMethod = "RegisterDefaultPasskeyAgent";
    }
    else {
        bluezMethod = "RegisterPasskeyAgent";
        args << addr;
    }

    QDBusReply<void> reply = iface->callWithArgumentList(QDBus::Block,
            bluezMethod, args);

    if (!reply.isValid()) {
        handleError(reply.error());
        return false;
    }

    return true;
}
lastfm::LNetworkConnectionMonitor::LNetworkConnectionMonitor( QObject* parent ) :
    NetworkConnectionMonitor( parent )
{
    m_nmInterface = new QDBusInterface( NM_DBUS_SERVICE,
                                        NM_DBUS_PATH,
                                        NM_DBUS_INTERFACE,
                                        QDBusConnection::systemBus(),
                                        this );
    if ( !m_nmInterface->isValid() )
    {
        qDebug() << "Unable to watch network state changes via D-Bus.";
        return;
    }

    //get current connection state
    QDBusReply<uint> reply = m_nmInterface->call( QDBus::AutoDetect, "state" );
    if ( reply.isValid() )
    {
        if ( reply.value() == NM_STATE_CONNECTED_GLOBAL )
        {
            setConnected( true );
        }
        else if ( reply.value() == NM_STATE_DISCONNECTED || reply.value() == NM_STATE_ASLEEP )
        {
            setConnected( false );
        }
    }
    else
    {
        qDebug() << "Error: " << reply.error();
    }

    //connect network manager signals
   m_nmInterface->connection().connect( NM_DBUS_SERVICE,
                                        NM_DBUS_PATH,
                                        NM_DBUS_INTERFACE,
                                        "StateChanged",
                                        this,
                                        SLOT( onStateChange( uint ) )
                                      );

}
Example #3
0
XesamCollectionBuilder::XesamCollectionBuilder( Collections::SqlCollection *collection )
    : QObject( collection )
    , m_collection( collection )
{
    DEBUG_BLOCK
    m_xesam = new OrgFreedesktopXesamSearchInterface( "org.freedesktop.xesam.searcher",
                                                  "/org/freedesktop/xesam/searcher/main",
                                                  QDBusConnection::sessionBus() );
    if( m_xesam->isValid() )
    {
        connect( m_xesam, SIGNAL( HitsAdded( QString , int ) ), SLOT( slotHitsAdded( QString, int ) ) );
        connect( m_xesam, SIGNAL( HitsModified( QString, QList<int> ) ), SLOT( slotHitsModified( QString, QList<int> ) ) );
        connect( m_xesam, SIGNAL( HitsRemoved( QString, QList<int> ) ), SLOT( slotHitsRemoved( QString, QList<int> ) ) );
        QDBusReply<QString> sessionId = m_xesam->NewSession();
        if( !sessionId.isValid() )
        {
            debug() << "Could not acquire Xesam session, aborting. error was: " << sessionId.error();
            return;
            //TODO error handling
        }
        m_session = sessionId.value();
        if( !setupXesam() )
        {
            debug() << "Warning, could not setup xesam correctly";
        }
        QDBusReply<QString> search = m_xesam->NewSearch( m_session, generateXesamQuery() );
        if( search.isValid() )
        {
            m_search = search.value();
            m_xesam->StartSearch( m_search );
        }
        else
        {
            debug() << "Invalid response for NewSearch";
        }
    }
    else
    {
        //TODO display warning about unavailable xesam daemon
    }

}
void PeopleApplication::composeEmail(const QString& address) 
{
    qDebug() << "PeopleApplication::composeEmail attempting email:" << address;

    if(QDBusConnection::sessionBus().interface()->isServiceRegistered("com.meego.email")){
      qDebug() << "PeopleApplication::composeEmail email is registered";
	emailToActiveService(address);	    
	return;
    }else{
      qDebug() << "PeopleApplication::composeEmail email is NOT registered";
      QDBusReply<void> reply = QDBusConnection::sessionBus().interface()->startService("com.meego.email");
      if (!reply.isValid()){
	qWarning() << "Starting Email failed:" << reply.error().message();  
      }else{
      qDebug() << "PeopleApplication::composeEmail saving address to email on registration";
	m_emailPending = true;
	m_email = address;
      }           
    }
}
void PeopleApplication::callNumber(const QString& number)
{
    qDebug() << "PeopleApplication::callNumber attempting call to:" << number;

    if(QDBusConnection::sessionBus().interface()->isServiceRegistered("com.meego.dialer")){
      qDebug() << "PeopleApplication::callNumber dialer is registered";
	callNumberToActiveService(number);	    
	return;
    }else{
      qDebug() << "PeopleApplication::callNumber dialer is NOT registered";
      QDBusReply<void> reply = QDBusConnection::sessionBus().interface()->startService("com.meego.dialer");
      if (!reply.isValid()){
	qWarning() << "Starting Dialer failed:" << reply.error().message();  
      }else{
      qDebug() << "PeopleApplication::callNumber saving number to call on registration";
	m_callPending = true;
	m_number = number;
      }           
    }
}
void PeopleApplication::composeSMS(const QString& number)
{
  qDebug() << "Attempting to compose SMS to" << number;

  if(QDBusConnection::sessionBus().interface()->isServiceRegistered("com.meego.sms")){
    qDebug() << "PeopleApplication::composeSMS SMS is registered";
    smsNumberToActiveService(number);	    
    return;
  }else{
    qDebug() << "PeopleApplication::composeSMS SMS is NOT registered";
    QDBusReply<void> reply = QDBusConnection::sessionBus().interface()->startService("com.meego.sms");
    if (!reply.isValid()){
      qWarning() << "Starting SMS failed:" << reply.error().message();  
    }else{
      qDebug() << "PeopleApplication::composeSMS saving number to text on registration";
      m_smsPending = true;
      m_smsNumber = number;
    }           
  }
}
Example #7
0
bool tst_Events::replaceEvent(const uint oldCookie, const qint64 timestamp,
                              const int dueInSeconds, uint &cookie)
{
    Maemo::Timed::Event event = createEvent(timestamp, dueInSeconds);

    // Open a connection to timed and replace the event
    Maemo::Timed::Interface timedIface;
    if (!timedIface.isValid()) {
        qWarning() << "Invalid timed interface:" << timedIface.lastError().message();
        return false;
    }

    QDBusReply<uint> reply = timedIface.replace_event_sync(event, oldCookie);
    if (!reply.isValid()) {
        qWarning() << "Replace event failed: %1" << reply.error().message();
        return false;
    }
    cookie = reply.value();
    return true;
}
Example #8
0
QStringList HalManager::allDevices()
{
    if (d->cacheSynced)
    {
        return d->devicesCache;
    }

    QDBusReply<QStringList> reply = d->manager.call("GetAllDevices");

    if (!reply.isValid())
    {
        qWarning() << Q_FUNC_INFO << " error: " << reply.error().name() << endl;
        return QStringList();
    }

    d->devicesCache = reply;
    d->cacheSynced = true;

    return reply;
}
Example #9
0
int main( int argc, char *argv[] )
{
	KAboutData aboutData("kwalletsync", 0, ki18n("kwalletsync"), "version");
	KComponentData componentData(&aboutData);
	QApplication app( argc, argv );

	// force name with D-BUS
        QDBusReply<QDBusConnectionInterface::RegisterServiceReply> reply
            = QDBusConnection::sessionBus().interface()->registerService( "org.kde.kwalletsync",
                                                                QDBusConnectionInterface::ReplaceExistingService );

        if ( !reply.isValid() )
        {
                _out << "D-BUS name request returned " << reply.error().name() << endl;
        }

	openWallet();

	return 0;
}
SystemMonitor::SystemMonitor(QObject *parent) :
    QObject(parent)
{
    connect(&m_settings, SIGNAL(updateIntervalChanged(int)), SLOT(updateIntervalChanged(int)));

    //Timer instead of dbus connection
    m_updateTimer.setTimerType(Qt::VeryCoarseTimer);
    connect(&m_updateTimer, SIGNAL(timeout()), SIGNAL(dataUpdated()));
    updateIntervalChanged(m_settings.updateInterval);
    m_updateTimer.start();
    /*
    qDebug() << "Connect to dataUpdate event" <<
    //TODO: enable if dbus connection will be available
    QDBusConnection::sessionBus().connect(
        SYSMON_DBUS_SERVICE, SYSMON_DBUS_PATH, SYSMON_DBUS_IFACE,
        "dataUpdated", this, SIGNAL(dataUpdated())
    );
    */

    //systemd connection
    systemd = new QDBusInterface("org.freedesktop.systemd1",
                                     "/org/freedesktop/systemd1",
                                     "org.freedesktop.systemd1.Manager",
                                     QDBusConnection::sessionBus(), this);

    systemd->call("Subscribe");

    QDBusReply<QDBusObjectPath> unit = systemd->call("LoadUnit", SYSMON_SYSTEMD_UNIT);
    if (unit.isValid()) {
        unitPath = unit.value();

        getUnitProperties();

        QDBusConnection::sessionBus().connect(
                    "org.freedesktop.systemd1", unitPath.path(),
                    "org.freedesktop.DBus.Properties", "PropertiesChanged",
                    this, SLOT(onPropertiesChanged(QString,QMap<QString,QVariant>,QStringList)));
    } else {
        qWarning() << unit.error().message();
    }
}
void SailfishPlatform::telepathyResponse(const QString &account, const QString &contact, const QString &text) const
{
    QDBusObjectPath acct(account);
    QVariantMap arg1,arg2;
    arg1.insert("message-type",0);
    arg2.insert("content-type",QString("text/plain"));
    arg2.insert("content",text);
    QDBusReply<QString> res = QDBusConnection::sessionBus().call(
                QDBusMessage::createMethodCall("org.freedesktop.Telepathy.ChannelDispatcher",
                                               "/org/freedesktop/Telepathy/ChannelDispatcher",
                                               "org.freedesktop.Telepathy.ChannelDispatcher.Interface.Messages.DRAFT", "SendMessage")
                << qVariantFromValue(acct) << contact << qVariantFromValue(QList<QVariantMap>({arg1,arg2})) << (quint32)0);
    if (res.isValid()) {
        if (res.value().isEmpty()) {
            qWarning() << "Unable to send response from" << account << "to" << contact << "with" << text;
        } else
            qDebug() << "Sent message under uuid" << res.value();
    } else {
        qWarning() << res.error().message();
    }
}
void PeopleApplication::imToActiveService(const QString& account){
  QStringList list = account.split(":");
  if(list.count() != 3)
    return;

  QString accountPath = list.at(2);
  QString accountUri = list.at(0);
  //index=1 is nickname, not used here

  // hard-coded details of the MeeGo IM application
  QDBusInterface im("com.meego.meego_handset_chat", "/com/meego/meego_handset_chat", "com.meego.meego_handset_chat");
  if (!im.isValid()) {
    qWarning() << "Composing IM to path: " <<accountPath << " accountUri: " << accountUri << "- could not find IM app";
    return;
  }

  QDBusReply<void> reply = im.call(QDBus::BlockWithGui, "showDialogPageForContact", accountPath , accountUri);
  if (!reply.isValid())
    qWarning() << "Composing IM to path: " <<accountPath << " accountUri: " << accountUri << "failed:" ;
  reply.error().message();
}
Example #13
0
ServiceControl::ServiceControl(QObject *parent) : QObject(parent),
    systemd(new QDBusInterface("org.freedesktop.systemd1",
                               "/org/freedesktop/systemd1",
                               "org.freedesktop.systemd1.Manager",
                               QDBusConnection::sessionBus(), this))
{
    systemd->call("Subscribe");

    QDBusReply<QDBusObjectPath> unit = systemd->call("LoadUnit", ROCKPOOLD_SYSTEMD_UNIT);
    if (unit.isValid()) {
        unitPath = unit.value();

        getUnitProperties();

        QDBusConnection::sessionBus().connect(
                    "org.freedesktop.systemd1", unitPath.path(),
                    "org.freedesktop.DBus.Properties", "PropertiesChanged",
                    this, SLOT(onPropertiesChanged(QString,QMap<QString,QVariant>,QStringList)));
    } else {
        qWarning() << unit.error().message();
    }
}
Example #14
0
int openAndClose()
{
	QDBusInterface service("org.kde.kwalletd", "/modules/kwalletd");
	if (!service.isValid()) {
		_out << "Constructed service is invalid!" << endl;
		return 1;
	}
	
	QDBusReply<int> h = service.call(QDBus::Block, "open", _kdewallet, (qlonglong)0, "kwalletnoautoclose");
	if (!h.isValid() || h.value() < 0) {
		_out << "Opening the wallet failed!" << endl;
		_out << "Error: " << h.error().message() << endl;
		return 1;
	} else {
		_out << "Wallet opened." << endl;
	}

	_out << "closing the wallet" << endl;
	QDBusReply<int> r = service.call(QDBus::Block, "close", h.value(), false, "kwalletnoautoclose");
	
	return r;
}
LNetworkConnectionMonitor::LNetworkConnectionMonitor( QObject* parent ) :
    NetworkConnectionMonitor( parent )
{
    m_nmInterface = new QDBusInterface( QString( "org.freedesktop.NetworkManager" ),
                                        QString( "/org/freedesktop/NetworkManager" ),
                                        QString( "org.freedesktop.NetworkManager" ),
                                        QDBusConnection::systemBus(),
                                        this );

    //get current connection state
    QDBusInterface* dbusInterface = new QDBusInterface( QString( "org.freedesktop.NetworkManager" ),
                                                        QString( "/org/freedesktop/NetworkManager" ),
                                                        QString( "org.freedesktop.DBus.Properties" ),
                                                        QDBusConnection::systemBus(),
                                                        this );

    QDBusReply<QVariant> reply = dbusInterface->call( "Get", "org.freedesktop.NetworkManager", "state" );
    if ( reply.isValid() )
    {
        if ( reply.value() == Connected )
        {
            setConnected( true );
        }
        else if ( reply.value() == Disconnected )
        {
            setConnected( false );
        }
    }
    else
    {
        qDebug() << "Error: " << reply.error();
    }
    delete dbusInterface;

    //connect network manager signals
   connect( m_nmInterface, SIGNAL( StateChange( uint ) ), this, SLOT( onStateChange( uint ) ) );

}
void DockManagerNotificationBackend::itemAdded(QDBusObjectPath p)
{
    Q_UNUSED(p);

    if (_item)
        return;

    // stupid implementations (awn; kde?) use wrong casing of PID, but proper type
    QDBusReply<QList<QDBusObjectPath>> paths = _dock->call("GetItemsByPid", (int)QCoreApplication::applicationPid());
    if (!paths.isValid()) {
        // stupid implementations (i.e. docky) use uint, but proper casing
        paths = _dock->call("GetItemsByPID", (unsigned int)QCoreApplication::applicationPid());
        if (!paths.isValid()) {
            qDebug() << "DBus error:" << paths.error().message();
            return;
        }
    }
    if (paths.value().count() == 0) {  // no icon for this instance
        return;
    }

    QString path = paths.value()[0].path();  // no sense in using multiple icons for one instance
    _item = new QDBusInterface("org.freedesktop.DockManager", path, "org.freedesktop.DockItem", _bus, this);
}
Example #17
0
QStringList
PlatformUdisks::getPartitionList(const QString &devicePath)
{
    QStringList devList;
    // First get the list of disks
    QDBusConnection connection = QDBusConnection::systemBus();
    QDBusMessage message;
    message = QDBusMessage::createMethodCall("org.freedesktop.UDisks", "/org/freedesktop/UDisks", "org.freedesktop.UDisks", "EnumerateDevices");

    QDBusReply<QList<QDBusObjectPath> > reply = connection.call(message);
    if (!reply.isValid())
    {
        qDebug() << "Failure: " <<  reply.error();
        return(devList);
    }

    QList<QDBusObjectPath> list = reply.value();
    QRegExp reg(QString("%1[0-9]+$").arg(devicePath));
    for (int i = 0; i < list.size(); ++i)
        if (list.at(i).path().contains(reg))
            devList << list.at(i).path();

    return(devList);
}
Example #18
0
QString KHotKeys::changeMenuEntryShortcut(
        const QString& entry_P,
        const QString shortcut_P )
{
    kDebug();

    if( !khotkeys_inited )
        init();

    if( !khotkeys_present || !khotkeysInterface->isValid())
        return "";

    QDBusReply<QString> reply = khotkeysInterface->register_menuentry_shortcut(
            entry_P,
            shortcut_P);

    if (!reply.isValid()) {
        kError() << reply.error();
        return "";

    } else {
        return reply;
    }
}
int main(int argc, char **argv)
{
  KAboutData about("kgrapheditor", 0, ki18n("KGraphEditor"), version, ki18n(description),
                    KAboutData::License_GPL, ki18n("(C) 2005-2010 Gaël de Chalendar"), KLocalizedString(), 0, "*****@*****.**");
  about.addAuthor( ki18n("Gaël de Chalendar"), KLocalizedString(), "*****@*****.**" );
  KCmdLineArgs::init(argc, argv, &about);

  KCmdLineOptions options;
  options.add("+[URL]", ki18n( "Dot graph to open" ));
  KCmdLineArgs::addCmdLineOptions( options );
  KApplication app;
  
// see if we are starting with session management
  if (app.isSessionRestored())
  {
      RESTORE(KGraphEditor);
  }
  else
  {
      // no session.. just start up normally
      KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

      KGraphEditor *widget = 0;
      if ( args->count() == 0 )
      {
        widget = new KGraphEditor;
        new KgrapheditorAdaptor(widget);
        QDBusConnection::sessionBus().registerObject("/KGraphEditor", widget);
        widget->show();
      }
      else
      {
        QDBusReply<bool> reply = QDBusConnection::sessionBus().interface()->isServiceRegistered( "org.kde.kgrapheditor" );
      
        bool instanceExists = reply.value();
  
        for (int i = 0; i < args->count(); i++ )
        {
          if (instanceExists 
              && (KMessageBox::questionYesNo(0, 
                                         i18n("A KGraphEditor window is already open, where do you want to open this file?"),
                                         i18n("Opening in new window confirmation"),
                                             KGuiItem(i18nc("Where to open a file", "Existing window")),
                                             KGuiItem(i18nc("Where to open a file", "New window")),
                                             "openInNewWindowMode"   ) == KMessageBox::Yes) )
          {
            QByteArray tosenddata;
            QDataStream arg(&tosenddata, QIODevice::WriteOnly);
            QString strarg = args->arg(i);
            KUrl url;
            if (strarg.left(1) == "/")
              url = KUrl(strarg);
            else url = KUrl(QDir::currentPath() + '/' + strarg);
            arg << url;
            QDBusInterface iface("org.kde.kgrapheditor", "/KGraphEditor", "", QDBusConnection::sessionBus());
            if (iface.isValid()) 
            {
              QDBusReply<void> reply = iface.call("openUrl", url.pathOrUrl());
              if (reply.isValid()) 
              {
                kDebug() << "Reply was valid" << endl;
                return 0;
              }

              kError() << "Call failed: " << reply.error().message() << endl;
              return 1;
            }
            kError() << "Invalid interface" << endl;
            exit(0);
          }
          else
          {
            widget = new KGraphEditor;
            new KgrapheditorAdaptor(widget);
            QDBusConnection::sessionBus().registerObject("/KGraphEditor", widget);
            widget->show();
            widget->openUrl( args->url( i ) );
          }
        }
      }
      args->clear();
    if (widget != 0)
    {
      widget->  reloadPreviousFiles();
    }
    
  }
  return app.exec();
}
Example #20
0
int main (int argc, char *argv[]) {
	QApplication app (argc, argv);
	QStringList args = app.arguments ();
	if (!args.isEmpty ()) args.pop_front ();	// The command itself
	qputenv ("DESKTOP_STARTUP_ID", qgetenv ("STARTUP_ID_COPY"));	// for startup notifications (set via rkward.desktop)
	qputenv ("STARTUP_ID_COPY", "");

	// Parse arguments that need handling in the wrapper
	bool usage = false;
	QStringList debugger_args;
	QStringList file_args;
	bool reuse = false;
	bool warn_external = true;
	QString r_exe_arg;
	int debug_level = 2;

	for (int i=0; i < args.size (); ++i) {
		if (args[i] == "--debugger") {
			args.removeAt (i);
			while (i < args.size ()) {
				QString arg = args.takeAt (i);
				if (arg == "--") break;
				debugger_args.append (arg);
			}
			if (debugger_args.isEmpty ()) usage = true;
		} else if (args[i] == "--r-executable") {
			if ((i+1) < args.size ()) {
				r_exe_arg = args.takeAt (i + 1);
			} else usage = true;
			args.removeAt (i);
			--i;
		} else if (args[i] == "--debug-level") {
			if ((i+1) < args.size ()) {
				debug_level = args[i+1].toInt ();
			}
		} else if (args[i] == "--reuse") {
			reuse = true;
		} else if (args[i] == "--nowarn-external") {
			warn_external = false;
		} else if (args[i].startsWith ("--")) {
			// all RKWard and KDE options (other than --reuse) are of the for --option <value>. So skip over the <value>
			i++;
		} else {
			QUrl url (args[i]);
			if (url.isRelative ()) {
				file_args.append (QDir::current ().absoluteFilePath (url.toLocalFile ()));
			} else {
				file_args.append (args[i]);
			}
		}
	}

	if (reuse) {
		if (!QDBusConnection::sessionBus ().isConnected ()) {
			if (debug_level > 2) qDebug ("Could not connect to session dbus");
		} else {
			QDBusInterface iface (RKDBUS_SERVICENAME, "/", "", QDBusConnection::sessionBus ());
			if (iface.isValid ()) {
				QDBusReply<void> reply = iface.call ("openAnyUrl", file_args, warn_external);
				if (!reply.isValid ()) {
					if (debug_level > 2) qDebug ("Error while placing dbus call: %s", qPrintable (reply.error ().message ()));
					return 1;
				}
				return 0;
			}
		}
	}

	// MacOS may need some path adjustments, first
#ifdef Q_WS_MAC
	QString oldpath = qgetenv ("PATH");
	if (!oldpath.contains (INSTALL_PATH)) {
		//ensure that PATH is set to include what we deliver with the bundle
		qputenv ("PATH", QString ("%1/bin:%1/sbin:%2").arg (INSTALL_PATH).arg (oldpath).toLocal8Bit ());
		if (debug_level > 3) qDebug ("Adjusting system path to %s", qPrintable (qgetenv ("PATH")));
	}
	// ensure that RKWard finds its own packages
	qputenv ("R_LIBS", R_LIBS);
	QProcess::execute ("launchctl", QStringList () << "load" << "-w" << INSTALL_PATH "/Library/LaunchAgents/org.freedesktop.dbus-session.plist");
#endif

	// Locate KDE and RKWard installations
	QString kde4_config_exe = findExeAtPath ("kde4-config", QDir::currentPath ());
	if (kde4_config_exe.isNull ()) kde4_config_exe = findExeAtPath ("kde4-config", app.applicationDirPath ());
	if (kde4_config_exe.isNull ()) kde4_config_exe = findExeAtPath ("kde4-config", QDir (app.applicationDirPath ()).filePath ("KDE/bin"));
	if (kde4_config_exe.isNull ()) {
#ifdef Q_WS_WIN
	QStringList syspath = QString (qgetenv ("PATH")).split (';');
#else
	QStringList syspath = QString (qgetenv ("PATH")).split (':');
#endif
		for (int i = 0; i < syspath.size (); ++i) {
			kde4_config_exe = findExeAtPath ("kde4-config", syspath[i]);
			if (!kde4_config_exe.isNull ()) break;
		}
	}

	if (kde4_config_exe.isNull ()) {
		QMessageBox::critical (0, "Could not find KDE installation", "The KDE installation could not be found (kde4-config). When moving / copying RKWard, make sure to copy the whole application folder, or create a shorcut / link, instead.");
		exit (1);
	}

	QDir kde_dir (QFileInfo (kde4_config_exe).absolutePath ());
	kde_dir.makeAbsolute ();
	QString kde_dir_safe_path = quoteCommand (kde_dir.path ());
#ifdef Q_WS_WIN
	QString kdeinit4_exe = findExeAtPath ("kdeinit4", kde_dir.path ());
	qputenv ("PATH", QString (kde_dir_safe_path + ';' + qgetenv ("PATH")).toLocal8Bit ());
	if (debug_level > 3) qDebug ("Adding %s to the system path", qPrintable (kde_dir_safe_path));
#endif
	// important if RKWard is not in KDEPREFIX/bin but e.g. KDEPREFIX/lib/libexec
	qputenv ("RKWARD_ENSURE_PREFIX", kde_dir_safe_path.toLocal8Bit ());
	if (debug_level > 3) qDebug ("Setting environment variable RKWARD_ENSURE_PREFIX=%s", qPrintable (kde_dir_safe_path));

	QString rkward_frontend_exe = findRKWardAtPath (app.applicationDirPath ());	// this is for running directly from a build tree
#ifdef Q_WS_MAC
	if (rkward_frontend_exe.isNull ()) rkward_frontend_exe = findRKWardAtPath (app.applicationDirPath () + "/rkward.frontend.app/Contents/MacOS"); 	// this is for running directly from a build tree
#endif
	if (rkward_frontend_exe.isNull ()) rkward_frontend_exe = findRKWardAtPath (RKWARD_FRONTEND_LOCATION);
	if (rkward_frontend_exe.isNull ()) rkward_frontend_exe = findRKWardAtPath (kde_dir.absoluteFilePath ("bin"));
	if (rkward_frontend_exe.isNull ()) rkward_frontend_exe = findRKWardAtPath (kde_dir.absoluteFilePath ("../lib/libexec"));

	if (rkward_frontend_exe.isNull ()) {
		QMessageBox::critical (0, "RKWard frontend binary missing", "RKWard frontend binary could not be found. When moving / copying RKWard, make sure to copy the whole application folder, or create a shorcut / link, instead.");
		exit (1);
	}

	if (usage) {
		QProcess::execute (rkward_frontend_exe, QStringList ("--help"));
		exit (1);
	}

#ifdef Q_WS_WIN
	// Explicit initialization of KDE, in case Windows 7 asks for admin privileges
	if (kdeinit4_exe.isNull ()) {
		kdeinit4_exe = findExeAtPath ("kdeinit4", QFileInfo (rkward_frontend_exe).absolutePath ());
	}
	if (!kdeinit4_exe.isNull ()) QProcess::execute (kdeinit4_exe, QStringList ());
#endif

	// Look for R:
	//- command line parameter
	//- Specified in cfg file next to rkward executable
	//- compile-time default
	QString r_exe = r_exe_arg;
	if (!r_exe.isNull ()) {
		if (!QFileInfo (r_exe).isExecutable ()) {
			QMessageBox::critical (0, "Specified R executable does not exist", QString ("The R executable specified on the command line (%1) does not exist or is not executable.").arg (r_exe));
			exit (1);
		}
		if (debug_level > 3) qDebug ("Using R specified on command line");
	} else {
		QFileInfo frontend_info (rkward_frontend_exe);
		QDir frontend_path = frontend_info.absoluteDir ();
		QFileInfo rkward_ini_file (frontend_path.absoluteFilePath ("rkward.ini"));
		if (rkward_ini_file.isReadable ()) {
			QSettings rkward_ini (rkward_ini_file.absoluteFilePath (), QSettings::IniFormat);
			r_exe = rkward_ini.value ("R executable").toString ();
			if (!r_exe.isNull ()) {
				if (QDir::isRelativePath (r_exe)) {
					r_exe = frontend_path.absoluteFilePath (r_exe);
				}
				if (!QFileInfo (r_exe).isExecutable ()) {
					QMessageBox::critical (0, "Specified R executable does not exist", QString ("The R executable specified in the rkward.ini file (%1) does not exist or is not executable.").arg (rkward_ini_file.absoluteFilePath ()));
					exit (1);
				}
			}
			if (debug_level > 3) qDebug ("Using R as configured in config file %s", qPrintable (rkward_ini_file.absoluteFilePath ()));
		}
		if (r_exe.isNull ()) {
			r_exe = R_EXECUTABLE;
			if (!QFileInfo (r_exe).isExecutable ()) {
				QMessageBox::critical (0, "Specified R executable does not exist", QString ("The R executable specified at compile time (%1) does not exist or is not executable. Probably the installation of R has moved. You can use the command line parameter '--R', or supply an rkward.ini file to specify the new location.").arg (r_exe));
				exit (1);
			}
			if (debug_level > 3) qDebug ("Using R as configured at compile time");
		}
	}

	qputenv ("R_BINARY", r_exe.toLocal8Bit ());
	QStringList call_args ("CMD");
	call_args.append (debugger_args);
	call_args.append (quoteCommand (rkward_frontend_exe));

	if (!args.isEmpty ()) {
		// NOTE: QProcess quotes its arguments, *but* properly passing all spaces and quotes through the R CMD wrapper, seems near(?) impossible on Windows. Instead, we use percent encoding, internally.
		for (int i = 0; i < args.size (); ++i) {
			call_args.append (QString::fromUtf8 (QUrl::toPercentEncoding (args[i], QByteArray (), " \"")));
		}
	}

	if (debug_level > 2) qDebug ("Starting frontend: %s %s", qPrintable (r_exe), qPrintable (call_args.join (" ")));

	InteractiveProcess proc;
#ifdef Q_WS_WIN
	if (debugger_args.isEmpty ()) {
		// start _without_ opening an annoying console window
		QTemporaryFile *vbsf = new QTemporaryFile (QDir::tempPath () + "/rkwardlaunchXXXXXX.vbs");
		vbsf->setAutoRemove (false);
		if (vbsf->open ()) {
			QTextStream vbs (vbsf);
			vbs << "Dim WinScriptHost\r\nSet WinScriptHost = CreateObject(\"WScript.Shell\")\r\nWinScriptHost.Run \"" << quoteCommand (r_exe);
			for (int i = 0;  i < call_args.length (); ++i) {
				vbs << " " << call_args[i];
			}
			vbs << "\", 0\r\nSet WomScriptHost = Nothing\r\n";
			vbsf->close ();
			QString filename = vbsf->fileName ();
			delete (vbsf);  // somehow, if creating vbsf on the stack, we cannot launch it, because "file is in use by another process", despite we have closed it.
			proc.start ("WScript.exe", QStringList (filename));
			bool ok = proc.waitForFinished (-1);
			if (proc.exitCode () || !ok) {
				QMessageBox::critical (0, "Error starting RKWard", QString ("Starting RKWard failed with error \"%1\"").arg (proc.errorString ()));
			}
			QFile (filename).remove ();
			return (0);
		}
	}
	// if that did not work or not on windows:
#endif
	proc.setProcessChannelMode (QProcess::ForwardedChannels);
	proc.start (quoteCommand (r_exe), call_args);
	bool ok = proc.waitForFinished (-1);
	if (proc.exitCode () || !ok) {
		QMessageBox::critical (0, "Error starting RKWard", QString ("Starting RKWard failed with error \"%1\"").arg (proc.errorString ()));
	}

	return (0);
}
Example #21
0
// Perform initialization, create the unique KSystemTimeZones instance,
// whose only function is to receive D-Bus signals from KTimeZoned,
// and create the unique KSystemTimeZonesPrivate instance.
KSystemTimeZonesPrivate *KSystemTimeZonesPrivate::instance()
{
    if (!m_instance)
    {
        m_instance = new KSystemTimeZonesPrivate;
#if !defined(TIMED_SUPPORT) && !defined(KCALCORE_FOR_MEEGO)
        // A KSystemTimeZones instance is required only to catch D-Bus signals.
        m_parent = new KSystemTimeZones;
        // Ensure that the KDED time zones module has initialized. The call loads the module on demand.
        QDBusInterface *ktimezoned = new QDBusInterface("org.kde.kded", "/modules/ktimezoned", KTIMEZONED_DBUS_IFACE);
        QDBusReply<void> reply = ktimezoned->call("initialize", false);
        if (!reply.isValid())
            kError(161) << "KSystemTimeZones: ktimezoned initialize() D-Bus call failed: " << reply.error().message() << endl;
kDebug(161)<<"instance(): ... initialised";
        delete ktimezoned;
#endif
        // Read the time zone config written by ktimezoned
        readConfig(true);

        // Go read the database.
#ifdef Q_OS_WIN
        // On Windows, HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones
        // is the place to look. The TZI binary value is the TIME_ZONE_INFORMATION structure.
#else
        // For Unix, read zone.tab.
        if (!m_zonetab.isEmpty())
            m_instance->readZoneTab(false);
#endif
        setLocalZone();
        if (!m_localZone.isValid()) {
            kDebug() << "m_localZone invalid";
            m_localZone = KTimeZone::utc();   // ensure a time zone is always returned
        }

        qAddPostRoutine(KSystemTimeZonesPrivate::cleanup);
    }
    return m_instance;
}
Example #22
0
Soprano::Node Soprano::Client::DBusModel::createBlankNode()
{
    QDBusReply<Node> reply = d->interface->createBlankNode( d->callMode );
    setError( DBus::convertError( reply.error() ) );
    return reply.value();
}
Example #23
0
int main(int argc, char *argv[])
{
    // TODO: Clean this up, update API, etc.
    if (argc < 5 || argc > 6)
    {
        qWarning() << "Error detected! Insufficient number of arguments.";
        qWarning() << "";
        qWarning() << "Usage: ambdbusaccess <R/W> <Object> <Property> <Zone> [Value]";
        qWarning() << "- <R/W>";
        qWarning() << "  Used for specifying [R]ead or [W]rite.";
        qWarning() << "- <Object>";
        qWarning() << "  The AMB object to access.";
        qWarning() << "- <Property>";
        qWarning() << "  The property within the object to access.";
        qWarning() << "- <Zone>";
        qWarning() << "  The AMB zone to access.";
        qWarning() << "- [Value]";
        qWarning() << "  The value to write, if writing.";
        qWarning() << "Example: ambdbusaccess Write ClimateControl FanSpeedLevel 0 7";
        qWarning() << "";
        qWarning() << "This program returns an int under the following conditions:";
        qWarning() << "Successful Read: <Value Read>";
        qWarning() << "Unsuccessful Read: -1";
        qWarning() << "Successful Write: <Value Written>";
        qWarning() << "Unsuccessful Write: -1";

        return -1;
    }

    // TODO: Error check input.
    bool read = !strncmp(argv[1], "R", 1);
    QString object = argv[2];
    QString property = argv[3];
    qint32 zone = atoi(argv[4]);
    qint32 value = 0;

    if (argc == 6)
    {
        value = atoi(argv[5]);
    }

    // Necessary to suppress Qt messages about touching the D-Bus before the application was created.
    QCoreApplication a(argc, argv);

    // Sanity check that the system bus is actually present.
    if (!QDBusConnection::systemBus().isConnected())
    {
        qCritical() << "Could not access system D-Bus!";
        return -1;
    }

    // Get ahold of the manager object.
    QDBusInterface *manager = new QDBusInterface("org.automotive.message.broker", "/", "org.automotive.Manager",
                                                 QDBusConnection::systemBus());

    // Go fetch the path for the AMB object we are concerned with.
    qDebug().nospace() << "Looking for property " << property.toStdString().c_str() << " of object " <<
                          object.toStdString().c_str() << " in zone " << zone << ".";
    QDBusReply<QDBusObjectPath> propertyPath = manager->call("FindObjectForZone", object.toStdString().c_str(), zone);
    if (!propertyPath.isValid())
    {
        qDebug() << "Invalid reply!" << propertyPath.error() << "Got the path:" << propertyPath.value().path();
    }

    // Now that we have the path, open an interface to the object.
    QDBusInterface *propertyInterface = new QDBusInterface("org.automotive.message.broker", propertyPath.value().path(),
                                                           "org.automotive.ClimateControl", QDBusConnection::systemBus());

    // Perform our read or write operation.
    if (read)
    {
        QVariant reply = propertyInterface->property(property.toStdString().c_str());
        if (!reply.isValid())
        {
            qDebug() << "Invalid reply when reading the property!" << propertyInterface->lastError() << "Property:" <<
                        reply.toString();
            value = -1;
        }
        else
        {
            qDebug().nospace() << "Got a valid reply for the property of " << reply.toString().toStdString().c_str() << ".";
            value = reply.toInt();
        }
    }
    else
    {
        QVariant reply = propertyInterface->setProperty(property.toStdString().c_str(), value);
        if (reply.toBool())
        {
            qDebug() << "Successfully wrote the property.";
        }
        else
        {
            qDebug() << "Failed to write the property.";
            value = -1;
        }
    }

    // Clean up.
    delete propertyInterface;
    delete manager;

    // Either provide the read value or some feedback to the calling application.
    return value;
}
QList<QVariantMap> TrackListInterfaceTest::testGetTracksMetadata(const QList<QDBusObjectPath>& trackIds)
{
    QDBusReply<QList<QVariantMap> > reply = iface->call("GetTracksMetadata");
    if (!reply.isValid()) {
        emit interfaceError(Method, "GetTracksMetadata", "Call to GetTracksMetadata failed with error " + reply.error().message());
    } else {
        QList<QVariantMap> metadataList = reply.value();
        QMap<QDBusObjectPath,QVariantMap> metadataMap;
        int i = 0;
        Q_FOREACH (const QVariantMap& metadata, metadataList) {
            if (metadata.isEmpty()) {
                emit interfaceWarning(Method, "GetTracksMetadata",
                        "Got an empty entry at position " + QString::number(i));
            } else if (!metadata.contains("mpris:trackid")) {
                emit interfaceError(Method, "GetTracksMetadata",
                        "No mpris:trackid entry at position " + QString::number(i));
            } else if (metadata.value("mpris:trackid").userType() != qMetaTypeId<QDBusObjectPath>()) {
                emit interfaceError(Method, "GetTracksMetadata",
                        "mpris:trackid entry was not sent as a D-Bus object path (D-Bus type 'o') at position " + QString::number(i));
            } else {
                QDBusObjectPath trackid = metadata.value("mpris:trackid").value<QDBusObjectPath>();
                if (trackid.path().isEmpty()) {
                    emit interfaceError(Method, "GetTracksMetadata",
                            "mpris:trackid entry is an empty path at position " + QString::number(i));
                } else if (!trackIds.contains(trackid)) {
                    emit interfaceWarning(Method, "GetTracksMetadata",
                            "Entry " + trackid.path() + " was not requested at position " + QString::number(i));
                } else {
                    metadataMap.put(trackid, metadata);
                }
            }
            ++i;
        }
    }
}
Example #25
0
// Convienence function to send notifications.  This function does some processing
// of the arguments.  In these functions:
//    expire_timeout: The amount of time in milliseconds the message is shown.
//                    A value of -1 means timeout is based on server's settings.
//    overwrite     : Will overwrite the previous message sent from this function.
//                    It will not overwrite notifications sent by other programs. 
//
//
// Show notification with summary, app_name, and body text
void NotifyClient::sendNotification ()
{
  // make sure we have a connection we can send the notification to.
  if (! b_validconnection) return;  
  
  // variables
  QString app_name = s_app_name;  
  quint32 replaces_id = 0;
  QString app_icon = "";
  QString body = ""; 
  QString summary = s_summary;
  QStringList actions = QStringList();
  QVariantMap hints;
  int expire_timeout = i_expire_timeout;
  
  // set replaces_id
  if (b_overwrite) replaces_id = current_id;
  
  // assemble the hints
  hints.clear();
  hints.insert("urgency", QVariant::fromValue(static_cast<uchar>(i_urgency)) );
  //if (! app_icon.isEmpty() ) hints.insert("image-path", QVariant::fromValue(app_icon));
  
  // make sure we can display the text on this server
  if (sl_capabilities.contains("body", Qt::CaseInsensitive) ) {
    body = s_body;
    if (! sl_capabilities.contains ("body-markup", Qt::CaseInsensitive) ) {
      QTextDocument td;
      td.setHtml(body);
      body = td.toPlainText();
    } // if server cannot display markup
  } // if capabilities contains body
  
  // process the icon, if we are using a fallback icon create a temporary file to hold it
    QTemporaryFile*  tempfileicon = NULL; 
    if (! s_icon.isEmpty() ) {   
			if (QFile::exists(s_icon) ) {
				tempfileicon = new QTemporaryFile(this);
				tempfileicon->setAutoRemove(false);
				if (tempfileicon->open() ) {
					QPixmap px = QPixmap(s_icon);
					px.save(tempfileicon->fileName(),"PNG");
					app_icon =  tempfileicon->fileName().prepend("file://");
				} // if tempfileicon could be opened
			} // if s_icon exists as a disk file

			// assume s_icon exists as a theme icon, don't check it here.  That
			// check needs to be done in the calling program.
			else app_icon = s_icon;
		} // if s_icon is not empty
    
  QDBusReply<quint32> reply = notifyclient->call(QLatin1String("Notify"), app_name, replaces_id, app_icon, summary, body, actions, hints, expire_timeout);
  
  if (reply.isValid() ) {
		current_id = reply.value();
    if (file_map.contains(current_id) && tempfileicon != NULL) {
			if (b_overwrite) {
				file_map.value(current_id)->remove();
				delete file_map.value(current_id);
				file_map.remove(current_id);				
			}	// if
			else {
				tempfileicon->remove();
				delete tempfileicon;
				tempfileicon = NULL;
			}	// else
		}	// if contains current_id and not NULL
		if (tempfileicon != NULL) file_map[current_id] = tempfileicon;
  }	// if reply is valid
  
  else
	#if QT_VERSION >= 0x050400 
		qCritical("CMST - Error reply received to the Notify method: %s", qUtf8Printable(reply.error().message()) );
  #else
    qCritical("CMST - Error reply received to the Notify method: %s", qPrintable(reply.error().message()) );
  #endif
  
  return;
} 
Example #26
0
//
// Function to get the capabilities of the server and write to a qstringlist data member
void NotifyClient::getCapabilities()
{
  // return if we don't have valid connection
  if (! b_validconnection) return;  
  
  // get the server capabilities
  QDBusReply<QStringList> reply = notifyclient->call(QLatin1String("GetCapabilities") );

  if (reply.isValid()) 
    sl_capabilities = reply.value();
  else
  #if QT_VERSION >= 0x050400 
		qCritical("CMST - Error reply received to GetCapabilities method: %s", qUtf8Printable(reply.error().message()) );
  #else
    qCritical("CMST - Error reply received to GetCapabilities method: %s", qPrintable(reply.error().message()) );
  #endif
  
  return;
}
Example #27
0
int main(int argc, char **argv)
{
  KAboutData about("syanot", 0, ki18n("Syanot"), version, ki18n(description),
                    KAboutData::License_GPL, ki18n("(C) 2007 Gael de Chalendar"), KLocalizedString(), 0, "*****@*****.**");
  about.addAuthor( ki18n("Gael de Chalendar"), KLocalizedString(), "*****@*****.**" );
  KCmdLineArgs::init(argc, argv, &about);

  KCmdLineOptions options;
  options.add("+[URL]", ki18n( "Dot graph to open" ));
  options.add("comparewith file", ki18n("URL of a file containing an analysis to compare the main analysis with"));
  options.add("utterances list", ki18n("List of utterances ids to display"));
  KCmdLineArgs::addCmdLineOptions( options );
  KApplication app;
  
// see if we are starting with session management
  if (app.isSessionRestored())
  {
      RESTORE(Syanot);
  }
  else
  {
      // no session.. just start up normally
      KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

      Syanot *widget = 0;
      if ( args->count() == 0 )
      {
        widget = new Syanot();
        new SyanotAdaptor(widget);
        QDBusConnection::sessionBus().registerObject("/Syanot", widget);
        widget->show();
      }
      else
      {
        QDBusReply<bool> reply = QDBusConnection::sessionBus().interface()->isServiceRegistered( "org.kde.syanot" );
      
        bool instanceExists = reply.value();
  
        for (int i = 0; i < args->count(); i++ )
        {
          if (instanceExists 
              && (KMessageBox::questionYesNo(0, 
                                         i18n("There is already a Syanot window opened. What's your choice ?"),
                                         i18n("Opening in new window confirmation"),
                                             KGuiItem("Open in the existing one"),
                                             KGuiItem("Open in new window"),
                                             "openInNewWindowMode"   ) == KMessageBox::Yes) )
          {
            QByteArray tosenddata;
            QDataStream arg(&tosenddata, QIODevice::WriteOnly);
            QString strarg = args->arg(i);
            KUrl url;
            if (strarg.left(1) == "/")
              url = KUrl(strarg);
            else url = KUrl(QDir::currentPath() + '/' + strarg);
            arg << url;
            QDBusInterface iface("org.kde.syanot", "/Syanot", "", QDBusConnection::sessionBus());
            if (iface.isValid()) 
            {
              if (args->isSet("utterances"))
              {
                QDBusReply<void> reply = iface.call("slotSetUtterances", args->getOption("utterances"));
                if (reply.isValid())
                {
                  kDebug() << "Reply was valid" << endl;
                }
                else
                {
                  kError() << "Call failed: " << reply.error().message() << endl;
                  return 1;
                }
              }
              QDBusReply<void> reply = iface.call("openUrl", url.pathOrUrl());
              if (reply.isValid()) 
              {
                kDebug() << "Reply was valid" << endl;
              }
              else
              {
                kError() << "Call failed: " << reply.error().message() << endl;
                return 1;
              }
              if (args->isSet("comparewith"))
              {
                QString strarg = args->getOption("comparewith");
                KUrl url;
                if (strarg.left(1) == "/")
                  url = KUrl(strarg);
                else url = KUrl(QDir::currentPath() + '/' + strarg);
                reply = iface.call("openSecondaryUrl", url.pathOrUrl());
                if (reply.isValid())
                {
                  kDebug() << "Reply was valid" << endl;
                }
                else
                {
                  kError() << "Call failed: " << reply.error().message() << endl;
                  return 1;
                }
                return 0;
              }
            }
            kError() << "Invalid interface" << endl;
            exit(0);
          }
          else
          {
            widget = new Syanot;
            new SyanotAdaptor(widget);
            QDBusConnection::sessionBus().registerObject("/Syanot", widget);
            widget->show();
            if (args->isSet("utterances"))
            {
              widget->slotSetUtterances(args->getOption("utterances"));
            }
            widget->openUrl( args->url( i ) );
            if (args->isSet("comparewith"))
            {
                QString strarg = args->getOption("comparewith");
              kDebug() << "comparewith" << args->getOption("comparewith");
                KUrl url;
                if (strarg.left(1) == "/")
                  url = KUrl(strarg);
                else url = KUrl(QDir::currentPath() + '/' + strarg);
              kDebug() << "openSecondaryUrl" << url.pathOrUrl();
              widget->openSecondaryUrl(url.pathOrUrl());
            }
          }
        }
      }
      args->clear();
  }
  return app.exec();
}
QString BTConnection::connectDevice( const QString& aBTAddress, const QString& aServiceUUID )
{
    FUNCTION_CALL_TRACE;

    QDBusInterface managerInterface( BLUEZ_DEST, "/", BLUEZ_MANAGER_INTERFACE, QDBusConnection::systemBus() );

    if( !managerInterface.isValid() ) {
        LOG_CRITICAL( "Could not find BlueZ manager interface" );
        return "";
    }

    QDBusReply<QDBusObjectPath> pathReply = managerInterface.call( QLatin1String( GET_DEFAULT_ADAPTER ) );
    if( !pathReply.isValid() ) {
        LOG_CRITICAL( "Could not find default adapter path:" << pathReply.error() );
        return "";
    }

    QString defaultAdapterPath = pathReply.value().path();

    LOG_DEBUG("Using adapter path: " << defaultAdapterPath );

    QDBusInterface adapterInterface( BLUEZ_DEST, defaultAdapterPath, BLUEZ_ADAPTER_INTERFACE, QDBusConnection::systemBus() );

    if( !adapterInterface.isValid() ) {
        LOG_CRITICAL( "Could not find adapter interface: " << adapterInterface.lastError() );
        return "";
    }

    QDBusReply<void> voidReply = adapterInterface.call( QLatin1String( REQUEST_SESSION ) );

    if( !voidReply.isValid() ) {
        LOG_CRITICAL( "Session request failed" );
        LOG_CRITICAL( "Reason:" <<  voidReply.error() );
    }

    LOG_DEBUG( "BT session created" );

    pathReply = adapterInterface.call( QLatin1String( FIND_DEVICE ), aBTAddress );

    if( !pathReply.isValid() ) {
        LOG_WARNING( "Couldn't find device " << aBTAddress << "Reason:" <<  pathReply.error() );
        LOG_DEBUG( "Create Device :" << aBTAddress );
        pathReply = adapterInterface.call( QLatin1String( CREATE_DEVICE ), aBTAddress );
            if (pathReply.isValid()){
        LOG_DEBUG( "Create Paired Device :" << aBTAddress << "Path :" << pathReply.value().path() );
            QDBusReply<QDBusObjectPath> reply =
                adapterInterface.call(QLatin1String( CREATE_PAIRED_DEVICE ),
                        aBTAddress, qVariantFromValue(pathReply.value()), QString());
        if( !reply.isValid() ) {
            LOG_CRITICAL( "Pairing failed Reason:" << reply.error());
        }
        }
    }

    if( !pathReply.isValid() ) {
        LOG_CRITICAL( "Couldn't find device " << aBTAddress );
        LOG_CRITICAL( "Reason:" <<  pathReply.error() );
        adapterInterface.call( QLatin1String( RELEASE_SESSION ) );
        LOG_CRITICAL( "BT session closed" );
        return "";
    }

    QString devicePath = pathReply.value().path();

    LOG_DEBUG( "Using path" << devicePath << "for device " << aBTAddress );

    QDBusInterface serialInterface( BLUEZ_DEST, devicePath, BLUEZ_SERIAL_INTERFACE, QDBusConnection::systemBus() );

    if( !serialInterface.isValid() ) {
        LOG_CRITICAL( "Could not find serial interface: " << serialInterface.lastError() );
        adapterInterface.call( QLatin1String( RELEASE_SESSION ) );
        LOG_CRITICAL( "BT session closed" );
        return "";
    }

    QDBusReply<QString> stringReply = serialInterface.call( QLatin1String( CONNECT ), aServiceUUID );

    if( !stringReply.isValid() ) {
        LOG_CRITICAL( "Could not connect to device " << devicePath << " with service uuid " << aServiceUUID );
        LOG_CRITICAL( "Reason:" <<  stringReply.error() );
        adapterInterface.call( QLatin1String( RELEASE_SESSION ) );
        LOG_CRITICAL( "BT session closed" );
        return "";
    }

    LOG_DEBUG("Device connected:" << aBTAddress );

    return stringReply.value();
}
void BTConnection::disconnectDevice( const QString& aBTAddress, const QString& aDevice )
{
    FUNCTION_CALL_TRACE;

    QDBusInterface managerInterface( BLUEZ_DEST, "/", BLUEZ_MANAGER_INTERFACE, QDBusConnection::systemBus() );

    if( !managerInterface.isValid() ) {
        LOG_CRITICAL( "Could not find BlueZ manager interface" );
        return;
    }

    QDBusReply<QDBusObjectPath> pathReply = managerInterface.call( QLatin1String( GET_DEFAULT_ADAPTER ) );

    if( !pathReply.isValid() ) {
        LOG_CRITICAL( "Could not find default adapter path" );
        LOG_CRITICAL( "Reason:" <<  pathReply.error() );
        return;
    }

    QString defaultAdapterPath = pathReply.value().path();

    LOG_DEBUG("Using adapter path: " << defaultAdapterPath );

    QDBusInterface adapterInterface( BLUEZ_DEST, defaultAdapterPath, BLUEZ_ADAPTER_INTERFACE, QDBusConnection::systemBus() );

    if( !adapterInterface.isValid() ) {
        LOG_CRITICAL( "Could not find adapter interface: " << adapterInterface.lastError() );
        return;
    }

    pathReply = adapterInterface.call( QLatin1String( FIND_DEVICE ), aBTAddress );

    if( !pathReply.isValid() ) {
        LOG_CRITICAL( "Couldn't find device " << aBTAddress );
        LOG_CRITICAL( "Reason:" <<  pathReply.error() );
        return;
    }

    QString devicePath = pathReply.value().path();

    LOG_DEBUG( "Using path" << devicePath << "for device " << aBTAddress );

    QDBusInterface serialInterface( BLUEZ_DEST, devicePath, BLUEZ_SERIAL_INTERFACE, QDBusConnection::systemBus() );

    if( !serialInterface.isValid() ) {
        LOG_CRITICAL( "Could not find serial interface: " << serialInterface.lastError() );
        return;
    }

    QDBusReply<void> voidReply = serialInterface.call( QLatin1String( DISCONNECT ), aDevice );

    if( !voidReply.isValid() ) {
        LOG_CRITICAL( "Device disconnection failed" );
        LOG_CRITICAL( "Reason:" <<  voidReply.error() );
        return;
    }

    LOG_DEBUG( "Device disconnected:" << aBTAddress );

    voidReply = adapterInterface.call( RELEASE_SESSION );

    if( !voidReply.isValid() ) {
        LOG_CRITICAL( "Session release failed" );
        LOG_CRITICAL( "Reason:" <<  voidReply.error() );
        return;
    }

    LOG_DEBUG( "BT session closed" );

    iDevice.clear();
}
bool ThermaldInterface::initialize()
{
    /* Create the D-Bus interface
     * Get the temperature sensor count and information from each sensor
     * Get the cooling device count and information from each device
     */
    if (!QDBusConnection::systemBus().isConnected()) {
        qCritical()  << "Cannot connect to the D-Bus session bus";
        return false;
    }

    iface = new QDBusInterface(SERVICE_NAME, "/org/freedesktop/thermald",
                               "org.freedesktop.thermald", QDBusConnection::systemBus());
    if (!iface->isValid()) {
        qCritical()  << "Cannot connect to interface" << SERVICE_NAME;
        return false;
    }

    // get temperature sensor count
    uint sensor_count;
    QDBusReply<uint> count  = iface->call("GetSensorCount");
    if (count.isValid()) {
        if (count <= MAX_TEMP_INPUT_COUNT){
            sensor_count = count;
        } else {
            qCritical() << "error: input sensor count of" << count
                        << "is larger than system maximum (" << MAX_TEMP_INPUT_COUNT
                        << ")";
            return false;
        }
    } else {
        qCritical() << "error from" << iface->interface() << "=" << count.error();
        return false;
    }

    // Read in all the the temperature sensor data from the thermal daemon
    for (uint i = 0; i < sensor_count; i++){
        sensorInformationType new_sensor;

        if (getSensorInformation(i, new_sensor) >= 0){
            sensors.append(new_sensor);
        }
    }
    if (sensor_count != (uint)sensors.count()){
        qCritical() << "error: ThermaldInterface::getSensorCount() sensor_count != sensors.count()),"
                    << sensor_count << "vs" << sensors.count();
    }

    // get cooling device count
    uint cooling_device_count;
    QDBusReply<uint> cdev_count  = iface->call("GetCdevCount");
    if (cdev_count.isValid()) {
        cooling_device_count = cdev_count;
    } else {
        qCritical() << "error from" << iface->interface() << "=" << cdev_count.error();
        return false;
    }

    // Read in all the the cooling device data from the thermal daemon
    for (uint i = 0; i < cooling_device_count; i++){
        coolingDeviceInformationType new_device;

        if (getCoolingDeviceInformation(i, new_device) >= 0){
            cooling_devices.append(new_device);
        }
    }
    if (cooling_device_count != (uint)cooling_devices.count()){
        qCritical() << "error: ThermaldInterface::getCoolingDeviceCount()"
                    << " cooling_device_count != cooling_devices.count(),"
                    << cooling_device_count << "vs" << cooling_devices.count();
    }

    // get zone count
    uint zone_count;
    QDBusReply<uint> z_count  = iface->call("GetZoneCount");
    if (z_count.isValid()) {
        zone_count = z_count;
    } else {
        qCritical() << "error from" << iface->interface() << "=" << cdev_count.error();
        return false;
    }

    // Read in all the the zone data from the thermal daemon
    for (uint i = 0; i < zone_count; i++){
        zoneInformationType new_zone;

        if (getZoneInformation(i, new_zone) >= 0){
            zones.append(new_zone);
        }
    }
    if (zone_count != (uint)zones.count()){
        qCritical() << "error: ThermaldInterface::getCoolingDeviceCount()"
                    << " zone_count != zones.count(),"
                    << zone_count << "vs" << zones.count();
    }

    // Read in all the the trip data from the thermal daemon
    for (uint i = 0; i < zone_count; i++){
        uint lowest_valid_index = (uint)zones[i].trip_count;
        for (uint j = 0; j < (uint)zones[i].trip_count; j++){
            tripInformationType new_trip;

            if (getTripInformation(i, j, new_trip) >= 0){
                zones[i].trips.append(new_trip);
                // Figure out the lowest valid trip index
                if (new_trip.trip_type == CRITICAL_TRIP ||
                        new_trip.trip_type == PASSIVE_TRIP){
                    if (j < lowest_valid_index){
                        lowest_valid_index = j;
                    }
                }
            }
        }
        // Store the actual number of trips, as opposed to the theoritical maximum
        zones[i].trip_count = zones[i].trips.count();

        // Store the first valid trip temp for the zone
        if (lowest_valid_index < (uint)zones[i].trip_count){
            zones[i].lowest_valid_index = lowest_valid_index;
            //trip_temps.append(zones[i].trips[lowest_valid_index].temp);
        } else {
            qCritical() << "error: ThermaldInterface::initialize()"
                        << " could not find valid trip for zone"
                        << i;
        }
        /* Yo!  zones[i].trip_count is the theoretical count
         * but  zones[i].trips.count() is the actual valid count
         *
         * So when you want the trip count for any given zone,
         * use zones[i].trips.count()
         */
    }
    return true;
}