Development/Tutorials/Plasma4/DataEngines: Difference between revisions

From KDE TechBase
No edit summary
(replace PLASMA_LIBS with KDE4_PLASMA_LIBS to make the code compile in kde 4.2)
Line 278: Line 278:
find_package(KDE4 REQUIRED)
find_package(KDE4 REQUIRED)
include(KDE4Defaults)
include(KDE4Defaults)
find_package(Plasma REQUIRED)


add_definitions (${QT_DEFINITIONS} ${KDE4_DEFINITIONS})
add_definitions (${QT_DEFINITIONS} ${KDE4_DEFINITIONS})
Line 294: Line 293:
target_link_libraries(plasma_engine_testtime
target_link_libraries(plasma_engine_testtime
                       ${KDE4_KDECORE_LIBS}
                       ${KDE4_KDECORE_LIBS}
                       ${PLASMA_LIBS})
                       ${KDE4_PLASMA_LIBS})


install(TARGETS plasma_engine_testtime
install(TARGETS plasma_engine_testtime

Revision as of 22:12, 14 January 2009

Writing a Data Engine
Tutorial Series   Plasma Tutorial
Previous   C++, Qt, KDE4 development environment
What's Next  
Further Reading   DataEngine API, CMake Tutorials, Writing a Plasmoid (Tutorial)


Abstract

DataEngines provide a standardized interface to various data sources for visualizations to use.

This tutorial will lead you through creating a simple data engine. The example we will use is a simplified version of the time data engine provided with the basic plasma installation in kdebase-workspace.

The time data engine provides the current date and time for any timezone that the system knows about. It is used by every one of the many clock plasmoids. The obvious benefit of this is that there is no need to reimplement the logic for selecting timezones in every clock plasmoid.


The Plasma Engine Explorer

A very useful tool for anyone writing data engines is the Plasma engine explorer. You can use it to see how the time data engine should work now by running plasmaengineexplorer

Near the top of the window is a drop-down box for selecting a data engine. Choose the "time" engine. You can now request a source. Try requesting the "Local" source, with an update interval of 500ms (twice a second). A single item, Local, should be visible in the sources list. Click the + on the left to expand it, and you should get the date, time, timezone, timezone continent and timezone city listed, together with the type for each.

Have a play with selecting other timezones, such as "Europe/Paris" and "Asia/Tokyo".

Remember to test your data engine using the Plasma engine explorer when you have created it!


The Code

The Desktop File

Every data engine needs a description file to tell plasma how to load it and what it is called.

plasma-engine-testtime.desktop [Desktop Entry] Name=Test Time Engine Comment=A duplicate of the Time Engine Type=Service

X-KDE-ServiceTypes=Plasma/DataEngine X-KDE-Library=plasma_engine_testtime X-Plasma-EngineName=testtime X-KDE-PluginInfo-Author=Aaron Seigo [email protected] X-KDE-PluginInfo-Name=testtime X-KDE-PluginInfo-Version=0.1 X-KDE-PluginInfo-Website=http://plasma.kde.org/ X-KDE-PluginInfo-Category=Examples X-KDE-PluginInfo-Depends= X-KDE-PluginInfo-License=LGPL X-KDE-PluginInfo-EnabledByDefault=true

The most important bits are:

  • the Name, Comment and Type fields, which are required for all desktop files
  • the X-KDE-ServiceTypes field, which tells plasma that this is a data engine
  • the X-KDE-Library field, which tells plasma how to load the data engine - in this case by loading plasma_engine_testtime.so from the plugin folder
  • the X-Plasma-EngineName field, which tells plasma what the exported plugin name is (as given to K_EXPORT_PLASMA_DATAENGINE)


The Header File

testtimeengine.h // the following header is required by the LGPL because // we are using the actual time engine code /*

*   Copyright 2007 Aaron Seigo <[email protected]>
*
*   This program is free software; you can redistribute it and/or modify
*   it under the terms of the GNU Library General Public License as
*   published by the Free Software Foundation; either version 2 or
*   (at your option) any later version.
*
*   This program is distributed in the hope that it will be useful,
*   but WITHOUT ANY WARRANTY; without even the implied warranty of
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*   GNU General Public License for more details
*
*   You should have received a copy of the GNU Library General Public
*   License along with this program; if not, write to the
*   Free Software Foundation, Inc.,
*   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

// a standard include guard to prevent problems if the // header is included multiple times

  1. ifndef TESTTIMEENGINE_H
  2. define TESTTIMEENGINE_H

// We need the DataEngine header, since we are inheriting it

  1. include <Plasma/DataEngine>

/**

* This engine provides the current date and time for a given
* timezone.
*
* "Local" is a special source that is an alias for the current
* timezone.
*/

class TestTimeEngine : public Plasma::DataEngine {

   // required since Plasma::DataEngine inherits QObject
   Q_OBJECT
   public:
       // every engine needs a constructor with these arguments
       TestTimeEngine(QObject* parent, const QVariantList& args);
   protected:
       // this virtual function is called when a new source is requested
       bool sourceRequestEvent(const QString& name);
       // this virtual function is called when an automatic update
       // is triggered for an existing source (ie: when a valid update
       // interval is set when requesting a source)
       bool updateSourceEvent(const QString& source);

};

  1. endif // TESTTIMEENGINE_H

A separate header file may seem a bit pointless for a plugin this small, but it is a good habit to get into.

Note that I don't put a K_EXPORT_PLASMA_DATAENGINE in the header file. When there is only one .cpp file in the project, there is no problem, but in larger plugins several files might include this header and there can only be one K_EXPORT_PLASMA_DATAENGINE in the project. If K_EXPORT_PLASMA_DATAENGINE is compiled in multiple times, you will get a linker error when compiling. Also note that the name should not end on "engine" (e.g. "testtimeengine"), because then Plasma does not find the DataEngine correctly.

The Main Code

testtimeengine.cpp // the following header is required by the LGPL because // we are using the actual time engine code /*

*   Copyright 2007 Aaron Seigo <[email protected]>
*
*   This program is free software; you can redistribute it and/or modify
*   it under the terms of the GNU Library General Public License as
*   published by the Free Software Foundation; either version 2 or
*   (at your option) any later version.
*
*   This program is distributed in the hope that it will be useful,
*   but WITHOUT ANY WARRANTY; without even the implied warranty of
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*   GNU General Public License for more details
*
*   You should have received a copy of the GNU Library General Public
*   License along with this program; if not, write to the
*   Free Software Foundation, Inc.,
*   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
  1. include "testtimeengine.h"
  1. include <QDate>
  2. include <QTime>
  1. include <KSystemTimeZones>
  2. include <KDateTime>
  1. include "plasma/datacontainer.h"

TestTimeEngine::TestTimeEngine(QObject* parent, const QVariantList& args)

   : Plasma::DataEngine(parent, args)

{

   // We ignore any arguments - data engines do not have much use for them
   Q_UNUSED(args)
   // This prevents applets from setting an unnecessarily high
   // update interval and using too much CPU.
   // In the case of a clock that only has second precision,
   // a third of a second should be more than enough.
   setMinimumPollingInterval(333);

}

bool TestTimeEngine::sourceRequestEvent(const QString &name) {

   // We do not have any special code to execute the
   // first time a source is requested, so we just call
   // updateSourceEvent().
   return updateSourceEvent(name);

}

bool TestTimeEngine::updateSourceEvent(const QString &name) {

   QString timezone;
   if (name == I18N_NOOP("Local")) {
       // Local is a special case - we just get the current time and date
       setData(name, I18N_NOOP("Time"), QTime::currentTime());
       setData(name, I18N_NOOP("Date"), QDate::currentDate());
   } else {
       // First check the timezone is valid
       KTimeZone newTz = KSystemTimeZones::zone(name);
       if (!newTz.isValid()) {
           return false;
       }
       // Get the date and time
       KDateTime dt = KDateTime::currentDateTime(newTz);
       setData(name, I18N_NOOP("Time"), dt.time());
       setData(name, I18N_NOOP("Date"), dt.date());
   }
   return true;

}

// This does the magic that allows Plasma to load // this plugin. The first argument must match // the X-Plasma-EngineName in the .desktop file. K_EXPORT_PLASMA_DATAENGINE(testtime, TestTimeEngine)

// this is needed since TestTimeEngine is a QObject

  1. include "timeengine.moc"


Responding to Requests for Sources

The sourceRequestEvent() method is called the first time a source is loaded. You can use this to do any special processing that should be done the first time a source is created, but not when it is subsequently updated.

If a source is created with a polling interval, updateSourceEvent() will be called each time that interval expires. For example, if an applet requests a source "foo" with a polling interval of 500ms, sourceRequestEvent("foo") will be called initially, then half a second later, and every half a second after that, updateSourceEvent("foo") will be called.

Note, however, that applets do not have to set a polling interval and may instead simply wait for an engine to push data to it.


Controlling Update Frequency

There are a couple of methods for controlling updates. We use setMinimumPollingInterval(333) to prevent updateSourceEvent() being called more than three times a second for any given source. You can also enforce a specific update interval for all sources provided by this engine with setPollingInterval(), which takes a time in milliseconds as its only argument.

Responding to Outside Events

Polling does not make sense for all engines. Some engines, such as the device engine, respond to outside events. You can use setData() at any time to create or update a source. removeData() and removeSource() are also useful methods.


Listing Potential Sources

Applets can request a list of the available sources for an engine. By default, this is just a list of every source that has been created (with setData() or addSource()) so far (and not removed, of course). However, you may wish to advertise sources but not actually create them. For example, we could advertise every timezone that the system knows about, but not actually create and populate the sources, since hardly any will actually be used.

This can be done by reimplementing virtual QStringList sources() const and returning a list of the names of all the available sources.


Initialisation

If you want to perform any initialisation beyond setting simple properties, such as populating sources, you cannot do it in the constructor, since the data engine has not been properly initialised at this point. Instead, reimplement the virtual void init() method.

For example, the tasks data engine uses the init() method to get a list of all the currently running tasks and creates sources for each of them.


More Control Over Data

The DataContainer class can be used to give you more control over updating data if you need it. The relevant methods of DataEngine are DataContainer* containerForSource(const QString& source), void addSource(DataContainer* source) and SourceDict containerDict() const.


Building It

The CMakeLists.txt file tells CMake how to build your plugin. The following file will work for this project:

  1. A name for the project

project(plasma-testtime)

  1. Find the required Libaries

find_package(KDE4 REQUIRED) include(KDE4Defaults)

add_definitions (${QT_DEFINITIONS} ${KDE4_DEFINITIONS}) include_directories(

  ${CMAKE_SOURCE_DIR}
  ${CMAKE_BINARY_DIR}
  ${KDE4_INCLUDES}
  )
  1. We add our source code here

set(testtime_engine_SRCS testtimeengine.cpp)

  1. Now make sure all files get to the right place

kde4_add_plugin(plasma_engine_testtime ${testtime_engine_SRCS}) target_link_libraries(plasma_engine_testtime

                     ${KDE4_KDECORE_LIBS}
                     ${KDE4_PLASMA_LIBS})

install(TARGETS plasma_engine_testtime

       DESTINATION ${PLUGIN_INSTALL_DIR})

install(FILES plasma-engine-testtime.desktop

       DESTINATION ${SERVICES_INSTALL_DIR})


Testing

Run cmake -DCMAKE_BUILD_TYPE=debugfull -DCMAKE_INSTALL_PREFIX=$KDEDIR make make install

Replace $KDEDIR with your kde installation directory if $KDEDIR is not set.

Alternatively, you can run the following cmake -DCMAKE_BUILD_TYPE=debugfull make cp ./lib/plasma_engine_testtime.so $KDEDIR/lib/kde4 cp ./plasma-engine-testtime.desktop $KDEDIR/share/kde4/services/

Now run kbuildsycoca4 to tell KDE applications (including plasma and the plasma engine explorer) about the new desktop file.

Now you can test it as we did the time engine. Run plasmaengineexplorer --engine testtime

Note that if you change a data engine, the change will not register in any running applications. After modifying and reinstalling a data engine, to make plasma register the change you must run kbuildsycoca4 kquitapp plasma plasma