Development/Tutorials/KWin/Scripting
KWin Scripting Tutorial
Quick Start: Desktop Console
The easiest way to test KWin scripts is to use the Plasma Desktop Scripting Console which can be opened via the KRunner window (Alt+F2, by default, or via the "Run Command" entry in various desktop menus) by entering "wm console" as the search term It can be triggered directly via dbus with
qdbus org.kde.plasma-desktop /MainApplication showInteractiveKWinConsole
The interactive console allows to send a script to the window manager which is directly loaded and executed. All debug output is displayed in the scripting console. This provides a very easy way to develop and test the script to be written. It is important to know that scripts executed from the scripting console are only used by the window manager as long as the window manager is running. In a new session the script has to be sent to the window manager again.
Packaging KWin Scripts
In order to have KWin load a script on each session start the script has to be packaged. KWin Scripts use the Plasma Package format. The recommended file ending for KWin Script packages is .kwinscript. In the metadata.desktop file of the package the value for "X-KDE-ServiceTypes" has to be KWin/Script, as "X-Plasma-API" only javascript and declarativescript are supported.
A packaged KWin Script can either be installed via the KWin Script KCM (note: the list does not yet reload after installing a script) or with the plasmapkg tool:
plasmapkg --type kwinscript -i /path/to/myscript.kwinscript
After installation the script has to be enabled in the KWin Script KCM. The window manager will load the newly installed script directly at runtime as well as in new sessions.
KWin scripting basics
To follow this tutorial, you must have some idea about ECMAScript (or JavaScript. A quick introduction can be found in the Plasma scripting tutorial.
KWin Scripts can either be written in QtScript (service type "javascript") or QML (service type "declarativescript"). In order to develop KWin Scripts you should know the basic concepts of signals and properties.
Global Objects and Functions
KWin Scripts can access two global properties workspace and options. The workspace object provides the interface to the core of the window manager, the options object provides read access to the current configuration options set on the window manager. To get an overview of what is available, please refer to the API documentation.
The following global functions are available to both QML and QtScript:
- print(QVariant...): prints the provided arguments to stdout. Takes an arbitrary number of arguments. Comparable to console.log() which should be preferred in QML scripts.
- readConfig(QString key, QVariant defaultValue=QVariant()): reads a config option of the KWin Script. First argument is the config key, second argument is an optional default value in case the config key does not exist in the config file.
Clients
The window manager calls a window it manages a "Client". Most methods of workspace operating on windows either return a Client or require a Client. Internally the window manager supports more types of windows, which are not clients. Those windows are not available for KWin Scripts, but for KWin Effects. To have a common set of properties some properties and signals are defined on the parent class of Client called Toplevel. Be sure to check the documentation of that class, too when looking for properties. Be aware that some properties are defined as read-only on Toplevel, but as read-write on Client.
The following examples illustrates how to get hold of all clients managed by the window manager and prints the clients' caption:
var clients = workspace.clientList();
for (var i=0; i<clients.length; i++) {
print(clients[i].caption);
}
The following example illustrates how to get informed about newly managed clients and prints out the window id of the new client:
workspace.clientAdded.connect(function(client) {
print(client.windowId);
});
To understand which parameters are passed to the event handlers (i.e. the functions we connect to), one can always refer the Development/Tutorials/KWin/Scripting/API.
Your first (useful) script
In this tutorial we will be creating a script based on a suggestion by Eike Hein. In Eike’s words: “A quick use case question: For many years I’ve desired the behavior of disabling keep-above on a window with keep-above enabled when it is maximized, and re-enabling keep-above when it is restored. Is that be possible with kwin scripting? It’ll need the ability to trigger methods on state changes and store information above a specific window across those state changes, I guess.”
Other than the really function and useful script idea, what is really great about this is that it makes for a perfect tutorial example. I get to cover most of the important aspects of KWin scripting while at the same time creating something useful.
So let’s get on with it…
The basic outline
Design statement: For every window that is set to ‘Keep Above’ others, the window should not be above all windows when it is maximized.
To do so, this is how we’ll proceed:
- Create an array of clients whose ‘Keep Above’ property is set.
- Whenever a script loads, make a list of all clients whose ‘Keep Above’ property is set and add it to the array.
- Whenever a client is maximized, if it’s '‘Keep Above’ property is set, remove the ‘Keep Above’ property.
- Whenever a client is restored, if it is in the ‘array’, set it’s ‘Keep Above’ property.
- Whenever a new client is added, check and see if it needs to be added to the array (depending on whether it’s ‘Keep Above’ property is set or not).
The basic framework
So, for first steps, let us just create an array:
var ka_clients = new Array();
Now, we need to make a list of all available clients whose ‘Keep Above’ property is set. From the KWin API docs you can lookup the workspace.getAllClients() method:
Allow me to present a small primer on how to read the KWin API docs. Here, the first line mentions the method, which is ‘workspace.getAllClients’. The ‘ret’ specifies the type of value that will be returned by the method. Here, it says ret: Array(client), which means that an array of client objects will be returned. It takes one parameter desktop_no, which specifies which desktop to fetch the clients from. The rest is clear from the description itself. So, to check all the clients whose ‘Keep Above’ property is set, we will use the following piece of code:
var c = workspace.getAllClients();
for(var i=0; i<c.length; i++) {
if(c[i].keepAbove()) {
print(client.caption() + " (yes)");
}
}
Explanation:
- First, it gets a list of all clients available from all the desktops and stores it in a variable ‘c’.
- Then it loops over the entire array and checks for clients whose ‘keepAbove’ property is set. To do this, one can use the client.keepAbove method. It returns true if the given clients ‘Keep Above’ property is set.
- Then it simply prints the clients caption.
Here, every element of ‘c’ is an object of type ‘client’. Every ‘client’ object represents a window. Here is how my terminal looks after writing this script:
Now, what we need to do, is add every such client to the array ka_clients. So this is how our code will look:
var ka_clients = new Array();
var c = workspace.getAllClients();
for(var i=0; i<c.length; i++) {
if(c[i].keepAbove()) {
ka_clients[ka_clients.length] = c[i];
}
}
What ka_clients[ka_clients.length] does is append an element to that array.
Manage maximization for clients
Now that we have added it to an array, we need to make a provision that whenever the client is maximized, it’s ‘Keep Above’ property does not stay. So, we’ll modify the previous code a little:
function manageKeepAbove(type) {
if((type.h == 1) && (type.v == 1)) {
this.setKeepAbove(0);
}
}
for(var i=0; i<c.length; i++) {
if(c[i].keepAbove()) {
ka_clients[ka_clients.length] = c[i];
ka_clients.onMaximizeSet.connect(c[i], manageKeepAbove);
}
}
For all events, there are two ways to connect it:
object.event.connect(h_function);
object.event.connect(f_this, h_function);
In either case, h_function is called whenever the event occurs, but in the second case, the function’s ‘this’ object is set to f_this. We use the second way because as you can see, multiple clients connect to the same function. So whenever a function is called, how does it know which client it must handle? Hence, we must specify the object it must ‘act on’, or in the other words, it’s ‘this object’.
client.onMaximizeSet is an event whenever a client is maximized. There are two parameters while specifying a maximization: horizontal maximization and vertical maximization. The function is passed only one value which has two properties ‘h’ and ‘v’. It specifies in which direction the client occupied the workspace dimension. We want the property to be triggered only when the client is maximized in both the directions. Note here that it is not necessary to write a function of our own in the global scope since we can use anonymous functions also. However, we are writing a function in the global scope so that we can even disconnect this slot later if needed.
Save and run this script and see if it works as one would expect it to.
Managing clients whose properties which are dynamically set
At this point however, if you set the ‘Keep Above’ property for a client, its property won’t be removed on maximization. This is because currently we are only covering the clients which are already present. To cover clients whose property is set after a script has been loaded, we’ll use the event workspace.clientSetKeepAbove. What we’ll do is, for every client whose ‘Keep Above’ property is changed, we’ll add it to the array if it is set, and we’ll remove it from the array if it is unset. This is how we’ll proceed:
workspace.clientSetKeepAbove.connect(function(client, set) {
var found = ka_clients.indexOf(client);
if(set == 1) {
if(found == -1) {
ka_clients[ka_clients.length] = client;
client.maximizeSet.connect(client, manageKeepAbove);
}
} else if(set == 0) {
ka_clients.splice(found, 1);
client.maximizeSet.disconnect(manageKeepAbove);
}
});
Explanation:
- In the event handler for workspace.clientSetKeepAbove, we’ve used an anonymous function, as I mentioned was also possible previously. This is because we want this event handler to be alive throughout the execution of the script i.e. we don’t want to ever disconnect it. In such cases, anonymous functions can be used.
- Here, we simply check for a client. If its property was set, we add it to the array (if it isn’t already there) and it was unset, we remove it from the array (if it is there in the array).
- Also, whenever it is added to the array, we need to connect it’s maximizeSet event as we did previously.
- Do note that we also disconnect the function if the ‘Keep Above’ property was unset. To disconnect, we need to provide a function name. This is the reason why we wrote a named function in the global scope instead of an anonymous function.
One point to note there is that, the client object is merely a ‘wrapper’ for an actual Client object (in C++). So then how does the ‘==’ operator work for the same object that was wrapped separately (the == relation is used to lookup up a value using the Array.indexOf() method)? Even though the object they wrap is the same, shouldn’t their wrapper be different? The answer is no. A scripting object to a kwin scripting object follows a strict 1:1 relation. Just as a wrapper can be mapped to a client, a client can be mapped back to a unique wrapper. This is achieved using script caching, details for which are here. This is why the ‘==’ and the ‘!=’ operator can be used safely to check if two variables actually wrap the same object or not.
Restoring it all
Now the last and most important part of it all. Whenver the client is restored, we must set it’s ‘Keep Above’ property if it was set earlier. To do this, we must simply extend our manageKeepAbove code to handle this scenario. In case the client is not maximized both vertically and horizontally, we check if the client is in our ka_clients arrray and if it is, we set its ‘Keep Above’ property, otherwise we don’t bother:
function manageKeepAbove(client, h, v) {
if (h && v) {
// maximized
if (client.keepAbove) {
keepAboveMaximized[keepAboveMaximized.length] = client;
client.keepAbove = false;
}
} else {
// no longer maximized
var found = keepAboveMaximized.indexOf(client);
if (found != -1) {
client.keepAbove = true;
keepAboveMaximized.splice(found, 1);
}
}
}
In the end, our entire script looks like:
var keepAboveMaximized = new Array();
function manageKeepAbove(client, h, v) {
if (h && v) {
// maximized
if (client.keepAbove) {
keepAboveMaximized[keepAboveMaximized.length] = client;
client.keepAbove = false;
}
} else {
// no longer maximized
var found = keepAboveMaximized.indexOf(client);
if (found != -1) {
client.keepAbove = true;
keepAboveMaximized.splice(found, 1);
}
}
}
workspace.clientMaximizeSet.connect(manageKeepAbove);
The script in Plasma Package structure can be found in the kde-examples repository.