Code

Pot and Dutch translation update
[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 "desktop.h"
45 #include "dir-util.h"
46 #include "display/nr-arena-item.h"
47 #include "document-private.h"
48 #include "helper/units.h"
49 #include "inkscape-private.h"
50 #include "inkscape-version.h"
51 #include "libavoid/router.h"
52 #include "persp3d.h"
53 #include "preferences.h"
54 #include "profile-manager.h"
55 #include "rdf.h"
56 #include "sp-item-group.h"
57 #include "sp-namedview.h"
58 #include "sp-object-repr.h"
59 #include "transf_mat_3x4.h"
60 #include "unit-constants.h"
61 #include "xml/repr.h"
62 #include "xml/rebase-hrefs.h"
64 // Higher number means lower priority.
65 #define SP_DOCUMENT_UPDATE_PRIORITY (G_PRIORITY_HIGH_IDLE - 2)
67 // Should have a lower priority than SP_DOCUMENT_UPDATE_PRIORITY,
68 // since we want it to happen when there are no more updates.
69 #define SP_DOCUMENT_REROUTING_PRIORITY (G_PRIORITY_HIGH_IDLE - 1)
72 static gint sp_document_idle_handler(gpointer data);
73 static gint sp_document_rerouting_handler(gpointer data);
75 gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data);
77 static gint doc_count = 0;
79 static unsigned long next_serial = 0;
81 SPDocument::SPDocument() :
82     keepalive(FALSE),
83     virgin(TRUE),
84     modified_since_save(FALSE),
85     rdoc(0),
86     rroot(0),
87     root(0),
88     style_cascade(cr_cascade_new(NULL, NULL, NULL)),
89     uri(0),
90     base(0),
91     name(0),
92     priv(0), // reset in ctor
93     actionkey(),
94     modified_id(0),
95     rerouting_handler_id(0),
96     profileManager(0), // deferred until after other initialization
97     router(new Avoid::Router(Avoid::PolyLineRouting|Avoid::OrthogonalRouting)),
98     _collection_queue(0),
99     oldSignalsConnected(false),
100     current_persp3d(0)
102     // Penalise libavoid for choosing paths with needless extra segments.
103     // This results in much better looking orthogonal connector paths.
104     router->setRoutingPenalty(Avoid::segmentPenalty);
106     SPDocumentPrivate *p = new SPDocumentPrivate();
108     p->serial = next_serial++;
110     p->iddef = g_hash_table_new(g_direct_hash, g_direct_equal);
111     p->reprdef = g_hash_table_new(g_direct_hash, g_direct_equal);
113     p->resources = g_hash_table_new(g_str_hash, g_str_equal);
115     p->sensitive = FALSE;
116     p->partial = NULL;
117     p->history_size = 0;
118     p->undo = NULL;
119     p->redo = NULL;
120     p->seeking = false;
122     priv = p;
124     // Once things are set, hook in the manager
125     profileManager = new Inkscape::ProfileManager(this);
127     // XXX only for testing!
128     priv->undoStackObservers.add(p->console_output_undo_observer);
131 SPDocument::~SPDocument() {
132     collectOrphans();
134     // kill/unhook this first
135     if ( profileManager ) {
136         delete profileManager;
137         profileManager = 0;
138     }
140     if (router) {
141         delete router;
142         router = NULL;
143     }
145     if (priv) {
146         if (priv->partial) {
147             sp_repr_free_log(priv->partial);
148             priv->partial = NULL;
149         }
151         sp_document_clear_redo(this);
152         sp_document_clear_undo(this);
154         if (root) {
155             root->releaseReferences();
156             sp_object_unref(root);
157             root = NULL;
158         }
160         if (priv->iddef) g_hash_table_destroy(priv->iddef);
161         if (priv->reprdef) g_hash_table_destroy(priv->reprdef);
163         if (rdoc) Inkscape::GC::release(rdoc);
165         /* Free resources */
166         g_hash_table_foreach_remove(priv->resources, sp_document_resource_list_free, this);
167         g_hash_table_destroy(priv->resources);
169         delete priv;
170         priv = NULL;
171     }
173     cr_cascade_unref(style_cascade);
174     style_cascade = NULL;
176     if (name) {
177         g_free(name);
178         name = NULL;
179     }
180     if (base) {
181         g_free(base);
182         base = NULL;
183     }
184     if (uri) {
185         g_free(uri);
186         uri = NULL;
187     }
189     if (modified_id) {
190         g_source_remove(modified_id);
191         modified_id = 0;
192     }
194     if (rerouting_handler_id) {
195         g_source_remove(rerouting_handler_id);
196         rerouting_handler_id = 0;
197     }
199     if (oldSignalsConnected) {
200         g_signal_handlers_disconnect_by_func(G_OBJECT(INKSCAPE),
201                                              reinterpret_cast<gpointer>(sp_document_reset_key),
202                                              static_cast<gpointer>(this));
203     } else {
204         _selection_changed_connection.disconnect();
205         _desktop_activated_connection.disconnect();
206     }
208     if (keepalive) {
209         inkscape_unref();
210         keepalive = FALSE;
211     }
212     //delete this->_whiteboard_session_manager;
215 Persp3D *
216 SPDocument::getCurrentPersp3D() {
217     // Check if current_persp3d is still valid
218     std::vector<Persp3D*> plist;
219     getPerspectivesInDefs(plist);
220     for (unsigned int i = 0; i < plist.size(); ++i) {
221         if (current_persp3d == plist[i])
222             return current_persp3d;
223     }
225     // If not, return the first perspective in defs (which may be NULL of none exists)
226     current_persp3d = persp3d_document_first_persp (this);
228     return current_persp3d;
231 Persp3DImpl *
232 SPDocument::getCurrentPersp3DImpl() {
233     return current_persp3d_impl;
236 void
237 SPDocument::setCurrentPersp3D(Persp3D * const persp) {
238     current_persp3d = persp;
239     //current_persp3d_impl = persp->perspective_impl;
242 void
243 SPDocument::getPerspectivesInDefs(std::vector<Persp3D*> &list) {
244     SPDefs *defs = SP_ROOT(this->root)->defs;
245     for (SPObject *i = sp_object_first_child(SP_OBJECT(defs)); i != NULL; i = SP_OBJECT_NEXT(i) ) {
246         if (SP_IS_PERSP3D(i))
247             list.push_back(SP_PERSP3D(i));
248     }
251 /**
252 void SPDocument::initialize_current_persp3d()
254     this->current_persp3d = persp3d_document_first_persp(this);
255     if (!this->current_persp3d) {
256         this->current_persp3d = persp3d_create_xml_element(this);
257     }
259 **/
261 unsigned long SPDocument::serial() const {
262     return priv->serial;
265 void SPDocument::queueForOrphanCollection(SPObject *object) {
266     g_return_if_fail(object != NULL);
267     g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
269     sp_object_ref(object, NULL);
270     _collection_queue = g_slist_prepend(_collection_queue, object);
273 void SPDocument::collectOrphans() {
274     while (_collection_queue) {
275         GSList *objects=_collection_queue;
276         _collection_queue = NULL;
277         for ( GSList *iter=objects ; iter ; iter = iter->next ) {
278             SPObject *object=reinterpret_cast<SPObject *>(iter->data);
279             object->collectOrphan();
280             sp_object_unref(object, NULL);
281         }
282         g_slist_free(objects);
283     }
286 void SPDocument::reset_key (void */*dummy*/)
288     actionkey.clear();
291 SPDocument *
292 sp_document_create(Inkscape::XML::Document *rdoc,
293                    gchar const *uri,
294                    gchar const *base,
295                    gchar const *name,
296                    unsigned int keepalive)
298     SPDocument *document;
299     Inkscape::XML::Node *rroot;
300     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
302     rroot = rdoc->root();
304     document = new SPDocument();
306     document->keepalive = keepalive;
308     document->rdoc = rdoc;
309     document->rroot = rroot;
311 #ifndef WIN32
312     document->uri = prepend_current_dir_if_relative(uri);
313 #else
314     // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
315     document->uri = uri? g_strdup(uri) : NULL;
316 #endif
318     // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
319     // which is why we use g_get_current_dir() in calculating the abs path above
320     //This is NULL for a new document
321     if (base)
322         document->base = g_strdup(base);
323     else
324         document->base = NULL;
325     document->name = g_strdup(name);
327     document->root = sp_object_repr_build_tree(document, rroot);
329     /* fixme: Not sure about this, but lets assume ::build updates */
330     rroot->setAttribute("inkscape:version", Inkscape::version_string);
331     /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
333     /* Quick hack 2 - get default image size into document */
334     if (!rroot->attribute("width")) rroot->setAttribute("width", "100%");
335     if (!rroot->attribute("height")) rroot->setAttribute("height", "100%");
336     /* End of quick hack 2 */
338     /* Quick hack 3 - Set uri attributes */
339     if (uri) {
340         rroot->setAttribute("sodipodi:docname", uri);
341     }
342     /* End of quick hack 3 */
344     /* Eliminate obsolete sodipodi:docbase, for privacy reasons */
345     rroot->setAttribute("sodipodi:docbase", NULL);
347     /* Eliminate any claim to adhere to a profile, as we don't try to */
348     rroot->setAttribute("baseProfile", NULL);
350     // creating namedview
351     if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
352         // if there's none in the document already,
353         Inkscape::XML::Node *rnew = NULL;
355         rnew = rdoc->createElement("sodipodi:namedview");
356         //rnew->setAttribute("id", "base");
358         // Add namedview data from the preferences
359         // we can't use getAllEntries because this could produce non-SVG doubles
360         Glib::ustring pagecolor = prefs->getString("/template/base/pagecolor");
361         if (!pagecolor.empty()) {
362             rnew->setAttribute("pagecolor", pagecolor.data());
363         }
364         Glib::ustring bordercolor = prefs->getString("/template/base/bordercolor");
365         if (!bordercolor.empty()) {
366             rnew->setAttribute("bordercolor", bordercolor.data());
367         }
368         sp_repr_set_svg_double(rnew, "borderopacity",
369             prefs->getDouble("/template/base/borderopacity", 1.0));
370         sp_repr_set_svg_double(rnew, "objecttolerance",
371             prefs->getDouble("/template/base/objecttolerance", 10.0));
372         sp_repr_set_svg_double(rnew, "gridtolerance",
373             prefs->getDouble("/template/base/gridtolerance", 10.0));
374         sp_repr_set_svg_double(rnew, "guidetolerance",
375             prefs->getDouble("/template/base/guidetolerance", 10.0));
376         sp_repr_set_svg_double(rnew, "inkscape:pageopacity",
377             prefs->getDouble("/template/base/inkscape:pageopacity", 0.0));
378         sp_repr_set_int(rnew, "inkscape:pageshadow",
379             prefs->getInt("/template/base/inkscape:pageshadow", 2));
380         sp_repr_set_int(rnew, "inkscape:window-width",
381             prefs->getInt("/template/base/inkscape:window-width", 640));
382         sp_repr_set_int(rnew, "inkscape:window-height",
383             prefs->getInt("/template/base/inkscape:window-height", 480));
385         // insert into the document
386         rroot->addChild(rnew, NULL);
387         // clean up
388         Inkscape::GC::release(rnew);
389     }
391     /* Defs */
392     if (!SP_ROOT(document->root)->defs) {
393         Inkscape::XML::Node *r;
394         r = rdoc->createElement("svg:defs");
395         rroot->addChild(r, NULL);
396         Inkscape::GC::release(r);
397         g_assert(SP_ROOT(document->root)->defs);
398     }
400     /* Default RDF */
401     rdf_set_defaults( document );
403     if (keepalive) {
404         inkscape_ref();
405     }
407     // Check if the document already has a perspective (e.g., when opening an existing
408     // document). If not, create a new one and set it as the current perspective.
409     document->setCurrentPersp3D(persp3d_document_first_persp(document));
410     if (!document->getCurrentPersp3D()) {
411         //document->setCurrentPersp3D(persp3d_create_xml_element (document));
412         Persp3DImpl *persp_impl = new Persp3DImpl();
413         document->setCurrentPersp3DImpl(persp_impl);
414     }
416     sp_document_set_undo_sensitive(document, true);
418     // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
419     g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
420                      G_CALLBACK(sp_document_reset_key), document);
421     g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
422                      G_CALLBACK(sp_document_reset_key), document);
423     document->oldSignalsConnected = true;
425     return document;
428 /**
429  * Fetches document from URI, or creates new, if NULL; public document
430  * appears in document list.
431  */
432 SPDocument *
433 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
435     SPDocument *doc;
436     Inkscape::XML::Document *rdoc;
437     gchar *base = NULL;
438     gchar *name = NULL;
440     if (uri) {
441         Inkscape::XML::Node *rroot;
442         gchar *s, *p;
443         /* Try to fetch repr from file */
444         rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
445         /* If file cannot be loaded, return NULL without warning */
446         if (rdoc == NULL) return NULL;
447         rroot = rdoc->root();
448         /* If xml file is not svg, return NULL without warning */
449         /* fixme: destroy document */
450         if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
451         s = g_strdup(uri);
452         p = strrchr(s, '/');
453         if (p) {
454             name = g_strdup(p + 1);
455             p[1] = '\0';
456             base = g_strdup(s);
457         } else {
458             base = NULL;
459             name = g_strdup(uri);
460         }
461         g_free(s);
462     } else {
463         rdoc = sp_repr_document_new("svg:svg");
464     }
466     if (make_new) {
467         base = NULL;
468         uri = NULL;
469         name = g_strdup_printf(_("New document %d"), ++doc_count);
470     }
472     //# These should be set by now
473     g_assert(name);
475     doc = sp_document_create(rdoc, uri, base, name, keepalive);
477     g_free(base);
478     g_free(name);
480     return doc;
483 SPDocument *
484 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
486     SPDocument *doc;
487     Inkscape::XML::Document *rdoc;
488     Inkscape::XML::Node *rroot;
489     gchar *name;
491     rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
493     /* If it cannot be loaded, return NULL without warning */
494     if (rdoc == NULL) return NULL;
496     rroot = rdoc->root();
497     /* If xml file is not svg, return NULL without warning */
498     /* fixme: destroy document */
499     if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
501     name = g_strdup_printf(_("Memory document %d"), ++doc_count);
503     doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
505     return doc;
508 SPDocument *
509 sp_document_ref(SPDocument *doc)
511     g_return_val_if_fail(doc != NULL, NULL);
512     Inkscape::GC::anchor(doc);
513     return doc;
516 SPDocument *
517 sp_document_unref(SPDocument *doc)
519     g_return_val_if_fail(doc != NULL, NULL);
520     Inkscape::GC::release(doc);
521     return NULL;
524 gdouble sp_document_width(SPDocument *document)
526     g_return_val_if_fail(document != NULL, 0.0);
527     g_return_val_if_fail(document->priv != NULL, 0.0);
528     g_return_val_if_fail(document->root != NULL, 0.0);
530     SPRoot *root = SP_ROOT(document->root);
532     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set)
533         return root->viewBox.x1 - root->viewBox.x0;
534     return root->width.computed;
537 void
538 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
540     SPRoot *root = SP_ROOT(document->root);
542     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
543         root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
544     } else { // set to width=
545         gdouble old_computed = root->width.computed;
546         root->width.computed = sp_units_get_pixels (width, *unit);
547         /* SVG does not support meters as a unit, so we must translate meters to
548          * cm when writing */
549         if (!strcmp(unit->abbr, "m")) {
550             root->width.value = 100*width;
551             root->width.unit = SVGLength::CM;
552         } else {
553             root->width.value = width;
554             root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
555         }
557         if (root->viewBox_set)
558             root->viewBox.x1 = root->viewBox.x0 + (root->width.computed / old_computed) * (root->viewBox.x1 - root->viewBox.x0);
559     }
561     SP_OBJECT (root)->updateRepr();
564 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
566     SPRoot *root = SP_ROOT(document->root);
568     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
569         root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
570     } else { // set to height=
571         gdouble old_computed = root->height.computed;
572         root->height.computed = sp_units_get_pixels (height, *unit);
573         /* SVG does not support meters as a unit, so we must translate meters to
574          * cm when writing */
575         if (!strcmp(unit->abbr, "m")) {
576             root->height.value = 100*height;
577             root->height.unit = SVGLength::CM;
578         } else {
579             root->height.value = height;
580             root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
581         }
583         if (root->viewBox_set)
584             root->viewBox.y1 = root->viewBox.y0 + (root->height.computed / old_computed) * (root->viewBox.y1 - root->viewBox.y0);
585     }
587     SP_OBJECT (root)->updateRepr();
590 gdouble sp_document_height(SPDocument *document)
592     g_return_val_if_fail(document != NULL, 0.0);
593     g_return_val_if_fail(document->priv != NULL, 0.0);
594     g_return_val_if_fail(document->root != NULL, 0.0);
596     SPRoot *root = SP_ROOT(document->root);
598     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set)
599         return root->viewBox.y1 - root->viewBox.y0;
600     return root->height.computed;
603 Geom::Point sp_document_dimensions(SPDocument *doc)
605     return Geom::Point(sp_document_width(doc), sp_document_height(doc));
608 /**
609  * Gets page fitting margin information from the namedview node in the XML.
610  * \param nv_repr reference to this document's namedview
611  * \param key the same key used by the RegisteredScalarUnit in
612  *        ui/widget/page-sizer.cpp
613  * \param margin_units units for the margin
614  * \param return_units units to return the result in
615  * \param width width in px (for percentage margins)
616  * \param height height in px (for percentage margins)
617  * \param use_width true if the this key is left or right margins, false
618  *        otherwise.  Used for percentage margins.
619  * \return the margin size in px, else 0.0 if anything is invalid.
620  */
621 static double getMarginLength(Inkscape::XML::Node * const nv_repr,
622                              gchar const * const key,
623                              SPUnit const * const margin_units,
624                              SPUnit const * const return_units,
625                              double const width,
626                              double const height,
627                              bool const use_width)
629     double value;
630     if (!sp_repr_get_double (nv_repr, key, &value)) {
631         return 0.0;
632     }
633     if (margin_units == &sp_unit_get_by_id (SP_UNIT_PERCENT)) {
634         return (use_width)? width * value : height * value; 
635     }
636     if (!sp_convert_distance (&value, margin_units, return_units)) {
637         return 0.0;
638     }
639     return value;
642 /**
643  * Given a Geom::Rect that may, for example, correspond to the bbox of an object,
644  * this function fits the canvas to that rect by resizing the canvas
645  * and translating the document root into position.
646  * \param rect fit document size to this
647  * \param with_margins add margins to rect, by taking margins from this
648  *        document's namedview (<sodipodi:namedview> "fit-margin-..."
649  *        attributes, and "units")
650  */
651 void SPDocument::fitToRect(Geom::Rect const &rect, bool with_margins)
653     double const w = rect.width();
654     double const h = rect.height();
656     double const old_height = sp_document_height(this);
657     SPUnit const &px(sp_unit_get_by_id(SP_UNIT_PX));
658     
659     /* in px */
660     double margin_top = 0.0;
661     double margin_left = 0.0;
662     double margin_right = 0.0;
663     double margin_bottom = 0.0;
664     
665     SPNamedView *nv = sp_document_namedview(this, 0);
666     
667     if (with_margins && nv) {
668         Inkscape::XML::Node *nv_repr = SP_OBJECT_REPR (nv);
669         if (nv_repr != NULL) {
670             gchar const * const units_abbr = nv_repr->attribute("units");
671             SPUnit const *margin_units = NULL;
672             if (units_abbr != NULL) {
673                 margin_units = sp_unit_get_by_abbreviation(units_abbr);
674             }
675             if (margin_units == NULL) {
676                 margin_units = &px;
677             }
678             margin_top = getMarginLength(nv_repr, "fit-margin-top",
679                                          margin_units, &px, w, h, false);
680             margin_left = getMarginLength(nv_repr, "fit-margin-left",
681                                           margin_units, &px, w, h, true);
682             margin_right = getMarginLength(nv_repr, "fit-margin-right",
683                                            margin_units, &px, w, h, true);
684             margin_bottom = getMarginLength(nv_repr, "fit-margin-bottom",
685                                             margin_units, &px, w, h, false);
686         }
687     }
688     
689     Geom::Rect const rect_with_margins(
690             rect.min() - Geom::Point(margin_left, margin_bottom),
691             rect.max() + Geom::Point(margin_right, margin_top));
692     
693     
694     sp_document_set_width(this, rect_with_margins.width(), &px);
695     sp_document_set_height(this, rect_with_margins.height(), &px);
697     Geom::Translate const tr(
698             Geom::Point(0, old_height - rect_with_margins.height())
699             - to_2geom(rect_with_margins.min()));
700     SP_GROUP(root)->translateChildItems(tr);
702     if(nv) {
703         Geom::Translate tr2(-rect_with_margins.min());
704         nv->translateGuides(tr2);
706         // update the viewport so the drawing appears to stay where it was
707         nv->scrollAllDesktops(-tr2[0], tr2[1], false);
708     }
711 static void
712 do_change_uri(SPDocument *const document, gchar const *const filename, bool const rebase)
714     g_return_if_fail(document != NULL);
716     gchar *new_base;
717     gchar *new_name;
718     gchar *new_uri;
719     if (filename) {
721 #ifndef WIN32
722         new_uri = prepend_current_dir_if_relative(filename);
723 #else
724         // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
725         new_uri = g_strdup(filename);
726 #endif
728         new_base = g_path_get_dirname(new_uri);
729         new_name = g_path_get_basename(new_uri);
730     } else {
731         new_uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
732         new_base = NULL;
733         new_name = g_strdup(document->uri);
734     }
736     // Update saveable repr attributes.
737     Inkscape::XML::Node *repr = sp_document_repr_root(document);
739     // Changing uri in the document repr must not be not undoable.
740     bool const saved = sp_document_get_undo_sensitive(document);
741     sp_document_set_undo_sensitive(document, false);
743     if (rebase) {
744         Inkscape::XML::rebase_hrefs(document, new_base, true);
745     }
747     repr->setAttribute("sodipodi:docname", document->name);
748     sp_document_set_undo_sensitive(document, saved);
751     g_free(document->name);
752     g_free(document->base);
753     g_free(document->uri);
754     document->name = new_name;
755     document->base = new_base;
756     document->uri = new_uri;
758     document->priv->uri_set_signal.emit(document->uri);
761 /**
762  * Sets base, name and uri members of \a document.  Doesn't update
763  * any relative hrefs in the document: thus, this is primarily for
764  * newly-created documents.
765  *
766  * \see sp_document_change_uri_and_hrefs
767  */
768 void sp_document_set_uri(SPDocument *document, gchar const *filename)
770     g_return_if_fail(document != NULL);
772     do_change_uri(document, filename, false);
775 /**
776  * Changes the base, name and uri members of \a document, and updates any
777  * relative hrefs in the document to be relative to the new base.
778  *
779  * \see sp_document_set_uri
780  */
781 void sp_document_change_uri_and_hrefs(SPDocument *document, gchar const *filename)
783     g_return_if_fail(document != NULL);
785     do_change_uri(document, filename, true);
788 void
789 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
791     g_return_if_fail(doc != NULL);
793     doc->priv->resized_signal.emit(width, height);
796 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
798     return priv->modified_signal.connect(slot);
801 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
803     return priv->uri_set_signal.connect(slot);
806 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
808     return priv->resized_signal.connect(slot);
811 sigc::connection
812 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
814     return priv->_reconstruction_start_signal.connect(slot);
817 void
818 SPDocument::emitReconstructionStart(void)
820     // printf("Starting Reconstruction\n");
821     priv->_reconstruction_start_signal.emit();
822     return;
825 sigc::connection
826 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type  slot)
828     return priv->_reconstruction_finish_signal.connect(slot);
831 void
832 SPDocument::emitReconstructionFinish(void)
834     // printf("Finishing Reconstruction\n");
835     priv->_reconstruction_finish_signal.emit();
837 /**    
838     // Reference to the old persp3d object is invalid after reconstruction.
839     initialize_current_persp3d();
840     
841     return;
842 **/
845 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
847     return priv->commit_signal.connect(slot);
852 void SPDocument::_emitModified() {
853     static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
854     root->emitModified(0);
855     priv->modified_signal.emit(flags);
858 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
859     GQuark idq = g_quark_from_string(id);
861     if (object) {
862         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
863         g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
864     } else {
865         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
866         g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
867     }
869     SPDocumentPrivate::IDChangedSignalMap::iterator pos;
871     pos = priv->id_changed_signals.find(idq);
872     if ( pos != priv->id_changed_signals.end() ) {
873         if (!(*pos).second.empty()) {
874             (*pos).second.emit(object);
875         } else { // discard unused signal
876             priv->id_changed_signals.erase(pos);
877         }
878     }
881 void
882 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
884     this->priv->undoStackObservers.add(observer);
887 void
888 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
890     this->priv->undoStackObservers.remove(observer);
893 SPObject *SPDocument::getObjectById(gchar const *id) {
894     g_return_val_if_fail(id != NULL, NULL);
896     GQuark idq = g_quark_from_string(id);
897     return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
900 sigc::connection SPDocument::connectIdChanged(gchar const *id,
901                                               SPDocument::IDChangedSignal::slot_type slot)
903     return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
906 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
907     if (object) {
908         g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
909         g_hash_table_insert(priv->reprdef, repr, object);
910     } else {
911         g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
912         g_hash_table_remove(priv->reprdef, repr);
913     }
916 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
917     g_return_val_if_fail(repr != NULL, NULL);
918     return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
921 Glib::ustring SPDocument::getLanguage() {
922     gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
923     if (document_language) {
924         while (isspace(*document_language))
925             document_language++;
926     }
927     if ( !document_language || 0 == *document_language) {
928         // retrieve system language
929         document_language = getenv("LC_ALL");
930         if ( NULL == document_language || *document_language == 0 ) {
931             document_language = getenv ("LC_MESSAGES");
932         }
933         if ( NULL == document_language || *document_language == 0 ) {
934             document_language = getenv ("LANG");
935         }
937         if ( NULL != document_language ) {
938             const char *pos = strchr(document_language, '_');
939             if ( NULL != pos ) {
940                 return Glib::ustring(document_language, pos - document_language);
941             }
942         }
943     }
945     if ( NULL == document_language )
946         return Glib::ustring();
947     return document_language;
950 /* Object modification root handler */
952 void
953 sp_document_request_modified(SPDocument *doc)
955     if (!doc->modified_id) {
956         doc->modified_id = g_idle_add_full(SP_DOCUMENT_UPDATE_PRIORITY, 
957                 sp_document_idle_handler, doc, NULL);
958     }
959     if (!doc->rerouting_handler_id) {
960         doc->rerouting_handler_id = g_idle_add_full(SP_DOCUMENT_REROUTING_PRIORITY, 
961                 sp_document_rerouting_handler, doc, NULL);
962     }
965 void
966 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
968     ctx->ctx.flags = 0;
969     ctx->i2doc = Geom::identity();
970     /* Set up viewport in case svg has it defined as percentages */
971     if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
972         ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
973         ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
974         ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
975         ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
976     } else { // as a last resort, set size to A4
977         ctx->vp.x0 = 0.0;
978         ctx->vp.y0 = 0.0;
979         ctx->vp.x1 = 210 * PX_PER_MM;
980         ctx->vp.y1 = 297 * PX_PER_MM;
981     }
982     ctx->i2vp = Geom::identity();
985 /**
986  * Tries to update the document state based on the modified and
987  * "update required" flags, and return true if the document has
988  * been brought fully up to date.
989  */
990 bool
991 SPDocument::_updateDocument()
993     /* Process updates */
994     if (this->root->uflags || this->root->mflags) {
995         if (this->root->uflags) {
996             SPItemCtx ctx;
997             sp_document_setup_viewport (this, &ctx);
999             bool saved = sp_document_get_undo_sensitive(this);
1000             sp_document_set_undo_sensitive(this, false);
1002             this->root->updateDisplay((SPCtx *)&ctx, 0);
1004             sp_document_set_undo_sensitive(this, saved);
1005         }
1006         this->_emitModified();
1007     }
1009     return !(this->root->uflags || this->root->mflags);
1013 /**
1014  * Repeatedly works on getting the document updated, since sometimes
1015  * it takes more than one pass to get the document updated.  But it
1016  * usually should not take more than a few loops, and certainly never
1017  * more than 32 iterations.  So we bail out if we hit 32 iterations,
1018  * since this typically indicates we're stuck in an update loop.
1019  */
1020 gint
1021 sp_document_ensure_up_to_date(SPDocument *doc)
1023     // Bring the document up-to-date, specifically via the following:
1024     //   1a) Process all document updates.
1025     //   1b) When completed, process connector routing changes.
1026     //   2a) Process any updates resulting from connector reroutings.
1027     int counter = 32;
1028     for (unsigned int pass = 1; pass <= 2; ++pass) {
1029         // Process document updates.
1030         while (!doc->_updateDocument()) {
1031             if (counter == 0) {
1032                 g_warning("More than 32 iteration while updating document '%s'", doc->uri);
1033                 break;
1034             }
1035             counter--;
1036         }
1037         if (counter == 0)
1038         {
1039             break;
1040         }
1042         // After updates on the first pass we get libavoid to process all the 
1043         // changed objects and provide new routings.  This may cause some objects
1044             // to be modified, hence the second update pass.
1045         if (pass == 1) {
1046             doc->router->processTransaction();
1047         }
1048     }
1049     
1050     if (doc->modified_id) {
1051         /* Remove handler */
1052         g_source_remove(doc->modified_id);
1053         doc->modified_id = 0;
1054     }
1055     if (doc->rerouting_handler_id) {
1056         /* Remove handler */
1057         g_source_remove(doc->rerouting_handler_id);
1058         doc->rerouting_handler_id = 0;
1059     }
1060     return counter>0;
1063 /**
1064  * An idle handler to update the document.  Returns true if
1065  * the document needs further updates.
1066  */
1067 static gint
1068 sp_document_idle_handler(gpointer data)
1070     SPDocument *doc = static_cast<SPDocument *>(data);
1071     if (doc->_updateDocument()) {
1072         doc->modified_id = 0;
1073         return false;
1074     } else {
1075         return true;
1076     }
1079 /**
1080  * An idle handler to reroute connectors in the document.  
1081  */
1082 static gint
1083 sp_document_rerouting_handler(gpointer data)
1085     // Process any queued movement actions and determine new routings for 
1086     // object-avoiding connectors.  Callbacks will be used to update and 
1087     // redraw affected connectors.
1088     SPDocument *doc = static_cast<SPDocument *>(data);
1089     doc->router->processTransaction();
1090     
1091     // We don't need to handle rerouting again until there are further 
1092     // diagram updates.
1093     doc->rerouting_handler_id = 0;
1094     return false;
1097 static bool is_within(Geom::Rect const &area, Geom::Rect const &box)
1099     return area.contains(box);
1102 static bool overlaps(Geom::Rect const &area, Geom::Rect const &box)
1104     return area.intersects(box);
1107 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, Geom::Rect const &area,
1108                                   bool (*test)(Geom::Rect const &, Geom::Rect const &), bool take_insensitive = false)
1110     g_return_val_if_fail(SP_IS_GROUP(group), s);
1112     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1113         if (!SP_IS_ITEM(o)) {
1114             continue;
1115         }
1116         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
1117             s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
1118         } else {
1119             SPItem *child = SP_ITEM(o);
1120             Geom::OptRect box = sp_item_bbox_desktop(child);
1121             if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1122                 s = g_slist_append(s, child);
1123             }
1124         }
1125     }
1127     return s;
1130 /**
1131 Returns true if an item is among the descendants of group (recursively).
1132  */
1133 bool item_is_in_group(SPItem *item, SPGroup *group)
1135     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1136         if (!SP_IS_ITEM(o)) continue;
1137         if (SP_ITEM(o) == item)
1138             return true;
1139         if (SP_IS_GROUP(o))
1140             if (item_is_in_group(item, SP_GROUP(o)))
1141                 return true;
1142     }
1143     return false;
1146 /**
1147 Returns the bottommost item from the list which is at the point, or NULL if none.
1148 */
1149 SPItem*
1150 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
1151                                            Geom::Point const p, bool take_insensitive)
1153     g_return_val_if_fail(group, NULL);
1154     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1155     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1157     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1159         if (!SP_IS_ITEM(o)) continue;
1161         SPItem *item = SP_ITEM(o);
1162         NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
1163         if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1164             && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
1165             if (g_slist_find((GSList *) list, item) != NULL)
1166                 return item;
1167         }
1169         if (SP_IS_GROUP(o)) {
1170             SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
1171             if (found)
1172                 return found;
1173         }
1175     }
1176     return NULL;
1179 /**
1180 Returns the topmost (in z-order) item from the descendants of group (recursively) which
1181 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
1182 non-layer groups or not. Honors take_insensitive on whether to return insensitive
1183 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
1184 upwards in z-order and returns what it has found so far (i.e. the found item is
1185 guaranteed to be lower than upto).
1186  */
1187 SPItem*
1188 find_item_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
1190     SPItem *seen = NULL, *newseen = NULL;
1191     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1192     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1194     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1195         if (!SP_IS_ITEM(o)) continue;
1197         if (upto && SP_ITEM(o) == upto)
1198             break;
1200         if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
1201             // if nothing found yet, recurse into the group
1202             newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
1203             if (newseen) {
1204                 seen = newseen;
1205                 newseen = NULL;
1206             }
1208             if (item_is_in_group(upto, SP_GROUP(o)))
1209                 break;
1211         } else {
1212             SPItem *child = SP_ITEM(o);
1213             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1215             // seen remembers the last (topmost) of items pickable at this point
1216             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1217                 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1218                 seen = child;
1219             }
1220         }
1221     }
1222     return seen;
1225 /**
1226 Returns the topmost non-layer group from the descendants of group which is at point
1227 p, or NULL if none. Recurses into layers but not into groups.
1228  */
1229 SPItem*
1230 find_group_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p)
1232     SPItem *seen = NULL;
1233     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1234     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1236     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1237         if (!SP_IS_ITEM(o)) continue;
1238         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1239             SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1240             if (newseen) {
1241                 seen = newseen;
1242             }
1243         }
1244         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1245             SPItem *child = SP_ITEM(o);
1246             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1248             // seen remembers the last (topmost) of groups pickable at this point
1249             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1250                 seen = child;
1251             }
1252         }
1253     }
1254     return seen;
1257 /*
1258  * Return list of items, contained in box
1259  *
1260  * Assumes box is normalized (and g_asserts it!)
1261  *
1262  */
1264 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1266     g_return_val_if_fail(document != NULL, NULL);
1267     g_return_val_if_fail(document->priv != NULL, NULL);
1269     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
1272 /*
1273  * Return list of items, that the parts of the item contained in box
1274  *
1275  * Assumes box is normalized (and g_asserts it!)
1276  *
1277  */
1279 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1281     g_return_val_if_fail(document != NULL, NULL);
1282     g_return_val_if_fail(document->priv != NULL, NULL);
1284     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1287 GSList *
1288 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<Geom::Point> points)
1290     GSList *items = NULL;
1291     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1293     // When picking along the path, we don't want small objects close together
1294     // (such as hatching strokes) to obscure each other by their deltas,
1295     // so we temporarily set delta to a small value
1296     gdouble saved_delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1297     prefs->setDouble("/options/cursortolerance/value", 0.25);
1299     for(unsigned int i = 0; i < points.size(); i++) {
1300         SPItem *item = sp_document_item_at_point(document, key, points[i],
1301                                                  false, NULL);
1302         if (item && !g_slist_find(items, item))
1303             items = g_slist_prepend (items, item);
1304     }
1306     // and now we restore it back
1307     prefs->setDouble("/options/cursortolerance/value", saved_delta);
1309     return items;
1312 SPItem *
1313 sp_document_item_at_point(SPDocument *document, unsigned const key, Geom::Point const p,
1314                           gboolean const into_groups, SPItem *upto)
1316     g_return_val_if_fail(document != NULL, NULL);
1317     g_return_val_if_fail(document->priv != NULL, NULL);
1319     return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1322 SPItem*
1323 sp_document_group_at_point(SPDocument *document, unsigned int key, Geom::Point const p)
1325     g_return_val_if_fail(document != NULL, NULL);
1326     g_return_val_if_fail(document->priv != NULL, NULL);
1328     return find_group_at_point(key, SP_GROUP(document->root), p);
1332 /* Resource management */
1334 gboolean
1335 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1337     GSList *rlist;
1338     GQuark q = g_quark_from_string(key);
1340     g_return_val_if_fail(document != NULL, FALSE);
1341     g_return_val_if_fail(key != NULL, FALSE);
1342     g_return_val_if_fail(*key != '\0', FALSE);
1343     g_return_val_if_fail(object != NULL, FALSE);
1344     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1346     if (SP_OBJECT_IS_CLONED(object))
1347         return FALSE;
1349     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1350     g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1351     rlist = g_slist_prepend(rlist, object);
1352     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1354     document->priv->resources_changed_signals[q].emit();
1356     return TRUE;
1359 gboolean
1360 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1362     GSList *rlist;
1363     GQuark q = g_quark_from_string(key);
1365     g_return_val_if_fail(document != NULL, FALSE);
1366     g_return_val_if_fail(key != NULL, FALSE);
1367     g_return_val_if_fail(*key != '\0', FALSE);
1368     g_return_val_if_fail(object != NULL, FALSE);
1369     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1371     if (SP_OBJECT_IS_CLONED(object))
1372         return FALSE;
1374     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1375     g_return_val_if_fail(rlist != NULL, FALSE);
1376     g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1377     rlist = g_slist_remove(rlist, object);
1378     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1380     document->priv->resources_changed_signals[q].emit();
1382     return TRUE;
1385 GSList const *
1386 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1388     g_return_val_if_fail(document != NULL, NULL);
1389     g_return_val_if_fail(key != NULL, NULL);
1390     g_return_val_if_fail(*key != '\0', NULL);
1392     return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1395 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1396                                                        gchar const *key,
1397                                                        SPDocument::ResourcesChangedSignal::slot_type slot)
1399     GQuark q = g_quark_from_string(key);
1400     return document->priv->resources_changed_signals[q].connect(slot);
1403 /* Helpers */
1405 gboolean
1406 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1408     g_slist_free((GSList *) value);
1409     return TRUE;
1412 unsigned int
1413 count_objects_recursive(SPObject *obj, unsigned int count)
1415     count++; // obj itself
1417     for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1418         count = count_objects_recursive(i, count);
1419     }
1421     return count;
1424 unsigned int
1425 objects_in_document(SPDocument *document)
1427     return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1430 void
1431 vacuum_document_recursive(SPObject *obj)
1433     if (SP_IS_DEFS(obj)) {
1434         for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1435             /* fixme: some inkscape-internal nodes in the future might not be collectable */
1436             def->requestOrphanCollection();
1437         }
1438     } else {
1439         for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1440             vacuum_document_recursive(i);
1441         }
1442     }
1445 unsigned int
1446 vacuum_document(SPDocument *document)
1448     unsigned int start = objects_in_document(document);
1449     unsigned int end;
1450     unsigned int newend = start;
1452     unsigned int iterations = 0;
1454     do {
1455         end = newend;
1457         vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1458         document->collectOrphans();
1459         iterations++;
1461         newend = objects_in_document(document);
1463     } while (iterations < 100 && newend < end);
1465     return start - newend;
1468 bool SPDocument::isSeeking() const {
1469     return priv->seeking;
1473 /*
1474   Local Variables:
1475   mode:c++
1476   c-file-style:"stroustrup"
1477   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1478   indent-tabs-mode:nil
1479   fill-column:99
1480   End:
1481 */
1482 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :