Code

Fixed copying of old settings, along with some data() vs. c_str() cleanup. Fixes...
[inkscape.git] / src / preferences.cpp
1 /** @file
2  * @brief  Singleton class to access the preferences file - implementation
3  */
4 /* Authors:
5  *   Krzysztof KosiƄski <tweenk.pl@gmail.com>
6  *   Jon A. Cruz <jon@joncruz.org>
7  *
8  * Copyright (C) 2008,2009 Authors
9  *
10  * Released under GNU GPL.  Read the file 'COPYING' for more information.
11  */
13 #include <cstring>
14 #include <glibmm/fileutils.h>
15 #include <glibmm/i18n.h>
16 #include <glib.h>
17 #include <glib/gstdio.h>
18 #include <gtk/gtk.h>
19 #include "preferences.h"
20 #include "preferences-skeleton.h"
21 #include "inkscape.h"
22 #include "xml/node-observer.h"
23 #include "xml/node-iterators.h"
24 #include "xml/attribute-record.h"
26 #define PREFERENCES_FILE_NAME "preferences.xml"
28 namespace Inkscape {
30 static Inkscape::XML::Document *loadImpl( std::string const& prefsFilename, Glib::ustring & errMsg );
31 static void migrateDetails( Inkscape::XML::Document *from, Inkscape::XML::Document *to );
33 static Inkscape::XML::Document *migrateFromDoc = 0;
35 // TODO clean up. Function copied from file.cpp:
36 // what gets passed here is not actually an URI... it is an UTF-8 encoded filename (!)
37 static void file_add_recent(gchar const *uri)
38 {
39     if (!uri) {
40         g_warning("file_add_recent: uri == NULL");
41     } else {
42         GtkRecentManager *recent = gtk_recent_manager_get_default();
43         gchar *fn = g_filename_from_utf8(uri, -1, NULL, NULL, NULL);
44         if (fn) {
45             if (g_file_test(fn, G_FILE_TEST_EXISTS)) {
46                 gchar *uriToAdd = g_filename_to_uri(fn, NULL, NULL);
47                 if (uriToAdd) {
48                     gtk_recent_manager_add_item(recent, uriToAdd);
49                     g_free(uriToAdd);
50                 }
51             }
52             g_free(fn);
53         }
54     }
55 }
58 // private inner class definition
60 /**
61  * @brief XML - prefs observer bridge
62  *
63  * This is an XML node observer that watches for changes in the XML document storing the preferences.
64  * It is used to implement preference observers.
65  */
66 class Preferences::PrefNodeObserver : public XML::NodeObserver {
67 public:
68     PrefNodeObserver(Observer &o, Glib::ustring const &filter) :
69         _observer(o),
70         _filter(filter)
71     {}
72     virtual ~PrefNodeObserver() {}
73     virtual void notifyAttributeChanged(XML::Node &node, GQuark name, Util::ptr_shared<char>, Util::ptr_shared<char>);
74 private:
75     Observer &_observer;
76     Glib::ustring const _filter;
77 };
79 Preferences::Preferences() :
80     _prefs_basename(PREFERENCES_FILE_NAME),
81     _prefs_dir(""),
82     _prefs_filename(""),
83     _prefs_doc(0),
84     _errorHandler(0),
85     _writable(false),
86     _hasError(false)
87 {
88     // profile_path essentailly returns the argument prefixed by the profile directory.
89     gchar *path = profile_path(NULL);
90     _prefs_dir = path;
91     g_free(path);
93     path = profile_path(_prefs_basename.c_str());
94     _prefs_filename = path;
95     g_free(path);
97     _loadDefaults();
98     _load();
99 }
101 Preferences::~Preferences()
103     // delete all PrefNodeObservers
104     for (_ObsMap::iterator i = _observer_map.begin(); i != _observer_map.end(); ) {
105         delete (*i++).second; // avoids reference to a deleted key
106     }
107     // unref XML document
108     Inkscape::GC::release(_prefs_doc);
111 /**
112  * @brief Load internal defaults
113  *
114  * In the future this will try to load the system-wide file before falling
115  * back to the internal defaults.
116  */
117 void Preferences::_loadDefaults()
119     _prefs_doc = sp_repr_read_mem(preferences_skeleton, PREFERENCES_SKELETON_SIZE, NULL);
122 /**
123  * @brief Load the user's customized preferences
124  *
125  * Tries to load the user's preferences.xml file. If there is none, creates it.
126  */
127 void Preferences::_load()
129     Glib::ustring const not_saved = _("Inkscape will run with default settings, "
130                                       "and new settings will not be saved. ");
132     // NOTE: After we upgrade to Glib 2.16, use Glib::ustring::compose
134     // 1. Does the file exist?
135     if (!g_file_test(_prefs_filename.c_str(), G_FILE_TEST_EXISTS)) {
136         // No - we need to create one.
137         // Does the profile directory exist?
138         if (!g_file_test(_prefs_dir.c_str(), G_FILE_TEST_EXISTS)) {
139             // No - create the profile directory
140             if (g_mkdir(_prefs_dir.c_str(), 0755)) {
141                 // the creation failed
142                 //_reportError(Glib::ustring::compose(_("Cannot create profile directory %1."),
143                 //    Glib::filename_to_utf8(_prefs_dir)), not_saved);
144                 gchar *msg = g_strdup_printf(_("Cannot create profile directory %s."),
145                     Glib::filename_to_utf8(_prefs_dir).c_str());
146                 _reportError(msg, not_saved);
147                 g_free(msg);
148                 return;
149             }
150             // create some subdirectories for user stuff
151             char const *user_dirs[] = {"keys", "templates", "icons", "extensions", "palettes", NULL};
152             for (int i=0; user_dirs[i]; ++i) {
153                 char *dir = profile_path(user_dirs[i]);
154                 g_mkdir(dir, 0755);
155                 g_free(dir);
156             }
158         } else if (!g_file_test(_prefs_dir.c_str(), G_FILE_TEST_IS_DIR)) {
159             // The profile dir is not actually a directory
160             //_reportError(Glib::ustring::compose(_("%1 is not a valid directory."),
161             //    Glib::filename_to_utf8(_prefs_dir)), not_saved);
162             gchar *msg = g_strdup_printf(_("%s is not a valid directory."),
163                 Glib::filename_to_utf8(_prefs_dir).c_str());
164             _reportError(msg, not_saved);
165             g_free(msg);
166             return;
167         }
168         // The profile dir exists and is valid.
169         if (!g_file_set_contents(_prefs_filename.c_str(), preferences_skeleton, PREFERENCES_SKELETON_SIZE, NULL)) {
170             // The write failed.
171             //_reportError(Glib::ustring::compose(_("Failed to create the preferences file %1."),
172             //    Glib::filename_to_utf8(_prefs_filename)), not_saved);
173             gchar *msg = g_strdup_printf(_("Failed to create the preferences file %s."),
174                 Glib::filename_to_utf8(_prefs_filename).c_str());
175             _reportError(msg, not_saved);
176             g_free(msg);
177             return;
178         }
180         if ( migrateFromDoc ) {
181             migrateDetails( migrateFromDoc, _prefs_doc );
182         }
184         // The prefs file was just created.
185         // We can return now and skip the rest of the load process.
186         _writable = true;
187         return;
188     }
190     // Yes, the pref file exists.
191     Glib::ustring errMsg;
192     Inkscape::XML::Document *prefs_read = loadImpl( _prefs_filename, errMsg );
194     if ( prefs_read ) {
195         // Merge the loaded prefs with defaults.
196         _prefs_doc->root()->mergeFrom(prefs_read->root(), "id");
197         Inkscape::GC::release(prefs_read);
198         _writable = true;
199     } else {
200         _reportError(errMsg, not_saved);
201     }
204 //_reportError(msg, not_saved);
205 static Inkscape::XML::Document *loadImpl( std::string const& prefsFilename, Glib::ustring & errMsg )
207     // 2. Is it a regular file?
208     if (!g_file_test(prefsFilename.c_str(), G_FILE_TEST_IS_REGULAR)) {
209         gchar *msg = g_strdup_printf(_("The preferences file %s is not a regular file."),
210             Glib::filename_to_utf8(prefsFilename).c_str());
211         errMsg = msg;
212         g_free(msg);
213         return 0;
214     }
216     // 3. Is the file readable?
217     gchar *prefs_xml = NULL; gsize len = 0;
218     if (!g_file_get_contents(prefsFilename.c_str(), &prefs_xml, &len, NULL)) {
219         gchar *msg = g_strdup_printf(_("The preferences file %s could not be read."),
220             Glib::filename_to_utf8(prefsFilename).c_str());
221         errMsg = msg;
222         g_free(msg);
223         return 0;
224     }
226     // 4. Is it valid XML?
227     Inkscape::XML::Document *prefs_read = sp_repr_read_mem(prefs_xml, len, NULL);
228     g_free(prefs_xml);
229     if (!prefs_read) {
230         gchar *msg = g_strdup_printf(_("The preferences file %s is not a valid XML document."),
231             Glib::filename_to_utf8(prefsFilename).c_str());
232         errMsg = msg;
233         g_free(msg);
234         return 0;
235     }
237     // 5. Basic sanity check: does the root element have a correct name?
238     if (strcmp(prefs_read->root()->name(), "inkscape")) {
239         gchar *msg = g_strdup_printf(_("The file %s is not a valid Inkscape preferences file."),
240             Glib::filename_to_utf8(prefsFilename).c_str());
241         errMsg = msg;
242         g_free(msg);
243         Inkscape::GC::release(prefs_read);
244         return 0;
245     }
247     return prefs_read;
250 static void migrateDetails( Inkscape::XML::Document *from, Inkscape::XML::Document *to )
252     // TODO pull in additional prefs with more granularity
253     to->root()->mergeFrom(from->root(), "id");
256 /**
257  * @brief Flush all pref changes to the XML file
258  */
259 void Preferences::save()
261     // no-op if the prefs file is not writable
262     if (_writable) {
263         // sp_repr_save_file uses utf-8 instead of the glib filename encoding.
264         // I don't know why filenames are kept in utf-8 in Inkscape and then
265         // converted to filename encoding when necessary through special functions
266         // - wouldn't it be easier to keep things in the encoding they are supposed
267         // to be in?
269         // No, it would not. There are many reasons, one key reason being that the
270         // rest of GTK+ is explicitly UTF-8. From an engineering standpoint, keeping
271         // the filesystem encoding would change things from a one-to-many problem to
272         // instead be a many-to-many problem. Also filesystem encoding can change
273         // from one run of the program to the next, so can not be stored.
274         // There are many other factors, so ask if you would like to learn them. - JAC
275         Glib::ustring utf8name = Glib::filename_to_utf8(_prefs_filename);
276         if (!utf8name.empty()) {
277             sp_repr_save_file(_prefs_doc, utf8name.c_str());
278         }
279     }
282 bool Preferences::getLastError( Glib::ustring& primary, Glib::ustring& secondary )
284     bool result = _hasError;
285     if ( _hasError ) {
286         primary = _lastErrPrimary;
287         secondary = _lastErrSecondary;
288         _hasError = false;
289         _lastErrPrimary.clear();
290         _lastErrSecondary.clear();
291     } else {
292         primary.clear();
293         secondary.clear();
294     }
295     return result;
298 void Preferences::migrate( std::string const& legacyDir, std::string const& prefdir )
300     int mode = S_IRWXU;
301 #ifdef S_IRGRP
302     mode |= S_IRGRP;
303 #endif
304 #ifdef S_IXGRP
305     mode |= S_IXGRP;
306 #endif
307 #ifdef S_IXOTH
308     mode |= S_IXOTH;
309 #endif
310     if ( g_mkdir_with_parents(prefdir.c_str(), mode) == -1 ) {
311     } else {
312     }
314     gchar * oldPrefFile = g_build_filename(legacyDir.c_str(), PREFERENCES_FILE_NAME, NULL);
315     if (oldPrefFile) {
316         if (g_file_test(oldPrefFile, G_FILE_TEST_EXISTS)) {
317             Glib::ustring errMsg;
318             Inkscape::XML::Document *oldPrefs = loadImpl( oldPrefFile, errMsg );
319             if (oldPrefs) {
320                 Glib::ustring docId("documents");
321                 Glib::ustring recentId("recent");
322                 Inkscape::XML::Node *node = oldPrefs->root();
323                 Inkscape::XML::Node *child = 0;
324                 Inkscape::XML::Node *recentNode = 0;
325                 if (node->attribute("version")) {
326                     node->setAttribute("version", "1");
327                 }
328                 for (child = node->firstChild(); child; child = child->next()) {
329                     if (docId == child->attribute("id")) {
330                         for (child = child->firstChild(); child; child = child->next()) {
331                             if (recentId == child->attribute("id")) {
332                                 recentNode = child;
333                                 for (child = child->firstChild(); child; child = child->next()) {
334                                     gchar const* uri = child->attribute("uri");
335                                     if (uri) {
336                                         file_add_recent(uri);
337                                     }
338                                 }
339                                 break;
340                             }
341                         }
342                         break;
343                     }
344                 }
346                 if (recentNode) {
347                     while (recentNode->firstChild()) {
348                         recentNode->removeChild(recentNode->firstChild());
349                     }
350                 }
351                 migrateFromDoc = oldPrefs;
352                 //Inkscape::GC::release(oldPrefs);
353                 oldPrefs = 0;
354             } else {
355                 g_warning( "%s", errMsg.c_str() );
356             }
357         }
358         g_free(oldPrefFile);
359         oldPrefFile = 0;
360     }
363 // Now for the meat.
365 /**
366  * @brief Get names of all entries in the specified path
367  * @param path Preference path to query
368  * @return A vector containing all entries in the given directory
369  */
370 std::vector<Preferences::Entry> Preferences::getAllEntries(Glib::ustring const &path)
372     std::vector<Entry> temp;
373     Inkscape::XML::Node *node = _getNode(path, false);
374     if (node) {
375         // argh - purge this Util::List nonsense from XML classes fast
376         Inkscape::Util::List<Inkscape::XML::AttributeRecord const> alist = node->attributeList();
377         for (; alist; ++alist) {
378             temp.push_back( Entry(path + '/' + g_quark_to_string(alist->key), static_cast<void const*>(alist->value.pointer())) );
379         }
380     }
381     return temp;
384 /**
385  * @brief Get the paths to all subdirectories of the specified path
386  * @param path Preference path to query
387  * @return A vector containing absolute paths to all subdirectories in the given path
388  */
389 std::vector<Glib::ustring> Preferences::getAllDirs(Glib::ustring const &path)
391     std::vector<Glib::ustring> temp;
392     Inkscape::XML::Node *node = _getNode(path, false);
393     if (node) {
394         for (Inkscape::XML::NodeSiblingIterator i = node->firstChild(); i; ++i) {
395             temp.push_back(path + '/' + i->attribute("id"));
396         }
397     }
398     return temp;
401 // getter methods
403 Preferences::Entry const Preferences::getEntry(Glib::ustring const &pref_path)
405     gchar const *v;
406     _getRawValue(pref_path, v);
407     return Entry(pref_path, v);
410 // setter methods
412 /**
413  * @brief Set a boolean attribute of a preference
414  * @param pref_path Path of the preference to modify
415  * @param value The new value of the pref attribute
416  */
417 void Preferences::setBool(Glib::ustring const &pref_path, bool value)
419     /// @todo Boolean values should be stored as "true" and "false",
420     /// but this is not possible due to an interaction with event contexts.
421     /// Investigate this in depth.
422     _setRawValue(pref_path, ( value ? "1" : "0" ));
425 /**
426  * @brief Set an integer attribute of a preference
427  * @param pref_path Path of the preference to modify
428  * @param value The new value of the pref attribute
429  */
430 void Preferences::setInt(Glib::ustring const &pref_path, int value)
432     gchar intstr[32];
433     g_snprintf(intstr, 32, "%d", value);
434     _setRawValue(pref_path, intstr);
437 /**
438  * @brief Set a floating point attribute of a preference
439  * @param pref_path Path of the preference to modify
440  * @param value The new value of the pref attribute
441  */
442 void Preferences::setDouble(Glib::ustring const &pref_path, double value)
444     gchar buf[G_ASCII_DTOSTR_BUF_SIZE];
445     g_ascii_dtostr(buf, G_ASCII_DTOSTR_BUF_SIZE, value);
446     _setRawValue(pref_path, buf);
449 /**
450  * @brief Set a string attribute of a preference
451  * @param pref_path Path of the preference to modify
452  * @param value The new value of the pref attribute
453  */
454 void Preferences::setString(Glib::ustring const &pref_path, Glib::ustring const &value)
456     _setRawValue(pref_path, value.c_str());
459 void Preferences::setStyle(Glib::ustring const &pref_path, SPCSSAttr *style)
461     gchar *css_str = sp_repr_css_write_string(style);
462     _setRawValue(pref_path, css_str);
463     g_free(css_str);
466 void Preferences::mergeStyle(Glib::ustring const &pref_path, SPCSSAttr *style)
468     SPCSSAttr *current = getStyle(pref_path);
469     sp_repr_css_merge(current, style);
470     gchar *css_str = sp_repr_css_write_string(current);
471     _setRawValue(pref_path, css_str);
472     g_free(css_str);
473     sp_repr_css_attr_unref(current);
477 // Observer stuff
478 namespace {
480 /**
481  * @brief Structure that holds additional information for registered Observers
482  */
483 struct _ObserverData {
484     Inkscape::XML::Node *_node; ///< Node at which the wrapping PrefNodeObserver is registered
485     bool _is_attr; ///< Whether this Observer watches a single attribute
486 };
488 } // anonymous namespace
490 Preferences::Observer::Observer(Glib::ustring const &path) :
491     observed_path(path)
495 Preferences::Observer::~Observer()
497     // on destruction remove observer to prevent invalid references
498     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
499     prefs->removeObserver(*this);
502 void Preferences::PrefNodeObserver::notifyAttributeChanged(XML::Node &node, GQuark name, Util::ptr_shared<char>, Util::ptr_shared<char> new_value)
504     // filter out attributes we don't watch
505     gchar const *attr_name = g_quark_to_string(name);
506     if ( _filter.empty() || (_filter == attr_name) ) {
507         _ObserverData *d = static_cast<_ObserverData*>(Preferences::_get_pref_observer_data(_observer));
508         Glib::ustring notify_path = _observer.observed_path;
510         if (!d->_is_attr) {
511             std::vector<gchar const *> path_fragments;
512             notify_path.reserve(256); // this will make appending operations faster
514             // walk the XML tree, saving each of the id attributes in a vector
515             // we terminate when we hit the observer's attachment node, because the path to this node
516             // is already stored in notify_path
517             for (XML::NodeParentIterator n = &node; static_cast<XML::Node*>(n) != d->_node; ++n) {
518                 path_fragments.push_back(n->attribute("id"));
519             }
520             // assemble the elements into a path
521             for (std::vector<gchar const *>::reverse_iterator i = path_fragments.rbegin(); i != path_fragments.rend(); ++i) {
522                 notify_path.push_back('/');
523                 notify_path.append(*i);
524             }
526             // append attribute name
527             notify_path.push_back('/');
528             notify_path.append(attr_name);
529         }
531         Entry const val = Preferences::_create_pref_value(notify_path, static_cast<void const*>(new_value.pointer()));
532         _observer.notify(val);
533     }
536 /**
537  * @brief Find the XML node to observe
538  */
539 XML::Node *Preferences::_findObserverNode(Glib::ustring const &pref_path, Glib::ustring &node_key, Glib::ustring &attr_key, bool create)
541     // first assume that the last path element is an entry.
542     _keySplit(pref_path, node_key, attr_key);
544     // find the node corresponding to the "directory".
545     Inkscape::XML::Node *node = _getNode(node_key, create), *child;
546     for (child = node->firstChild(); child; child = child->next()) {
547         // If there is a node with id corresponding to the attr key,
548         // this means that the last part of the path is actually a key (folder).
549         // Change values accordingly.
550         if (attr_key == child->attribute("id")) {
551             node = child;
552             attr_key = "";
553             node_key = pref_path;
554             break;
555         }
556     }
557     return node;
560 void Preferences::addObserver(Observer &o)
562     // prevent adding the same observer twice
563     if ( _observer_map.find(&o) == _observer_map.end() ) {
564         Glib::ustring node_key, attr_key;
565         Inkscape::XML::Node *node;
566         node = _findObserverNode(o.observed_path, node_key, attr_key, false);
567         if (node) {
568             // set additional data
569             _ObserverData *priv_data = new _ObserverData;
570             priv_data->_node = node;
571             priv_data->_is_attr = !attr_key.empty();
572             o._data = static_cast<void*>(priv_data);
574             _observer_map[&o] = new PrefNodeObserver(o, attr_key);
576             // if we watch a single pref, we want to receive notifications only for a single node
577             if (priv_data->_is_attr) {
578                 node->addObserver( *(_observer_map[&o]) );
579             } else {
580                 node->addSubtreeObserver( *(_observer_map[&o]) );
581             }
582         }
583     }
586 void Preferences::removeObserver(Observer &o)
588     // prevent removing an observer which was not added
589     if ( _observer_map.find(&o) != _observer_map.end() ) {
590         Inkscape::XML::Node *node = static_cast<_ObserverData*>(o._data)->_node;
591         _ObserverData *priv_data = static_cast<_ObserverData*>(o._data);
592         o._data = NULL;
594         if (priv_data->_is_attr) {
595             node->removeObserver( *(_observer_map[&o]) );
596         } else {
597             node->removeSubtreeObserver( *(_observer_map[&o]) );
598         }
600         delete priv_data;
601         delete _observer_map[&o];
602         _observer_map.erase(&o);
603     }
607 /**
608  * @brief Get the XML node corresponding to the given pref key
609  * @param pref_key Preference key (path) to get
610  * @param create Whether to create the corresponding node if it doesn't exist
611  * @param separator The character used to separate parts of the pref key
612  * @return XML node corresponding to the specified key
613  *
614  * Derived from former inkscape_get_repr(). Private because it assumes that the backend is
615  * a flat XML file, which may not be the case e.g. if we are using GConf (in future).
616  */
617 Inkscape::XML::Node *Preferences::_getNode(Glib::ustring const &pref_key, bool create)
619     // verify path
620     g_assert( pref_key.at(0) == '/' );
621     // No longer necessary, can cause problems with input devices which have a dot in the name
622     // g_assert( pref_key.find('.') == Glib::ustring::npos );
624     Inkscape::XML::Node *node = _prefs_doc->root();
625     Inkscape::XML::Node *child = NULL;
626     gchar **splits = g_strsplit(pref_key.c_str(), "/", 0);
628     if ( splits ) {
629         for (int part_i = 0; splits[part_i]; ++part_i) {
630             // skip empty path segments
631             if (!splits[part_i][0]) {
632                 continue;
633             }
635             for (child = node->firstChild(); child; child = child->next()) {
636                 if (!strcmp(splits[part_i], child->attribute("id"))) {
637                     break;
638                 }
639             }
641             // If the previous loop found a matching key, child now contains the node
642             // matching the processed key part. If no node was found then it is NULL.
643             if (!child) {
644                 if (create) {
645                     // create the rest of the key
646                     while(splits[part_i]) {
647                         child = node->document()->createElement("group");
648                         child->setAttribute("id", splits[part_i]);
649                         node->appendChild(child);
651                         ++part_i;
652                         node = child;
653                     }
654                     g_strfreev(splits);
655                     return node;
656                 } else {
657                     return NULL;
658                 }
659             }
661             node = child;
662         }
663         g_strfreev(splits);
664     }
665     return node;
668 void Preferences::_getRawValue(Glib::ustring const &path, gchar const *&result)
670     // create node and attribute keys
671     Glib::ustring node_key, attr_key;
672     _keySplit(path, node_key, attr_key);
674     // retrieve the attribute
675     Inkscape::XML::Node *node = _getNode(node_key, false);
676     if ( node == NULL ) {
677         result = NULL;
678     } else {
679         gchar const *attr = node->attribute(attr_key.c_str());
680         if ( attr == NULL ) {
681             result = NULL;
682         } else {
683             result = attr;
684         }
685     }
688 void Preferences::_setRawValue(Glib::ustring const &path, gchar const *value)
690     // create node and attribute keys
691     Glib::ustring node_key, attr_key;
692     _keySplit(path, node_key, attr_key);
694     // set the attribute
695     Inkscape::XML::Node *node = _getNode(node_key, true);
696     node->setAttribute(attr_key.c_str(), value);
699 // The _extract* methods are where the actual wrok is done - they define how preferences are stored
700 // in the XML file.
702 bool Preferences::_extractBool(Entry const &v)
704     gchar const *s = static_cast<gchar const *>(v._value);
705     if ( !s[0] || !strcmp(s, "0") || !strcmp(s, "false") ) {
706         return false;
707     } else {
708         return true;
709     }
712 int Preferences::_extractInt(Entry const &v)
714     gchar const *s = static_cast<gchar const *>(v._value);
715     if ( !strcmp(s, "true") ) {
716         return true;
717     } else if ( !strcmp(s, "false") ) {
718         return false;
719     } else {
720         return atoi(s);
721     }
724 double Preferences::_extractDouble(Entry const &v)
726     gchar const *s = static_cast<gchar const *>(v._value);
727     return g_ascii_strtod(s, NULL);
730 Glib::ustring Preferences::_extractString(Entry const &v)
732     return Glib::ustring(static_cast<gchar const *>(v._value));
735 SPCSSAttr *Preferences::_extractStyle(Entry const &v)
737     SPCSSAttr *style = sp_repr_css_attr_new();
738     sp_repr_css_attr_add_from_string(style, static_cast<gchar const*>(v._value));
739     return style;
742 SPCSSAttr *Preferences::_extractInheritedStyle(Entry const &v)
744     // This is the dirtiest extraction method. Generally we ignore whatever was in v._value
745     // and just get the style using sp_repr_css_attr_inherited. To implement this in GConf,
746     // we'll have to walk up the tree and call sp_repr_css_attr_add_from_string
747     Glib::ustring node_key, attr_key;
748     _keySplit(v._pref_path, node_key, attr_key);
750     Inkscape::XML::Node *node = _getNode(node_key, false);
751     return sp_repr_css_attr_inherited(node, attr_key.c_str());
754 // XML backend helper: Split the path into a node key and an attribute key.
755 void Preferences::_keySplit(Glib::ustring const &pref_path, Glib::ustring &node_key, Glib::ustring &attr_key)
757     // everything after the last slash
758     attr_key = pref_path.substr(pref_path.rfind('/') + 1, Glib::ustring::npos);
759     // everything before the last slash
760     node_key = pref_path.substr(0, pref_path.rfind('/'));
763 void Preferences::_reportError(Glib::ustring const &msg, Glib::ustring const &secondary)
765     _hasError = true;
766     _lastErrPrimary = msg;
767     _lastErrSecondary = secondary;
768     if (_errorHandler) {
769         _errorHandler->handleError(msg, secondary);
770     }
773 Preferences::Entry const Preferences::_create_pref_value(Glib::ustring const &path, void const *ptr)
775     return Entry(path, ptr);
778 void Preferences::setErrorHandler(ErrorReporter* handler)
780     _errorHandler = handler;
783 void Preferences::unload(bool save)
785     if (_instance)
786     {
787         if (save) {
788             _instance->save();
789         }
790         delete _instance;
791         _instance = NULL;
792     }
795 Preferences *Preferences::_instance = NULL;
798 } // namespace Inkscape
800 /*
801   Local Variables:
802   mode:c++
803   c-file-style:"stroustrup"
804   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
805   indent-tabs-mode:nil
806   fill-column:99
807   End:
808 */
809 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :