Tuesday, March 12, 2013

extending plasma desktop scripting

The Plasma Desktop Scripting system allows one to add, remove or alter essentially any aspect of a running Plasma Desktop or Netbook shell at runtime using nothing more than javascript. This scripting system is used to define the initial setup you get when you log in for the first time, to provide configure updates and to provide user-friendly ways of adding new kinds of panels and desktop layouts. You can even write scripts interactively by typing "desktop console" into krunner.

Today I was asked on irc if one could extend the Javascript API at runtime so that instead of people writing scripts having to know how your applet works internally they could just call things like "awesomeWidget.setTheme('foo')" and have that do the correct thing.

At first I said "no" because the API is defined and managed by the shell and that's all C++ and there is no plugin mechanism .. but then about five seconds later I remembered that I had indeed added a plugin system. In fact, that is how the "New panel" menu works in Plasma Desktop. I even had an example on disk: org.kde.plasma-desktop.findWidgets. This is a small  desktop scripting template package with ~13 lines of Javascript that adds a findWidgets call to the API.

Here is how you use it in practice:

var finder = loadTemplate('org.kde.plasma-desktop.findWidgets');
finder.findWidgets("pager", function(widget, containment) {
    print("Found a pager with id " + widget.id + " in a " + containment.type + " containment with id " + containment.id);
})
Which gets me output like this on my laptop:
Found a pager with id 4 in a panel containment with id 1
The "big trick" is that the findWidgets package does not have an X-Plasma-ContainmentCategories entry in the metadata.desktop file which prevents it from showing up anywhere in the user interface. As a result, it is only accessible via the loadTemplate call when installed into share/apps/plasma/layout-templates/.

You can distribute layout template packages with your Plasmoids or other Plasma add-ons to allow easy (and future-proof) interaction with your add-ons from user written scripts.

 Such fun.

2 comments:

Ricardo Barberis said...

This is great, I remember reading about customising the initial desktop with JS and then completely forgot aout it.

I manage an LTSP installation and several desktops at work, and automatically providing some defaults (instead of configuring by hand) for new users would be great, I'll have to remember to take a look this time.

But I have a question: is desktop scripting only possible in JS or are there alternatives (eg: python, ruby)?

Cheers!

Aaron Seigo said...

Just javascript. It's an automation feature, so having multiple languages isn't much use there.