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.data());
94 _prefs_filename = path;
95 g_free(path);
97 _loadDefaults();
98 _load();
99 }
101 Preferences::~Preferences()
102 {
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);
109 }
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()
118 {
119 _prefs_doc = sp_repr_read_mem(preferences_skeleton, PREFERENCES_SKELETON_SIZE, NULL);
120 }
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()
128 {
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.data(), G_FILE_TEST_EXISTS)) {
136 // No - we need to create one.
137 // Does the profile directory exist?
138 if (!g_file_test(_prefs_dir.data(), G_FILE_TEST_EXISTS)) {
139 // No - create the profile directory
140 if (g_mkdir(_prefs_dir.data(), 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).data());
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.data(), 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).data());
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.data(), 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).data());
175 _reportError(msg, not_saved);
176 g_free(msg);
177 return;
178 }
180 // The prefs file was just created.
181 // We can return now and skip the rest of the load process.
182 _writable = true;
183 return;
184 }
186 // Yes, the pref file exists.
187 Glib::ustring errMsg;
188 Inkscape::XML::Document *prefs_read = loadImpl( _prefs_filename, errMsg );
190 if ( prefs_read ) {
191 if ( migrateFromDoc ) {
192 migrateDetails( migrateFromDoc, _prefs_doc );
193 }
194 // Merge the loaded prefs with defaults.
195 _prefs_doc->root()->mergeFrom(prefs_read->root(), "id");
196 Inkscape::GC::release(prefs_read);
197 _writable = true;
198 } else {
199 _reportError(errMsg, not_saved);
200 }
201 }
203 //_reportError(msg, not_saved);
204 static Inkscape::XML::Document *loadImpl( std::string const& prefsFilename, Glib::ustring & errMsg )
205 {
206 // 2. Is it a regular file?
207 if (!g_file_test(prefsFilename.data(), G_FILE_TEST_IS_REGULAR)) {
208 gchar *msg = g_strdup_printf(_("The preferences file %s is not a regular file."),
209 Glib::filename_to_utf8(prefsFilename).data());
210 errMsg = msg;
211 g_free(msg);
212 return 0;
213 }
215 // 3. Is the file readable?
216 gchar *prefs_xml = NULL; gsize len = 0;
217 if (!g_file_get_contents(prefsFilename.data(), &prefs_xml, &len, NULL)) {
218 gchar *msg = g_strdup_printf(_("The preferences file %s could not be read."),
219 Glib::filename_to_utf8(prefsFilename).data());
220 errMsg = msg;
221 g_free(msg);
222 return 0;
223 }
225 // 4. Is it valid XML?
226 Inkscape::XML::Document *prefs_read = sp_repr_read_mem(prefs_xml, len, NULL);
227 g_free(prefs_xml);
228 if (!prefs_read) {
229 gchar *msg = g_strdup_printf(_("The preferences file %s is not a valid XML document."),
230 Glib::filename_to_utf8(prefsFilename).data());
231 errMsg = msg;
232 g_free(msg);
233 return 0;
234 }
236 // 5. Basic sanity check: does the root element have a correct name?
237 if (strcmp(prefs_read->root()->name(), "inkscape")) {
238 gchar *msg = g_strdup_printf(_("The file %s is not a valid Inkscape preferences file."),
239 Glib::filename_to_utf8(prefsFilename).data());
240 errMsg = msg;
241 g_free(msg);
242 Inkscape::GC::release(prefs_read);
243 return 0;
244 }
246 return prefs_read;
247 }
249 static void migrateDetails( Inkscape::XML::Document *from, Inkscape::XML::Document *to )
250 {
251 // TODO pull in additional prefs with more granularity
252 to->root()->mergeFrom(from->root(), "id");
253 }
255 /**
256 * @brief Flush all pref changes to the XML file
257 */
258 void Preferences::save()
259 {
260 // no-op if the prefs file is not writable
261 if (_writable) {
262 // sp_repr_save_file uses utf-8 instead of the glib filename encoding.
263 // I don't know why filenames are kept in utf-8 in Inkscape and then
264 // converted to filename encoding when necessary through special functions
265 // - wouldn't it be easier to keep things in the encoding they are supposed
266 // to be in?
268 // No, it would not. There are many reasons, one key reason being that the
269 // rest of GTK+ is explicitly UTF-8. From an engineering standpoint, keeping
270 // the filesystem encoding would change things from a one-to-many problem to
271 // instead be a many-to-many problem. Also filesystem encoding can change
272 // from one run of the program to the next, so can not be stored.
273 // There are many other factors, so ask if you would like to learn them. - JAC
274 Glib::ustring utf8name = Glib::filename_to_utf8(_prefs_filename);
275 if (!utf8name.empty()) {
276 sp_repr_save_file(_prefs_doc, utf8name.data());
277 }
278 }
279 }
281 bool Preferences::getLastError( Glib::ustring& primary, Glib::ustring& secondary )
282 {
283 bool result = _hasError;
284 if ( _hasError ) {
285 primary = _lastErrPrimary;
286 secondary = _lastErrSecondary;
287 _hasError = false;
288 _lastErrPrimary.clear();
289 _lastErrSecondary.clear();
290 } else {
291 primary.clear();
292 secondary.clear();
293 }
294 return result;
295 }
297 void Preferences::migrate( std::string const& legacyDir, std::string const& prefdir )
298 {
299 int mode = S_IRWXU;
300 #ifdef S_IRGRP
301 mode |= S_IRGRP;
302 #endif
303 #ifdef S_IXGRP
304 mode |= S_IXGRP;
305 #endif
306 #ifdef S_IXOTH
307 mode |= S_IXOTH;
308 #endif
309 if ( g_mkdir_with_parents(prefdir.data(), mode) == -1 ) {
310 } else {
311 }
313 gchar * oldPrefFile = g_build_filename(legacyDir.data(), PREFERENCES_FILE_NAME, NULL);
314 if (oldPrefFile) {
315 if (g_file_test(oldPrefFile, G_FILE_TEST_EXISTS)) {
316 Glib::ustring errMsg;
317 Inkscape::XML::Document *oldPrefs = loadImpl( oldPrefFile, errMsg );
318 if (oldPrefs) {
319 Glib::ustring docId("documents");
320 Glib::ustring recentId("recent");
321 Inkscape::XML::Node *node = oldPrefs->root();
322 Inkscape::XML::Node *child = NULL;
323 for (child = node->firstChild(); child; child = child->next()) {
324 if (docId == child->attribute("id")) {
325 for (child = child->firstChild(); child; child = child->next()) {
326 if (recentId == child->attribute("id")) {
327 for (child = child->firstChild(); child; child = child->next()) {
328 gchar const* uri = child->attribute("uri");
329 if (uri) {
330 file_add_recent(uri);
331 }
332 }
333 break;
334 }
335 }
336 break;
337 }
338 }
340 migrateFromDoc = oldPrefs;
341 //Inkscape::GC::release(oldPrefs);
342 oldPrefs = 0;
343 } else {
344 g_warning( "%s", errMsg.c_str() );
345 }
346 }
347 g_free(oldPrefFile);
348 oldPrefFile = 0;
349 }
350 }
352 // Now for the meat.
354 /**
355 * @brief Get names of all entries in the specified path
356 * @param path Preference path to query
357 * @return A vector containing all entries in the given directory
358 */
359 std::vector<Preferences::Entry> Preferences::getAllEntries(Glib::ustring const &path)
360 {
361 std::vector<Entry> temp;
362 Inkscape::XML::Node *node = _getNode(path, false);
363 if (node) {
364 // argh - purge this Util::List nonsense from XML classes fast
365 Inkscape::Util::List<Inkscape::XML::AttributeRecord const> alist = node->attributeList();
366 for (; alist; ++alist) {
367 temp.push_back( Entry(path + '/' + g_quark_to_string(alist->key), static_cast<void const*>(alist->value.pointer())) );
368 }
369 }
370 return temp;
371 }
373 /**
374 * @brief Get the paths to all subdirectories of the specified path
375 * @param path Preference path to query
376 * @return A vector containing absolute paths to all subdirectories in the given path
377 */
378 std::vector<Glib::ustring> Preferences::getAllDirs(Glib::ustring const &path)
379 {
380 std::vector<Glib::ustring> temp;
381 Inkscape::XML::Node *node = _getNode(path, false);
382 if (node) {
383 for (Inkscape::XML::NodeSiblingIterator i = node->firstChild(); i; ++i) {
384 temp.push_back(path + '/' + i->attribute("id"));
385 }
386 }
387 return temp;
388 }
390 // getter methods
392 Preferences::Entry const Preferences::getEntry(Glib::ustring const &pref_path)
393 {
394 gchar const *v;
395 _getRawValue(pref_path, v);
396 return Entry(pref_path, v);
397 }
399 // setter methods
401 /**
402 * @brief Set a boolean attribute of a preference
403 * @param pref_path Path of the preference to modify
404 * @param value The new value of the pref attribute
405 */
406 void Preferences::setBool(Glib::ustring const &pref_path, bool value)
407 {
408 /// @todo Boolean values should be stored as "true" and "false",
409 /// but this is not possible due to an interaction with event contexts.
410 /// Investigate this in depth.
411 _setRawValue(pref_path, ( value ? "1" : "0" ));
412 }
414 /**
415 * @brief Set an integer attribute of a preference
416 * @param pref_path Path of the preference to modify
417 * @param value The new value of the pref attribute
418 */
419 void Preferences::setInt(Glib::ustring const &pref_path, int value)
420 {
421 gchar intstr[32];
422 g_snprintf(intstr, 32, "%d", value);
423 _setRawValue(pref_path, intstr);
424 }
426 /**
427 * @brief Set a floating point attribute of a preference
428 * @param pref_path Path of the preference to modify
429 * @param value The new value of the pref attribute
430 */
431 void Preferences::setDouble(Glib::ustring const &pref_path, double value)
432 {
433 gchar buf[G_ASCII_DTOSTR_BUF_SIZE];
434 g_ascii_dtostr(buf, G_ASCII_DTOSTR_BUF_SIZE, value);
435 _setRawValue(pref_path, buf);
436 }
438 /**
439 * @brief Set a string attribute of a preference
440 * @param pref_path Path of the preference to modify
441 * @param value The new value of the pref attribute
442 */
443 void Preferences::setString(Glib::ustring const &pref_path, Glib::ustring const &value)
444 {
445 _setRawValue(pref_path, value.data());
446 }
448 void Preferences::setStyle(Glib::ustring const &pref_path, SPCSSAttr *style)
449 {
450 gchar *css_str = sp_repr_css_write_string(style);
451 _setRawValue(pref_path, css_str);
452 g_free(css_str);
453 }
455 void Preferences::mergeStyle(Glib::ustring const &pref_path, SPCSSAttr *style)
456 {
457 SPCSSAttr *current = getStyle(pref_path);
458 sp_repr_css_merge(current, style);
459 gchar *css_str = sp_repr_css_write_string(current);
460 _setRawValue(pref_path, css_str);
461 g_free(css_str);
462 sp_repr_css_attr_unref(current);
463 }
466 // Observer stuff
467 namespace {
469 /**
470 * @brief Structure that holds additional information for registered Observers
471 */
472 struct _ObserverData {
473 Inkscape::XML::Node *_node; ///< Node at which the wrapping PrefNodeObserver is registered
474 bool _is_attr; ///< Whether this Observer watches a single attribute
475 };
477 } // anonymous namespace
479 Preferences::Observer::Observer(Glib::ustring const &path) :
480 observed_path(path)
481 {
482 }
484 Preferences::Observer::~Observer()
485 {
486 // on destruction remove observer to prevent invalid references
487 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
488 prefs->removeObserver(*this);
489 }
491 void Preferences::PrefNodeObserver::notifyAttributeChanged(XML::Node &node, GQuark name, Util::ptr_shared<char>, Util::ptr_shared<char> new_value)
492 {
493 // filter out attributes we don't watch
494 gchar const *attr_name = g_quark_to_string(name);
495 if ( _filter.empty() || (_filter == attr_name) ) {
496 _ObserverData *d = static_cast<_ObserverData*>(Preferences::_get_pref_observer_data(_observer));
497 Glib::ustring notify_path = _observer.observed_path;
499 if (!d->_is_attr) {
500 std::vector<gchar const *> path_fragments;
501 notify_path.reserve(256); // this will make appending operations faster
503 // walk the XML tree, saving each of the id attributes in a vector
504 // we terminate when we hit the observer's attachment node, because the path to this node
505 // is already stored in notify_path
506 for (XML::NodeParentIterator n = &node; static_cast<XML::Node*>(n) != d->_node; ++n) {
507 path_fragments.push_back(n->attribute("id"));
508 }
509 // assemble the elements into a path
510 for (std::vector<gchar const *>::reverse_iterator i = path_fragments.rbegin(); i != path_fragments.rend(); ++i) {
511 notify_path.push_back('/');
512 notify_path.append(*i);
513 }
515 // append attribute name
516 notify_path.push_back('/');
517 notify_path.append(attr_name);
518 }
520 Entry const val = Preferences::_create_pref_value(notify_path, static_cast<void const*>(new_value.pointer()));
521 _observer.notify(val);
522 }
523 }
525 /**
526 * @brief Find the XML node to observe
527 */
528 XML::Node *Preferences::_findObserverNode(Glib::ustring const &pref_path, Glib::ustring &node_key, Glib::ustring &attr_key, bool create)
529 {
530 // first assume that the last path element is an entry.
531 _keySplit(pref_path, node_key, attr_key);
533 // find the node corresponding to the "directory".
534 Inkscape::XML::Node *node = _getNode(node_key, create), *child;
535 for (child = node->firstChild(); child; child = child->next()) {
536 // If there is a node with id corresponding to the attr key,
537 // this means that the last part of the path is actually a key (folder).
538 // Change values accordingly.
539 if (attr_key == child->attribute("id")) {
540 node = child;
541 attr_key = "";
542 node_key = pref_path;
543 break;
544 }
545 }
546 return node;
547 }
549 void Preferences::addObserver(Observer &o)
550 {
551 // prevent adding the same observer twice
552 if ( _observer_map.find(&o) == _observer_map.end() ) {
553 Glib::ustring node_key, attr_key;
554 Inkscape::XML::Node *node;
555 node = _findObserverNode(o.observed_path, node_key, attr_key, false);
556 if (node) {
557 // set additional data
558 _ObserverData *priv_data = new _ObserverData;
559 priv_data->_node = node;
560 priv_data->_is_attr = !attr_key.empty();
561 o._data = static_cast<void*>(priv_data);
563 _observer_map[&o] = new PrefNodeObserver(o, attr_key);
565 // if we watch a single pref, we want to receive notifications only for a single node
566 if (priv_data->_is_attr) {
567 node->addObserver( *(_observer_map[&o]) );
568 } else {
569 node->addSubtreeObserver( *(_observer_map[&o]) );
570 }
571 }
572 }
573 }
575 void Preferences::removeObserver(Observer &o)
576 {
577 // prevent removing an observer which was not added
578 if ( _observer_map.find(&o) != _observer_map.end() ) {
579 Inkscape::XML::Node *node = static_cast<_ObserverData*>(o._data)->_node;
580 _ObserverData *priv_data = static_cast<_ObserverData*>(o._data);
581 o._data = NULL;
583 if (priv_data->_is_attr) {
584 node->removeObserver( *(_observer_map[&o]) );
585 } else {
586 node->removeSubtreeObserver( *(_observer_map[&o]) );
587 }
589 delete priv_data;
590 delete _observer_map[&o];
591 _observer_map.erase(&o);
592 }
593 }
596 /**
597 * @brief Get the XML node corresponding to the given pref key
598 * @param pref_key Preference key (path) to get
599 * @param create Whether to create the corresponding node if it doesn't exist
600 * @param separator The character used to separate parts of the pref key
601 * @return XML node corresponding to the specified key
602 *
603 * Derived from former inkscape_get_repr(). Private because it assumes that the backend is
604 * a flat XML file, which may not be the case e.g. if we are using GConf (in future).
605 */
606 Inkscape::XML::Node *Preferences::_getNode(Glib::ustring const &pref_key, bool create)
607 {
608 // verify path
609 g_assert( pref_key.at(0) == '/' );
610 // No longer necessary, can cause problems with input devices which have a dot in the name
611 // g_assert( pref_key.find('.') == Glib::ustring::npos );
613 Inkscape::XML::Node *node = _prefs_doc->root();
614 Inkscape::XML::Node *child = NULL;
615 gchar **splits = g_strsplit(pref_key.data(), "/", 0);
617 if ( splits ) {
618 for (int part_i = 0; splits[part_i]; ++part_i) {
619 // skip empty path segments
620 if (!splits[part_i][0]) {
621 continue;
622 }
624 for (child = node->firstChild(); child; child = child->next()) {
625 if (!strcmp(splits[part_i], child->attribute("id"))) {
626 break;
627 }
628 }
630 // If the previous loop found a matching key, child now contains the node
631 // matching the processed key part. If no node was found then it is NULL.
632 if (!child) {
633 if (create) {
634 // create the rest of the key
635 while(splits[part_i]) {
636 child = node->document()->createElement("group");
637 child->setAttribute("id", splits[part_i]);
638 node->appendChild(child);
640 ++part_i;
641 node = child;
642 }
643 g_strfreev(splits);
644 return node;
645 } else {
646 return NULL;
647 }
648 }
650 node = child;
651 }
652 g_strfreev(splits);
653 }
654 return node;
655 }
657 void Preferences::_getRawValue(Glib::ustring const &path, gchar const *&result)
658 {
659 // create node and attribute keys
660 Glib::ustring node_key, attr_key;
661 _keySplit(path, node_key, attr_key);
663 // retrieve the attribute
664 Inkscape::XML::Node *node = _getNode(node_key, false);
665 if ( node == NULL ) {
666 result = NULL;
667 } else {
668 gchar const *attr = node->attribute(attr_key.data());
669 if ( attr == NULL ) {
670 result = NULL;
671 } else {
672 result = attr;
673 }
674 }
675 }
677 void Preferences::_setRawValue(Glib::ustring const &path, gchar const *value)
678 {
679 // create node and attribute keys
680 Glib::ustring node_key, attr_key;
681 _keySplit(path, node_key, attr_key);
683 // set the attribute
684 Inkscape::XML::Node *node = _getNode(node_key, true);
685 node->setAttribute(attr_key.data(), value);
686 }
688 // The _extract* methods are where the actual wrok is done - they define how preferences are stored
689 // in the XML file.
691 bool Preferences::_extractBool(Entry const &v)
692 {
693 gchar const *s = static_cast<gchar const *>(v._value);
694 if ( !s[0] || !strcmp(s, "0") || !strcmp(s, "false") ) {
695 return false;
696 } else {
697 return true;
698 }
699 }
701 int Preferences::_extractInt(Entry const &v)
702 {
703 gchar const *s = static_cast<gchar const *>(v._value);
704 if ( !strcmp(s, "true") ) {
705 return true;
706 } else if ( !strcmp(s, "false") ) {
707 return false;
708 } else {
709 return atoi(s);
710 }
711 }
713 double Preferences::_extractDouble(Entry const &v)
714 {
715 gchar const *s = static_cast<gchar const *>(v._value);
716 return g_ascii_strtod(s, NULL);
717 }
719 Glib::ustring Preferences::_extractString(Entry const &v)
720 {
721 return Glib::ustring(static_cast<gchar const *>(v._value));
722 }
724 SPCSSAttr *Preferences::_extractStyle(Entry const &v)
725 {
726 SPCSSAttr *style = sp_repr_css_attr_new();
727 sp_repr_css_attr_add_from_string(style, static_cast<gchar const*>(v._value));
728 return style;
729 }
731 SPCSSAttr *Preferences::_extractInheritedStyle(Entry const &v)
732 {
733 // This is the dirtiest extraction method. Generally we ignore whatever was in v._value
734 // and just get the style using sp_repr_css_attr_inherited. To implement this in GConf,
735 // we'll have to walk up the tree and call sp_repr_css_attr_add_from_string
736 Glib::ustring node_key, attr_key;
737 _keySplit(v._pref_path, node_key, attr_key);
739 Inkscape::XML::Node *node = _getNode(node_key, false);
740 return sp_repr_css_attr_inherited(node, attr_key.data());
741 }
743 // XML backend helper: Split the path into a node key and an attribute key.
744 void Preferences::_keySplit(Glib::ustring const &pref_path, Glib::ustring &node_key, Glib::ustring &attr_key)
745 {
746 // everything after the last slash
747 attr_key = pref_path.substr(pref_path.rfind('/') + 1, Glib::ustring::npos);
748 // everything before the last slash
749 node_key = pref_path.substr(0, pref_path.rfind('/'));
750 }
752 void Preferences::_reportError(Glib::ustring const &msg, Glib::ustring const &secondary)
753 {
754 _hasError = true;
755 _lastErrPrimary = msg;
756 _lastErrSecondary = secondary;
757 if (_errorHandler) {
758 _errorHandler->handleError(msg, secondary);
759 }
760 }
762 Preferences::Entry const Preferences::_create_pref_value(Glib::ustring const &path, void const *ptr)
763 {
764 return Entry(path, ptr);
765 }
767 void Preferences::setErrorHandler(ErrorReporter* handler)
768 {
769 _errorHandler = handler;
770 }
772 void Preferences::unload(bool save)
773 {
774 if (_instance)
775 {
776 if (save) {
777 _instance->save();
778 }
779 delete _instance;
780 _instance = NULL;
781 }
782 }
784 Preferences *Preferences::_instance = NULL;
787 } // namespace Inkscape
789 /*
790 Local Variables:
791 mode:c++
792 c-file-style:"stroustrup"
793 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
794 indent-tabs-mode:nil
795 fill-column:99
796 End:
797 */
798 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :