Code

Extensions. Shebangs branch merge.
[inkscape.git] / src / document.cpp
1 #define __SP_DOCUMENT_C__
3 /** \file
4  * SPDocument manipulation
5  *
6  * Authors:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   MenTaLguY <mental@rydia.net>
9  *   bulia byak <buliabyak@users.sf.net>
10  *
11  * Copyright (C) 2004-2005 MenTaLguY
12  * Copyright (C) 1999-2002 Lauris Kaplinski
13  * Copyright (C) 2000-2001 Ximian, Inc.
14  *
15  * Released under GNU GPL, read the file 'COPYING' for more information
16  */
18 /** \class SPDocument
19  * SPDocument serves as the container of both model trees (agnostic XML
20  * and typed object tree), and implements all of the document-level
21  * functionality used by the program. Many document level operations, like
22  * load, save, print, export and so on, use SPDocument as their basic datatype.
23  *
24  * SPDocument implements undo and redo stacks and an id-based object
25  * dictionary.  Thanks to unique id attributes, the latter can be used to
26  * map from the XML tree back to the object tree.
27  *
28  * SPDocument performs the basic operations needed for asynchronous
29  * update notification (SPObject ::modified virtual method), and implements
30  * the 'modified' signal, as well.
31  */
34 #define noSP_DOCUMENT_DEBUG_IDLE
35 #define noSP_DOCUMENT_DEBUG_UNDO
37 #ifdef HAVE_CONFIG_H
38 # include "config.h"
39 #endif
40 #include <gtk/gtkmain.h>
41 #include <string>
42 #include <cstring>
44 #include "application/application.h"
45 #include "application/editor.h"
46 #include "desktop.h"
47 #include "dir-util.h"
48 #include "display/nr-arena-item.h"
49 #include "document-private.h"
50 #include "helper/units.h"
51 #include "inkscape-private.h"
52 #include "inkscape-version.h"
53 #include "libavoid/router.h"
54 #include "persp3d.h"
55 #include "preferences.h"
56 #include "profile-manager.h"
57 #include "rdf.h"
58 #include "sp-item-group.h"
59 #include "sp-namedview.h"
60 #include "sp-object-repr.h"
61 #include "transf_mat_3x4.h"
62 #include "unit-constants.h"
63 #include "xml/repr.h"
64 #include "xml/rebase-hrefs.h"
66 // Higher number means lower priority.
67 #define SP_DOCUMENT_UPDATE_PRIORITY (G_PRIORITY_HIGH_IDLE - 2)
69 // Should have a lower priority than SP_DOCUMENT_UPDATE_PRIORITY,
70 // since we want it to happen when there are no more updates.
71 #define SP_DOCUMENT_REROUTING_PRIORITY (G_PRIORITY_HIGH_IDLE - 1)
74 static gint sp_document_idle_handler(gpointer data);
75 static gint sp_document_rerouting_handler(gpointer data);
77 gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data);
79 static gint doc_count = 0;
81 static unsigned long next_serial = 0;
83 SPDocument::SPDocument() :
84     keepalive(FALSE),
85     virgin(TRUE),
86     modified_since_save(FALSE),
87     rdoc(0),
88     rroot(0),
89     root(0),
90     style_cascade(cr_cascade_new(NULL, NULL, NULL)),
91     uri(0),
92     base(0),
93     name(0),
94     priv(0), // reset in ctor
95     actionkey(),
96     modified_id(0),
97     rerouting_handler_id(0),
98     profileManager(0), // deferred until after other initialization
99     router(new Avoid::Router(Avoid::PolyLineRouting|Avoid::OrthogonalRouting)),
100     _collection_queue(0),
101     oldSignalsConnected(false),
102     current_persp3d(0)
104     // Penalise libavoid for choosing paths with needless extra segments.
105     // This results in much better looking orthogonal connector paths.
106     router->setRoutingPenalty(Avoid::segmentPenalty);
108     SPDocumentPrivate *p = new SPDocumentPrivate();
110     p->serial = next_serial++;
112     p->iddef = g_hash_table_new(g_direct_hash, g_direct_equal);
113     p->reprdef = g_hash_table_new(g_direct_hash, g_direct_equal);
115     p->resources = g_hash_table_new(g_str_hash, g_str_equal);
117     p->sensitive = FALSE;
118     p->partial = NULL;
119     p->history_size = 0;
120     p->undo = NULL;
121     p->redo = NULL;
122     p->seeking = false;
124     priv = p;
126     // Once things are set, hook in the manager
127     profileManager = new Inkscape::ProfileManager(this);
129     // XXX only for testing!
130     priv->undoStackObservers.add(p->console_output_undo_observer);
133 SPDocument::~SPDocument() {
134     collectOrphans();
136     // kill/unhook this first
137     if ( profileManager ) {
138         delete profileManager;
139         profileManager = 0;
140     }
142     if (router) {
143         delete router;
144         router = NULL;
145     }
147     if (priv) {
148         if (priv->partial) {
149             sp_repr_free_log(priv->partial);
150             priv->partial = NULL;
151         }
153         sp_document_clear_redo(this);
154         sp_document_clear_undo(this);
156         if (root) {
157             root->releaseReferences();
158             sp_object_unref(root);
159             root = NULL;
160         }
162         if (priv->iddef) g_hash_table_destroy(priv->iddef);
163         if (priv->reprdef) g_hash_table_destroy(priv->reprdef);
165         if (rdoc) Inkscape::GC::release(rdoc);
167         /* Free resources */
168         g_hash_table_foreach_remove(priv->resources, sp_document_resource_list_free, this);
169         g_hash_table_destroy(priv->resources);
171         delete priv;
172         priv = NULL;
173     }
175     cr_cascade_unref(style_cascade);
176     style_cascade = NULL;
178     if (name) {
179         g_free(name);
180         name = NULL;
181     }
182     if (base) {
183         g_free(base);
184         base = NULL;
185     }
186     if (uri) {
187         g_free(uri);
188         uri = NULL;
189     }
191     if (modified_id) {
192         g_source_remove(modified_id);
193         modified_id = 0;
194     }
196     if (rerouting_handler_id) {
197         g_source_remove(rerouting_handler_id);
198         rerouting_handler_id = 0;
199     }
201     if (oldSignalsConnected) {
202         g_signal_handlers_disconnect_by_func(G_OBJECT(INKSCAPE),
203                                              reinterpret_cast<gpointer>(sp_document_reset_key),
204                                              static_cast<gpointer>(this));
205     } else {
206         _selection_changed_connection.disconnect();
207         _desktop_activated_connection.disconnect();
208     }
210     if (keepalive) {
211         inkscape_unref();
212         keepalive = FALSE;
213     }
214     //delete this->_whiteboard_session_manager;
217 Persp3D *
218 SPDocument::getCurrentPersp3D() {
219     // Check if current_persp3d is still valid
220     std::vector<Persp3D*> plist;
221     getPerspectivesInDefs(plist);
222     for (unsigned int i = 0; i < plist.size(); ++i) {
223         if (current_persp3d == plist[i])
224             return current_persp3d;
225     }
227     // If not, return the first perspective in defs (which may be NULL of none exists)
228     current_persp3d = persp3d_document_first_persp (this);
230     return current_persp3d;
233 Persp3DImpl *
234 SPDocument::getCurrentPersp3DImpl() {
235     return current_persp3d_impl;
238 void
239 SPDocument::setCurrentPersp3D(Persp3D * const persp) {
240     current_persp3d = persp;
241     //current_persp3d_impl = persp->perspective_impl;
244 void
245 SPDocument::getPerspectivesInDefs(std::vector<Persp3D*> &list) {
246     SPDefs *defs = SP_ROOT(this->root)->defs;
247     for (SPObject *i = sp_object_first_child(SP_OBJECT(defs)); i != NULL; i = SP_OBJECT_NEXT(i) ) {
248         if (SP_IS_PERSP3D(i))
249             list.push_back(SP_PERSP3D(i));
250     }
253 /**
254 void SPDocument::initialize_current_persp3d()
256     this->current_persp3d = persp3d_document_first_persp(this);
257     if (!this->current_persp3d) {
258         this->current_persp3d = persp3d_create_xml_element(this);
259     }
261 **/
263 unsigned long SPDocument::serial() const {
264     return priv->serial;
267 void SPDocument::queueForOrphanCollection(SPObject *object) {
268     g_return_if_fail(object != NULL);
269     g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
271     sp_object_ref(object, NULL);
272     _collection_queue = g_slist_prepend(_collection_queue, object);
275 void SPDocument::collectOrphans() {
276     while (_collection_queue) {
277         GSList *objects=_collection_queue;
278         _collection_queue = NULL;
279         for ( GSList *iter=objects ; iter ; iter = iter->next ) {
280             SPObject *object=reinterpret_cast<SPObject *>(iter->data);
281             object->collectOrphan();
282             sp_object_unref(object, NULL);
283         }
284         g_slist_free(objects);
285     }
288 void SPDocument::reset_key (void */*dummy*/)
290     actionkey.clear();
293 SPDocument *
294 sp_document_create(Inkscape::XML::Document *rdoc,
295                    gchar const *uri,
296                    gchar const *base,
297                    gchar const *name,
298                    unsigned int keepalive)
300     SPDocument *document;
301     Inkscape::XML::Node *rroot;
302     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
304     rroot = rdoc->root();
306     document = new SPDocument();
308     document->keepalive = keepalive;
310     document->rdoc = rdoc;
311     document->rroot = rroot;
313 #ifndef WIN32
314     document->uri = prepend_current_dir_if_relative(uri);
315 #else
316     // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
317     document->uri = uri? g_strdup(uri) : NULL;
318 #endif
320     // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
321     // which is why we use g_get_current_dir() in calculating the abs path above
322     //This is NULL for a new document
323     if (base)
324         document->base = g_strdup(base);
325     else
326         document->base = NULL;
327     document->name = g_strdup(name);
329     document->root = sp_object_repr_build_tree(document, rroot);
331     /* fixme: Not sure about this, but lets assume ::build updates */
332     rroot->setAttribute("inkscape:version", Inkscape::version_string);
333     /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
335     /* Quick hack 2 - get default image size into document */
336     if (!rroot->attribute("width")) rroot->setAttribute("width", "100%");
337     if (!rroot->attribute("height")) rroot->setAttribute("height", "100%");
338     /* End of quick hack 2 */
340     /* Quick hack 3 - Set uri attributes */
341     if (uri) {
342         rroot->setAttribute("sodipodi:docname", uri);
343     }
344     /* End of quick hack 3 */
346     /* Eliminate obsolete sodipodi:docbase, for privacy reasons */
347     rroot->setAttribute("sodipodi:docbase", NULL);
349     /* Eliminate any claim to adhere to a profile, as we don't try to */
350     rroot->setAttribute("baseProfile", NULL);
352     // creating namedview
353     if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
354         // if there's none in the document already,
355         Inkscape::XML::Node *rnew = NULL;
357         rnew = rdoc->createElement("sodipodi:namedview");
358         //rnew->setAttribute("id", "base");
360         // Add namedview data from the preferences
361         // we can't use getAllEntries because this could produce non-SVG doubles
362         Glib::ustring pagecolor = prefs->getString("/template/base/pagecolor");
363         if (!pagecolor.empty()) {
364             rnew->setAttribute("pagecolor", pagecolor.data());
365         }
366         Glib::ustring bordercolor = prefs->getString("/template/base/bordercolor");
367         if (!bordercolor.empty()) {
368             rnew->setAttribute("bordercolor", bordercolor.data());
369         }
370         sp_repr_set_svg_double(rnew, "borderopacity",
371             prefs->getDouble("/template/base/borderopacity", 1.0));
372         sp_repr_set_svg_double(rnew, "objecttolerance",
373             prefs->getDouble("/template/base/objecttolerance", 10.0));
374         sp_repr_set_svg_double(rnew, "gridtolerance",
375             prefs->getDouble("/template/base/gridtolerance", 10.0));
376         sp_repr_set_svg_double(rnew, "guidetolerance",
377             prefs->getDouble("/template/base/guidetolerance", 10.0));
378         sp_repr_set_svg_double(rnew, "inkscape:pageopacity",
379             prefs->getDouble("/template/base/inkscape:pageopacity", 0.0));
380         sp_repr_set_int(rnew, "inkscape:pageshadow",
381             prefs->getInt("/template/base/inkscape:pageshadow", 2));
382         sp_repr_set_int(rnew, "inkscape:window-width",
383             prefs->getInt("/template/base/inkscape:window-width", 640));
384         sp_repr_set_int(rnew, "inkscape:window-height",
385             prefs->getInt("/template/base/inkscape:window-height", 480));
387         // insert into the document
388         rroot->addChild(rnew, NULL);
389         // clean up
390         Inkscape::GC::release(rnew);
391     }
393     /* Defs */
394     if (!SP_ROOT(document->root)->defs) {
395         Inkscape::XML::Node *r;
396         r = rdoc->createElement("svg:defs");
397         rroot->addChild(r, NULL);
398         Inkscape::GC::release(r);
399         g_assert(SP_ROOT(document->root)->defs);
400     }
402     /* Default RDF */
403     rdf_set_defaults( document );
405     if (keepalive) {
406         inkscape_ref();
407     }
409     // Check if the document already has a perspective (e.g., when opening an existing
410     // document). If not, create a new one and set it as the current perspective.
411     document->setCurrentPersp3D(persp3d_document_first_persp(document));
412     if (!document->getCurrentPersp3D()) {
413         //document->setCurrentPersp3D(persp3d_create_xml_element (document));
414         Persp3DImpl *persp_impl = new Persp3DImpl();
415         document->setCurrentPersp3DImpl(persp_impl);
416     }
418     sp_document_set_undo_sensitive(document, true);
420     // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
421     if (!Inkscape::NSApplication::Application::getNewGui()) {
422         g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
423                          G_CALLBACK(sp_document_reset_key), document);
424         g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
425                          G_CALLBACK(sp_document_reset_key), document);
426         document->oldSignalsConnected = true;
427     } else {
428         document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
429         document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
430         document->oldSignalsConnected = false;
431     }
433     return document;
436 /**
437  * Fetches document from URI, or creates new, if NULL; public document
438  * appears in document list.
439  */
440 SPDocument *
441 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
443     SPDocument *doc;
444     Inkscape::XML::Document *rdoc;
445     gchar *base = NULL;
446     gchar *name = NULL;
448     if (uri) {
449         Inkscape::XML::Node *rroot;
450         gchar *s, *p;
451         /* Try to fetch repr from file */
452         rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
453         /* If file cannot be loaded, return NULL without warning */
454         if (rdoc == NULL) return NULL;
455         rroot = rdoc->root();
456         /* If xml file is not svg, return NULL without warning */
457         /* fixme: destroy document */
458         if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
459         s = g_strdup(uri);
460         p = strrchr(s, '/');
461         if (p) {
462             name = g_strdup(p + 1);
463             p[1] = '\0';
464             base = g_strdup(s);
465         } else {
466             base = NULL;
467             name = g_strdup(uri);
468         }
469         g_free(s);
470     } else {
471         rdoc = sp_repr_document_new("svg:svg");
472     }
474     if (make_new) {
475         base = NULL;
476         uri = NULL;
477         name = g_strdup_printf(_("New document %d"), ++doc_count);
478     }
480     //# These should be set by now
481     g_assert(name);
483     doc = sp_document_create(rdoc, uri, base, name, keepalive);
485     g_free(base);
486     g_free(name);
488     return doc;
491 SPDocument *
492 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
494     SPDocument *doc;
495     Inkscape::XML::Document *rdoc;
496     Inkscape::XML::Node *rroot;
497     gchar *name;
499     rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
501     /* If it cannot be loaded, return NULL without warning */
502     if (rdoc == NULL) return NULL;
504     rroot = rdoc->root();
505     /* If xml file is not svg, return NULL without warning */
506     /* fixme: destroy document */
507     if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
509     name = g_strdup_printf(_("Memory document %d"), ++doc_count);
511     doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
513     return doc;
516 SPDocument *
517 sp_document_ref(SPDocument *doc)
519     g_return_val_if_fail(doc != NULL, NULL);
520     Inkscape::GC::anchor(doc);
521     return doc;
524 SPDocument *
525 sp_document_unref(SPDocument *doc)
527     g_return_val_if_fail(doc != NULL, NULL);
528     Inkscape::GC::release(doc);
529     return NULL;
532 gdouble sp_document_width(SPDocument *document)
534     g_return_val_if_fail(document != NULL, 0.0);
535     g_return_val_if_fail(document->priv != NULL, 0.0);
536     g_return_val_if_fail(document->root != NULL, 0.0);
538     SPRoot *root = SP_ROOT(document->root);
540     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set)
541         return root->viewBox.x1 - root->viewBox.x0;
542     return root->width.computed;
545 void
546 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
548     SPRoot *root = SP_ROOT(document->root);
550     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
551         root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
552     } else { // set to width=
553         gdouble old_computed = root->width.computed;
554         root->width.computed = sp_units_get_pixels (width, *unit);
555         /* SVG does not support meters as a unit, so we must translate meters to
556          * cm when writing */
557         if (!strcmp(unit->abbr, "m")) {
558             root->width.value = 100*width;
559             root->width.unit = SVGLength::CM;
560         } else {
561             root->width.value = width;
562             root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
563         }
565         if (root->viewBox_set)
566             root->viewBox.x1 = root->viewBox.x0 + (root->width.computed / old_computed) * (root->viewBox.x1 - root->viewBox.x0);
567     }
569     SP_OBJECT (root)->updateRepr();
572 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
574     SPRoot *root = SP_ROOT(document->root);
576     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
577         root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
578     } else { // set to height=
579         gdouble old_computed = root->height.computed;
580         root->height.computed = sp_units_get_pixels (height, *unit);
581         /* SVG does not support meters as a unit, so we must translate meters to
582          * cm when writing */
583         if (!strcmp(unit->abbr, "m")) {
584             root->height.value = 100*height;
585             root->height.unit = SVGLength::CM;
586         } else {
587             root->height.value = height;
588             root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
589         }
591         if (root->viewBox_set)
592             root->viewBox.y1 = root->viewBox.y0 + (root->height.computed / old_computed) * (root->viewBox.y1 - root->viewBox.y0);
593     }
595     SP_OBJECT (root)->updateRepr();
598 gdouble sp_document_height(SPDocument *document)
600     g_return_val_if_fail(document != NULL, 0.0);
601     g_return_val_if_fail(document->priv != NULL, 0.0);
602     g_return_val_if_fail(document->root != NULL, 0.0);
604     SPRoot *root = SP_ROOT(document->root);
606     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set)
607         return root->viewBox.y1 - root->viewBox.y0;
608     return root->height.computed;
611 Geom::Point sp_document_dimensions(SPDocument *doc)
613     return Geom::Point(sp_document_width(doc), sp_document_height(doc));
616 /**
617  * Gets page fitting margin information from the namedview node in the XML.
618  * \param nv_repr reference to this document's namedview
619  * \param key the same key used by the RegisteredScalarUnit in
620  *        ui/widget/page-sizer.cpp
621  * \param margin_units units for the margin
622  * \param return_units units to return the result in
623  * \param width width in px (for percentage margins)
624  * \param height height in px (for percentage margins)
625  * \param use_width true if the this key is left or right margins, false
626  *        otherwise.  Used for percentage margins.
627  * \return the margin size in px, else 0.0 if anything is invalid.
628  */
629 static double getMarginLength(Inkscape::XML::Node * const nv_repr,
630                              gchar const * const key,
631                              SPUnit const * const margin_units,
632                              SPUnit const * const return_units,
633                              double const width,
634                              double const height,
635                              bool const use_width)
637     double value;
638     if (!sp_repr_get_double (nv_repr, key, &value)) {
639         return 0.0;
640     }
641     if (margin_units == &sp_unit_get_by_id (SP_UNIT_PERCENT)) {
642         return (use_width)? width * value : height * value; 
643     }
644     if (!sp_convert_distance (&value, margin_units, return_units)) {
645         return 0.0;
646     }
647     return value;
650 /**
651  * Given a Geom::Rect that may, for example, correspond to the bbox of an object,
652  * this function fits the canvas to that rect by resizing the canvas
653  * and translating the document root into position.
654  * \param rect fit document size to this
655  * \param with_margins add margins to rect, by taking margins from this
656  *        document's namedview (<sodipodi:namedview> "fit-margin-..."
657  *        attributes, and "units")
658  */
659 void SPDocument::fitToRect(Geom::Rect const &rect, bool with_margins)
661     double const w = rect.width();
662     double const h = rect.height();
664     double const old_height = sp_document_height(this);
665     SPUnit const &px(sp_unit_get_by_id(SP_UNIT_PX));
666     
667     /* in px */
668     double margin_top = 0.0;
669     double margin_left = 0.0;
670     double margin_right = 0.0;
671     double margin_bottom = 0.0;
672     
673     SPNamedView *nv = sp_document_namedview(this, 0);
674     
675     if (with_margins && nv) {
676         Inkscape::XML::Node *nv_repr = SP_OBJECT_REPR (nv);
677         if (nv_repr != NULL) {
678             gchar const * const units_abbr = nv_repr->attribute("units");
679             SPUnit const *margin_units = NULL;
680             if (units_abbr != NULL) {
681                 margin_units = sp_unit_get_by_abbreviation(units_abbr);
682             }
683             if (margin_units == NULL) {
684                 margin_units = &px;
685             }
686             margin_top = getMarginLength(nv_repr, "fit-margin-top",
687                                          margin_units, &px, w, h, false);
688             margin_left = getMarginLength(nv_repr, "fit-margin-left",
689                                           margin_units, &px, w, h, true);
690             margin_right = getMarginLength(nv_repr, "fit-margin-right",
691                                            margin_units, &px, w, h, true);
692             margin_bottom = getMarginLength(nv_repr, "fit-margin-bottom",
693                                             margin_units, &px, w, h, false);
694         }
695     }
696     
697     Geom::Rect const rect_with_margins(
698             rect.min() - Geom::Point(margin_left, margin_bottom),
699             rect.max() + Geom::Point(margin_right, margin_top));
700     
701     
702     sp_document_set_width(this, rect_with_margins.width(), &px);
703     sp_document_set_height(this, rect_with_margins.height(), &px);
705     Geom::Translate const tr(
706             Geom::Point(0, old_height - rect_with_margins.height())
707             - to_2geom(rect_with_margins.min()));
708     SP_GROUP(root)->translateChildItems(tr);
710     if(nv) {
711         Geom::Translate tr2(-rect_with_margins.min());
712         nv->translateGuides(tr2);
714         // update the viewport so the drawing appears to stay where it was
715         nv->scrollAllDesktops(-tr2[0], tr2[1], false);
716     }
719 static void
720 do_change_uri(SPDocument *const document, gchar const *const filename, bool const rebase)
722     g_return_if_fail(document != NULL);
724     gchar *new_base;
725     gchar *new_name;
726     gchar *new_uri;
727     if (filename) {
729 #ifndef WIN32
730         new_uri = prepend_current_dir_if_relative(filename);
731 #else
732         // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
733         new_uri = g_strdup(filename);
734 #endif
736         new_base = g_path_get_dirname(new_uri);
737         new_name = g_path_get_basename(new_uri);
738     } else {
739         new_uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
740         new_base = NULL;
741         new_name = g_strdup(document->uri);
742     }
744     // Update saveable repr attributes.
745     Inkscape::XML::Node *repr = sp_document_repr_root(document);
747     // Changing uri in the document repr must not be not undoable.
748     bool const saved = sp_document_get_undo_sensitive(document);
749     sp_document_set_undo_sensitive(document, false);
751     if (rebase) {
752         Inkscape::XML::rebase_hrefs(document, new_base, true);
753     }
755     repr->setAttribute("sodipodi:docname", document->name);
756     sp_document_set_undo_sensitive(document, saved);
759     g_free(document->name);
760     g_free(document->base);
761     g_free(document->uri);
762     document->name = new_name;
763     document->base = new_base;
764     document->uri = new_uri;
766     document->priv->uri_set_signal.emit(document->uri);
769 /**
770  * Sets base, name and uri members of \a document.  Doesn't update
771  * any relative hrefs in the document: thus, this is primarily for
772  * newly-created documents.
773  *
774  * \see sp_document_change_uri_and_hrefs
775  */
776 void sp_document_set_uri(SPDocument *document, gchar const *filename)
778     g_return_if_fail(document != NULL);
780     do_change_uri(document, filename, false);
783 /**
784  * Changes the base, name and uri members of \a document, and updates any
785  * relative hrefs in the document to be relative to the new base.
786  *
787  * \see sp_document_set_uri
788  */
789 void sp_document_change_uri_and_hrefs(SPDocument *document, gchar const *filename)
791     g_return_if_fail(document != NULL);
793     do_change_uri(document, filename, true);
796 void
797 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
799     g_return_if_fail(doc != NULL);
801     doc->priv->resized_signal.emit(width, height);
804 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
806     return priv->modified_signal.connect(slot);
809 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
811     return priv->uri_set_signal.connect(slot);
814 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
816     return priv->resized_signal.connect(slot);
819 sigc::connection
820 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
822     return priv->_reconstruction_start_signal.connect(slot);
825 void
826 SPDocument::emitReconstructionStart(void)
828     // printf("Starting Reconstruction\n");
829     priv->_reconstruction_start_signal.emit();
830     return;
833 sigc::connection
834 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type  slot)
836     return priv->_reconstruction_finish_signal.connect(slot);
839 void
840 SPDocument::emitReconstructionFinish(void)
842     // printf("Finishing Reconstruction\n");
843     priv->_reconstruction_finish_signal.emit();
845 /**    
846     // Reference to the old persp3d object is invalid after reconstruction.
847     initialize_current_persp3d();
848     
849     return;
850 **/
853 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
855     return priv->commit_signal.connect(slot);
860 void SPDocument::_emitModified() {
861     static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
862     root->emitModified(0);
863     priv->modified_signal.emit(flags);
866 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
867     GQuark idq = g_quark_from_string(id);
869     if (object) {
870         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
871         g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
872     } else {
873         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
874         g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
875     }
877     SPDocumentPrivate::IDChangedSignalMap::iterator pos;
879     pos = priv->id_changed_signals.find(idq);
880     if ( pos != priv->id_changed_signals.end() ) {
881         if (!(*pos).second.empty()) {
882             (*pos).second.emit(object);
883         } else { // discard unused signal
884             priv->id_changed_signals.erase(pos);
885         }
886     }
889 void
890 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
892     this->priv->undoStackObservers.add(observer);
895 void
896 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
898     this->priv->undoStackObservers.remove(observer);
901 SPObject *SPDocument::getObjectById(gchar const *id) {
902     g_return_val_if_fail(id != NULL, NULL);
904     GQuark idq = g_quark_from_string(id);
905     return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
908 sigc::connection SPDocument::connectIdChanged(gchar const *id,
909                                               SPDocument::IDChangedSignal::slot_type slot)
911     return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
914 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
915     if (object) {
916         g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
917         g_hash_table_insert(priv->reprdef, repr, object);
918     } else {
919         g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
920         g_hash_table_remove(priv->reprdef, repr);
921     }
924 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
925     g_return_val_if_fail(repr != NULL, NULL);
926     return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
929 Glib::ustring SPDocument::getLanguage() {
930     gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
931     if (document_language) {
932         while (isspace(*document_language))
933             document_language++;
934     }
935     if ( !document_language || 0 == *document_language) {
936         // retrieve system language
937         document_language = getenv("LC_ALL");
938         if ( NULL == document_language || *document_language == 0 ) {
939             document_language = getenv ("LC_MESSAGES");
940         }
941         if ( NULL == document_language || *document_language == 0 ) {
942             document_language = getenv ("LANG");
943         }
945         if ( NULL != document_language ) {
946             const char *pos = strchr(document_language, '_');
947             if ( NULL != pos ) {
948                 return Glib::ustring(document_language, pos - document_language);
949             }
950         }
951     }
953     if ( NULL == document_language )
954         return Glib::ustring();
955     return document_language;
958 /* Object modification root handler */
960 void
961 sp_document_request_modified(SPDocument *doc)
963     if (!doc->modified_id) {
964         doc->modified_id = g_idle_add_full(SP_DOCUMENT_UPDATE_PRIORITY, 
965                 sp_document_idle_handler, doc, NULL);
966     }
967     if (!doc->rerouting_handler_id) {
968         doc->rerouting_handler_id = g_idle_add_full(SP_DOCUMENT_REROUTING_PRIORITY, 
969                 sp_document_rerouting_handler, doc, NULL);
970     }
973 void
974 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
976     ctx->ctx.flags = 0;
977     ctx->i2doc = Geom::identity();
978     /* Set up viewport in case svg has it defined as percentages */
979     if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
980         ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
981         ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
982         ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
983         ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
984     } else { // as a last resort, set size to A4
985         ctx->vp.x0 = 0.0;
986         ctx->vp.y0 = 0.0;
987         ctx->vp.x1 = 210 * PX_PER_MM;
988         ctx->vp.y1 = 297 * PX_PER_MM;
989     }
990     ctx->i2vp = Geom::identity();
993 /**
994  * Tries to update the document state based on the modified and
995  * "update required" flags, and return true if the document has
996  * been brought fully up to date.
997  */
998 bool
999 SPDocument::_updateDocument()
1001     /* Process updates */
1002     if (this->root->uflags || this->root->mflags) {
1003         if (this->root->uflags) {
1004             SPItemCtx ctx;
1005             sp_document_setup_viewport (this, &ctx);
1007             bool saved = sp_document_get_undo_sensitive(this);
1008             sp_document_set_undo_sensitive(this, false);
1010             this->root->updateDisplay((SPCtx *)&ctx, 0);
1012             sp_document_set_undo_sensitive(this, saved);
1013         }
1014         this->_emitModified();
1015     }
1017     return !(this->root->uflags || this->root->mflags);
1021 /**
1022  * Repeatedly works on getting the document updated, since sometimes
1023  * it takes more than one pass to get the document updated.  But it
1024  * usually should not take more than a few loops, and certainly never
1025  * more than 32 iterations.  So we bail out if we hit 32 iterations,
1026  * since this typically indicates we're stuck in an update loop.
1027  */
1028 gint
1029 sp_document_ensure_up_to_date(SPDocument *doc)
1031     // Bring the document up-to-date, specifically via the following:
1032     //   1a) Process all document updates.
1033     //   1b) When completed, process connector routing changes.
1034     //   2a) Process any updates resulting from connector reroutings.
1035     int counter = 32;
1036     for (unsigned int pass = 1; pass <= 2; ++pass) {
1037         // Process document updates.
1038         while (!doc->_updateDocument()) {
1039             if (counter == 0) {
1040                 g_warning("More than 32 iteration while updating document '%s'", doc->uri);
1041                 break;
1042             }
1043             counter--;
1044         }
1045         if (counter == 0)
1046         {
1047             break;
1048         }
1050         // After updates on the first pass we get libavoid to process all the 
1051         // changed objects and provide new routings.  This may cause some objects
1052             // to be modified, hence the second update pass.
1053         if (pass == 1) {
1054             doc->router->processTransaction();
1055         }
1056     }
1057     
1058     if (doc->modified_id) {
1059         /* Remove handler */
1060         g_source_remove(doc->modified_id);
1061         doc->modified_id = 0;
1062     }
1063     if (doc->rerouting_handler_id) {
1064         /* Remove handler */
1065         g_source_remove(doc->rerouting_handler_id);
1066         doc->rerouting_handler_id = 0;
1067     }
1068     return counter>0;
1071 /**
1072  * An idle handler to update the document.  Returns true if
1073  * the document needs further updates.
1074  */
1075 static gint
1076 sp_document_idle_handler(gpointer data)
1078     SPDocument *doc = static_cast<SPDocument *>(data);
1079     if (doc->_updateDocument()) {
1080         doc->modified_id = 0;
1081         return false;
1082     } else {
1083         return true;
1084     }
1087 /**
1088  * An idle handler to reroute connectors in the document.  
1089  */
1090 static gint
1091 sp_document_rerouting_handler(gpointer data)
1093     // Process any queued movement actions and determine new routings for 
1094     // object-avoiding connectors.  Callbacks will be used to update and 
1095     // redraw affected connectors.
1096     SPDocument *doc = static_cast<SPDocument *>(data);
1097     doc->router->processTransaction();
1098     
1099     // We don't need to handle rerouting again until there are further 
1100     // diagram updates.
1101     doc->rerouting_handler_id = 0;
1102     return false;
1105 static bool is_within(Geom::Rect const &area, Geom::Rect const &box)
1107     return area.contains(box);
1110 static bool overlaps(Geom::Rect const &area, Geom::Rect const &box)
1112     return area.intersects(box);
1115 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, Geom::Rect const &area,
1116                                   bool (*test)(Geom::Rect const &, Geom::Rect const &), bool take_insensitive = false)
1118     g_return_val_if_fail(SP_IS_GROUP(group), s);
1120     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1121         if (!SP_IS_ITEM(o)) {
1122             continue;
1123         }
1124         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
1125             s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
1126         } else {
1127             SPItem *child = SP_ITEM(o);
1128             Geom::OptRect box = sp_item_bbox_desktop(child);
1129             if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1130                 s = g_slist_append(s, child);
1131             }
1132         }
1133     }
1135     return s;
1138 /**
1139 Returns true if an item is among the descendants of group (recursively).
1140  */
1141 bool item_is_in_group(SPItem *item, SPGroup *group)
1143     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1144         if (!SP_IS_ITEM(o)) continue;
1145         if (SP_ITEM(o) == item)
1146             return true;
1147         if (SP_IS_GROUP(o))
1148             if (item_is_in_group(item, SP_GROUP(o)))
1149                 return true;
1150     }
1151     return false;
1154 /**
1155 Returns the bottommost item from the list which is at the point, or NULL if none.
1156 */
1157 SPItem*
1158 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
1159                                            Geom::Point const p, bool take_insensitive)
1161     g_return_val_if_fail(group, NULL);
1162     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1163     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1165     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1167         if (!SP_IS_ITEM(o)) continue;
1169         SPItem *item = SP_ITEM(o);
1170         NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
1171         if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1172             && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
1173             if (g_slist_find((GSList *) list, item) != NULL)
1174                 return item;
1175         }
1177         if (SP_IS_GROUP(o)) {
1178             SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
1179             if (found)
1180                 return found;
1181         }
1183     }
1184     return NULL;
1187 /**
1188 Returns the topmost (in z-order) item from the descendants of group (recursively) which
1189 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
1190 non-layer groups or not. Honors take_insensitive on whether to return insensitive
1191 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
1192 upwards in z-order and returns what it has found so far (i.e. the found item is
1193 guaranteed to be lower than upto).
1194  */
1195 SPItem*
1196 find_item_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
1198     SPItem *seen = NULL, *newseen = NULL;
1199     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1200     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1202     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1203         if (!SP_IS_ITEM(o)) continue;
1205         if (upto && SP_ITEM(o) == upto)
1206             break;
1208         if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
1209             // if nothing found yet, recurse into the group
1210             newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
1211             if (newseen) {
1212                 seen = newseen;
1213                 newseen = NULL;
1214             }
1216             if (item_is_in_group(upto, SP_GROUP(o)))
1217                 break;
1219         } else {
1220             SPItem *child = SP_ITEM(o);
1221             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1223             // seen remembers the last (topmost) of items pickable at this point
1224             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1225                 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1226                 seen = child;
1227             }
1228         }
1229     }
1230     return seen;
1233 /**
1234 Returns the topmost non-layer group from the descendants of group which is at point
1235 p, or NULL if none. Recurses into layers but not into groups.
1236  */
1237 SPItem*
1238 find_group_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p)
1240     SPItem *seen = NULL;
1241     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1242     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1244     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1245         if (!SP_IS_ITEM(o)) continue;
1246         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1247             SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1248             if (newseen) {
1249                 seen = newseen;
1250             }
1251         }
1252         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1253             SPItem *child = SP_ITEM(o);
1254             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1256             // seen remembers the last (topmost) of groups pickable at this point
1257             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1258                 seen = child;
1259             }
1260         }
1261     }
1262     return seen;
1265 /*
1266  * Return list of items, contained in box
1267  *
1268  * Assumes box is normalized (and g_asserts it!)
1269  *
1270  */
1272 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1274     g_return_val_if_fail(document != NULL, NULL);
1275     g_return_val_if_fail(document->priv != NULL, NULL);
1277     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
1280 /*
1281  * Return list of items, that the parts of the item contained in box
1282  *
1283  * Assumes box is normalized (and g_asserts it!)
1284  *
1285  */
1287 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1289     g_return_val_if_fail(document != NULL, NULL);
1290     g_return_val_if_fail(document->priv != NULL, NULL);
1292     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1295 GSList *
1296 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<Geom::Point> points)
1298     GSList *items = NULL;
1299     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1301     // When picking along the path, we don't want small objects close together
1302     // (such as hatching strokes) to obscure each other by their deltas,
1303     // so we temporarily set delta to a small value
1304     gdouble saved_delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1305     prefs->setDouble("/options/cursortolerance/value", 0.25);
1307     for(unsigned int i = 0; i < points.size(); i++) {
1308         SPItem *item = sp_document_item_at_point(document, key, points[i],
1309                                                  false, NULL);
1310         if (item && !g_slist_find(items, item))
1311             items = g_slist_prepend (items, item);
1312     }
1314     // and now we restore it back
1315     prefs->setDouble("/options/cursortolerance/value", saved_delta);
1317     return items;
1320 SPItem *
1321 sp_document_item_at_point(SPDocument *document, unsigned const key, Geom::Point const p,
1322                           gboolean const into_groups, SPItem *upto)
1324     g_return_val_if_fail(document != NULL, NULL);
1325     g_return_val_if_fail(document->priv != NULL, NULL);
1327     return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1330 SPItem*
1331 sp_document_group_at_point(SPDocument *document, unsigned int key, Geom::Point const p)
1333     g_return_val_if_fail(document != NULL, NULL);
1334     g_return_val_if_fail(document->priv != NULL, NULL);
1336     return find_group_at_point(key, SP_GROUP(document->root), p);
1340 /* Resource management */
1342 gboolean
1343 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1345     GSList *rlist;
1346     GQuark q = g_quark_from_string(key);
1348     g_return_val_if_fail(document != NULL, FALSE);
1349     g_return_val_if_fail(key != NULL, FALSE);
1350     g_return_val_if_fail(*key != '\0', FALSE);
1351     g_return_val_if_fail(object != NULL, FALSE);
1352     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1354     if (SP_OBJECT_IS_CLONED(object))
1355         return FALSE;
1357     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1358     g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1359     rlist = g_slist_prepend(rlist, object);
1360     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1362     document->priv->resources_changed_signals[q].emit();
1364     return TRUE;
1367 gboolean
1368 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1370     GSList *rlist;
1371     GQuark q = g_quark_from_string(key);
1373     g_return_val_if_fail(document != NULL, FALSE);
1374     g_return_val_if_fail(key != NULL, FALSE);
1375     g_return_val_if_fail(*key != '\0', FALSE);
1376     g_return_val_if_fail(object != NULL, FALSE);
1377     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1379     if (SP_OBJECT_IS_CLONED(object))
1380         return FALSE;
1382     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1383     g_return_val_if_fail(rlist != NULL, FALSE);
1384     g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1385     rlist = g_slist_remove(rlist, object);
1386     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1388     document->priv->resources_changed_signals[q].emit();
1390     return TRUE;
1393 GSList const *
1394 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1396     g_return_val_if_fail(document != NULL, NULL);
1397     g_return_val_if_fail(key != NULL, NULL);
1398     g_return_val_if_fail(*key != '\0', NULL);
1400     return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1403 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1404                                                        gchar const *key,
1405                                                        SPDocument::ResourcesChangedSignal::slot_type slot)
1407     GQuark q = g_quark_from_string(key);
1408     return document->priv->resources_changed_signals[q].connect(slot);
1411 /* Helpers */
1413 gboolean
1414 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1416     g_slist_free((GSList *) value);
1417     return TRUE;
1420 unsigned int
1421 count_objects_recursive(SPObject *obj, unsigned int count)
1423     count++; // obj itself
1425     for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1426         count = count_objects_recursive(i, count);
1427     }
1429     return count;
1432 unsigned int
1433 objects_in_document(SPDocument *document)
1435     return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1438 void
1439 vacuum_document_recursive(SPObject *obj)
1441     if (SP_IS_DEFS(obj)) {
1442         for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1443             /* fixme: some inkscape-internal nodes in the future might not be collectable */
1444             def->requestOrphanCollection();
1445         }
1446     } else {
1447         for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1448             vacuum_document_recursive(i);
1449         }
1450     }
1453 unsigned int
1454 vacuum_document(SPDocument *document)
1456     unsigned int start = objects_in_document(document);
1457     unsigned int end;
1458     unsigned int newend = start;
1460     unsigned int iterations = 0;
1462     do {
1463         end = newend;
1465         vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1466         document->collectOrphans();
1467         iterations++;
1469         newend = objects_in_document(document);
1471     } while (iterations < 100 && newend < end);
1473     return start - newend;
1476 bool SPDocument::isSeeking() const {
1477     return priv->seeking;
1481 /*
1482   Local Variables:
1483   mode:c++
1484   c-file-style:"stroustrup"
1485   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1486   indent-tabs-mode:nil
1487   fill-column:99
1488   End:
1489 */
1490 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :