NOV
15
2007

Loading KParts in KDE4 Korundum

Last night I was discussing how to load KParts in Korundum with CapitalT on the #kde-ruby IRC channel. It took me a bit of googling to work out what to do, and I eventually realised I'd left the KDE::PluginLoader class out of the Smoke library that the KDE4 version of Korundum uses.

Once I'd fixed that it was pretty straightforward, here is some example code to load a Kate part in a KDE::MainWindow:

require 'korundum4'

about = KDE::AboutData.new( "part_test", "Load KPart", 
                            KDE.ki18n("Test loading KParts"), "0.1")
KDE::CmdLineArgs.init(ARGV, about)
a = KDE::Application.new
window = KDE::MainWindow.new

# A KHTML part is the first KDE::Service in the offers list,
# and a Kate part is the second. So load the second one:
offers = KDE::MimeTypeTrader.self.query("text/xml", "KParts/ReadOnlyPart")
factory = KDE::PluginLoader.new(offers[1].library).factory
part = factory.create("KParts::ReadWritePart", window, nil, [], "")
part.widget.resize(300, 300)

window.show
a.exec

It is now possible to invoke slots directly without needing to connect to them. So you can find out what slots the part has like this:

part.metaObject.slotNames.sort.each do |slot|
    puts slot
end

Which prints a list like this:

KTextEditor::Search::SearchOptions supportedSearchOptions()
QVector searchText(KTextEditor::Range,QString,KTextEditor::Search::SearchOptions)
bool clear()
bool documentReload()
bool documentSave()
bool documentSaveAs()
bool insertLine(int,QString)
bool insertLines(int,QStringList)
bool insertText(KTextEditor::Cursor,QString)
bool insertText(KTextEditor::Cursor,QString,bool)
bool insertText(KTextEditor::Cursor,QStringList)
bool insertText(KTextEditor::Cursor,QStringList,bool)
bool print()
...

To insert some lines we can just make a call to the insertLines slot on the part like this:

part.insertLines(0, ["here is a line", "and yet another line"])

I've recently been converting some of the various code examples to KDE4, and everything seems to work well. All the tutorials p1 to p9 are working, and they show how you can easily create a web browser with a KHTMLPart, that communicates both ways with a little bookmark server over DBUS. Once I've worked out how to edit the Tech Base wiki I'll try and translate the full text of the tutorials and put them up there.

The main thing missing is that KDE::ConfigGroup.readEntry() and writeEntry() methods use templated code and they need to be special cased in the korundum runtime.

I've found some problems with the layout of widgets in the UI Sampler example, and I think they are more to do with the Oxygen style than the Ruby code itself.