Difference between revisions of "Development/Tutorials/KDE2/Extending the KDE Panel"

Jump to: navigation, search
(it's KDE2 stuff)
m (Text replace - "</code>" to "</syntaxhighlight>")
 
(5 intermediate revisions by 2 users not shown)
Line 6: Line 6:
 
Panel applets are small applications living inside the panel. Available applets range from desktop pagers and task bars to little games or other toys. In contrast to applets the panel extension API is an interface for extensions living outside of the panel, in the window manager dock area (as defined in the  [http://www.freedesktop.org/standards/wm-spec.html freedesktop.org window manager specifications] and are managed by the panel. Examples for panel extensions are the external task bar and the dock application bar which adds support for [http://www.windowmaker.org Window Maker] applets and other applications using the standard X11 docking mechanism to kicker.
 
Panel applets are small applications living inside the panel. Available applets range from desktop pagers and task bars to little games or other toys. In contrast to applets the panel extension API is an interface for extensions living outside of the panel, in the window manager dock area (as defined in the  [http://www.freedesktop.org/standards/wm-spec.html freedesktop.org window manager specifications] and are managed by the panel. Examples for panel extensions are the external task bar and the dock application bar which adds support for [http://www.windowmaker.org Window Maker] applets and other applications using the standard X11 docking mechanism to kicker.
  
Starting with a short technology overview this tutorial discusses the implementation of a simple panel applet. Both the applet and extension APIs are simple. This qualifies writing a panel applet as a suitable task for an introduction to KDE programming. This tutorial presumes that the reader has some basic C++ and Qt knowledge. You can find a basic Qt tutorial at:  [http://doc.trolltech.com/tutorial.html http://doc.trolltech.com/tutorial.html]
+
Starting with a short technology overview this tutorial discusses the implementation of a simple panel applet. Both the applet and extension APIs are simple. This qualifies writing a panel applet as a suitable task for an introduction to KDE programming. This tutorial presumes that the reader has some basic C++ and Qt knowledge. You can also start with [http://doc.trolltech.com/2.3/tutorial.html a basic Qt2 tutorial].
  
 
== Overview ==
 
== Overview ==
Line 23: Line 23:
  
 
=== HelloWorldApplet class declaration ===
 
=== HelloWorldApplet class declaration ===
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt" line>
 
class HelloWorldApplet : public KPanelApplet
 
class HelloWorldApplet : public KPanelApplet
 
{
 
{
Line 39: Line 39:
  
 
};
 
};
</code>
+
</syntaxhighlight>
  
 
Having a look at {{path|kpanelapplet.h}} see that all we do is re-implement the constant virtual functions int widthForHeight(int) and heightForWidth(int) Playing around with kicker you may notice that you can arrange the panel either horizontally or vertically at the desktop borders. You will also notice that there is a fixed set of panel sizes (representing panel height for horizontal panels and width for vertical panels) to choose from.
 
Having a look at {{path|kpanelapplet.h}} see that all we do is re-implement the constant virtual functions int widthForHeight(int) and heightForWidth(int) Playing around with kicker you may notice that you can arrange the panel either horizontally or vertically at the desktop borders. You will also notice that there is a fixed set of panel sizes (representing panel height for horizontal panels and width for vertical panels) to choose from.
Line 48: Line 48:
  
 
=== HelloWorldApplet class implementation ===
 
=== HelloWorldApplet class implementation ===
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt" line>
 
HelloWorldApplet::HelloWorldApplet( const QString& configFile,
 
HelloWorldApplet::HelloWorldApplet( const QString& configFile,
 
                                   Type type, int actions,
 
                                   Type type, int actions,
Line 70: Line 70:
 
   return w; // we want to be quadratic
 
   return w; // we want to be quadratic
 
}
 
}
</code>
+
</syntaxhighlight>
 
Our constructor simply passes its default arguments to the KPanelApplet constructor, sets the frame style to StyledPanel Sunken (see {{path|qframe.h}}) and sets the background color of the applet to blue so we recognize it later running in the panel. Both widthForHeight() and heightForHeight() are implemented to choose a quadratic geometry for the applet. Thus we expect our applet to show up as a sunken blue square on the panel when run.
 
Our constructor simply passes its default arguments to the KPanelApplet constructor, sets the frame style to StyledPanel Sunken (see {{path|qframe.h}}) and sets the background color of the applet to blue so we recognize it later running in the panel. Both widthForHeight() and heightForHeight() are implemented to choose a quadratic geometry for the applet. Thus we expect our applet to show up as a sunken blue square on the panel when run.
  
Line 77: Line 77:
  
 
=== The factory function ===
 
=== The factory function ===
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt" line>
 
extern "C"  
 
extern "C"  
 
{
 
{
Line 88: Line 88:
 
   }
 
   }
 
}
 
}
</code>
+
</syntaxhighlight>
  
 
The factory function is mostly copy&paste work where you would replace "helloworldapplet" with "myapplet" to adjust it to your custom applet. {{note|Don't change the factory function's signature or the panel will fail to load your applet. After adding the factory function, we are done with the code part and only the description file and the Makefile.am remain to be written.}}
 
The factory function is mostly copy&paste work where you would replace "helloworldapplet" with "myapplet" to adjust it to your custom applet. {{note|Don't change the factory function's signature or the panel will fail to load your applet. After adding the factory function, we are done with the code part and only the description file and the Makefile.am remain to be written.}}
  
 
=== The description file: helloworldapplet.desktop ===
 
=== The description file: helloworldapplet.desktop ===
<code ini>
+
<syntaxhighlight lang="ini">
 
[Desktop Entry]  
 
[Desktop Entry]  
 
Name = Hello World
 
Name = Hello World
Line 99: Line 99:
 
X-KDE-Library = libhelloworldapplet
 
X-KDE-Library = libhelloworldapplet
 
X-KDE-UniqueApplet = true
 
X-KDE-UniqueApplet = true
</code>
+
</syntaxhighlight>
  
 
Besides standard {{path|.desktop}} file keys like "Name", "Comment" and "Icon" there are two panel applet specific keys:
 
Besides standard {{path|.desktop}} file keys like "Name", "Comment" and "Icon" there are two panel applet specific keys:
Line 122: Line 122:
  
 
=== The automake input file: Makefile.am ===
 
=== The automake input file: Makefile.am ===
<code>
+
<syntaxhighlight lang="text">
 
INCLUDES = $(all_includes)  
 
INCLUDES = $(all_includes)  
  
Line 146: Line 146:
 
messages:
 
messages:
 
       $(XGETTEXT) *.cpp *.h -o $(podir)/helloworldapplet.pot
 
       $(XGETTEXT) *.cpp *.h -o $(podir)/helloworldapplet.pot
</code>
+
</syntaxhighlight>
 
Explaining the details of this particular automake input file and the KDE build system in general is not the goal of this tutorial. So to adjust it to your applet project simply replace all occurrences of "helloworldapplet" with "myapplet".
 
Explaining the details of this particular automake input file and the KDE build system in general is not the goal of this tutorial. So to adjust it to your applet project simply replace all occurrences of "helloworldapplet" with "myapplet".
  
 
=== Building and installing ===
 
=== Building and installing ===
 
You can download a complete helloworldapplet.tar.gz tarball here: [http://developer.kde.org/documentation/tutorials/dot/khelloworldapplet.tar.gz khelloworldapplet.tar.gz] (308 kB), which in addition to the four files mentioned above contains the automake/autoconf magic of the KDE build system. It's convenient to base your own panel applets on as the build system magic is already in place. Untar it, change into the untarred directory and build and install it with:
 
You can download a complete helloworldapplet.tar.gz tarball here: [http://developer.kde.org/documentation/tutorials/dot/khelloworldapplet.tar.gz khelloworldapplet.tar.gz] (308 kB), which in addition to the four files mentioned above contains the automake/autoconf magic of the KDE build system. It's convenient to base your own panel applets on as the build system magic is already in place. Untar it, change into the untarred directory and build and install it with:
<code>
+
<syntaxhighlight lang="text">
 
./configure -prefix=<your-kde-dir>  
 
./configure -prefix=<your-kde-dir>  
 
make
 
make
 
su -c 'make install'
 
su -c 'make install'
</code>
+
</syntaxhighlight>
  
 
=== Hello world! ===
 
=== Hello world! ===
Line 163: Line 163:
 
Searching for a panel applet suitable for this tutorial I stumbled over a screenshot of an applet implementation of the old fifteen pieces game for another desktop environment. While it's more a toy than of any real use it is simple and fast to implement and thus perfect for a tutorial. I'm sure you know the fifteen pieces game with the goal to put fifteen sliding pieces into numerical oder. The idea of the game is that on a 4x4 cell quadratic game board fifteen numbered (1 to 15) quadratic pieces must be put into numerical order while pieces can only be moved horizontally or vertically and with only one free cell to perform move operations on.
 
Searching for a panel applet suitable for this tutorial I stumbled over a screenshot of an applet implementation of the old fifteen pieces game for another desktop environment. While it's more a toy than of any real use it is simple and fast to implement and thus perfect for a tutorial. I'm sure you know the fifteen pieces game with the goal to put fifteen sliding pieces into numerical oder. The idea of the game is that on a 4x4 cell quadratic game board fifteen numbered (1 to 15) quadratic pieces must be put into numerical order while pieces can only be moved horizontally or vertically and with only one free cell to perform move operations on.
  
We are going to use a customized {{qt|QTableView}} widget for the game board. Similar to the hello world applet our little project will consist of three files, {{path|fiftenapplet.cpp}}, {{path|fifteenapplet.h}}, {{path|fifteenapplet.desktop}} and the {{path|Makefile.am}} file.
+
We are going to use a customized {{qt2|QTableView}} widget for the game board. Similar to the hello world applet our little project will consist of three files, {{path|fiftenapplet.cpp}}, {{path|fifteenapplet.h}}, {{path|fifteenapplet.desktop}} and the {{path|Makefile.am}} file.
  
 
{{path|fifteenapplet.h}} contains the declaration of FifteenApplet, the class inheriting from KPanelApplet :
 
{{path|fifteenapplet.h}} contains the declaration of FifteenApplet, the class inheriting from KPanelApplet :
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt" line>
 
class FifteenApplet : public KPanelApplet  
 
class FifteenApplet : public KPanelApplet  
 
{
 
{
Line 189: Line 189:
  
 
};
 
};
</code>
+
</syntaxhighlight>
 
While it is very similar to the declaration of HelloWorldApplet, we have added a reimplementation of void about() (as defined in {{path|kpanelapplet.h}}) and private pointers for our game board class and a KAboutData object (see {{path|kdelibs/kdecore/kaboutdata.h}}) used to build an about dialog from.
 
While it is very similar to the declaration of HelloWorldApplet, we have added a reimplementation of void about() (as defined in {{path|kpanelapplet.h}}) and private pointers for our game board class and a KAboutData object (see {{path|kdelibs/kdecore/kaboutdata.h}}) used to build an about dialog from.
  
Line 195: Line 195:
  
 
The second class declared in {{path|fifteenapplet.h}} is our game board inheriting from QTableView :
 
The second class declared in {{path|fifteenapplet.h}} is our game board inheriting from QTableView :
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt" line>
 
class PiecesTable : public QTableView  
 
class PiecesTable : public QTableView  
 
{
 
{
Line 237: Line 237:
  
 
};
 
};
</code>
+
</syntaxhighlight>
 
I'm going to explain the details of this class below by means of the class implementation.
 
I'm going to explain the details of this class below by means of the class implementation.
  
 
The factory function is very similar to the one of the helloworld applet with all occurrences of "helloworldapplet" replaced with "fifteenapplet". The second difference you might notice is that we pass KPanelApplet::About as the third parameter of the FifteenApplet constructor to make sure the "About" context menu entry will be there:
 
The factory function is very similar to the one of the helloworld applet with all occurrences of "helloworldapplet" replaced with "fifteenapplet". The second difference you might notice is that we pass KPanelApplet::About as the third parameter of the FifteenApplet constructor to make sure the "About" context menu entry will be there:
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt" line>
 
extern "C"  
 
extern "C"  
 
{
 
{
Line 252: Line 252:
 
   }
 
   }
 
}
 
}
</code>
+
</syntaxhighlight>
 
The implementation of the FifteenApplet class is very short as the game board class will handle all the drawing and game logic.
 
The implementation of the FifteenApplet class is very short as the game board class will handle all the drawing and game logic.
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt" line>
 
FifteenApplet::FifteenApplet(const QString& configFile, Type type, int actions,
 
FifteenApplet::FifteenApplet(const QString& configFile, Type type, int actions,
 
                           QWidget *parent, const char *name)
 
                           QWidget *parent, const char *name)
Line 272: Line 272:
 
   srand(time(0));
 
   srand(time(0));
 
}
 
}
</code>
+
</syntaxhighlight>
 
The constructor creates an instance of our game board class and places it into a simple layout object to resize it to the full applet size every time the applet itself is resized. srandom is used to initialize the random number generator with the current time in seconds (see the man pages of srandom and random) as seed.
 
The constructor creates an instance of our game board class and places it into a simple layout object to resize it to the full applet size every time the applet itself is resized. srandom is used to initialize the random number generator with the current time in seconds (see the man pages of srandom and random) as seed.
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt" line>
 
int FifteenApplet::widthForHeight(int h) const  
 
int FifteenApplet::widthForHeight(int h) const  
 
{
 
{
Line 284: Line 284:
 
   return w; // we want to be quadratic
 
   return w; // we want to be quadratic
 
}
 
}
</code>
+
</syntaxhighlight>
 
Similar to the hello world applet the fifteen pieces applet will have a quadratic shape.
 
Similar to the hello world applet the fifteen pieces applet will have a quadratic shape.
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt" line>
 
void FifteenApplet::about()  
 
void FifteenApplet::about()  
 
{
 
{
Line 304: Line 304:
 
   dialog.show();
 
   dialog.show();
 
}
 
}
</code>
+
</syntaxhighlight>
 
The implementation of the void about() action handler we reimplement from KPanelApplet creates a KAboutData object (see {{path|kdelibs/kdecore/kaboutdata.h}}) and makes use of KAboutApplication (see {{path|kdelibs/kdeui.kaboutapplication.h}}) to display a nice about dialog when the user selects "About" from the applet's context menu.
 
The implementation of the void about() action handler we reimplement from KPanelApplet creates a KAboutData object (see {{path|kdelibs/kdecore/kaboutdata.h}}) and makes use of KAboutApplication (see {{path|kdelibs/kdeui.kaboutapplication.h}}) to display a nice about dialog when the user selects "About" from the applet's context menu.
  
Line 311: Line 311:
  
 
Now let's have a look at the implementation of the game board class called PiecesTable As it inherits from QTableView you might want to have a look at the description of this abstract base class for tables in the excellent Qt documentation:  [http://doc.trolltech.com/qtableview.html#details http://doc.trolltech.com/qtableview.html#details]
 
Now let's have a look at the implementation of the game board class called PiecesTable As it inherits from QTableView you might want to have a look at the description of this abstract base class for tables in the excellent Qt documentation:  [http://doc.trolltech.com/qtableview.html#details http://doc.trolltech.com/qtableview.html#details]
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt" line>
 
PiecesTable::PiecesTable(QWidget* parent, const char* name )
 
PiecesTable::PiecesTable(QWidget* parent, const char* name )
 
   : QTableView(parent, name), _menu(0), _activeRow(-1),  
 
   : QTableView(parent, name), _menu(0), _activeRow(-1),  
Line 335: Line 335:
 
   initColors();
 
   initColors();
 
}
 
}
</code>
+
</syntaxhighlight>
 
The constructor initializes a few member variables used by the game board, sets up the frame style of the table ( QTableView inherits from QFrame ), sets the background mode to NoBackground (we do this to avoid flicker), enables mouse tracking for the widget and configures the number of rows and columns of the table. We also call two protected initialization functions we have defined in PiecesTable to set up two arrays, one (array of ints) used to represent the game board and another (array of QColor ) where we store color values for the 15 pieces.
 
The constructor initializes a few member variables used by the game board, sets up the frame style of the table ( QTableView inherits from QFrame ), sets the background mode to NoBackground (we do this to avoid flicker), enables mouse tracking for the widget and configures the number of rows and columns of the table. We also call two protected initialization functions we have defined in PiecesTable to set up two arrays, one (array of ints) used to represent the game board and another (array of QColor ) where we store color values for the 15 pieces.
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt" line>
 
void PiecesTable::initMap()  
 
void PiecesTable::initMap()  
 
{
 
{
Line 347: Line 347:
 
   _randomized = false;
 
   _randomized = false;
 
}
 
}
</code>
+
</syntaxhighlight>
 
initMap() resizes the QArray<int> we use to represent the game board to 16 (4x4 fields on the board) and initializes it with the values one to fifteen.
 
initMap() resizes the QArray<int> we use to represent the game board to 16 (4x4 fields on the board) and initializes it with the values one to fifteen.
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt" line>
 
void PiecesTable::initColors()  
 
void PiecesTable::initColors()  
 
{
 
{
Line 358: Line 358:
 
           _colors[c + r *numCols()] = QColor(255 - 70 * c,255 - 70 * r, 150);
 
           _colors[c + r *numCols()] = QColor(255 - 70 * c,255 - 70 * r, 150);
 
}
 
}
</code>
+
</syntaxhighlight>
 
initColors() is similar but calculates different color values for each piece to increase the eye candy effect of our applet.
 
initColors() is similar but calculates different color values for each piece to increase the eye candy effect of our applet.
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt" line>
 
void PiecesTable::paintCell(QPainter *p, int row, int col)
 
void PiecesTable::paintCell(QPainter *p, int row, int col)
 
{
 
{
Line 416: Line 416:
 
               QString::number(number));
 
               QString::number(number));
 
}
 
}
</code>
+
</syntaxhighlight>
We have reimplemented void paintCell() from QTableView to actually paint the table cells, which on our game board represent sliding pieces, when the widgets receives a paint event. The function is a bit to long to explain in all detail but is quite easy to understand looking up calls you are unsure about in the Qt documentation for {{qt3|QPainter}} and {{qt3|QTableView}}
+
We have reimplemented void paintCell() from QTableView to actually paint the table cells, which on our game board represent sliding pieces, when the widgets receives a paint event. The function is a bit to long to explain in all detail but is quite easy to understand looking up calls you are unsure about in the Qt documentation for {{qt2|QPainter}} and {{qt2|QTableView}}
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt" line>
 
void PiecesTable::resizeEvent(QResizeEvent *e)  
 
void PiecesTable::resizeEvent(QResizeEvent *e)  
 
{
 
{
Line 446: Line 446:
  
 
}
 
}
</code>
+
</syntaxhighlight>
 
We also reimplement the resizeEvent() action handler of the QTableView widgets to adjust the game board according to the geometry we are resized to by the panel. You remember that the panel and thus also the applets can have different sizes and what we do in the resizeEvent is to adjust the font size used to draw on the widget (and thus used in the paintEvent to draw the piece numbers) to the widget size to increase readability on small panels. We furthermore set the cell width and height according to the widget geometry. The algorithm is simple as all cells (pieces) on our game board have the same size.
 
We also reimplement the resizeEvent() action handler of the QTableView widgets to adjust the game board according to the geometry we are resized to by the panel. You remember that the panel and thus also the applets can have different sizes and what we do in the resizeEvent is to adjust the font size used to draw on the widget (and thus used in the paintEvent to draw the piece numbers) to the widget size to increase readability on small panels. We furthermore set the cell width and height according to the widget geometry. The algorithm is simple as all cells (pieces) on our game board have the same size.
  
 
For some extra eye candy we reimplement the mouseMoveEvent() action handler of the game board widget to highlight the cell (piece) under the mouse cursor if the mouse is moved over the board:
 
For some extra eye candy we reimplement the mouseMoveEvent() action handler of the game board widget to highlight the cell (piece) under the mouse cursor if the mouse is moved over the board:
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt" line>
 
void PiecesTable::mouseMoveEvent(QMouseEvent* e)  
 
void PiecesTable::mouseMoveEvent(QMouseEvent* e)  
 
{
 
{
Line 482: Line 482:
 
   updateCell(row, col, false);
 
   updateCell(row, col, false);
 
}
 
}
</code>
+
</syntaxhighlight>
 
We are done now with drawing the game board and adjusting its size to game board geometry. While the applet already looks nice it is not of much use without the game logic for moving pieces around in place.
 
We are done now with drawing the game board and adjusting its size to game board geometry. While the applet already looks nice it is not of much use without the game logic for moving pieces around in place.
  
Line 489: Line 489:
  
 
As the idea of the game is to put randomized pieces in numerical order, we first implement a helper function used to randomize the arrangement of the pieces on the game board:
 
As the idea of the game is to put randomized pieces in numerical order, we first implement a helper function used to randomize the arrangement of the pieces on the game board:
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt" line>
 
void PiecesTable::randomizeMap()  
 
void PiecesTable::randomizeMap()  
 
{
 
{
Line 515: Line 515:
 
   _randomized = true;
 
   _randomized = true;
 
}
 
}
</code>
+
</syntaxhighlight>
 
We need a second helper function to be called after each move operation to check whether the player won with the previous move and to display a message box in case of victory. You may have notice the _randomized member variable in the functions above and from the code in checkwin() you see that it is used to make sure that we trigger the "You win!" message box only if the player actually did randomize the game board before putting it into numerical order.
 
We need a second helper function to be called after each move operation to check whether the player won with the previous move and to display a message box in case of victory. You may have notice the _randomized member variable in the functions above and from the code in checkwin() you see that it is used to make sure that we trigger the "You win!" message box only if the player actually did randomize the game board before putting it into numerical order.
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt" line>
 
void PiecesTable::checkwin()  
 
void PiecesTable::checkwin()  
 
{
 
{
Line 534: Line 534:
  
 
}
 
}
</code>
+
</syntaxhighlight>
 
Move operations are triggered by the player clicking on one of the sliding pieces. We reimplement the mousePressEvent() handler of the game board widgets to handle mouse clicks on the board. Right mouse button clicks trigger an additional context menu with actions to randomize or reset the game board. A left mouse button click triggers the game logic which is pretty simple if you take 5 minutes to think about it. You should be able to understand the details reading the numerous comments in the code:
 
Move operations are triggered by the player clicking on one of the sliding pieces. We reimplement the mousePressEvent() handler of the game board widgets to handle mouse clicks on the board. Right mouse button clicks trigger an additional context menu with actions to randomize or reset the game board. A left mouse button click triggers the game logic which is pretty simple if you take 5 minutes to think about it. You should be able to understand the details reading the numerous comments in the code:
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt" line>
 
void PiecesTable::mousePressEvent(QMouseEvent* e)
 
void PiecesTable::mousePressEvent(QMouseEvent* e)
 
{
 
{
Line 666: Line 666:
 
   }
 
   }
 
}
 
}
</code>
+
</syntaxhighlight>
 
Ok, we are done, now either download and modify modify [http://developer.kde.org/documentation/tutorials/dot/khelloworldapplet.tar.gz khelloworldapplet.tar.gz] (308 kB) as described above or download [http://developer.kde.org/documentation/tutorials/dot/kfifteenapplet-1.0.tar.gz kfifteenapplet-1.0.tar.gz] (311 kB) to try the applet. I'm quite sure that you will agree that while the fifteen pieces applet is more or less useless it's a nifty toy to waste your time playing around with. You are good if you manage to figure out the basic move patterns used to win basically every game in less than 10min. ;-)
 
Ok, we are done, now either download and modify modify [http://developer.kde.org/documentation/tutorials/dot/khelloworldapplet.tar.gz khelloworldapplet.tar.gz] (308 kB) as described above or download [http://developer.kde.org/documentation/tutorials/dot/kfifteenapplet-1.0.tar.gz kfifteenapplet-1.0.tar.gz] (311 kB) to try the applet. I'm quite sure that you will agree that while the fifteen pieces applet is more or less useless it's a nifty toy to waste your time playing around with. You are good if you manage to figure out the basic move patterns used to win basically every game in less than 10min. ;-)
  

Latest revision as of 21:52, 29 June 2011

Contents

[edit] Introduction

The KDE panel (below referred to as "kicker") has been rewritten from scratch for KDE 2.0 and one of the main goals of the rewrite was to increase extensibility. For this reason with KDE 2.0 an API for panel applets has been introduced followed by an API for panel extension introduced with the KDE 2.1 release. Panel applets and extensions are simply referred to as "plugins" in the following paragraphs.

Panel applets are small applications living inside the panel. Available applets range from desktop pagers and task bars to little games or other toys. In contrast to applets the panel extension API is an interface for extensions living outside of the panel, in the window manager dock area (as defined in the freedesktop.org window manager specifications and are managed by the panel. Examples for panel extensions are the external task bar and the dock application bar which adds support for Window Maker applets and other applications using the standard X11 docking mechanism to kicker.

Starting with a short technology overview this tutorial discusses the implementation of a simple panel applet. Both the applet and extension APIs are simple. This qualifies writing a panel applet as a suitable task for an introduction to KDE programming. This tutorial presumes that the reader has some basic C++ and Qt knowledge. You can also start with a basic Qt2 tutorial.

[edit] Overview

Panel plugins are implemented as DSO s (Dynamic Shared Objects). The panel locates available applets by searching for applet description files in (ALL_KDEDIRS)/share/apps/kicker/applets. Every plugin must install a description file to be recognized by the panel. Available panel extensions are located by searching (A_KDEDIR)/share/apps/kicker/extensions for similar description files.

Implementing a panel applet is as easy as inheriting from the base class KPanelApplet (declared in kdelibs/kdeui/kpanelapplet.h), providing a factory function and installing the description file mentioned above. For extensions the respective base class is KPanelExtension, declared in kdelibs/kdeui/kpanelextension.h.

While plugins are implemented as shared libraries and thus loaded into the panel's address space, for security and stability reasons kicker also implements loading of plugins via external proxy processes called appletproxy and extensionproxy. The loading behavior is user configurable via kcontrol, with the obvious benefit that users may configure their panel to load untrusted third party plugins via the proxies to avoid buggy plugins taking the whole panel down with them.

While as an plugin author you don't have to be concerned about these implementation details it is good to know what happens behind the scenes. Therefore I might mention here that the panel communicates with the proxies via the DCOP protocol (see kdelibs/dcop) and makes use of QXEmbed (see kdelibs/kdeui/qxembed.h) to embed external (loaded via one of the two proxies) plugins into the panel.

[edit] A hello world panel applet

We start with a hello world panel applet that can be implemented in only a few lines of code and is a good base upon which to build a more complex applet. As already mentioned in the overview section all that needs to be done is inheriting from KPanelApplet, providing a factory function and a .desktop description file.

Our little project consists of four files: helloworldapplet.h containing the class declaration, helloworldapplet.cpp containing the class implementation and the factory function, helloworldapplet.desktop the description file and Makefile.am as input for the automake/autoconf KDE build system.

[edit] HelloWorldApplet class declaration

  1. class HelloWorldApplet : public KPanelApplet
  2. {
  3.   Q_OBJECT
  4.  
  5. public:
  6.  
  7.   HelloWorldApplet( const QString& configFile, Type t = Stretch, 
  8.                     int actions = 0, QWidget *parent = 0, 
  9.                     const char *name = 0 );
  10.  
  11.   int widthForHeight( int height ) const;
  12.  
  13.   int heightForWidth( int width ) const;
  14.  
  15. };

Having a look at kpanelapplet.h see that all we do is re-implement the constant virtual functions int widthForHeight(int) and heightForWidth(int) Playing around with kicker you may notice that you can arrange the panel either horizontally or vertically at the desktop borders. You will also notice that there is a fixed set of panel sizes (representing panel height for horizontal panels and width for vertical panels) to choose from.

The concept of panel applets is that one size component is dictated by the panel while the other one is free for the applet to choose. On horizontal panels the applet's height is fixed according to the panel height while the applet is free to choose its width. Respectively on vertical panels the applet's height is fixed while it is free to choose its height.

Every panel applet should be prepared to be used both on horizontal and vertical panels. The panel uses the two functions we are re-implementing for the HelloWorldApplet to query the applet's preferred size. A horizontal panel will call widthForHeight() while a vertical panel will call heightForWidth() to query the free size component of the applet. Applets are guaranteed to be resized according to the size they request.

[edit] HelloWorldApplet class implementation

  1. HelloWorldApplet::HelloWorldApplet( const QString& configFile,
  2.                                   Type type, int actions,
  3.                                   QWidget *parent, const char *name )
  4.  
  5.   : KPanelApplet( configFile, type, actions, parent, name )
  6.  
  7. {
  8.   setBackgroundColor( blue );
  9.  
  10.   setFrameStyle( StyledPanel | Sunken );
  11. }
  12.  
  13. int HelloWorldApplet::widthForHeight( int h ) const
  14. {
  15.   return h; // we want to be quadratic
  16. }
  17.  
  18. int HelloWorldApplet::heightForWidth( int w ) const
  19. {
  20.   return w; // we want to be quadratic
  21. }

Our constructor simply passes its default arguments to the KPanelApplet constructor, sets the frame style to StyledPanel Sunken (see qframe.h) and sets the background color of the applet to blue so we recognize it later running in the panel. Both widthForHeight() and heightForHeight() are implemented to choose a quadratic geometry for the applet. Thus we expect our applet to show up as a sunken blue square on the panel when run.

[edit] Screenshot of 'Hello, World!' applet

Helloworld applet.png

[edit] The factory function

  1. extern "C" 
  2. {
  3.   KPanelApplet* init( QWidget *parent, const QString& configFile )
  4.   {
  5.       KGlobal::locale()->insertCatalogue( "helloworldapplet");
  6.  
  7.       return new HelloWorldApplet( configFile, KPanelApplet::Normal,
  8.                                    0, parent, "helloworldapplet");
  9.   }
  10. }
The factory function is mostly copy&paste work where you would replace "helloworldapplet" with "myapplet" to adjust it to your custom applet.
noframe
 
Note
Don't change the factory function's signature or the panel will fail to load your applet. After adding the factory function, we are done with the code part and only the description file and the Makefile.am remain to be written.

[edit] The description file: helloworldapplet.desktop

[Desktop Entry] 
Name = Hello World
Comment = Hello World Applet
X-KDE-Library = libhelloworldapplet
X-KDE-UniqueApplet = true

Besides standard .desktop file keys like "Name", "Comment" and "Icon" there are two panel applet specific keys:

X-KDE-Library
is used by the panel to locate the applet DSO (Dynamic Shared Object)

Example: X-KDE-Library=libexampleapplet

X-KDE-UniqueApplet
Similar to KApplication and KUniqueApplication there are two types of panel applets. Use unique applets when it makes no sense to run more than one instance of an applet in the panel. A good example for unique applets is the taskbar applet. Use normal applets when you need instance specific configuration. An example is the koolclock applet where you might want to run two instances in your panel, one configured as analog clock, the other one as digital clock. X-KDE-UniqueApplet is a boolean key which defaults to "false".

Example: X-KDE-UniqueApplet=true

The following conventions are used for the applet

DSOs:
Name
libappletnameapplet.la
LDFLAGS
-module -no-undefined

[edit] The automake input file: Makefile.am

INCLUDES = $(all_includes) 
 
lib_LTLIBRARIES = libhelloworldapplet.la
 
libhelloworldapplet_la_SOURCES = helloworldapplet.cpp
 
METASOURCES = AUTO
 
noinst_HEADERS = helloworldapplet.h
 
lnkdir = $(kde_datadir)/kicker/applets
 
lnk_DATA = helloworldapplet.desktop
 
EXTRA_DIST = $(lnk_DATA)
 
libhelloworldapplet_la_LDFLAGS = $(all_libraries) -version-info 1:0:0 -module \
                               -no-undefined
 
libhelloworldapplet_la_LIBADD = $(LIB_KDEUI)
 
messages:
      $(XGETTEXT) *.cpp *.h -o $(podir)/helloworldapplet.pot

Explaining the details of this particular automake input file and the KDE build system in general is not the goal of this tutorial. So to adjust it to your applet project simply replace all occurrences of "helloworldapplet" with "myapplet".

[edit] Building and installing

You can download a complete helloworldapplet.tar.gz tarball here: khelloworldapplet.tar.gz (308 kB), which in addition to the four files mentioned above contains the automake/autoconf magic of the KDE build system. It's convenient to base your own panel applets on as the build system magic is already in place. Untar it, change into the untarred directory and build and install it with:

./configure -prefix=<your-kde-dir> 
make
su -c 'make install'

[edit] Hello world!

Now that your applet is installed and the description file in place, a "Hello World" entry will show up in the Add-Applet sub menu of the panel menu. Select the "Hello World" entry and you will see our blue sunken quadratic panel applet show up in the panel. You will also notice a small grey handle on the left side of the applet. Use the right mouse button context menu of the applet handle to move or remove the applet. You can also move applets by dragging the handle.

[edit] Fifteen pieces panel applet

Searching for a panel applet suitable for this tutorial I stumbled over a screenshot of an applet implementation of the old fifteen pieces game for another desktop environment. While it's more a toy than of any real use it is simple and fast to implement and thus perfect for a tutorial. I'm sure you know the fifteen pieces game with the goal to put fifteen sliding pieces into numerical oder. The idea of the game is that on a 4x4 cell quadratic game board fifteen numbered (1 to 15) quadratic pieces must be put into numerical order while pieces can only be moved horizontally or vertically and with only one free cell to perform move operations on.

We are going to use a customized QTableView widget for the game board. Similar to the hello world applet our little project will consist of three files, fiftenapplet.cpp, fifteenapplet.h, fifteenapplet.desktop and the Makefile.am file.

fifteenapplet.h contains the declaration of FifteenApplet, the class inheriting from KPanelApplet :

  1. class FifteenApplet : public KPanelApplet 
  2. {
  3.   Q_OBJECT
  4.  
  5. public:
  6.  
  7.   FifteenApplet(const QString& configFile, Type t = Stretch,
  8.                 int actions = 0,
  9.                 QWidget *parent = 0, const char *name = 0);
  10.  
  11.   int widthForHeight(int height) const;
  12.  
  13.   int heightForWidth(int width) const;
  14.  
  15.   void about();
  16.  
  17. private:
  18.  
  19.   PiecesTable *_table;
  20.   KAboutData  *_aboutData;
  21.  
  22. };

While it is very similar to the declaration of HelloWorldApplet, we have added a reimplementation of void about() (as defined in kpanelapplet.h) and private pointers for our game board class and a KAboutData object (see kdelibs/kdecore/kaboutdata.h) used to build an about dialog from.

Searching for void about() in the KPanelApplet class declaration you will find two similar protected functions void help() and void preferences() In the right mouse button context menu of some applets you find in addition to the already mentioned "Move" and "Remove" entries, entries called "About", "Help" and "Preferences". The three protected functions are action handlers called when a user selects "About", "Help" or "Preferences" from the applets context menu. You have to reimplement them in your applet class to handle them. Not every applet implements for example the "Preferences" action because it might not have any preferences to configure. To avoid unused menu actions in the applet's context menu, kicker will only display those that you configure it to do by passing the according actions you reimplement or'ed together as the third parameter of the applet's class constructor.

The second class declared in fifteenapplet.h is our game board inheriting from QTableView :

  1. class PiecesTable : public QTableView 
  2. {
  3.   Q_OBJECT
  4.  
  5. public:
  6.  
  7.   PiecesTable(QWidget* parent = 0, const char* name = 0);
  8.  
  9. protected:
  10.  
  11.   void resizeEvent(QResizeEvent*);
  12.  
  13.   void mousePressEvent(QMouseEvent*);
  14.  
  15.   void mouseMoveEvent(QMouseEvent*);
  16.  
  17.   void paintCell(QPainter *, int row, int col);
  18.  
  19.   void initMap();
  20.  
  21.   void initColors();
  22.  
  23.   void randomizeMap();
  24.  
  25.   void checkwin();
  26.  
  27. private:
  28.  
  29.   QArray<int>     _map;
  30.  
  31.   QArray<QColor>  _colors;
  32.  
  33.   QPopupMenu     *_menu;
  34.  
  35.   int             _activeRow, _activeCol;
  36.  
  37.   bool            _randomized;
  38.  
  39.   enum MenuOp { mRandomize = 1, mReset = 2 };
  40.  
  41. };

I'm going to explain the details of this class below by means of the class implementation.

The factory function is very similar to the one of the helloworld applet with all occurrences of "helloworldapplet" replaced with "fifteenapplet". The second difference you might notice is that we pass KPanelApplet::About as the third parameter of the FifteenApplet constructor to make sure the "About" context menu entry will be there:

  1. extern "C" 
  2. {
  3.   KPanelApplet* init(QWidget *parent, const QString& configFile)
  4.   {
  5.       KGlobal::locale()->insertCatalogue("kfifteenapplet");
  6.  
  7.       return new FifteenApplet(configFile, KPanelApplet::Normal,
  8.                                KPanelApplet::About, parent, "kfifteenapplet");
  9.   }
  10. }

The implementation of the FifteenApplet class is very short as the game board class will handle all the drawing and game logic.

  1. FifteenApplet::FifteenApplet(const QString& configFile, Type type, int actions,
  2.                            QWidget *parent, const char *name)
  3.  
  4.   : KPanelApplet(configFile, type, actions, parent, name), _aboutData(0)
  5. {
  6.   // setup table
  7.  
  8.   _table = new PiecesTable(this);
  9.  
  10.   // setup layout
  11.  
  12.   QHBoxLayout *_layout = new QHBoxLayout(this);
  13.  
  14.   _layout->add(_table);
  15.  
  16.   srand(time(0));
  17. }

The constructor creates an instance of our game board class and places it into a simple layout object to resize it to the full applet size every time the applet itself is resized. srandom is used to initialize the random number generator with the current time in seconds (see the man pages of srandom and random) as seed.

  1. int FifteenApplet::widthForHeight(int h) const 
  2. {
  3.   return h; // we want to be quadratic
  4. }
  5.  
  6. int FifteenApplet::heightForWidth(int w) const
  7. {
  8.   return w; // we want to be quadratic
  9. }

Similar to the hello world applet the fifteen pieces applet will have a quadratic shape.

  1. void FifteenApplet::about() 
  2. {
  3.   if(!_aboutData) {
  4.  
  5.       _aboutData = new KAboutData("kfifteenapplet", I18N_NOOP("KFifteenApplet"), 
  6.               "1.0", I18N_NOOP("Fifteen pieces applet.\n\n"
  7.               "The goal is to put the sliding pieces into numerical order.\n"
  8.               "Select \"Randomize Pieces\" from the RMB menu to start a game."),
  9.               KAboutData::License_BSD, "(c) 2001, Matthias Elter");
  10.  
  11.       _aboutData->addAuthor("Matthias Elter", 0, "elter@kde.org");
  12.   }
  13.  
  14.   KAboutApplication dialog(_aboutData);
  15.  
  16.   dialog.show();
  17. }

The implementation of the void about() action handler we reimplement from KPanelApplet creates a KAboutData object (see kdelibs/kdecore/kaboutdata.h) and makes use of KAboutApplication (see kdelibs/kdeui.kaboutapplication.h) to display a nice about dialog when the user selects "About" from the applet's context menu.

[edit] Screenshot of fifteenpieces 'about' dialog

Fifteenpieces about.png

Now let's have a look at the implementation of the game board class called PiecesTable As it inherits from QTableView you might want to have a look at the description of this abstract base class for tables in the excellent Qt documentation: http://doc.trolltech.com/qtableview.html#details

  1. PiecesTable::PiecesTable(QWidget* parent, const char* name )
  2.   : QTableView(parent, name), _menu(0), _activeRow(-1), 
  3.     _activeCol(-1), _randomized(false)
  4.  
  5. {
  6.   // setup table view
  7.  
  8.   setFrameStyle(StyledPanel | Sunken);
  9.  
  10.   setBackgroundMode(NoBackground);
  11.  
  12.   setMouseTracking(true);
  13.  
  14.   setNumRows(4);
  15.  
  16.   setNumCols(4);
  17.  
  18.   // init arrays
  19.  
  20.   initMap();
  21.  
  22.   initColors();
  23. }

The constructor initializes a few member variables used by the game board, sets up the frame style of the table ( QTableView inherits from QFrame ), sets the background mode to NoBackground (we do this to avoid flicker), enables mouse tracking for the widget and configures the number of rows and columns of the table. We also call two protected initialization functions we have defined in PiecesTable to set up two arrays, one (array of ints) used to represent the game board and another (array of QColor ) where we store color values for the 15 pieces.

  1. void PiecesTable::initMap() 
  2. {
  3.   _map.resize(16);
  4.  
  5.   for (unsigned int i = 0; i < 16; i++)
  6.       _map[i] = i;
  7.  
  8.   _randomized = false;
  9. }

initMap() resizes the QArray<int> we use to represent the game board to 16 (4x4 fields on the board) and initializes it with the values one to fifteen.

  1. void PiecesTable::initColors() 
  2. {
  3.   _colors.resize(numRows() * numCols());
  4.  
  5.   for (int r = 0; r < numRows(); r++)
  6.       for (int c = 0; c < numCols(); c++)
  7.           _colors[c + r *numCols()] = QColor(255 - 70 * c,255 - 70 * r, 150);
  8. }

initColors() is similar but calculates different color values for each piece to increase the eye candy effect of our applet.

  1. void PiecesTable::paintCell(QPainter *p, int row, int col)
  2. {
  3.   int w = cellWidth();
  4.   int h = cellHeight();
  5.  
  6.   int x2 = w - 1;
  7.   int y2 = h - 1;
  8.  
  9.   int number = _map[col + row * numCols()] + 1;
  10.  
  11.   bool active = (row == _activeRow && col == _activeCol);
  12.  
  13.   // draw cell background
  14.  
  15.   if(number == 16)
  16.       p->setBrush(colorGroup().background());
  17.  
  18.   else
  19.       p->setBrush(_colors[number-1]);
  20.  
  21.   p->setPen(NoPen);
  22.  
  23.   p->drawRect(0, 0, w, h);
  24.  
  25.   // draw borders
  26.  
  27.   if (height() > 40) {
  28.  
  29.       p->setPen(colorGroup().text());
  30.  
  31.       if(col < numCols()-1)
  32.  
  33.           p->drawLine(x2, 0, x2, y2); // right border line
  34.  
  35.       if(row < numRows()-1)
  36.  
  37.           p->drawLine(0, y2, x2, y2); // bottom border line
  38.  
  39.   }
  40.  
  41.   // draw number
  42.  
  43.   if (number == 16) return;
  44.  
  45.   if(active)
  46.  
  47.       p->setPen(white);
  48.  
  49.   else
  50.  
  51.       p->setPen(black);
  52.  
  53.   p->drawText(0, 0, x2, y2, AlignHCenter | AlignVCenter, 
  54.               QString::number(number));
  55. }

We have reimplemented void paintCell() from QTableView to actually paint the table cells, which on our game board represent sliding pieces, when the widgets receives a paint event. The function is a bit to long to explain in all detail but is quite easy to understand looking up calls you are unsure about in the Qt documentation for QPainter and QTableView

  1. void PiecesTable::resizeEvent(QResizeEvent *e) 
  2. {
  3.   QTableView::resizeEvent(e);
  4.  
  5.   // set font
  6.  
  7.   QFont f = font();
  8.  
  9.   if (height() > 50)
  10.       f.setPixelSize(8);
  11.  
  12.   else if (height() > 40)
  13.       f.setPixelSize(7);
  14.  
  15.   else if (height() > 24)
  16.       f.setPixelSize(5);
  17.  
  18.   else
  19.       f.setPixelSize(3);
  20.  
  21.   setFont(f);
  22.  
  23.   setCellWidth(contentsRect().width()/ numRows());
  24.  
  25.   setCellHeight(contentsRect().height() / numCols());
  26.  
  27. }

We also reimplement the resizeEvent() action handler of the QTableView widgets to adjust the game board according to the geometry we are resized to by the panel. You remember that the panel and thus also the applets can have different sizes and what we do in the resizeEvent is to adjust the font size used to draw on the widget (and thus used in the paintEvent to draw the piece numbers) to the widget size to increase readability on small panels. We furthermore set the cell width and height according to the widget geometry. The algorithm is simple as all cells (pieces) on our game board have the same size.

For some extra eye candy we reimplement the mouseMoveEvent() action handler of the game board widget to highlight the cell (piece) under the mouse cursor if the mouse is moved over the board:

  1. void PiecesTable::mouseMoveEvent(QMouseEvent* e) 
  2. {
  3.   QTableView::mouseMoveEvent(e);
  4.  
  5.   // highlight on mouse over
  6.  
  7.   int row = findRow(e->y());
  8.   int col = findCol(e->x());
  9.  
  10.   int oldrow = _activeRow;
  11.   int oldcol = _activeCol;
  12.  
  13.   if(row >= numRows()
  14.      || col >= numCols()
  15.      || row < 0
  16.      || col < 0) {
  17.  
  18.       _activeRow = -1;
  19.       _activeCol = -1;
  20.  
  21.   }
  22.  
  23.   else {
  24.  
  25.       _activeRow = row;
  26.       _activeCol = col;
  27.   }
  28.  
  29.   updateCell(oldrow, oldcol, false);
  30.   updateCell(row, col, false);
  31. }

We are done now with drawing the game board and adjusting its size to game board geometry. While the applet already looks nice it is not of much use without the game logic for moving pieces around in place.

[edit] Screenshot of fifteenpieces applet

Fifteenpieces applet.png

As the idea of the game is to put randomized pieces in numerical order, we first implement a helper function used to randomize the arrangement of the pieces on the game board:

  1. void PiecesTable::randomizeMap() 
  2. {
  3.   QArray<int> positions;
  4.  
  5.   positions.fill(0, 16);
  6.  
  7.   for (unsigned int i = 0; i < 16; i++) {
  8.  
  9.       while(1) {
  10.  
  11.           int r = (int) (((double)rand() / RAND_MAX) * 16);
  12.  
  13.           if(positions[r] == 0) {
  14.  
  15.               _map[i] = r;
  16.               positions[r] = 1;
  17.               break;
  18.           }
  19.       }
  20.   }
  21.  
  22.   repaint();
  23.  
  24.   _randomized = true;
  25. }

We need a second helper function to be called after each move operation to check whether the player won with the previous move and to display a message box in case of victory. You may have notice the _randomized member variable in the functions above and from the code in checkwin() you see that it is used to make sure that we trigger the "You win!" message box only if the player actually did randomize the game board before putting it into numerical order.

  1. void PiecesTable::checkwin() 
  2. {
  3.   if(!_randomized) return;
  4.  
  5.   int i;
  6.  
  7.   for (i = 0; i < 16; i++)
  8.       if(i != _map[i])
  9.           break;
  10.  
  11.   if (i == 16)
  12.       KMessageBox::information(this, 
  13.                                i18n("Congratulations!\nYou win the game!"),
  14.                                i18n("Fifteen Pieces"));
  15.  
  16. }

Move operations are triggered by the player clicking on one of the sliding pieces. We reimplement the mousePressEvent() handler of the game board widgets to handle mouse clicks on the board. Right mouse button clicks trigger an additional context menu with actions to randomize or reset the game board. A left mouse button click triggers the game logic which is pretty simple if you take 5 minutes to think about it. You should be able to understand the details reading the numerous comments in the code:

  1. void PiecesTable::mousePressEvent(QMouseEvent* e)
  2. {
  3.   QTableView::mousePressEvent(e);
  4.  
  5.   if (e->button() == RightButton) {
  6.  
  7.       // setup RMB pupup menu
  8.  
  9.       if(!_menu) {
  10.  
  11.           _menu = new QPopupMenu(this);
  12.           _menu->insertItem(i18n("R&andomize Pieces"), mRandomize);
  13.           _menu->insertItem(i18n("&Reset Pieces"), mReset);
  14.           _menu->adjustSize();
  15.       }
  16.  
  17.  
  18.       // execute RMB popup and check result
  19.  
  20.       switch(_menu->exec(mapToGlobal(e->pos()))) {
  21.  
  22.           case mRandomize:
  23.               randomizeMap();
  24.               break;
  25.  
  26.  
  27.           case mReset:
  28.               initMap();
  29.               repaint();
  30.               break;
  31.  
  32.           default:
  33.               break;
  34.       }
  35.   }
  36.  
  37.   else {
  38.  
  39.       // GAME LOGIC
  40.  
  41.       // find the free position
  42.  
  43.       int pos = _map.find(15);
  44.  
  45.       if(pos < 0) return;
  46.  
  47.       int frow = pos / numCols();
  48.  
  49.       int fcol = pos - frow * numCols();
  50.  
  51.       // find click position
  52.  
  53.       int row = findRow(e->y());
  54.  
  55.       int col = findCol(e->x());
  56.  
  57.       // sanity check
  58.  
  59.       if (row < 0 || row >= numRows()) return;
  60.  
  61.       if (col < 0 || col >= numCols()) return;
  62.  
  63.       // valid move?
  64.  
  65.       if(row != frow && col != fcol) return;
  66.  
  67.       // rows match -> shift pieces
  68.  
  69.       if(row == frow) {
  70.  
  71.           if (col < fcol) {
  72.  
  73.               for(int c = fcol; c > col; c-) {
  74.  
  75.                   _map[c + row * numCols()] = _map[ c-1 + row *numCols()];
  76.  
  77.                   updateCell(row, c, false);
  78.  
  79.               }
  80.  
  81.           }
  82.  
  83.           else if (col > fcol) {
  84.  
  85.               for(int c = fcol; c < col; c++) {
  86.  
  87.                   _map[c + row * numCols()] = _map[ c+1 + row *numCols()];
  88.  
  89.                   updateCell(row, c, false);
  90.               }
  91.           }
  92.       }
  93.  
  94.       // cols match -> shift pieces
  95.  
  96.       else if (col == fcol) {
  97.  
  98.           if (row < frow) {
  99.  
  100.               for(int r = frow; r > row; r-) {
  101.  
  102.                   _map[col + r * numCols()] = _map[ col + (r-1) *numCols()];
  103.  
  104.                   updateCell(r, col, false);
  105.               }
  106.           }
  107.  
  108.           else if (row > frow) {
  109.  
  110.               for(int r = frow; r < row; r++) {
  111.  
  112.                   _map[col + r * numCols()] = _map[ col + (r+1) *numCols()];
  113.  
  114.                   updateCell(r, col, false);
  115.               }
  116.           }
  117.       }
  118.  
  119.       // move free cell to click position
  120.  
  121.       _map[col + row * numCols()] = 15;
  122.  
  123.       updateCell(row, col, false);
  124.  
  125.       // check if the player wins with this move
  126.  
  127.       checkwin();
  128.   }
  129. }

Ok, we are done, now either download and modify modify khelloworldapplet.tar.gz (308 kB) as described above or download kfifteenapplet-1.0.tar.gz (311 kB) to try the applet. I'm quite sure that you will agree that while the fifteen pieces applet is more or less useless it's a nifty toy to waste your time playing around with. You are good if you manage to figure out the basic move patterns used to win basically every game in less than 10min. ;-)

[edit] Screenshot of popup menu above applet

Now that we have implemented a demo applet I'm going to discuss the "advanced" API features we did not make use of for the simple fifteen pieces applet.

[edit] Applets of variable size

Some panel applets like the pager applet need variable sizes depending on their state (for example the number of desktops for the pager applet). To change the width or height of your applet simply emit the signal void updateLayout() (see kpanelapplet.h) and kicker will relayout the panel and requery widthForHeight() (horizontal panel) or heightForWidth() Session management Unlike normal KDE applications panel applets are not managed by ksmserver, the KDE session manager, but saved and restored by the panel. Session management is transparent to the applet. All that needs to be done to implement functional session management for your applet is to ensure you _always_ use the KConfig object returned by KPanelApplet::config() to save and read applet configuration settings. For unique applets ( X-KDE-UniqueApplet=true ) this config object will write settings to $KDEDIR/share/config/appletidrc with "appletid" being the library name as defined in the .desktop file with X-KDE-Library For non-unique applets the name of the config file will contain a unique session id.

[edit] Stretch applets

Both the hello world and fifteen pieces applet we have discussed are of type KPanelApplet::Normal as passed in the applet constructor to the KPanelApplet constructor. However there is a second type KPanelApplet::Stretch that is used for stretch applets like the taskbar applet that comes with kicker. For stretch applets the values returned by widthForHeight() and heightForWidth() are interpreted as minimal size values by kicker. This means a stretch applet will never be smaller than the size value you choose, but will be stretched by kicker to take up all the available space to the next applet on the panel. Move around the taskbar applet on the panel to see this effect.

[edit] General action dispatcher

Looking at the class declaration of KPanelApplet you may have noticed that there is one value ( ReportBug ) in the Action enumeration which does not have a virtual action handler function. The reason for this is ReportBug was added after the release of KDE 2.0 and it is not possible to add virtual functions without breaking binary compatibility of the KDE 2 platform. For this reason to handle the ReportBug action you must reimplement the general action dispatcher function void action(Action) It is called when the user selects any of the actions from the applet's context menu.

[edit] Requesting keyboard focus

The panel normally does not accept keyboard focus. For this reason applets that need keyboard focus (for example to input text) have to emit the void requestFocus() signal (for example as reaction to a mouse click event on the applet) to retrieve keyboard focus.

[edit] Applet GUI layout

As mentioned earlier the panel can have different orientations (horizontal or vertical) and can be placed on different borders of the desktop. Thus you might want to adjust the GUI layout of your applet depending on the panel orientation. There are two protected functions declared in KPanelApplet for applets to query the panel orientation and the direction in which popup menus should be positioned depending on the panel position. The functions are Orientation orientation() and Direction popupDirection() There are also two virtual handlers ( void orientationChange() and void popupDirectionChange() ) an applet can reimplement to react on orientation or direction changes.

[edit] Tips 'n' tricks

Never call show() in the applet's constructor. There is absolutely no reason to call show() in a widget constructor. The reason why this is important for panel applets is that QXEmbed (kdelibs/kdecore/qxembed.h), the class used to embed external applets (those run via the proxy) into kicker, often suffers from race conditions when a window is visible before it is reparented.

As panel applets provide but a very small GUI it is often easier to do the layouting by hand in the resizeEvent() instead of using QLayout.


This page was last modified on 29 June 2011, at 21:52. This page has been accessed 6,641 times. Content is available under Creative Commons License SA 3.0 as well as the GNU Free Documentation License 1.2.
KDE® and the K Desktop Environment® logo are registered trademarks of KDE e.V.Legal