Fun with QScript and DBus

· by Simon Hausmann · 1 min read · original post ↗

·

Since it’s a natural thing to combine the two I wrote some code that binds QDBus to QScript. It binds most of the QDBus API, allowing you to place calls, connect signals and slots and read/write properties of remote dbus objects. It was an overall easy thing to do because of QDBus provides a QObject that wraps the methods, signals & slots and properties of a remote object. And QScript on the other hand can map QObjects very nicely to script code. So all I had to do was map a few value types and auxiliary QDBus classes. The resulting code is inthe Qt 4.3 snapshots in the examples/script/qscript directory, as part of the little interpreter example.

So how does it look? Well, here’s some example code to remotely control Qt
Assistant a little bit:


// get a reference to assistant  

assistant = QDBusInterface("com.trolltech.assistant", "/Assistant");

if (!assistant.isValid) {  

    print("Assistant does not seem to be running")  

    return  

}



// play around with the currently viewed document  

tab = assistant.currentTab();



print("Currently viewing:" + tab.source)  

tab.backward();  

print("Previously viewing:" + tab.source)



// create a new tab and load a document  

newTab = assistant.createNewTab()  

newTab.source = "/path/to/the/qt/docs/qwidget.html"

As you can see remote methods and properties are dynamically created. But you can of course also place manual calls through QDBusMessage, just like in C++.

In the process of exploring the dbus services on my system I discovered an interesting object in Hal, called ‘computer’. Let’s see what it can do:


computer = QDBusInterface("org.freedesktop.Hal", "/org/freedesktop/Hal/devices/computer",  

                          "org.freedesktop.Hal.Device.SystemPowerManagement",  

                          QDBusConnection.systemBus)

computer.Reboot()

Right, this simple script will actually reboot your machine. Use at your own risk ;-)

More from Simon Hausmann