Difference between revisions of "Development/Tutorials/KConfig"

Jump to: navigation, search
m (fix broken link to desktop file spec)
 
(2 intermediate revisions by 2 users not shown)
Line 1: Line 1:
{{Template:I18n/Language Navigation Bar|Development/Tutorials/KConfig}}
+
 
 
{{TutorialBrowser|
 
{{TutorialBrowser|
  
Line 24: Line 24:
 
These configuration objects are broken down into a two level hierarchy: groups and keys. A configuration object can have any number of groups and each group can have one or more keys with associated values.
 
These configuration objects are broken down into a two level hierarchy: groups and keys. A configuration object can have any number of groups and each group can have one or more keys with associated values.
  
Values stored may be of any number of data types. They are stored and retreived as the objects themselves. For example, a {{qt|QColor}} object is passed to a config object directly when storing a color value and when retreived a {{qt|QColor}} object is returned. Applications themselves therefore generally do not have to perform serialization and deserialization of objects themselves.
+
Values stored may be of any number of data types. They are stored and retrieved as the objects themselves. For example, a {{qt|QColor}} object is passed to a config object directly when storing a color value and when retrieved a {{qt|QColor}} object is returned. Applications themselves therefore generally do not have to perform serialization and deserialization of objects themselves.
  
 
== The KConfig Class ==
 
== The KConfig Class ==
Line 30: Line 30:
 
The {{class|KConfig}} object is used to access a given configuration object. There are a number of ways to create a config object:
 
The {{class|KConfig}} object is used to access a given configuration object. There are a number of ways to create a config object:
  
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt" line="">
 
// a plain old read/write config object
 
// a plain old read/write config object
 
KConfig config("myapprc");
 
KConfig config("myapprc");
Line 49: Line 49:
 
// outside the standard config resource
 
// outside the standard config resource
 
KConfig dataResource( "data", "myapp/somefile" );
 
KConfig dataResource( "data", "myapp/somefile" );
</code>
+
</syntaxhighlight>
  
 
The KConfig object create on line 2 is a regular config object. We can read values from it, write new entries and ask for various properties of the object.  This object will be loaded from the config resource as determined by {{class|KStandardDirs}}, meaning that every instance of the <tt>myapprc</tt> object in each of the directories in the config resource hierarchy will be merged to create the values seen in this object. This is how system wide and per-user/group profiles are generated and supported and it all happens transparently to the application itself.
 
The KConfig object create on line 2 is a regular config object. We can read values from it, write new entries and ask for various properties of the object.  This object will be loaded from the config resource as determined by {{class|KStandardDirs}}, meaning that every instance of the <tt>myapprc</tt> object in each of the directories in the config resource hierarchy will be merged to create the values seen in this object. This is how system wide and per-user/group profiles are generated and supported and it all happens transparently to the application itself.
Line 67: Line 67:
 
Each application has its own configuration object that uses the name provided to {{class|KAboutData}} appended with "rc" as its name. So an app named "myapp" would have the default configuration object of "myapprc" (located in $KDEHOME/share/config/). This configuration file can be retrieved in this way:
 
Each application has its own configuration object that uses the name provided to {{class|KAboutData}} appended with "rc" as its name. So an app named "myapp" would have the default configuration object of "myapprc" (located in $KDEHOME/share/config/). This configuration file can be retrieved in this way:
  
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt" line="">
 
#include <KComponentData>
 
#include <KComponentData>
 
#include <KConfig>
 
#include <KConfig>
Line 78: Line 78:
 
     KConfig* config = KGlobal::config();
 
     KConfig* config = KGlobal::config();
 
}
 
}
</code>
+
</syntaxhighlight>
  
 
The default configuration object for the application is accessed when no name is specified when creating a {{class|KConfig}} object. So we could also do this instead - but it would be slower because it would have to parse the whole file again:
 
The default configuration object for the application is accessed when no name is specified when creating a {{class|KConfig}} object. So we could also do this instead - but it would be slower because it would have to parse the whole file again:
  
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt" line="">
 
#include <KConfig>
 
#include <KConfig>
  
Line 89: Line 89:
 
     KConfig config;
 
     KConfig config;
 
}
 
}
</code>
+
</syntaxhighlight>
  
 
Additionally, each component may have its own configuration object. This is generally accessed via the plugin's <tt>componentData()</tt> rather than <tt>{{class|KGlobal}}::mainComponent()</tt>.
 
Additionally, each component may have its own configuration object. This is generally accessed via the plugin's <tt>componentData()</tt> rather than <tt>{{class|KGlobal}}::mainComponent()</tt>.
Line 105: Line 105:
 
Listing all groups in a configuration object is as simple as calling <tt>groupList()</tt> as in this code snippet:
 
Listing all groups in a configuration object is as simple as calling <tt>groupList()</tt> as in this code snippet:
  
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt">
 
KSharedConfigPtr config = KGlobal::mainComponent().config();
 
KSharedConfigPtr config = KGlobal::mainComponent().config();
  
Line 111: Line 111:
 
     kDebug() << "next group:" << group;
 
     kDebug() << "next group:" << group;
 
}
 
}
</code>
+
</syntaxhighlight>
  
 
== KSharedConfig ==
 
== KSharedConfig ==
Line 119: Line 119:
 
Accessing a {{class|KSharedConfig}} object is as easy as this:
 
Accessing a {{class|KSharedConfig}} object is as easy as this:
  
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt">
 
KSharedConfigPtr config = KSharedConfig::openConfig("ksomefilerc");
 
KSharedConfigPtr config = KSharedConfig::openConfig("ksomefilerc");
</code>
+
</syntaxhighlight>
  
 
<tt>openConfig()</tt> take the same parameters as {{class|KConfig}}'s constructors do, allowing one to define which configuration file to open, flags to control merging and non-<tt>config</tt> resources.
 
<tt>openConfig()</tt> take the same parameters as {{class|KConfig}}'s constructors do, allowing one to define which configuration file to open, flags to control merging and non-<tt>config</tt> resources.
Line 131: Line 131:
 
Now that we have a configuration object, the next step is to actually use it. The first thing we must do is to define which group of key/value pairs we wish to access in the object. We do this by creating a KConfigGroup object:
 
Now that we have a configuration object, the next step is to actually use it. The first thing we must do is to define which group of key/value pairs we wish to access in the object. We do this by creating a KConfigGroup object:
  
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt">
 
KConfig config;
 
KConfig config;
 
KConfigGroup generalGroup( &config, "General" );
 
KConfigGroup generalGroup( &config, "General" );
 
KConfigGroup colorsGroup = config.group( "Colors" ); // ... or a bit differently ...
 
KConfigGroup colorsGroup = config.group( "Colors" ); // ... or a bit differently ...
</code>
+
</syntaxhighlight>
  
 
You can pass {{class|KConfig}} or {{class|KSharedConfig}} objects to {{class|KConfigGroup}}.
 
You can pass {{class|KConfig}} or {{class|KSharedConfig}} objects to {{class|KConfigGroup}}.
Line 141: Line 141:
 
Config groups can be nested as well:
 
Config groups can be nested as well:
  
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt">
 
KConfigGroup subGroup1( &generalGroup, "LessGeneral" );
 
KConfigGroup subGroup1( &generalGroup, "LessGeneral" );
 
KConfigGroup subGroup2 = colorsGroup.group( "Dialogs" );
 
KConfigGroup subGroup2 = colorsGroup.group( "Dialogs" );
</code>
+
</syntaxhighlight>
  
 
== Reading Entries ==
 
== Reading Entries ==
Line 150: Line 150:
 
With a {{class|KConfigGroup}} object in hand reading entries is now quite straight forward:
 
With a {{class|KConfigGroup}} object in hand reading entries is now quite straight forward:
  
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt">
 
QString accountName = generalGroup.readEntry( "Account",
 
QString accountName = generalGroup.readEntry( "Account",
 
                                               QString() );
 
                                               QString() );
Line 159: Line 159:
 
QString path = generalGroup.readPathEntry( "SaveTo",
 
QString path = generalGroup.readPathEntry( "SaveTo",
 
                                           defaultPath );
 
                                           defaultPath );
</code>
+
</syntaxhighlight>
  
 
As can be seen from the above, you can mix reads from different {{class|KConfigGroup}} objects created on the same {{class|KConfig}} object. The read methods take the key, which is case sensitive, as the first argument and the default value as the second argument. This argument controls what kind of data, e.g. a color in line 3 above, is to be expected as well as the type of object returned. The returned object is wrapped in a {{qt|QVariant}} to make this magic happen.
 
As can be seen from the above, you can mix reads from different {{class|KConfigGroup}} objects created on the same {{class|KConfig}} object. The read methods take the key, which is case sensitive, as the first argument and the default value as the second argument. This argument controls what kind of data, e.g. a color in line 3 above, is to be expected as well as the type of object returned. The returned object is wrapped in a {{qt|QVariant}} to make this magic happen.
Line 171: Line 171:
 
Setting new values is similarly straightforward:
 
Setting new values is similarly straightforward:
  
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt">
 
generalGroup.writeEntry( "Account", accountName );
 
generalGroup.writeEntry( "Account", accountName );
 
generalGroup.writePathEntry( "SaveTo", savePath );
 
generalGroup.writePathEntry( "SaveTo", savePath );
 
colorGroup.writeEntry( "background", color );
 
colorGroup.writeEntry( "background", color );
 
generalGroup.config()->sync();
 
generalGroup.config()->sync();
</code>
+
</syntaxhighlight>
  
 
Note the use of <tt>writePathEntry</tt> and how the type of object we use, such as {{qt|QColor}} on line 3, dictates how the data is serialized. Additionally, once we are done writing entries, <tt>sync()</tt> must be called on the config object for it to be saved to disk. We can also simply wait for the object to be destroyed, which triggers an automatic <tt>sync()</tt> if necessary.
 
Note the use of <tt>writePathEntry</tt> and how the type of object we use, such as {{qt|QColor}} on line 3, dictates how the data is serialized. Additionally, once we are done writing entries, <tt>sync()</tt> must be called on the config object for it to be saved to disk. We can also simply wait for the object to be destroyed, which triggers an automatic <tt>sync()</tt> if necessary.
Line 192: Line 192:
 
Entries in configuration objects that are locked down using the kiosk facilities are said to be ''immutable''. An application can check for immutability of entire configuration objects, groups or keys as shown in this example:
 
Entries in configuration objects that are locked down using the kiosk facilities are said to be ''immutable''. An application can check for immutability of entire configuration objects, groups or keys as shown in this example:
  
<code cppqt n>
+
<syntaxhighlight lang="cpp-qt">
 
KSharedConfigPtr config = KGlobal::config();
 
KSharedConfigPtr config = KGlobal::config();
  
Line 207: Line 207:
 
     kDebug() << "URL entry in group General is immutable";
 
     kDebug() << "URL entry in group General is immutable";
 
}
 
}
</code>
+
</syntaxhighlight>
  
 
This can be useful in particular situations where an action should be taken when an item is immutable. For instance, the KDE panels will not offer configuration options to the user or allow them to otherwise change the order of applets and icons when the panel's configuration object is marked as immutable.
 
This can be useful in particular situations where an action should be taken when an item is immutable. For instance, the KDE panels will not offer configuration options to the user or allow them to otherwise change the order of applets and icons when the panel's configuration object is marked as immutable.

Latest revision as of 17:17, 13 July 2012

Introduction to KConfig
Tutorial Series   KConfig
Previous   None
What's Next   Using KConfig XT
Further Reading   KConfig apidocs

Contents

[edit] Abstract

This tutorial looks at the KDE configuration data system, starting with an overview of the design fundamentals from an application developer's point of view. It then looks at the classes relevant to application development one by one before moving on to kiosk (user and group profiles) integration.

[edit] Design Essentials

KConfig is designed to abstract away the concept of actual storage and retrieval of configuration settings behind an API that allows easy fetching and setting of information. Where and in what format the data is stored is not relevant to an application using KConfig. This keeps all KDE applications consistent in their handling of configurations while alleviating each and every application author to build such a system on their own from scratch, which can be a highly error prone exercise.

A KConfig object represents a single configuration object. Each configuration object is referenced by its unique name and may be actually read from multiple local or remote files or services. Each application has a default configuration object associated with it and there is also a global configuration object.

These configuration objects are broken down into a two level hierarchy: groups and keys. A configuration object can have any number of groups and each group can have one or more keys with associated values.

Values stored may be of any number of data types. They are stored and retrieved as the objects themselves. For example, a QColor object is passed to a config object directly when storing a color value and when retrieved a QColor object is returned. Applications themselves therefore generally do not have to perform serialization and deserialization of objects themselves.

[edit] The KConfig Class

The KConfig object is used to access a given configuration object. There are a number of ways to create a config object:

  1. // a plain old read/write config object
  2. KConfig config("myapprc");
  3.  
  4. // a specific file in the filesystem
  5. // currently must be an INI style file
  6. KConfig fullPath("/etc/kderc");
  7.  
  8. // not merged with global values
  9. KConfig globalFree( "localsrc", KConfig::NoGlobals );
  10.  
  11. // not merged with globals or the $KDEDIRS hierarchy
  12. KConfig simpleConfig( "simplerc", KConfig::SimpleConfig );
  13.  
  14. // config specific to a component, in this case a plugin
  15. KConfig pluginConfig( componentData(), "pluginrc" );
  16.  
  17. // outside the standard config resource
  18. KConfig dataResource( "data", "myapp/somefile" );

The KConfig object create on line 2 is a regular config object. We can read values from it, write new entries and ask for various properties of the object. This object will be loaded from the config resource as determined by KStandardDirs, meaning that every instance of the myapprc object in each of the directories in the config resource hierarchy will be merged to create the values seen in this object. This is how system wide and per-user/group profiles are generated and supported and it all happens transparently to the application itself.

Ktip.png
 
Tip
For more information on how the merging works, see the KDE Filesystem Hierarchy article.


On line 6 we open a specific local file, this case /etc/kderc. This performs no merging of values and expects an INI style file.

Line 9 sees the creation of a configuration object that is not merged with the global kdeglobals configuration object, while the configuration file on line 12 is additionally not merged with any files in the $KDEDIRS hierarchy. This can noticeably improve performance in the case where one is simply reading values out of a simple configuration for which global values are not meaningful.

Line 15 creates a configuration object using the KComponentData object that belongs to a plugin or other component. The plugin may have a different set of directories defined in its KStandardDirs and this is a way of ensuring that KConfig respects this.

Finally on line 18 we see the creation of a configuration object that does not exist in the config resource but rather in the application data resource. You may use any resource that KStandardDirs is aware of, including ones that are added at runtime.

[edit] Special Configuration Objects

Each application has its own configuration object that uses the name provided to KAboutData appended with "rc" as its name. So an app named "myapp" would have the default configuration object of "myapprc" (located in $KDEHOME/share/config/). This configuration file can be retrieved in this way:

  1. #include <KComponentData>
  2. #include <KConfig>
  3. #include <KGlobal>
  4.  
  5. MyClass::MyClass()
  6. {
  7.     // note that this is actually a KSharedConfig
  8.     // more on that class in a bit!
  9.     KConfig* config = KGlobal::config();
  10. }

The default configuration object for the application is accessed when no name is specified when creating a KConfig object. So we could also do this instead - but it would be slower because it would have to parse the whole file again:

  1. #include <KConfig>
  2.  
  3. MyClass::MyClass()
  4. {
  5.     KConfig config;
  6. }

Additionally, each component may have its own configuration object. This is generally accessed via the plugin's componentData() rather than KGlobal::mainComponent().

Finally there is a global configuration object, kdeglobals, that is shared by every application. It holds such information as the default application shortcuts for various actions. It is "blended" into the configuration object if the KConfig::IncludeGlobals flag is passed to the KConfig constructor, which is the default.

[edit] Commonly Useful Methods

To save the current state of the configuration object we call the sync() method. This method is also called when the object is destroyed. If no changes have been made or the resource reports itself as non-writable (such as in the case of the user not having write permissions to the file) then no disk activity occurs. sync() merges changes performed concurrently by other processes - local changes have priority, though.

If we want to make sure that we have the latest values from disk we can call reparseConfiguration() which calls sync() and then reloads the data from disk.

If we need to prevent the config object from saving already made modifications to disk we need to call markAsClean(). A particular use case for this is rolling back the configuration to the on-disk state by calling markAsClean() followed by reparseConfiguration().

Listing all groups in a configuration object is as simple as calling groupList() as in this code snippet:

KSharedConfigPtr config = KGlobal::mainComponent().config();
 
foreach ( const QString& group, config->groupList() ) {
    kDebug() << "next group:" << group;
}

[edit] KSharedConfig

The KSharedConfig class is a reference counted pointer to a KConfig. It thus provides a way to reference the same configuration object from multiple places in your application without the extra overhead of separate objects or concerns about synchronizing writes to disk even if the configuration object is updated from multiple code paths.

Accessing a KSharedConfig object is as easy as this:

KSharedConfigPtr config = KSharedConfig::openConfig("ksomefilerc");

openConfig() take the same parameters as KConfig's constructors do, allowing one to define which configuration file to open, flags to control merging and non-config resources.

KSharedConfig is generally recommended over using KConfig itself, and the object returned from KComponentData is indeed a KSharedConfig object.

[edit] KConfigGroup

Now that we have a configuration object, the next step is to actually use it. The first thing we must do is to define which group of key/value pairs we wish to access in the object. We do this by creating a KConfigGroup object:

KConfig config;
KConfigGroup generalGroup( &config, "General" );
KConfigGroup colorsGroup = config.group( "Colors" ); // ... or a bit differently ...

You can pass KConfig or KSharedConfig objects to KConfigGroup.

Config groups can be nested as well:

KConfigGroup subGroup1( &generalGroup, "LessGeneral" );
KConfigGroup subGroup2 = colorsGroup.group( "Dialogs" );

[edit] Reading Entries

With a KConfigGroup object in hand reading entries is now quite straight forward:

QString accountName = generalGroup.readEntry( "Account",
                                              QString() );
QColor color = colorsGroup.readEntry( "background",
                                      Qt::white );
QStringList list = generalGroup.readEntry( "List",
                                           QStringList() );
QString path = generalGroup.readPathEntry( "SaveTo",
                                           defaultPath );

As can be seen from the above, you can mix reads from different KConfigGroup objects created on the same KConfig object. The read methods take the key, which is case sensitive, as the first argument and the default value as the second argument. This argument controls what kind of data, e.g. a color in line 3 above, is to be expected as well as the type of object returned. The returned object is wrapped in a QVariant to make this magic happen.

There are a couple of special read methods, including readPathEntry which returns a file system path. It is vital that one uses readPathEntry if it is a path as this enables such features as roaming profiles to work properly.

If no such key currently exists in the configuration object, the default value is returned instead. If there is a localized (e.g. translated into another language) entry for the key that matches the current locale, that is returned.

[edit] Writing Entries

Setting new values is similarly straightforward:

generalGroup.writeEntry( "Account", accountName );
generalGroup.writePathEntry( "SaveTo", savePath );
colorGroup.writeEntry( "background", color );
generalGroup.config()->sync();

Note the use of writePathEntry and how the type of object we use, such as QColor on line 3, dictates how the data is serialized. Additionally, once we are done writing entries, sync() must be called on the config object for it to be saved to disk. We can also simply wait for the object to be destroyed, which triggers an automatic sync() if necessary.

[edit] KDesktopFile: A Special Case

When is a configuration file not a configuration file? When it is a desktop file. These files, which are essentially configuration files at their heart, are used to describe entries for application menus, mimetypes, plugins and various services.

When accessing a .desktop file, one should instead use the KDesktopFile class which, while a KConfig class offering all the capabilities described above, offers a set of methods designed to make accessing standard attributes of these files consistent and reliable.

[edit] Kiosk: Lockdown and User/Group Profiles

KConfig provides a powerful set of lockdown and configuration definition capabilities, collectively known as "Kiosk", that many system administrators and system integrators rely on. While most of this framework is provided transparently to the application, there is occassion when an application will want to check on the read/write status of a configuration object.

Entries in configuration objects that are locked down using the kiosk facilities are said to be immutable. An application can check for immutability of entire configuration objects, groups or keys as shown in this example:

KSharedConfigPtr config = KGlobal::config();
 
if ( config->isImmutable() ) {
    kDebug() << "configuration object is immutable";
}
 
KConfigGroup group(config, "General");
if ( group.isImmutable() ) {
    kDebug() << "group General is immutable";
}
 
if ( group.isEntryImmutable("URL") ) {
    kDebug() << "URL entry in group General is immutable";
}

This can be useful in particular situations where an action should be taken when an item is immutable. For instance, the KDE panels will not offer configuration options to the user or allow them to otherwise change the order of applets and icons when the panel's configuration object is marked as immutable.

[edit] KConfig XT

There is a way to make certain use cases of KConfig easier, faster and more reliable: KConfig XT. In particular, for main application or plugin configuration objects and when syncing configuration dialogs and other interfaces with these values, KConfig XT can help immensely. It also simultaneously documents the configuration options available, which makes every sys admin and system integrator that uses KDE that much more happy.

The next tutorial in the KConfig series covers what KConfig XT is and how to use it.


This page was last modified on 13 July 2012, at 17:17. This page has been accessed 30,214 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