Difference between revisions of "KDE System Administration/PlasmaDesktopScripting"

Jump to: navigation, search
(Activities and Panels)
(add link to removeSystrayApplet.js, this is not simple)
(52 intermediate revisions by 10 users not shown)
Line 1: Line 1:
== ECMA Script Interaction With The Plasma Desktop Shell (plasma-desktop) ==
+
== ECMA Script Interaction With Plasma Shells ==
  
It is possible to control and interact with a plasma-desktop session using ECMA Script (aka JavaScript). This scripting mechanism exposes containments (Desktop Activities and Panels), widgets and various other aspects of plasma-desktop configuration using the widely known and used ECMA Script language. The QtScript engine is used for the runtime environment.
+
It is possible to control and interact with a Plasma user interface shell such as a plasma-desktop or (starting in KDE SC 4.5) plasma-netbook session using ECMA Script (aka JavaScript). This scripting mechanism exposes containments (Desktop Activities and Panels), widgets and various other aspects of plasma-desktop configuration using the widely known and used ECMA Script language. The QtScript engine is used for the runtime environment.
  
 
This document describes the API that is provided along with how to
 
This document describes the API that is provided along with how to
 
run such scripts in plasma-desktop.
 
run such scripts in plasma-desktop.
 +
 +
== Examples ==
 +
 +
A set of examples can be found [https://projects.kde.org/projects/kde/kdeexamples/repository/revisions/master/show/plasma/javascript/plasma-shell-scripting here] that demonstrate the use of various aspects of Plasma shell scripting.
 +
 +
Contributions of additional examples are welcome and an be sent to the Plasma development mailing list (plasma-devel at kde.org) for inclusion if you do not have commit rights to the kdeexamples module.
  
 
== Running Scripts ==
 
== Running Scripts ==
Line 14: Line 20:
  
 
* '''on update''': when plasma-desktop is started, it will check in
 
* '''on update''': when plasma-desktop is started, it will check in
  `kde4-config --path data`/plasma-desktop/updates/  
+
<syntaxhighlight lang="bash">
 +
`kde4-config --path data`/plasma-desktop/updates/
 +
</syntaxhighlight>
 
with a ".js" suffix for scripts that have not yet been run. If there is more than one script which has not been run yet they will be executed serially in the alphabetical order of the file names.
 
with a ".js" suffix for scripts that have not yet been run. If there is more than one script which has not been run yet they will be executed serially in the alphabetical order of the file names.
  
Line 21: Line 29:
 
{{note|For security reasons, scripts located in the user's home directory will '''not''' be run during this phase.}}
 
{{note|For security reasons, scripts located in the user's home directory will '''not''' be run during this phase.}}
  
* '''interactively''': an interactive scripting dialog can be requested either via the KRunner window (Alt+F2, by default, or via the "Run Command" entry in various desktop menus) by entering "desktop console" as the search term. It can also be triggered directly via dbus with <code bash>qdbus org.kde.plasma-desktop /MainApplication showInteractiveConsole</code>
+
* '''interactively''': an interactive scripting dialog can be requested either via the KRunner window (Alt+F2, by default, or via the "Run Command" entry in various desktop menus) by entering "desktop console" as the search term. It can also be triggered directly via dbus with <syntaxhighlight lang="bash">qdbus org.kde.plasma-desktop /MainApplication showInteractiveConsole</syntaxhighlight>
 +
 
 +
{{note|This method is not available for plasma-netbook.}}
  
 
:ECMA Script may be entered directly into this window for execution and output appears in the lower half of the window. Ctrl+E is a shortcut to run scripts, and scripts can be saved to and loaded from disk.
 
:ECMA Script may be entered directly into this window for execution and output appears in the lower half of the window. Ctrl+E is a shortcut to run scripts, and scripts can be saved to and loaded from disk.
  
 
:Scripts from files can also be loaded using KRunner with "desktop console /path/to/file" or via dbus with
 
:Scripts from files can also be loaded using KRunner with "desktop console /path/to/file" or via dbus with
<code bash>qdbus org.kde.plasma-desktop /MainApplication loadScriptInInteractiveConsole /path/to/file</code>
+
<syntaxhighlight lang="bash">qdbus org.kde.plasma-desktop /MainApplication loadScriptInInteractiveConsole /path/to/file</syntaxhighlight>
  
 
== Templates ==
 
== Templates ==
  
Templates are a type of Plasma package that contains a script using the Plasma Desktop Scripting API. Templates can be loaded from other scripts by name and may appear elsewhere in the Plasma UI. This allows common elements to be kept as separate scripts which can be referenced from multiple other places as a way to increase consistency and lower maintenance costs.
+
Templates are named packages that contain scripts. This provides a way for common functionality to be easily reused, helping to increase consistency and lower maintenance costs. Templates can be loaded from other scripts by name and they are also used to populate some parts of the user interface, such as the entries in the Add Panels menu.
 
+
The use case that triggered the inclusion of this feature was the desire to make it easy for users to re-create the default panel (whatever that might be). There is a Template called org.kde.plasma-desktop.defaultPanel that ships with the KDE Plasma Workspace which contains the layout for the initial default panel. This is referenced by the Plasma Desktop init script and, because it is marked as a Panel Template in the metadata.desktop file it also shows up to the user in the Add Panels menu. When selected by the user from the menu, the exact same panel that is created on desktop start up is created for them, complete with Plasma Widgets and configuration.
+
  
A Template is a small set of files in a specified file hierarchy (or, in Plasma terms, a "Package"). In particular, a Template package contains the following files:
+
A template is a small set of files in a specified file hierarchy (or, in Plasma terms, a "Package"). In particular, a Template package contains the following files:
  
 
* metadata.desktop: a .desktop file describing the template
 
* metadata.desktop: a .desktop file describing the template
 
* contents/layout.js: a Javascript file containing the actual script
 
* contents/layout.js: a Javascript file containing the actual script
  
Templates are stored under share/apps/plasma/layout-templates and may be installed using `plasmapkg -t layout_template path/to/package`. Template packages may also be provided as a .zip file with a .plasmalayout suffix.
+
Templates are stored under share/apps/plasma/layout-templates and may be installed using `plasmapkg -t layout-template -i /path/to/package`. Template packages may also be provided as a .zip file with a .plasmalayout suffix.
  
 
The metadata.desktop file contains the usual .desktop entries such as Name and Icon but must also contain Type=Service and ServiceTypes=Plasma/LayoutTemplate entries. If the layout is specific to a given Plasma application, such as plasma-desktop, this can be specific using X-Plasma-Shell. X-Plasma-ContainmentCategories defines what kind of layout it is with possible values being panel and desktop. Finally a X-KDE-PluginInfo-Name entry is required to provide a globally unique internal name for the Template. Here is an example of a Template that provides a Panel layout for Plasma Netbook:
 
The metadata.desktop file contains the usual .desktop entries such as Name and Icon but must also contain Type=Service and ServiceTypes=Plasma/LayoutTemplate entries. If the layout is specific to a given Plasma application, such as plasma-desktop, this can be specific using X-Plasma-Shell. X-Plasma-ContainmentCategories defines what kind of layout it is with possible values being panel and desktop. Finally a X-KDE-PluginInfo-Name entry is required to provide a globally unique internal name for the Template. Here is an example of a Template that provides a Panel layout for Plasma Netbook:
  
<code ini>
+
<syntaxhighlight lang="ini">
 
[Desktop Entry]
 
[Desktop Entry]
 
Encoding=UTF-8
 
Encoding=UTF-8
Line 60: Line 68:
 
X-KDE-PluginInfo-License=GPL
 
X-KDE-PluginInfo-License=GPL
 
X-KDE-PluginInfo-EnabledByDefault=true
 
X-KDE-PluginInfo-EnabledByDefault=true
</code>
+
</syntaxhighlight>
 +
 
 +
When running a template, two global variables will be accessible in read-only mode: templateName and templateComment. They will contain the Name and Comment fields of the above desktop file, and are translated if a localization is available.
 +
 
 +
=== Examples of Usage ===
 +
 
 +
==== Creating panels ====
 +
A good example of the use of templates is the use case that triggered the creation of this feature: the desire to make it easy for users to re-create the default panel that is created on first start. There is a Template called org.kde.plasma-desktop.defaultPanel that ships with the KDE Plasma Workspace which contains the layout for the initial default panel. This is referenced by the default Plasma Desktop init script and, because it is marked as a Panel Template in the metadata.desktop file it also shows up to the user in the Add Panels menu. When selected by the user from the menu, the exact same panel that is created on desktop start up is created for them, complete with Plasma Widgets and configuration.
 +
 
 +
==== Automating tasks ====
 +
Another example of the usefulness of templates is the "Find Widgets" template. This template, which first shipped with Plasma Desktop v4.5, provides a function for finding widgets by name. It appears in the toolbar "Load" and "Use" menus in the Desktop Console in plasma-desktop, and makes finding widgets as simple as:
 +
 
 +
<syntaxhighlight lang="javascript">
 +
var template = loadTemplate('org.kde.plasma-desktop.findWidgets')
 +
template.findWidgets('systemtray')
 +
</syntaxhighlight>
 +
 
 +
 
 +
Since just finding the widget is not enough, you can connect a callback to do additional operations, such as removing the widget :
 +
 
 +
<syntaxhighlight lang="javascript">
 +
removeWidget = function(widget, containment)
 +
{
 +
  widget.remove()
 +
}
 +
 
 +
var template = loadTemplate('org.kde.plasma-desktop.findWidgets')
 +
template.findWidgets('systemtray', removeWidget)
 +
</syntaxhighlight>
 +
 
 +
 
 +
==== Activity templates ====
 +
Probably the most user visible use of templates are "Activity templates". The structure of Activity templates is similar to the other use of templates, but a few extra features are provided in the metadata.desktop file. Here is an example of such an activity template:
 +
 
 +
<syntaxhighlight lang="ini">
 +
[Desktop Entry]
 +
Encoding=UTF-8
 +
Name=Cool Activity Template
 +
Icon=user-desktop
 +
Type=Service
 +
ServiceTypes=Plasma/LayoutTemplate
 +
X-Plasma-Shell=plasma-desktop
 +
X-Plasma-ContainmentCategories=desktop
 +
X-Plasma-ContainmentLayout-ExecuteOnCreation=dolphin $desktop, gwenview $pictures
 +
X-Plasma-ContainmentLayout-ShowAsExisting=true
 +
X-KDE-PluginInfo-Author=John Doe
 +
X-KDE-PluginInfo-Email=john@doe.org
 +
X-KDE-PluginInfo-Name=org.kde.plasma-desktop.CoolTemplate
 +
X-KDE-PluginInfo-Version=1.0
 +
X-KDE-PluginInfo-Website=http://john.doe.org
 +
X-KDE-PluginInfo-Category=
 +
X-KDE-PluginInfo-Depends=
 +
X-KDE-PluginInfo-License=GPL
 +
X-KDE-PluginInfo-EnabledByDefault=true
 +
</syntaxhighlight>
 +
 
 +
The layout itself is still created from the layout.js file as usual, but this template also shows as a precreated activity to the user thanks to the <tt>X-Plasma-ContainmentLayout-ShowAsExisting</tt> key. Additionally, it starts applications in the newly created activity using the <tt>X-Plasma-ContainmentLayout-ExecuteOnCreation</tt> key.
 +
 
 +
That key is a list of commands to execute, and it supports the following variables:
 +
* $desktop
 +
* $autostart
 +
* $documents
 +
* $music
 +
* $video
 +
* $downloads
 +
* $pictures
 +
 
 +
They all expand into the path toward the user corresponding default folder.
  
 
== API ==
 
== API ==
Line 75: Line 150:
  
 
* ''String'' '''applicationVersion''': the version of the application, e.g. 0.3
 
* ''String'' '''applicationVersion''': the version of the application, e.g. 0.3
 +
* ''String'' '''platformVersion''': the version of the KDE Platform, e.g. 0.3
 
* ''number'' '''scriptingVersion''': the version of the scripting API; e.g. in KDE SC 4.5 this is 2
 
* ''number'' '''scriptingVersion''': the version of the scripting API; e.g. in KDE SC 4.5 this is 2
  
Line 81: Line 157:
  
 
New Activities can be created using the Activity constructor, like this:
 
New Activities can be created using the Activity constructor, like this:
 
+
<syntaxhighlight lang="javascript">
    var activity = new Activity("folderview")
+
var activity = new Activity("folderview")
 +
</syntaxhighlight>
  
 
The string passed into the constructor maps to the X-KDE-PluginInfo-Name= entry
 
The string passed into the constructor maps to the X-KDE-PluginInfo-Name= entry
Line 89: Line 166:
 
Read-only properties:
 
Read-only properties:
 
* ''Array[number]'' '''activityIds''': returns a list of integer ids of all existing Plasma activities
 
* ''Array[number]'' '''activityIds''': returns a list of integer ids of all existing Plasma activities
 +
* ''Array[String]'' '''knownActivityTypes''':  (scripting version >= 2) a list of types of activities that can be created. This is useful to check if an Activity type is available on the system before trying to construct one.
  
 
Functions:
 
Functions:
 
* ''Activity'' '''activityById(number id)''': return an object representing the activity with the given id
 
* ''Activity'' '''activityById(number id)''': return an object representing the activity with the given id
 
* ''Activity'' '''activityForScreen(number screen[, number dekstop])''': returns an object representing the activity  currently associated with the given screen and, optionally, the given desktop.
 
* ''Activity'' '''activityForScreen(number screen[, number dekstop])''': returns an object representing the activity  currently associated with the given screen and, optionally, the given desktop.
 +
* ''Array[Activity]'' '''activities()''': returns an array of all activities that currently exist
  
 
=== Panels ===
 
=== Panels ===
Line 98: Line 177:
  
 
New Panels can be created using the Panel constructor, like this:
 
New Panels can be created using the Panel constructor, like this:
 
+
<syntaxhighlight lang="javascript">
    var panel = new Panel("dock")
+
var panel = new Panel("dock")
 
+
</syntaxhighlight>
 
The string passed into the constructor maps to the X-KDE-PluginInfo-Name= entry
 
The string passed into the constructor maps to the X-KDE-PluginInfo-Name= entry
 
in the plugin's .desktop file).
 
in the plugin's .desktop file).
Line 106: Line 185:
 
Read-only properties:
 
Read-only properties:
 
* ''Array[number]'' '''panelIds''': returns a list of integer ids of all existing Plasma panels
 
* ''Array[number]'' '''panelIds''': returns a list of integer ids of all existing Plasma panels
 +
* ''Array[String]'' '''knownPanelTypes''':  (scripting version >= 2) a list of types of panels that can be created. This is useful to check if a Panel type is available on the system before trying to construct one.
  
 
Functions:
 
Functions:
 
* ''Panel'' '''panelById(int id)''': returns an object representing the Panel that matches the given id
 
* ''Panel'' '''panelById(int id)''': returns an object representing the Panel that matches the given id
 
+
* ''Array[Panels]'' '''panels()''': returns an array of all panels that currently exist
  
 
=== Activities and Panels ===
 
=== Activities and Panels ===
Line 130: Line 210:
 
* ''String'' '''wallpaperPlugin''': (scriptingVersion >= 2) the wallpaper plugin to use with the Activity
 
* ''String'' '''wallpaperPlugin''': (scriptingVersion >= 2) the wallpaper plugin to use with the Activity
 
* ''String'' '''wallpaperMode''': (scriptingVersion >= 2) the wallpaper plugin mode to use with the Activity
 
* ''String'' '''wallpaperMode''': (scriptingVersion >= 2) the wallpaper plugin mode to use with the Activity
* ''Array[String]'' '''currentConfigGroup''': (scriptingVersion >= 2) the current configuration group path, with each entry in the array representing a sub-group. This allows one to access trees of groups with code such as: widget.currentConfigGroup = new Array('topGroup', 'subGroupOfTopGroup'). An empty Array means the default (top-level) configuration group for the widget  
+
* ''Array[String]'' '''currentConfigGroup''': (scriptingVersion >= 2) the current configuration group path, with each entry in the array representing a sub-group. This allows one to access trees of groups with code such as: widget.currentConfigGroup = new Array('topGroup', 'subGroupOfTopGroup'). An empty Array means the default (top-level) configuration group for the widget
 
* ''String'' '''version''': (scriptingVersion >= 2) the version of the Activity or Panel
 
* ''String'' '''version''': (scriptingVersion >= 2) the version of the Activity or Panel
  
Line 137: Line 217:
 
* '''remove()''': deletes this activity and all widgets inside of it
 
* '''remove()''': deletes this activity and all widgets inside of it
 
* ''Widget'' '''widgetById(number id)''': returns an object representing the widget with the given id
 
* ''Widget'' '''widgetById(number id)''': returns an object representing the widget with the given id
* ''Widget'' '''addWidget(String name)''': adds a new widget to the activity; the name maps to the X-KDE-PluginInfo-Name= entry
+
* ''Widget'' '''addWidget(String name)''': adds a new widget to the activity; the name maps to the <tt>X-KDE-PluginInfo-Name=</tt> entry in the widget's .desktop file
  in the widget's .desktop file
+
 
* ''Widget'' '''addWidget(Widget widget)''': adds an existing widget to this activity; useful for moving widgets between Activities and Panels
 
* ''Widget'' '''addWidget(Widget widget)''': adds an existing widget to this activity; useful for moving widgets between Activities and Panels
 
* '''showConfigurationInteface()''': shows the configuration user interface for this Activity or Panel on the screen
 
* '''showConfigurationInteface()''': shows the configuration user interface for this Activity or Panel on the screen
 
* '''readConfig(String key, any default)''': (scriptingVersion >= 2) reads the value of key in the config with default for the default value
 
* '''readConfig(String key, any default)''': (scriptingVersion >= 2) reads the value of key in the config with default for the default value
* '''writeConfig(String key, any value)''': (scriptingVersion >= 2) sets key to value in the config  
+
* '''writeConfig(String key, any value)''': (scriptingVersion >= 2) sets key to value in the config
* '''readGlobalConfig(String key, any default)''': (scriptingVersion >= 2) reads the value of key in the global config with default
+
* '''readGlobalConfig(String key, any default)''': (scriptingVersion >= 2) reads the value of key in the global config with default for the default value
  for the default value
+
 
* '''writeGlobalConfig(String key, any value)''': (scriptingVersion >= 2) sets key to value in the global config
 
* '''writeGlobalConfig(String key, any value)''': (scriptingVersion >= 2) sets key to value in the global config
 
* '''reloadConfig()''': (scriptingVersion >= 2) causes the Activity or Panel to reload its configuration; reaction to configuration changes made using readConfig are usually activated on script exit, but this can be triggered earlier on a per-widget basis using this method
 
* '''reloadConfig()''': (scriptingVersion >= 2) causes the Activity or Panel to reload its configuration; reaction to configuration changes made using readConfig are usually activated on script exit, but this can be triggered earlier on a per-widget basis using this method
Line 160: Line 238:
 
Widgets may be enumerated by calling the widgetIds property on a Activity or Panel object. With a widget id in hand, a Widget object can be retrieved by calling widgetById(id) on an Activity or Panel object. New Widgets can be created with add addWidget(String) function provided by Activity and Panel objects.
 
Widgets may be enumerated by calling the widgetIds property on a Activity or Panel object. With a widget id in hand, a Widget object can be retrieved by calling widgetById(id) on an Activity or Panel object. New Widgets can be created with add addWidget(String) function provided by Activity and Panel objects.
  
 +
==== Checking if a widget is installed ====
 +
A list of all installed widget types can be retrieved the following read-only property:
 +
 +
* ''Array[String]'' '''knownWidgetTypes''' (scripting version >= 2)
 +
 +
This can be used most conveniently with the indexOf() method, like this:
 +
 +
<syntaxhighlight lang="javascript">
 +
if (knownWidgeTypes.indexOf('someWidgetPluginName') > -1) {
 +
    print("It is installed on this system!");
 +
} else {
 +
    print("It is not installed :(");
 +
}
 +
</syntaxhighlight>
 +
 +
==== Widget Object API ====
 
A Widget object provides the following read-only properties:
 
A Widget object provides the following read-only properties:
  
Line 168: Line 262:
 
* ''Array[String]'' '''globalConfigKeys''':  (scriptingVersion >= 2) a list of all keys that are set in the current global configuration group
 
* ''Array[String]'' '''globalConfigKeys''':  (scriptingVersion >= 2) a list of all keys that are set in the current global configuration group
 
* ''Array[String]'' '''globalConfigGroups''': (scriptingVersion >= 2)  a list of all the groups in the current global configuration group
 
* ''Array[String]'' '''globalConfigGroups''': (scriptingVersion >= 2)  a list of all the groups in the current global configuration group
 +
* ''String'' '''version''': (scriptingVersion >= 2) the version of the Activity or Panel
  
 
as well as the following read-write properties:
 
as well as the following read-write properties:
Line 180: Line 275:
  
 
* '''remove()''': deletes this widget
 
* '''remove()''': deletes this widget
* '''readConfig(String key, any default)''': reads the value of key in the config with default
+
* '''readConfig(String key, any default)''': reads the value of key in the config with default for the default value
  for the default value
+
 
* '''writeConfig(String key, any value)''': sets key to value in the config
 
* '''writeConfig(String key, any value)''': sets key to value in the config
* '''readGlobalConfig(String key, any default)''': (scriptingVersion >= 2) reads the value of key in the global config with default
+
* '''readGlobalConfig(String key, any default)''': (scriptingVersion >= 2) reads the value of key in the global config with default for the default value
  for the default value
+
 
* '''writeGlobalConfig(String key, any value)''': (scriptingVersion >= 2) sets key to value in the global config
 
* '''writeGlobalConfig(String key, any value)''': (scriptingVersion >= 2) sets key to value in the global config
 
* '''reloadConfig()''': causes the widget to reload its configuration; reaction to configuration changes made using readConfig are usually activated on script exit, but this can be triggered earlier on a per-widget basis using this method
 
* '''reloadConfig()''': causes the widget to reload its configuration; reaction to configuration changes made using readConfig are usually activated on script exit, but this can be triggered earlier on a per-widget basis using this method
Line 195: Line 288:
 
Functions:
 
Functions:
 
* ''QRectF'' '''screenGeometry(number screen)''': returns a rect object representing the geometry of a screen
 
* ''QRectF'' '''screenGeometry(number screen)''': returns a rect object representing the geometry of a screen
 +
 +
=== Wallpaper Plugins ===
 +
 +
* ''Array[String => Array[String]]'' '''knownWallpaperPlugins()''': (scripting version >= 4) returns a list of all installed wallpaper plugins. The keys of the array are the wallpaper plugin names. The values are arrays containing the modes available for that wallpaper plugin. The mode array may be empty, as most wallpaper plugins only offer one mode.
 +
 +
=== Locating Applications and Paths ===
 +
* ''boolean'' '''applicationExists(String name)''': (scripting version >= 4) searches $PATH first, then tries in the application menu system by application storage name (aka the .desktop file name), then Name= entries for apps with installed .desktop files, then GenericName= entries for same
 +
* ''mixed'' '''defaultApplication(String kind [, boolean storageId = false])''': (scripting version >= 4) returns the executable (or if storageId is true, then the app menu system id, e.g. its .desktop file name) of the default app. The "kind" parameter may be a well-known application type including "browser", "mailer", "filemanager", "terminal", "imClient" and "windowmanager" (or any other entry in share/apps/kcm_componentchooser/kcm_*.desktop); it may also be a mimetype (e.g. "application/pdf"). On failure, it returns false.
 +
* ''String'' '''applicationPath(String name)''':  (scripting version >= 4) returns the full local path to a given application or .desktop file if it exists. Example:
 +
 +
<syntaxhighlight lang="javascript">
 +
var desktopfile = "firefox.desktop"
 +
var executable  = "firefox"
 +
if (applicationExists(executable)) { 
 +
    print (executable + " exists " + " with this path:  " + applicationPath(executable))
 +
    print (executable + " .desktop file is located here :    " + applicationPath(desktopfile))
 +
} else{
 +
    print (executable + " does not exist ")
 +
}
 +
</syntaxhighlight>
 +
 +
* ''String'' '''userDataPath([String type, String path])''':  (scripting version >= 4) returns the default path for user data. Called with no parameters, it returns the user's home directory. If only one string is passed in, the standard directory for that type of data in the user's home directory will be located; the following values are recognized:
 +
** documents
 +
** music
 +
** video
 +
** downloads
 +
** pictures
 +
** autostart
 +
** desktop (should be considered deprecated for Plasma workspaces)
 +
 +
If a second string is passed in, it is considered a request for a specific path and the following types are recognized:
 +
** apps - Applications menu (.desktop files).
 +
** autostart - Autostart directories (both XDG and kde-specific)
 +
** cache - Cached information (e.g. favicons, web-pages)
 +
** cgi - CGIs to run from kdehelp.
 +
** config - Configuration files.
 +
** data - Where applications store data.
 +
** emoticons - Emoticons themes
 +
** exe - Executables in $prefix/bin. findExe() for a function that takes $PATH into account.
 +
** html - HTML documentation.
 +
** icon - Icons, see KIconLoader.
 +
** kcfg - KConfigXT config files.
 +
** lib - Libraries.
 +
** locale - Translation files for KLocale.
 +
** mime - Mime types defined by KDE-specific .desktop files.
 +
** module - Module (dynamically loaded library).
 +
** qtplugins - Qt plugins (dynamically loaded objects for Qt)
 +
** services - Services.
 +
** servicetypes - Service types.
 +
** sound - Application sounds.
 +
** templates - Templates for the "Create new file" functionality.
 +
** wallpaper - Wallpapers.
 +
** tmp - Temporary files (specific for both current host and current user)
 +
** socket - UNIX Sockets (specific for both current host and current user)
 +
** xdgconf-menu - Freedesktop.org standard location for menu layout (.menu) files.
 +
** xdgdata-apps - Freedesktop.org standard location for application desktop files.
 +
** xdgdata-dirs - Freedesktop.org standard location for menu descriptions (.directory files).
 +
** xdgdata-mime - Freedesktop.org standard location for MIME type definitions.
 +
** xdgdata-icon - Freedesktop.org standard location for icons.
 +
** xdgdata-pixmap - Gnome-compatibility location for pixmaps.
 +
 +
The second parameter should be a specific resource to find the path to. An example might be userDataPath("data", "plasma-desktop").
 +
 +
=== External Configuration Files ===
 +
Scripting version >=6
 +
 +
Access to configuration files outside of the application's appletsrc file is provided by the ConfigFile object which has the following constructors:
 +
* ''ConfigFile(ConfigFile other)'': creates a new ConfigFile object with the first as its parent, which automatically makes all groups of this object child groups of that parent
 +
* ''ConfigFile(string file[, string group])'': creates a new ConfigFile object for file and optionally set to group group
 +
 +
ConfigFile has the following functions:
 +
* ''writeEntry(string key, any value)'': writes value for key in the current group
 +
* ''readEntry(string key)'': returns the value of key in the current group
 +
* ''deleteEntry(key)'': deletes key in the current group
 +
 +
ConfigFile has the following read/write properties:
 +
* ''file'': the name of the configuration file. May be an absolute path or just a file name to be located automatically in the system's configuration repository.
 +
* ''group'': the name of the current group. To get to child groups, create a new ConfigFile with another ConfigFile as its parent.
 +
 +
ConfigFile has the follow read-only properties:
 +
* ''entryList'': all the keys in the current group
 +
* ''groupList'': all the child groups in the current group
 +
 +
Example usage:
 +
 +
<syntaxhighlight lang="javascript">
 +
// open the kickoffrc file
 +
var config = ConfigFile('kickoffrc');
 +
// switch to the RecentlyUsed group
 +
config.group = 'RecentlyUsed';
 +
// write an entry into it
 +
config.writeEntry('MaxApplications', 25);
 +
 +
// now put Yes=20 into RecentlyUsed/Test
 +
var config2 = ConfigFile(config, 'Test);
 +
config2.writeEntry('Yes', 20);
 +
</syntaxhighlight>
  
 
=== Misc. Global Properties and Functions ===
 
=== Misc. Global Properties and Functions ===
 
Read-write properties:
 
Read-write properties:
* ''bool'' '''locked''': whether the desktop shell and widgets are locked or not (settable)
+
* ''boolean'' '''locked''': whether the desktop shell and widgets are locked or not (settable)
 +
* ''string'' '''theme''': (scripting version >= 3) the name of the desktop theme to use for the interface, e.g. default, Air, Oxygen, etc.
  
Read-only property:
+
Read-only properties:
 
* ''boolean'' '''hasBattery''': whether or not the system has the ability to run on battery power, e.g. a laptop or mobile device
 
* ''boolean'' '''hasBattery''': whether or not the system has the ability to run on battery power, e.g. a laptop or mobile device
 +
* ''boolean'' '''multihead''': (scripting version >= 3) true if the system is running with multiple screens in a "Xaphod" multiple display server configuration
 +
* ''int'' '''multiheadScreen''': (scripting version >= 3) if multihead is true, contains the (real) screen id of the current screen
  
 
Functions:
 
Functions:
Line 217: Line 410:
 
* ''number'' '''left'''
 
* ''number'' '''left'''
 
* ''number'' '''top'''
 
* ''number'' '''top'''
* ''number'' '''bottom'''  
+
* ''number'' '''bottom'''
 
* ''number'' '''right'''
 
* ''number'' '''right'''
 
* ''number'' '''height'''
 
* ''number'' '''height'''
Line 224: Line 417:
 
* ''number'' '''y'''
 
* ''number'' '''y'''
  
Constructors:  
+
Constructors:
 
* '''QRectF'''
 
* '''QRectF'''
 
* '''QRectF(number x, number y, number width, number height)''': Sets the coordinates of the rectangle's top-left corner to (x, y), and its size to the given width and height.
 
* '''QRectF(number x, number y, number width, number height)''': Sets the coordinates of the rectangle's top-left corner to (x, y), and its size to the given width and height.
Line 230: Line 423:
 
Functions:
 
Functions:
 
* '''adjust(number dx1, number dy1, number dx2, number dy2)''': adds dx1, dy1, dx2 and dy2 respectively to the existing coordinates of the rectangle
 
* '''adjust(number dx1, number dy1, number dx2, number dy2)''': adds dx1, dy1, dx2 and dy2 respectively to the existing coordinates of the rectangle
* ''QRectF'' '''adjusted(number dx1, number dy1, number dx2, number dy2)''': returns a new QRectF with dx1, dy1, dx2 and dy2 added respectively to the existing coordinates of the rectangle  
+
* ''QRectF'' '''adjusted(number dx1, number dy1, number dx2, number dy2)''': returns a new QRectF with dx1, dy1, dx2 and dy2 added respectively to the existing coordinates of the rectangle
 
* '''translate(number dx, number dy)''': translates the rect by dx, dy
 
* '''translate(number dx, number dy)''': translates the rect by dx, dy
 
* '''setCoords(number x1, number y1, number x2, number y2)''': sets the coordinates of the rectangle's top-left corner to (x1, y1), and the coordinates of its bottom-right corner to (x2, y2).
 
* '''setCoords(number x1, number y1, number x2, number y2)''': sets the coordinates of the rectangle's top-left corner to (x1, y1), and the coordinates of its bottom-right corner to (x2, y2).
Line 240: Line 433:
 
* '''moveTo(number x, number y)''': moves the top left of the rect to point (x, y)
 
* '''moveTo(number x, number y)''': moves the top left of the rect to point (x, y)
 
* '''moveTop(number delta)''': moves the top by delta pixels
 
* '''moveTop(number delta)''': moves the top by delta pixels
 +
 +
 +
== Configuration Keys ==
 +
Here you find a list of commonly used configuration keys to use with the '''writeConfig''' command. Where the documentation notes that a key is in a subgroup, remember to first use '''currentConfigGroup'''.
 +
 +
=== Common configuration keys ===
 +
Here are some keys that can be used with all widgets:
 +
 +
* '''Share''' (true/false): Whether or not the widget is to be announces throughout the network (Share tab)
 +
 +
=== Common time and date keys ===
 +
Most of the settings listed below apply to all widgets dealing with date and time (clock, digital-clock, binary-clock, …)
 +
Settings for individual plasmoids can be found in their respective category and usually only affect the plasmoid’s appearance.
 +
* '''announceInterval''' (number ≥ 0): Interval in minutes that the time is read out loud
 +
* '''calendarType''' (local/coptic/ethopian/gregorian/gregorian-proleptic/hebrew/hijri/indian-national/jalali/japanese/julian/minguo/thai): Calendar system to be used, defaults to local
 +
* '''defaultTimezone''' (Local/…): Time zone to be used
 +
* '''displayHolidays''' (true/false): Whether holidays are to be displayed
 +
* '''holidayRegions''' (tbd): tbd
 +
* '''holidayRegionaDaysOff''' (tbd): tbd
 +
* '''timeZones''' (Europe/Andorra,…): Comma-separated list of timezones to be used (e. g. Europe/Andorra,Indian/Antananarivo,Asia/Aqtau)
 +
 +
=== Analog clock (clock) ===
 +
* '''showSecondHand''' (true/false): self-explanatory
 +
* '''showTimezoneString''' (true/false): self-explanatory
 +
 +
=== Battery status (battery) ===
 +
* '''showBatteryString''' (true/false): Whether or not battery status is shown as overlay for the battery icon (if in systemtray or panel)
 +
* '''showMultipleBatteries''' (true/false): Whether or not battery status is shown for each battery separately
 +
 +
=== Digital clock (digital-clock) ===
 +
* '''plainClockColor''' (rrr,ggg,bbb): Color set for clock font (e. g. 192,0,0 - to be used with useCustomColor=true!)
 +
* '''plainClockDrawShadow''' (true/false): Whether a shadow is to bed drawn (defaults to true)
 +
* '''plainClockShadowColor''' (rrr,ggg,bbb): Color set for clock shadow (e. g. 64,97,128 - to be used with useCustomShadowColor=true!)
 +
* '''plainClockFont''' (tbd): Font to be used for clock (e. g. Serif,12,-1,5,75,0,0,0,0,0)
 +
* '''showDate''' (true/false): self-explanatory
 +
* '''showDay''' (true/false): self-explanatory
 +
* '''showSeconds''' (true/false): self-explanatory
 +
* '''showTimezone''' (true/false): self-explanatory
 +
* '''showYear''' (true/false): self-explanatory
 +
* '''useCustomColor''' (true/false): Whether or not a custom color is to be used (use with plainClockColor=rrr,ggg,bbb!)
 +
* '''useCustomShadowColor''' (true/false): Whether or not a custom shadow color is to be used (use with plainClockShadowColor=rrr,ggg,bbb!)
 +
 +
=== Folderview (folderview) ===
 +
* '''alignToGrid''' (true/false): self-explanatory
 +
* '''customIconSize''' (16/22/24/32/48/…): Use custom icon size for files/folders (use only default/common icon sizes, powers of 2)
 +
* '''customLabel''': Use custom title rather than default path or place name
 +
* '''drawShadows''' (true/false): Whether or not file labels are to draw shadows
 +
* '''filter''' (0/1/2): Defines whether a filter is to be used or not (0 = No filter, 1 = Show only matching files, 2 = Hide matching files)
 +
* '''filterFiles''': Wildcard filter to filter file names
 +
* '''mimeFilter''': Comma-separated list of mimetypes to be filtered (shown/hidden depends on filter-setting)
 +
* '''iconsLocked''' (true/false): Whether or not icons can be moved
 +
* '''numTextLines''' (number > 0): Amount of lines a file name can have before it is truncated
 +
* '''url''': Folder URL to be displayed (e. g. desktop:/// or file:///home/yourusername)
 +
* '''sortColumn''' (-1/0/1/2/3/4/5): The way files and folders are sorted (-1 = No sorting, 0 = By name, 1 = By size, 2 = By type, 3 = By date)
 +
* '''sortDirsFirst''' (true/false): Whether or not folders are displayed before files (defaults to true)
 +
* '''textColor''' (rrr,ggg,bbb): Color the icon labels will have
 +
 +
=== Kickoff menu (launcher) ===
 +
* '''SwitchTabsOnHover''' (true/false): self-explanatory
 +
* '''ShowAppsByName''' (true/false): Apps are sorted by name rather than by description
 +
 +
=== Pager (pager) ===
 +
* '''displayedText''' (0/1/2): Text to be shown on individual virtual desktops (0 = Workspace number, 1 = Workspace title, 2 = None)
 +
* '''ShowWindowIcons''' (true/false): Whether or not the application icon is to be shown on each individual window
 +
* '''currentDesktopSelected''' (0/1/2): Defines what should happen if the user clicks on the virtual desktop that is currently active (0 = Nothing, 1 = Show Workspace, i. e. minimize windows, 2 = Show Dashboard)
 +
* '''rows''' (number > 0): Amount of rows the pager should have. (Note: ''This is a global option, so you need to use '''writeGlobalConfig''' instead'')
 +
 +
=== Notifications (notifications) ===
 +
{{note|This applet is likely to be embedded to system tray. For Systrem Tray specific tasks, i. e. how to add, manage and remove plasmoids inside it, see sections below}}
 +
* '''AutoHidePopup''' (true/false): Whether or not popups are to be hidden automatiaclly
 +
* '''ShowJobs''' (true/false): Whether or not jobs are to be shown (e. g. file transfer progress)
 +
* '''ShowNotifications''' (true/false): Whether or not notifications are to be shown
 +
 +
=== Removable media notifier (notifier) ===
 +
* '''ShowDevices''' (0/1/2): Defines what kind of devices are to be shown (0 = Removable media only, 1 = Non-removable media only, 2 = All)
 +
{{note|Auto-mount settings and device actions are not stored in this Plasmoid’s settings.}}
 +
 +
=== Taskbar (tasks) ===
 +
* '''groupingStrategy''' (0/1/2): Defines how taskbar entries are to be grouped (0 = Never, 1 = Manually, 2 = By Program Name)
 +
* '''groupWhenFull''' (true/false): Only group when taskbar is full (to be used with groupingStrategy=2 only!)
 +
* '''highlightWindows''' (true/false): Highlight a window if your mouse cursor is hovering its taskbar entry (requires Desktop Compositing and “Highlight windows” effect enabled to work)
 +
* '''maxRows''' (number > 0): Amount of rows taskbar entries can take
 +
* '''forceRows''' (true/false): Force row setting for taskbar entries
 +
* '''showOnlyCurrentActivity''' (true/false): Show only windows from current activity
 +
* '''showOnlyCurrentDesktop''' (true/false): Show only windows from current virtual desktop
 +
* '''showOnlyCurrentScreen''' (true/false): Show only windows from current screen (multi monitor setup)
 +
* '''showTooltip''' (true/false): Whether or not tooltips are to be shown
 +
* '''sortingStrategy''' (0/1/2/3): How taskbar entries are to be sorted (0 = Never, 1 = Manually, 2 = Alphabetically, 3 = By Desktop)
 +
 +
=== System Tray ===
 +
The System Tray has some unique behaviors since it can host widgets and configuring it is not as easy as most other widgets, particularly when adding and removing widgets. This section will help you deal with its specific behavior.
 +
 +
==== Generic System Tray configuration keys ====
 +
* '''DefaultAppletAdded''' (true/false): Remembers whether the default plasmoids (networkmanagement, device manager, notifications) have already been added(??)
 +
* '''ShowApplicationStatus''' (true/false): Show system tray icons of applications that belong to the group “Applications”
 +
* '''ShowCommunications''' (true/false): Show system tray icons of applications that belong to the group “Applications” (i. e. Messenger, IRC chat)
 +
* '''ShowHardware''' (true/false): Show system tray icons of applications that belong to the group “Hardware” (i. e. volume control, printer applet)
 +
* '''ShowSystemServices''' (true/false): Show system tray icons of applications that belong to the group “System Services” (i. e. Nepomuk Indexing Agent)
 +
* '''ShowUnknown''' (true/false): Show system tray icons that do not belong into one of the categories mentioned above (or that do not use KDE’s system tray protocol and thus do not provide such information)
 +
* '''alwaysShown''': Comma-separated list of widgets and entries that are to be shown all the time (e. g. KMix,notifier)
 +
* '''hidden''': Comma-separated list of widgets and entries that are to be hidden all the time (e. g. Nepomuk Indexing Agent,Klipper,kmail)
 +
{{note|Although notifications appear to be part of the System Tray, they are handled by a separate plasmoid which is embedded to the system tray. For its configuration keys, see section above}}
 +
 +
==== Add a widget to systemtray ====
 +
You can not add widgets to the systemtray in a similar way like you would add them to a panel or containment using addWidget. Instead, to add, manage and remove them, you need to utilize writeConfig changing the currentConfigGroup.
 +
<syntaxhighlight lang="cpp-qt">
 +
systray = panel.addWidget("systemtray") // First add a systemtray to your panel
 +
systray.currentConfigGroup = Array("Applets","0") // then change the currentConfig Group
 +
 +
// to the subnode [Applets][0]. Use any number you like(?)
 +
</syntaxhighlight>
 +
 +
Now you can “create” the plasmoid by adding a “plugin” configuration entry
 +
<syntaxhighlight lang="cpp-qt">
 +
systray.writeConfig("plugin","notifier") // This will add a Device Notifier Plasmoid
 +
</syntaxhighlight>
 +
You can modify the plasmoid’s configuration by using writeConfig.
 +
<syntaxhighlight lang="cpp-qt">
 +
systray.writeConfig("property","value")
 +
</syntaxhighlight>
 +
To change back to the top configuration level and thus edit the systemtray plasmoid itself pass an empty array to currentConfigGroup.
 +
 +
==== Edit existing widgets in systemtray ====
 +
 +
==== Remove a widget from systemtray ====
 +
 +
To remove a widget, delete the corresponding configuration group.
 +
 +
See removeSystrayApplet.js in [https://projects.kde.org/projects/kde/kdeexamples/repository/revisions/master/show/plasma/javascript/plasma-shell-scripting kdeexamples]

Revision as of 16:47, 13 September 2013

Contents

ECMA Script Interaction With Plasma Shells

It is possible to control and interact with a Plasma user interface shell such as a plasma-desktop or (starting in KDE SC 4.5) plasma-netbook session using ECMA Script (aka JavaScript). This scripting mechanism exposes containments (Desktop Activities and Panels), widgets and various other aspects of plasma-desktop configuration using the widely known and used ECMA Script language. The QtScript engine is used for the runtime environment.

This document describes the API that is provided along with how to run such scripts in plasma-desktop.

Examples

A set of examples can be found here that demonstrate the use of various aspects of Plasma shell scripting.

Contributions of additional examples are welcome and an be sent to the Plasma development mailing list (plasma-devel at kde.org) for inclusion if you do not have commit rights to the kdeexamples module.

Running Scripts

There are three ways that scripts can be executed in plasma-desktop:

  • on first run: when plasma-desktop is started without any pre-existing configuration, any scripts in $APPDATA/plasma-desktop/init/ with a ".js" suffix are run. If there is more than one script, they are run sequentially in the alphabetical order of the file names.
noframe
 
Note
For security reasons, scripts located in the user's home directory will not be run during this phase.
  • on update: when plasma-desktop is started, it will check in
`kde4-config --path data`/plasma-desktop/updates/

with a ".js" suffix for scripts that have not yet been run. If there is more than one script which has not been run yet they will be executed serially in the alphabetical order of the file names.

A record of which update scripts have been run is kept in the application's config file in the [Updates] group. This means that if the plasma-desktop configuraiton file is removed, all the update scripts will be run again.

noframe
 
Note
For security reasons, scripts located in the user's home directory will not be run during this phase.
  • interactively: an interactive scripting dialog can be requested either via the KRunner window (Alt+F2, by default, or via the "Run Command" entry in various desktop menus) by entering "desktop console" as the search term. It can also be triggered directly via dbus with
    qdbus org.kde.plasma-desktop /MainApplication showInteractiveConsole
noframe
 
Note
This method is not available for plasma-netbook.
ECMA Script may be entered directly into this window for execution and output appears in the lower half of the window. Ctrl+E is a shortcut to run scripts, and scripts can be saved to and loaded from disk.
Scripts from files can also be loaded using KRunner with "desktop console /path/to/file" or via dbus with
qdbus org.kde.plasma-desktop /MainApplication loadScriptInInteractiveConsole /path/to/file

Templates

Templates are named packages that contain scripts. This provides a way for common functionality to be easily reused, helping to increase consistency and lower maintenance costs. Templates can be loaded from other scripts by name and they are also used to populate some parts of the user interface, such as the entries in the Add Panels menu.

A template is a small set of files in a specified file hierarchy (or, in Plasma terms, a "Package"). In particular, a Template package contains the following files:

  • metadata.desktop: a .desktop file describing the template
  • contents/layout.js: a Javascript file containing the actual script

Templates are stored under share/apps/plasma/layout-templates and may be installed using `plasmapkg -t layout-template -i /path/to/package`. Template packages may also be provided as a .zip file with a .plasmalayout suffix.

The metadata.desktop file contains the usual .desktop entries such as Name and Icon but must also contain Type=Service and ServiceTypes=Plasma/LayoutTemplate entries. If the layout is specific to a given Plasma application, such as plasma-desktop, this can be specific using X-Plasma-Shell. X-Plasma-ContainmentCategories defines what kind of layout it is with possible values being panel and desktop. Finally a X-KDE-PluginInfo-Name entry is required to provide a globally unique internal name for the Template. Here is an example of a Template that provides a Panel layout for Plasma Netbook:

[Desktop Entry]
Encoding=UTF-8
Name=Cool Panel
Type=Service
ServiceTypes=Plasma/LayoutTemplate
X-Plasma-Shell=plasma-netbook
X-Plasma-ContainmentCategories=panel
X-KDE-PluginInfo-Author=Aaron Seigo
X-KDE-PluginInfo-Email=aseigo@kde.org
X-KDE-PluginInfo-Name=org.kde.CoolNetbookPanel
X-KDE-PluginInfo-Version=1.0
X-KDE-PluginInfo-Website=http://plasma.kde.org/
X-KDE-PluginInfo-Category=
X-KDE-PluginInfo-Depends=
X-KDE-PluginInfo-License=GPL
X-KDE-PluginInfo-EnabledByDefault=true

When running a template, two global variables will be accessible in read-only mode: templateName and templateComment. They will contain the Name and Comment fields of the above desktop file, and are translated if a localization is available.

Examples of Usage

Creating panels

A good example of the use of templates is the use case that triggered the creation of this feature: the desire to make it easy for users to re-create the default panel that is created on first start. There is a Template called org.kde.plasma-desktop.defaultPanel that ships with the KDE Plasma Workspace which contains the layout for the initial default panel. This is referenced by the default Plasma Desktop init script and, because it is marked as a Panel Template in the metadata.desktop file it also shows up to the user in the Add Panels menu. When selected by the user from the menu, the exact same panel that is created on desktop start up is created for them, complete with Plasma Widgets and configuration.

Automating tasks

Another example of the usefulness of templates is the "Find Widgets" template. This template, which first shipped with Plasma Desktop v4.5, provides a function for finding widgets by name. It appears in the toolbar "Load" and "Use" menus in the Desktop Console in plasma-desktop, and makes finding widgets as simple as:

var template = loadTemplate('org.kde.plasma-desktop.findWidgets')
template.findWidgets('systemtray')


Since just finding the widget is not enough, you can connect a callback to do additional operations, such as removing the widget :

removeWidget = function(widget, containment)
{
  widget.remove()
}
 
var template = loadTemplate('org.kde.plasma-desktop.findWidgets')
template.findWidgets('systemtray', removeWidget)


Activity templates

Probably the most user visible use of templates are "Activity templates". The structure of Activity templates is similar to the other use of templates, but a few extra features are provided in the metadata.desktop file. Here is an example of such an activity template:

[Desktop Entry]
Encoding=UTF-8
Name=Cool Activity Template
Icon=user-desktop
Type=Service
ServiceTypes=Plasma/LayoutTemplate
X-Plasma-Shell=plasma-desktop
X-Plasma-ContainmentCategories=desktop
X-Plasma-ContainmentLayout-ExecuteOnCreation=dolphin $desktop, gwenview $pictures
X-Plasma-ContainmentLayout-ShowAsExisting=true
X-KDE-PluginInfo-Author=John Doe
X-KDE-PluginInfo-Email=john@doe.org
X-KDE-PluginInfo-Name=org.kde.plasma-desktop.CoolTemplate
X-KDE-PluginInfo-Version=1.0
X-KDE-PluginInfo-Website=http://john.doe.org
X-KDE-PluginInfo-Category=
X-KDE-PluginInfo-Depends=
X-KDE-PluginInfo-License=GPL
X-KDE-PluginInfo-EnabledByDefault=true

The layout itself is still created from the layout.js file as usual, but this template also shows as a precreated activity to the user thanks to the X-Plasma-ContainmentLayout-ShowAsExisting key. Additionally, it starts applications in the newly created activity using the X-Plasma-ContainmentLayout-ExecuteOnCreation key.

That key is a list of commands to execute, and it supports the following variables:

  • $desktop
  • $autostart
  • $documents
  • $music
  • $video
  • $downloads
  • $pictures

They all expand into the path toward the user corresponding default folder.

API

In addition to the normal ECMA Script API and the Qt-specific extensions (such as signal/slot support) provided by QtScript, the following API is provided for use by scripts.

All of the API below, unless otherwise noted with a version noticed, appear as below in the KDE Software Compilation v4.4.0 and later. API that is not noted as being part of a given class or object is part of the global namespace.

noframe
 
Note
API compatibility is guaranteed from version to version starting with KDE Software Compilation v4.4.0.

Version Numbers

Starting with KDE SC 4.5, the version number of both the scripting API and the application is available to the script via the following read-only properties:

  • String applicationVersion: the version of the application, e.g. 0.3
  • String platformVersion: the version of the KDE Platform, e.g. 0.3
  • number scriptingVersion: the version of the scripting API; e.g. in KDE SC 4.5 this is 2

Activities

Activities are the desktop layer in a plasma-desktop session and may contain widgts. In sightly more technical terms, they are desktop containments. Activities can be created, enumerated, modified and destroyed.

New Activities can be created using the Activity constructor, like this:

var activity = new Activity("folderview")

The string passed into the constructor maps to the X-KDE-PluginInfo-Name= entry in the plugin's .desktop file). See the documentation on the Containment object class below.

Read-only properties:

  • Array[number] activityIds: returns a list of integer ids of all existing Plasma activities
  • Array[String] knownActivityTypes: (scripting version >= 2) a list of types of activities that can be created. This is useful to check if an Activity type is available on the system before trying to construct one.

Functions:

  • Activity activityById(number id): return an object representing the activity with the given id
  • Activity activityForScreen(number screen[, number dekstop]): returns an object representing the activity currently associated with the given screen and, optionally, the given desktop.
  • Array[Activity] activities(): returns an array of all activities that currently exist

Panels

Panels can be created, enumerated, modified and destroyed. A panel object combines both a containment as well as the container itself, allowing for full control of things such as where it appears on screen and the hiding features associated with them.

New Panels can be created using the Panel constructor, like this:

var panel = new Panel("dock")

The string passed into the constructor maps to the X-KDE-PluginInfo-Name= entry in the plugin's .desktop file).

Read-only properties:

  • Array[number] panelIds: returns a list of integer ids of all existing Plasma panels
  • Array[String] knownPanelTypes: (scripting version >= 2) a list of types of panels that can be created. This is useful to check if a Panel type is available on the system before trying to construct one.

Functions:

  • Panel panelById(int id): returns an object representing the Panel that matches the given id
  • Array[Panels] panels(): returns an array of all panels that currently exist

Activities and Panels

Activity and Panel objects, once created by the script, or as returned by activityById, activityForScreen, or panelById) provide the following read-only properties:

  • number id: the integer id of this activity
  • String formFactor: returns the form factor of the activity, e.g. "planar" for most desktop activities,"mediacenter" for media centers and either "horizontal" or "vertical" for panels.
  • Array[number] widgetIds: a list of integer ids of all the widgets in this Activity
  • Array[String] configKeys: (scriptingVersion >= 2) a list of all keys that are set in the current configuration group
  • Array[String] configGroups: (scriptingVersion >= 2) a list of all the groups in the current configuration group
  • Array[String] globalConfigKeys: (scriptingVersion >= 2) a list of all keys that are set in the current global configuration group
  • Array[String] globalConfigGroups: (scriptingVersion >= 2) a list of all the groups in the current global configuration group

as well as the following read/write properties:

  • number desktop: the virtual desktop this activity is associated with, or -1 for none
  • number screen: the screen this activity is associated with, or -1 for none
  • String name: the name of this activity
  • String wallpaperPlugin: (scriptingVersion >= 2) the wallpaper plugin to use with the Activity
  • String wallpaperMode: (scriptingVersion >= 2) the wallpaper plugin mode to use with the Activity
  • Array[String] currentConfigGroup: (scriptingVersion >= 2) the current configuration group path, with each entry in the array representing a sub-group. This allows one to access trees of groups with code such as: widget.currentConfigGroup = new Array('topGroup', 'subGroupOfTopGroup'). An empty Array means the default (top-level) configuration group for the widget
  • String version: (scriptingVersion >= 2) the version of the Activity or Panel

and the following methods:

  • remove(): deletes this activity and all widgets inside of it
  • Widget widgetById(number id): returns an object representing the widget with the given id
  • Widget addWidget(String name): adds a new widget to the activity; the name maps to the X-KDE-PluginInfo-Name= entry in the widget's .desktop file
  • Widget addWidget(Widget widget): adds an existing widget to this activity; useful for moving widgets between Activities and Panels
  • showConfigurationInteface(): shows the configuration user interface for this Activity or Panel on the screen
  • readConfig(String key, any default): (scriptingVersion >= 2) reads the value of key in the config with default for the default value
  • writeConfig(String key, any value): (scriptingVersion >= 2) sets key to value in the config
  • readGlobalConfig(String key, any default): (scriptingVersion >= 2) reads the value of key in the global config with default for the default value
  • writeGlobalConfig(String key, any value): (scriptingVersion >= 2) sets key to value in the global config
  • reloadConfig(): (scriptingVersion >= 2) causes the Activity or Panel to reload its configuration; reaction to configuration changes made using readConfig are usually activated on script exit, but this can be triggered earlier on a per-widget basis using this method
  • Array[String] currentGlobalConfigGroup: (scriptingVersion >= 2) the current global configuration group path, with each entry in the array representing a sub-group, similar to currentConfigGroup. However, global configuration is shared by all instances of panels and activities of the same type.
  • Array[Widget] widgets([String type]): (scriptingVersion >= 2) returns all the widgets in the Panel or Activity. If the optional type is specified, only widgets matching that type will be returned.

In addition to all of the above properties and functions, Panel objects also provide the folowing read/write properties:

  • number length: the number of pixels along the screen edge used
  • number height: the height (or for vertical panels, the width) of the panel
  • String hiding: the hiding mode of the panel, one of "none" (for no hiding), "autohide", "windowscover" or "windowsbelow"
  • String alignment: right, left or center alignment of the panel (for vertical panels, right corrsponds to top and left to bottom)
  • String location: returns the location of the activity (only relevant for Panels); valid values include "top", "bottom", "left", "right" and "floating"

Widgets

Widgets may be enumerated by calling the widgetIds property on a Activity or Panel object. With a widget id in hand, a Widget object can be retrieved by calling widgetById(id) on an Activity or Panel object. New Widgets can be created with add addWidget(String) function provided by Activity and Panel objects.

Checking if a widget is installed

A list of all installed widget types can be retrieved the following read-only property:

  • Array[String] knownWidgetTypes (scripting version >= 2)

This can be used most conveniently with the indexOf() method, like this:

if (knownWidgeTypes.indexOf('someWidgetPluginName') > -1) {
    print("It is installed on this system!");
} else {
    print("It is not installed :(");
}

Widget Object API

A Widget object provides the following read-only properties:

  • number id: the id of the widget
  • String type: the plugin type of this widget
  • Array[String] configKeys: a list of all keys that are set in the current configuration
  • Array[String] configGroups: a list of all the groups in the current configuration
  • Array[String] globalConfigKeys: (scriptingVersion >= 2) a list of all keys that are set in the current global configuration group
  • Array[String] globalConfigGroups: (scriptingVersion >= 2) a list of all the groups in the current global configuration group
  • String version: (scriptingVersion >= 2) the version of the Activity or Panel

as well as the following read-write properties:

  • Array[String] currentConfigGroup: the current configuration group path, with each entry in the array representing a sub-group. This allows one to access trees of groups with code such as: widget.currentConfigGroup = new Array('topGroup', 'subGroupOfTopGroup'). An empty Array means the default (top-level) configuration group for the widget
  • Array[String] currentGlobalConfigGroup: (scriptingVersion >= 2) the current global configuration group path, with each entry in the array representing a sub-group, similar to currentConfigGroup. However, global configuration is shared by all instances of widgets of the same type.
  • QRectF geometry: the geometry of the widget (settable)
  • String globalShortcut: the shortcut sequence (in the format used by QKeySequence, e.g. "Alt+F1") associated with this widget
  • number index: the layout index of the widget; in a Panel this corresponds to the order the widget appears in. Changing the value of the index will change the position of the widget in Panels and may do so in some Activities as well.

and the following methods:

  • remove(): deletes this widget
  • readConfig(String key, any default): reads the value of key in the config with default for the default value
  • writeConfig(String key, any value): sets key to value in the config
  • readGlobalConfig(String key, any default): (scriptingVersion >= 2) reads the value of key in the global config with default for the default value
  • writeGlobalConfig(String key, any value): (scriptingVersion >= 2) sets key to value in the global config
  • reloadConfig(): causes the widget to reload its configuration; reaction to configuration changes made using readConfig are usually activated on script exit, but this can be triggered earlier on a per-widget basis using this method
  • showConfigurationInteface(): shows the configuration user interface for this widget on the screen

Screen Geometry

Read-only properties:

  • number screenCount: returns the number of screens connected to the computer

Functions:

  • QRectF screenGeometry(number screen): returns a rect object representing the geometry of a screen

Wallpaper Plugins

  • Array[String => Array[String]] knownWallpaperPlugins(): (scripting version >= 4) returns a list of all installed wallpaper plugins. The keys of the array are the wallpaper plugin names. The values are arrays containing the modes available for that wallpaper plugin. The mode array may be empty, as most wallpaper plugins only offer one mode.

Locating Applications and Paths

  • boolean applicationExists(String name): (scripting version >= 4) searches $PATH first, then tries in the application menu system by application storage name (aka the .desktop file name), then Name= entries for apps with installed .desktop files, then GenericName= entries for same
  • mixed defaultApplication(String kind [, boolean storageId = false]): (scripting version >= 4) returns the executable (or if storageId is true, then the app menu system id, e.g. its .desktop file name) of the default app. The "kind" parameter may be a well-known application type including "browser", "mailer", "filemanager", "terminal", "imClient" and "windowmanager" (or any other entry in share/apps/kcm_componentchooser/kcm_*.desktop); it may also be a mimetype (e.g. "application/pdf"). On failure, it returns false.
  • String applicationPath(String name): (scripting version >= 4) returns the full local path to a given application or .desktop file if it exists. Example:
var desktopfile = "firefox.desktop"
var executable  = "firefox"
if (applicationExists(executable)) {  
    print (executable + " exists " + " with this path:  " + applicationPath(executable))
    print (executable + " .desktop file is located here :    " + applicationPath(desktopfile))
} else{
    print (executable + " does not exist ")
}
  • String userDataPath([String type, String path]): (scripting version >= 4) returns the default path for user data. Called with no parameters, it returns the user's home directory. If only one string is passed in, the standard directory for that type of data in the user's home directory will be located; the following values are recognized:
    • documents
    • music
    • video
    • downloads
    • pictures
    • autostart
    • desktop (should be considered deprecated for Plasma workspaces)

If a second string is passed in, it is considered a request for a specific path and the following types are recognized:

    • apps - Applications menu (.desktop files).
    • autostart - Autostart directories (both XDG and kde-specific)
    • cache - Cached information (e.g. favicons, web-pages)
    • cgi - CGIs to run from kdehelp.
    • config - Configuration files.
    • data - Where applications store data.
    • emoticons - Emoticons themes
    • exe - Executables in $prefix/bin. findExe() for a function that takes $PATH into account.
    • html - HTML documentation.
    • icon - Icons, see KIconLoader.
    • kcfg - KConfigXT config files.
    • lib - Libraries.
    • locale - Translation files for KLocale.
    • mime - Mime types defined by KDE-specific .desktop files.
    • module - Module (dynamically loaded library).
    • qtplugins - Qt plugins (dynamically loaded objects for Qt)
    • services - Services.
    • servicetypes - Service types.
    • sound - Application sounds.
    • templates - Templates for the "Create new file" functionality.
    • wallpaper - Wallpapers.
    • tmp - Temporary files (specific for both current host and current user)
    • socket - UNIX Sockets (specific for both current host and current user)
    • xdgconf-menu - Freedesktop.org standard location for menu layout (.menu) files.
    • xdgdata-apps - Freedesktop.org standard location for application desktop files.
    • xdgdata-dirs - Freedesktop.org standard location for menu descriptions (.directory files).
    • xdgdata-mime - Freedesktop.org standard location for MIME type definitions.
    • xdgdata-icon - Freedesktop.org standard location for icons.
    • xdgdata-pixmap - Gnome-compatibility location for pixmaps.

The second parameter should be a specific resource to find the path to. An example might be userDataPath("data", "plasma-desktop").

External Configuration Files

Scripting version >=6

Access to configuration files outside of the application's appletsrc file is provided by the ConfigFile object which has the following constructors:

  • ConfigFile(ConfigFile other): creates a new ConfigFile object with the first as its parent, which automatically makes all groups of this object child groups of that parent
  • ConfigFile(string file[, string group]): creates a new ConfigFile object for file and optionally set to group group

ConfigFile has the following functions:

  • writeEntry(string key, any value): writes value for key in the current group
  • readEntry(string key): returns the value of key in the current group
  • deleteEntry(key): deletes key in the current group

ConfigFile has the following read/write properties:

  • file: the name of the configuration file. May be an absolute path or just a file name to be located automatically in the system's configuration repository.
  • group: the name of the current group. To get to child groups, create a new ConfigFile with another ConfigFile as its parent.

ConfigFile has the follow read-only properties:

  • entryList: all the keys in the current group
  • groupList: all the child groups in the current group

Example usage:

// open the kickoffrc file
var config = ConfigFile('kickoffrc');
// switch to the RecentlyUsed group
config.group = 'RecentlyUsed';
// write an entry into it
config.writeEntry('MaxApplications', 25);
 
// now put Yes=20 into RecentlyUsed/Test
var config2 = ConfigFile(config, 'Test);
config2.writeEntry('Yes', 20);

Misc. Global Properties and Functions

Read-write properties:

  • boolean locked: whether the desktop shell and widgets are locked or not (settable)
  • string theme: (scripting version >= 3) the name of the desktop theme to use for the interface, e.g. default, Air, Oxygen, etc.

Read-only properties:

  • boolean hasBattery: whether or not the system has the ability to run on battery power, e.g. a laptop or mobile device
  • boolean multihead: (scripting version >= 3) true if the system is running with multiple screens in a "Xaphod" multiple display server configuration
  • int multiheadScreen: (scripting version >= 3) if multihead is true, contains the (real) screen id of the current screen

Functions:

  • sleep(number ms): sleeps the script for the specified number of millseconds

QRectF

A rectangle class is also provided for use with Widget, Panel and screen geometry properties and functions.

Read-only properites:

  • boolean empty: true if the rectangle's width or height is less than, or equal to, 0; an empty rectangle is also invalid
  • boolean null: true if the rectangle has both the width and the height set to 0; a null rectangle is also empty and not valid
  • boolean valid: true if the rectangle has a width > 0 and height 0.

Read-write properties:

  • number left
  • number top
  • number bottom
  • number right
  • number height
  • number width
  • number x
  • number y

Constructors:

  • QRectF
  • QRectF(number x, number y, number width, number height): Sets the coordinates of the rectangle's top-left corner to (x, y), and its size to the given width and height.

Functions:

  • adjust(number dx1, number dy1, number dx2, number dy2): adds dx1, dy1, dx2 and dy2 respectively to the existing coordinates of the rectangle
  • QRectF adjusted(number dx1, number dy1, number dx2, number dy2): returns a new QRectF with dx1, dy1, dx2 and dy2 added respectively to the existing coordinates of the rectangle
  • translate(number dx, number dy): translates the rect by dx, dy
  • setCoords(number x1, number y1, number x2, number y2): sets the coordinates of the rectangle's top-left corner to (x1, y1), and the coordinates of its bottom-right corner to (x2, y2).
  • setRect(number x, number y, number width, number height): sets the coordinates of the rectangle's top-left corner to (x, y), and its size to the given width and height.
  • boolean contains(number x, number y): returns true if the rect contains the point (x, y)
  • 'moveBottom(number delta): moves the bottom by delta pixels
  • moveLeft(number delta): moves the left by delta pixels
  • moveRight(number delta): moves the right by delta pixels
  • moveTo(number x, number y): moves the top left of the rect to point (x, y)
  • moveTop(number delta): moves the top by delta pixels


Configuration Keys

Here you find a list of commonly used configuration keys to use with the writeConfig command. Where the documentation notes that a key is in a subgroup, remember to first use currentConfigGroup.

Common configuration keys

Here are some keys that can be used with all widgets:

  • Share (true/false): Whether or not the widget is to be announces throughout the network (Share tab)

Common time and date keys

Most of the settings listed below apply to all widgets dealing with date and time (clock, digital-clock, binary-clock, …) Settings for individual plasmoids can be found in their respective category and usually only affect the plasmoid’s appearance.

  • announceInterval (number ≥ 0): Interval in minutes that the time is read out loud
  • calendarType (local/coptic/ethopian/gregorian/gregorian-proleptic/hebrew/hijri/indian-national/jalali/japanese/julian/minguo/thai): Calendar system to be used, defaults to local
  • defaultTimezone (Local/…): Time zone to be used
  • displayHolidays (true/false): Whether holidays are to be displayed
  • holidayRegions (tbd): tbd
  • holidayRegionaDaysOff (tbd): tbd
  • timeZones (Europe/Andorra,…): Comma-separated list of timezones to be used (e. g. Europe/Andorra,Indian/Antananarivo,Asia/Aqtau)

Analog clock (clock)

  • showSecondHand (true/false): self-explanatory
  • showTimezoneString (true/false): self-explanatory

Battery status (battery)

  • showBatteryString (true/false): Whether or not battery status is shown as overlay for the battery icon (if in systemtray or panel)
  • showMultipleBatteries (true/false): Whether or not battery status is shown for each battery separately

Digital clock (digital-clock)

  • plainClockColor (rrr,ggg,bbb): Color set for clock font (e. g. 192,0,0 - to be used with useCustomColor=true!)
  • plainClockDrawShadow (true/false): Whether a shadow is to bed drawn (defaults to true)
  • plainClockShadowColor (rrr,ggg,bbb): Color set for clock shadow (e. g. 64,97,128 - to be used with useCustomShadowColor=true!)
  • plainClockFont (tbd): Font to be used for clock (e. g. Serif,12,-1,5,75,0,0,0,0,0)
  • showDate (true/false): self-explanatory
  • showDay (true/false): self-explanatory
  • showSeconds (true/false): self-explanatory
  • showTimezone (true/false): self-explanatory
  • showYear (true/false): self-explanatory
  • useCustomColor (true/false): Whether or not a custom color is to be used (use with plainClockColor=rrr,ggg,bbb!)
  • useCustomShadowColor (true/false): Whether or not a custom shadow color is to be used (use with plainClockShadowColor=rrr,ggg,bbb!)

Folderview (folderview)

  • alignToGrid (true/false): self-explanatory
  • customIconSize (16/22/24/32/48/…): Use custom icon size for files/folders (use only default/common icon sizes, powers of 2)
  • customLabel: Use custom title rather than default path or place name
  • drawShadows (true/false): Whether or not file labels are to draw shadows
  • filter (0/1/2): Defines whether a filter is to be used or not (0 = No filter, 1 = Show only matching files, 2 = Hide matching files)
  • filterFiles: Wildcard filter to filter file names
  • mimeFilter: Comma-separated list of mimetypes to be filtered (shown/hidden depends on filter-setting)
  • iconsLocked (true/false): Whether or not icons can be moved
  • numTextLines (number > 0): Amount of lines a file name can have before it is truncated
  • url: Folder URL to be displayed (e. g. desktop:/// or file:///home/yourusername)
  • sortColumn (-1/0/1/2/3/4/5): The way files and folders are sorted (-1 = No sorting, 0 = By name, 1 = By size, 2 = By type, 3 = By date)
  • sortDirsFirst (true/false): Whether or not folders are displayed before files (defaults to true)
  • textColor (rrr,ggg,bbb): Color the icon labels will have

Kickoff menu (launcher)

  • SwitchTabsOnHover (true/false): self-explanatory
  • ShowAppsByName (true/false): Apps are sorted by name rather than by description

Pager (pager)

  • displayedText (0/1/2): Text to be shown on individual virtual desktops (0 = Workspace number, 1 = Workspace title, 2 = None)
  • ShowWindowIcons (true/false): Whether or not the application icon is to be shown on each individual window
  • currentDesktopSelected (0/1/2): Defines what should happen if the user clicks on the virtual desktop that is currently active (0 = Nothing, 1 = Show Workspace, i. e. minimize windows, 2 = Show Dashboard)
  • rows (number > 0): Amount of rows the pager should have. (Note: This is a global option, so you need to use writeGlobalConfig instead)

Notifications (notifications)

noframe
 
Note
This applet is likely to be embedded to system tray. For Systrem Tray specific tasks, i. e. how to add, manage and remove plasmoids inside it, see sections below
  • AutoHidePopup (true/false): Whether or not popups are to be hidden automatiaclly
  • ShowJobs (true/false): Whether or not jobs are to be shown (e. g. file transfer progress)
  • ShowNotifications (true/false): Whether or not notifications are to be shown

Removable media notifier (notifier)

  • ShowDevices (0/1/2): Defines what kind of devices are to be shown (0 = Removable media only, 1 = Non-removable media only, 2 = All)
noframe
 
Note
Auto-mount settings and device actions are not stored in this Plasmoid’s settings.

Taskbar (tasks)

  • groupingStrategy (0/1/2): Defines how taskbar entries are to be grouped (0 = Never, 1 = Manually, 2 = By Program Name)
  • groupWhenFull (true/false): Only group when taskbar is full (to be used with groupingStrategy=2 only!)
  • highlightWindows (true/false): Highlight a window if your mouse cursor is hovering its taskbar entry (requires Desktop Compositing and “Highlight windows” effect enabled to work)
  • maxRows (number > 0): Amount of rows taskbar entries can take
  • forceRows (true/false): Force row setting for taskbar entries
  • showOnlyCurrentActivity (true/false): Show only windows from current activity
  • showOnlyCurrentDesktop (true/false): Show only windows from current virtual desktop
  • showOnlyCurrentScreen (true/false): Show only windows from current screen (multi monitor setup)
  • showTooltip (true/false): Whether or not tooltips are to be shown
  • sortingStrategy (0/1/2/3): How taskbar entries are to be sorted (0 = Never, 1 = Manually, 2 = Alphabetically, 3 = By Desktop)

System Tray

The System Tray has some unique behaviors since it can host widgets and configuring it is not as easy as most other widgets, particularly when adding and removing widgets. This section will help you deal with its specific behavior.

Generic System Tray configuration keys

  • DefaultAppletAdded (true/false): Remembers whether the default plasmoids (networkmanagement, device manager, notifications) have already been added(??)
  • ShowApplicationStatus (true/false): Show system tray icons of applications that belong to the group “Applications”
  • ShowCommunications (true/false): Show system tray icons of applications that belong to the group “Applications” (i. e. Messenger, IRC chat)
  • ShowHardware (true/false): Show system tray icons of applications that belong to the group “Hardware” (i. e. volume control, printer applet)
  • ShowSystemServices (true/false): Show system tray icons of applications that belong to the group “System Services” (i. e. Nepomuk Indexing Agent)
  • ShowUnknown (true/false): Show system tray icons that do not belong into one of the categories mentioned above (or that do not use KDE’s system tray protocol and thus do not provide such information)
  • alwaysShown: Comma-separated list of widgets and entries that are to be shown all the time (e. g. KMix,notifier)
  • hidden: Comma-separated list of widgets and entries that are to be hidden all the time (e. g. Nepomuk Indexing Agent,Klipper,kmail)
noframe
 
Note
Although notifications appear to be part of the System Tray, they are handled by a separate plasmoid which is embedded to the system tray. For its configuration keys, see section above

Add a widget to systemtray

You can not add widgets to the systemtray in a similar way like you would add them to a panel or containment using addWidget. Instead, to add, manage and remove them, you need to utilize writeConfig changing the currentConfigGroup.

systray = panel.addWidget("systemtray")	// First add a systemtray to your panel
systray.currentConfigGroup = Array("Applets","0") // then change the currentConfig Group
 
// to the subnode [Applets][0]. Use any number you like(?)

Now you can “create” the plasmoid by adding a “plugin” configuration entry

systray.writeConfig("plugin","notifier") // This will add a Device Notifier Plasmoid

You can modify the plasmoid’s configuration by using writeConfig.

systray.writeConfig("property","value")

To change back to the top configuration level and thus edit the systemtray plasmoid itself pass an empty array to currentConfigGroup.

Edit existing widgets in systemtray

Remove a widget from systemtray

To remove a widget, delete the corresponding configuration group.

See removeSystrayApplet.js in kdeexamples


KDE® and the K Desktop Environment® logo are registered trademarks of KDE e.V.Legal