Code

eff6d6e818b86f9db51ef9a8e3f087e820deb9bf
[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(0),
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     }
215     //delete this->_whiteboard_session_manager;
218 Persp3D *
219 SPDocument::getCurrentPersp3D() {
220     // Check if current_persp3d is still valid
221     std::vector<Persp3D*> plist;
222     getPerspectivesInDefs(plist);
223     for (unsigned int i = 0; i < plist.size(); ++i) {
224         if (current_persp3d == plist[i])
225             return current_persp3d;
226     }
228     // If not, return the first perspective in defs (which may be NULL of none exists)
229     current_persp3d = persp3d_document_first_persp (this);
231     return current_persp3d;
234 Persp3DImpl *
235 SPDocument::getCurrentPersp3DImpl() {
236     return current_persp3d_impl;
239 void
240 SPDocument::setCurrentPersp3D(Persp3D * const persp) {
241     current_persp3d = persp;
242     //current_persp3d_impl = persp->perspective_impl;
245 void
246 SPDocument::getPerspectivesInDefs(std::vector<Persp3D*> &list) {
247     SPDefs *defs = SP_ROOT(this->root)->defs;
248     for (SPObject *i = sp_object_first_child(SP_OBJECT(defs)); i != NULL; i = SP_OBJECT_NEXT(i) ) {
249         if (SP_IS_PERSP3D(i))
250             list.push_back(SP_PERSP3D(i));
251     }
254 /**
255 void SPDocument::initialize_current_persp3d()
257     this->current_persp3d = persp3d_document_first_persp(this);
258     if (!this->current_persp3d) {
259         this->current_persp3d = persp3d_create_xml_element(this);
260     }
262 **/
264 unsigned long SPDocument::serial() const {
265     return priv->serial;
268 void SPDocument::queueForOrphanCollection(SPObject *object) {
269     g_return_if_fail(object != NULL);
270     g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
272     sp_object_ref(object, NULL);
273     _collection_queue = g_slist_prepend(_collection_queue, object);
276 void SPDocument::collectOrphans() {
277     while (_collection_queue) {
278         GSList *objects=_collection_queue;
279         _collection_queue = NULL;
280         for ( GSList *iter=objects ; iter ; iter = iter->next ) {
281             SPObject *object=reinterpret_cast<SPObject *>(iter->data);
282             object->collectOrphan();
283             sp_object_unref(object, NULL);
284         }
285         g_slist_free(objects);
286     }
289 void SPDocument::reset_key (void */*dummy*/)
291     actionkey = NULL;
294 SPDocument *
295 sp_document_create(Inkscape::XML::Document *rdoc,
296                    gchar const *uri,
297                    gchar const *base,
298                    gchar const *name,
299                    unsigned int keepalive)
301     SPDocument *document;
302     Inkscape::XML::Node *rroot;
303     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
305     rroot = rdoc->root();
307     document = new SPDocument();
309     document->keepalive = keepalive;
311     document->rdoc = rdoc;
312     document->rroot = rroot;
314 #ifndef WIN32
315     document->uri = prepend_current_dir_if_relative(uri);
316 #else
317     // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
318     document->uri = uri? g_strdup(uri) : NULL;
319 #endif
321     // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
322     // which is why we use g_get_current_dir() in calculating the abs path above
323     //This is NULL for a new document
324     if (base)
325         document->base = g_strdup(base);
326     else
327         document->base = NULL;
328     document->name = g_strdup(name);
330     document->root = sp_object_repr_build_tree(document, rroot);
332     /* fixme: Not sure about this, but lets assume ::build updates */
333     rroot->setAttribute("inkscape:version", Inkscape::version_string);
334     /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
336     /* Quick hack 2 - get default image size into document */
337     if (!rroot->attribute("width")) rroot->setAttribute("width", "100%");
338     if (!rroot->attribute("height")) rroot->setAttribute("height", "100%");
339     /* End of quick hack 2 */
341     /* Quick hack 3 - Set uri attributes */
342     if (uri) {
343         rroot->setAttribute("sodipodi:docname", uri);
344     }
345     /* End of quick hack 3 */
347     /* Eliminate obsolete sodipodi:docbase, for privacy reasons */
348     rroot->setAttribute("sodipodi:docbase", NULL);
350     /* Eliminate any claim to adhere to a profile, as we don't try to */
351     rroot->setAttribute("baseProfile", NULL);
353     // creating namedview
354     if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
355         // if there's none in the document already,
356         Inkscape::XML::Node *rnew = NULL;
358         rnew = rdoc->createElement("sodipodi:namedview");
359         //rnew->setAttribute("id", "base");
361         // Add namedview data from the preferences
362         // we can't use getAllEntries because this could produce non-SVG doubles
363         Glib::ustring pagecolor = prefs->getString("/template/base/pagecolor");
364         if (!pagecolor.empty()) {
365             rnew->setAttribute("pagecolor", pagecolor.data());
366         }
367         Glib::ustring bordercolor = prefs->getString("/template/base/bordercolor");
368         if (!bordercolor.empty()) {
369             rnew->setAttribute("bordercolor", bordercolor.data());
370         }
371         sp_repr_set_svg_double(rnew, "borderopacity",
372             prefs->getDouble("/template/base/borderopacity", 1.0));
373         sp_repr_set_svg_double(rnew, "objecttolerance",
374             prefs->getDouble("/template/base/objecttolerance", 10.0));
375         sp_repr_set_svg_double(rnew, "gridtolerance",
376             prefs->getDouble("/template/base/gridtolerance", 10.0));
377         sp_repr_set_svg_double(rnew, "guidetolerance",
378             prefs->getDouble("/template/base/guidetolerance", 10.0));
379         sp_repr_set_svg_double(rnew, "inkscape:pageopacity",
380             prefs->getDouble("/template/base/inkscape:pageopacity", 0.0));
381         sp_repr_set_int(rnew, "inkscape:pageshadow",
382             prefs->getInt("/template/base/inkscape:pageshadow", 2));
383         sp_repr_set_int(rnew, "inkscape:window-width",
384             prefs->getInt("/template/base/inkscape:window-width", 640));
385         sp_repr_set_int(rnew, "inkscape:window-height",
386             prefs->getInt("/template/base/inkscape:window-height", 480));
388         // insert into the document
389         rroot->addChild(rnew, NULL);
390         // clean up
391         Inkscape::GC::release(rnew);
392     }
394     /* Defs */
395     if (!SP_ROOT(document->root)->defs) {
396         Inkscape::XML::Node *r;
397         r = rdoc->createElement("svg:defs");
398         rroot->addChild(r, NULL);
399         Inkscape::GC::release(r);
400         g_assert(SP_ROOT(document->root)->defs);
401     }
403     /* Default RDF */
404     rdf_set_defaults( document );
406     if (keepalive) {
407         inkscape_ref();
408     }
410     // Check if the document already has a perspective (e.g., when opening an existing
411     // document). If not, create a new one and set it as the current perspective.
412     document->setCurrentPersp3D(persp3d_document_first_persp(document));
413     if (!document->getCurrentPersp3D()) {
414         //document->setCurrentPersp3D(persp3d_create_xml_element (document));
415         Persp3DImpl *persp_impl = new Persp3DImpl();
416         document->setCurrentPersp3DImpl(persp_impl);
417     }
419     sp_document_set_undo_sensitive(document, true);
421     // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
422     if (!Inkscape::NSApplication::Application::getNewGui()) {
423         g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
424                          G_CALLBACK(sp_document_reset_key), document);
425         g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
426                          G_CALLBACK(sp_document_reset_key), document);
427         document->oldSignalsConnected = true;
428     } else {
429         document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
430         document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
431         document->oldSignalsConnected = false;
432     }
434     return document;
437 /**
438  * Fetches document from URI, or creates new, if NULL; public document
439  * appears in document list.
440  */
441 SPDocument *
442 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
444     SPDocument *doc;
445     Inkscape::XML::Document *rdoc;
446     gchar *base = NULL;
447     gchar *name = NULL;
449     if (uri) {
450         Inkscape::XML::Node *rroot;
451         gchar *s, *p;
452         /* Try to fetch repr from file */
453         rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
454         /* If file cannot be loaded, return NULL without warning */
455         if (rdoc == NULL) return NULL;
456         rroot = rdoc->root();
457         /* If xml file is not svg, return NULL without warning */
458         /* fixme: destroy document */
459         if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
460         s = g_strdup(uri);
461         p = strrchr(s, '/');
462         if (p) {
463             name = g_strdup(p + 1);
464             p[1] = '\0';
465             base = g_strdup(s);
466         } else {
467             base = NULL;
468             name = g_strdup(uri);
469         }
470         g_free(s);
471     } else {
472         rdoc = sp_repr_document_new("svg:svg");
473     }
475     if (make_new) {
476         base = NULL;
477         uri = NULL;
478         name = g_strdup_printf(_("New document %d"), ++doc_count);
479     }
481     //# These should be set by now
482     g_assert(name);
484     doc = sp_document_create(rdoc, uri, base, name, keepalive);
486     g_free(base);
487     g_free(name);
489     return doc;
492 SPDocument *
493 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
495     SPDocument *doc;
496     Inkscape::XML::Document *rdoc;
497     Inkscape::XML::Node *rroot;
498     gchar *name;
500     rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
502     /* If it cannot be loaded, return NULL without warning */
503     if (rdoc == NULL) return NULL;
505     rroot = rdoc->root();
506     /* If xml file is not svg, return NULL without warning */
507     /* fixme: destroy document */
508     if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
510     name = g_strdup_printf(_("Memory document %d"), ++doc_count);
512     doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
514     return doc;
517 SPDocument *
518 sp_document_ref(SPDocument *doc)
520     g_return_val_if_fail(doc != NULL, NULL);
521     Inkscape::GC::anchor(doc);
522     return doc;
525 SPDocument *
526 sp_document_unref(SPDocument *doc)
528     g_return_val_if_fail(doc != NULL, NULL);
529     Inkscape::GC::release(doc);
530     return NULL;
533 gdouble sp_document_width(SPDocument *document)
535     g_return_val_if_fail(document != NULL, 0.0);
536     g_return_val_if_fail(document->priv != NULL, 0.0);
537     g_return_val_if_fail(document->root != NULL, 0.0);
539     SPRoot *root = SP_ROOT(document->root);
541     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set)
542         return root->viewBox.x1 - root->viewBox.x0;
543     return root->width.computed;
546 void
547 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
549     SPRoot *root = SP_ROOT(document->root);
551     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
552         root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
553     } else { // set to width=
554         gdouble old_computed = root->width.computed;
555         root->width.computed = sp_units_get_pixels (width, *unit);
556         /* SVG does not support meters as a unit, so we must translate meters to
557          * cm when writing */
558         if (!strcmp(unit->abbr, "m")) {
559             root->width.value = 100*width;
560             root->width.unit = SVGLength::CM;
561         } else {
562             root->width.value = width;
563             root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
564         }
566         if (root->viewBox_set)
567             root->viewBox.x1 = root->viewBox.x0 + (root->width.computed / old_computed) * (root->viewBox.x1 - root->viewBox.x0);
568     }
570     SP_OBJECT (root)->updateRepr();
573 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
575     SPRoot *root = SP_ROOT(document->root);
577     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
578         root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
579     } else { // set to height=
580         gdouble old_computed = root->height.computed;
581         root->height.computed = sp_units_get_pixels (height, *unit);
582         /* SVG does not support meters as a unit, so we must translate meters to
583          * cm when writing */
584         if (!strcmp(unit->abbr, "m")) {
585             root->height.value = 100*height;
586             root->height.unit = SVGLength::CM;
587         } else {
588             root->height.value = height;
589             root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
590         }
592         if (root->viewBox_set)
593             root->viewBox.y1 = root->viewBox.y0 + (root->height.computed / old_computed) * (root->viewBox.y1 - root->viewBox.y0);
594     }
596     SP_OBJECT (root)->updateRepr();
599 gdouble sp_document_height(SPDocument *document)
601     g_return_val_if_fail(document != NULL, 0.0);
602     g_return_val_if_fail(document->priv != NULL, 0.0);
603     g_return_val_if_fail(document->root != NULL, 0.0);
605     SPRoot *root = SP_ROOT(document->root);
607     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set)
608         return root->viewBox.y1 - root->viewBox.y0;
609     return root->height.computed;
612 Geom::Point sp_document_dimensions(SPDocument *doc)
614     return Geom::Point(sp_document_width(doc), sp_document_height(doc));
617 /**
618  * Gets page fitting margin information from the namedview node in the XML.
619  * \param nv_repr reference to this document's namedview
620  * \param key the same key used by the RegisteredScalarUnit in
621  *        ui/widget/page-sizer.cpp
622  * \param margin_units units for the margin
623  * \param return_units units to return the result in
624  * \param width width in px (for percentage margins)
625  * \param height height in px (for percentage margins)
626  * \param use_width true if the this key is left or right margins, false
627  *        otherwise.  Used for percentage margins.
628  * \return the margin size in px, else 0.0 if anything is invalid.
629  */
630 static double getMarginLength(Inkscape::XML::Node * const nv_repr,
631                              gchar const * const key,
632                              SPUnit const * const margin_units,
633                              SPUnit const * const return_units,
634                              double const width,
635                              double const height,
636                              bool const use_width)
638     double value;
639     if (!sp_repr_get_double (nv_repr, key, &value)) {
640         return 0.0;
641     }
642     if (margin_units == &sp_unit_get_by_id (SP_UNIT_PERCENT)) {
643         return (use_width)? width * value : height * value; 
644     }
645     if (!sp_convert_distance (&value, margin_units, return_units)) {
646         return 0.0;
647     }
648     return value;
651 /**
652  * Given a Geom::Rect that may, for example, correspond to the bbox of an object,
653  * this function fits the canvas to that rect by resizing the canvas
654  * and translating the document root into position.
655  * \param rect fit document size to this
656  * \param with_margins add margins to rect, by taking margins from this
657  *        document's namedview (<sodipodi:namedview> "fit-margin-..."
658  *        attributes, and "units")
659  */
660 void SPDocument::fitToRect(Geom::Rect const &rect, bool with_margins)
662     double const w = rect.width();
663     double const h = rect.height();
665     double const old_height = sp_document_height(this);
666     SPUnit const &px(sp_unit_get_by_id(SP_UNIT_PX));
667     
668     /* in px */
669     double margin_top = 0.0;
670     double margin_left = 0.0;
671     double margin_right = 0.0;
672     double margin_bottom = 0.0;
673     
674     SPNamedView *nv = sp_document_namedview(this, 0);
675     
676     if (with_margins && nv) {
677         Inkscape::XML::Node *nv_repr = SP_OBJECT_REPR (nv);
678         if (nv_repr != NULL) {
679             gchar const * const units_abbr = nv_repr->attribute("units");
680             SPUnit const *margin_units = NULL;
681             if (units_abbr != NULL) {
682                 margin_units = sp_unit_get_by_abbreviation(units_abbr);
683             }
684             if (margin_units == NULL) {
685                 margin_units = &px;
686             }
687             margin_top = getMarginLength(nv_repr, "fit-margin-top",
688                                          margin_units, &px, w, h, false);
689             margin_left = getMarginLength(nv_repr, "fit-margin-left",
690                                           margin_units, &px, w, h, true);
691             margin_right = getMarginLength(nv_repr, "fit-margin-right",
692                                            margin_units, &px, w, h, true);
693             margin_bottom = getMarginLength(nv_repr, "fit-margin-bottom",
694                                             margin_units, &px, w, h, false);
695         }
696     }
697     
698     Geom::Rect const rect_with_margins(
699             rect.min() - Geom::Point(margin_left, margin_bottom),
700             rect.max() + Geom::Point(margin_right, margin_top));
701     
702     
703     sp_document_set_width(this, rect_with_margins.width(), &px);
704     sp_document_set_height(this, rect_with_margins.height(), &px);
706     Geom::Translate const tr(
707             Geom::Point(0, old_height - rect_with_margins.height())
708             - to_2geom(rect_with_margins.min()));
709     SP_GROUP(root)->translateChildItems(tr);
711     if(nv) {
712         Geom::Translate tr2(-rect_with_margins.min());
713         nv->translateGuides(tr2);
715         // update the viewport so the drawing appears to stay where it was
716         nv->scrollAllDesktops(-tr2[0], tr2[1], false);
717     }
720 static void
721 do_change_uri(SPDocument *const document, gchar const *const filename, bool const rebase)
723     g_return_if_fail(document != NULL);
725     gchar *new_base;
726     gchar *new_name;
727     gchar *new_uri;
728     if (filename) {
730 #ifndef WIN32
731         new_uri = prepend_current_dir_if_relative(filename);
732 #else
733         // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
734         new_uri = g_strdup(filename);
735 #endif
737         new_base = g_path_get_dirname(new_uri);
738         new_name = g_path_get_basename(new_uri);
739     } else {
740         new_uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
741         new_base = NULL;
742         new_name = g_strdup(document->uri);
743     }
745     // Update saveable repr attributes.
746     Inkscape::XML::Node *repr = sp_document_repr_root(document);
748     // Changing uri in the document repr must not be not undoable.
749     bool const saved = sp_document_get_undo_sensitive(document);
750     sp_document_set_undo_sensitive(document, false);
752     if (rebase) {
753         Inkscape::XML::rebase_hrefs(document, new_base, true);
754     }
756     repr->setAttribute("sodipodi:docname", document->name);
757     sp_document_set_undo_sensitive(document, saved);
760     g_free(document->name);
761     g_free(document->base);
762     g_free(document->uri);
763     document->name = new_name;
764     document->base = new_base;
765     document->uri = new_uri;
767     document->priv->uri_set_signal.emit(document->uri);
770 /**
771  * Sets base, name and uri members of \a document.  Doesn't update
772  * any relative hrefs in the document: thus, this is primarily for
773  * newly-created documents.
774  *
775  * \see sp_document_change_uri_and_hrefs
776  */
777 void sp_document_set_uri(SPDocument *document, gchar const *filename)
779     g_return_if_fail(document != NULL);
781     do_change_uri(document, filename, false);
784 /**
785  * Changes the base, name and uri members of \a document, and updates any
786  * relative hrefs in the document to be relative to the new base.
787  *
788  * \see sp_document_set_uri
789  */
790 void sp_document_change_uri_and_hrefs(SPDocument *document, gchar const *filename)
792     g_return_if_fail(document != NULL);
794     do_change_uri(document, filename, true);
797 void
798 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
800     g_return_if_fail(doc != NULL);
802     doc->priv->resized_signal.emit(width, height);
805 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
807     return priv->modified_signal.connect(slot);
810 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
812     return priv->uri_set_signal.connect(slot);
815 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
817     return priv->resized_signal.connect(slot);
820 sigc::connection
821 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
823     return priv->_reconstruction_start_signal.connect(slot);
826 void
827 SPDocument::emitReconstructionStart(void)
829     // printf("Starting Reconstruction\n");
830     priv->_reconstruction_start_signal.emit();
831     return;
834 sigc::connection
835 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type  slot)
837     return priv->_reconstruction_finish_signal.connect(slot);
840 void
841 SPDocument::emitReconstructionFinish(void)
843     // printf("Finishing Reconstruction\n");
844     priv->_reconstruction_finish_signal.emit();
846 /**    
847     // Reference to the old persp3d object is invalid after reconstruction.
848     initialize_current_persp3d();
849     
850     return;
851 **/
854 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
856     return priv->commit_signal.connect(slot);
861 void SPDocument::_emitModified() {
862     static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
863     root->emitModified(0);
864     priv->modified_signal.emit(flags);
867 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
868     GQuark idq = g_quark_from_string(id);
870     if (object) {
871         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
872         g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
873     } else {
874         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
875         g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
876     }
878     SPDocumentPrivate::IDChangedSignalMap::iterator pos;
880     pos = priv->id_changed_signals.find(idq);
881     if ( pos != priv->id_changed_signals.end() ) {
882         if (!(*pos).second.empty()) {
883             (*pos).second.emit(object);
884         } else { // discard unused signal
885             priv->id_changed_signals.erase(pos);
886         }
887     }
890 void
891 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
893     this->priv->undoStackObservers.add(observer);
896 void
897 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
899     this->priv->undoStackObservers.remove(observer);
902 SPObject *SPDocument::getObjectById(gchar const *id) {
903     g_return_val_if_fail(id != NULL, NULL);
905     GQuark idq = g_quark_from_string(id);
906     return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
909 sigc::connection SPDocument::connectIdChanged(gchar const *id,
910                                               SPDocument::IDChangedSignal::slot_type slot)
912     return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
915 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
916     if (object) {
917         g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
918         g_hash_table_insert(priv->reprdef, repr, object);
919     } else {
920         g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
921         g_hash_table_remove(priv->reprdef, repr);
922     }
925 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
926     g_return_val_if_fail(repr != NULL, NULL);
927     return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
930 Glib::ustring SPDocument::getLanguage() {
931     gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
932     if (document_language) {
933         while (isspace(*document_language))
934             document_language++;
935     }
936     if ( !document_language || 0 == *document_language) {
937         // retrieve system language
938         document_language = getenv("LC_ALL");
939         if ( NULL == document_language || *document_language == 0 ) {
940             document_language = getenv ("LC_MESSAGES");
941         }
942         if ( NULL == document_language || *document_language == 0 ) {
943             document_language = getenv ("LANG");
944         }
946         if ( NULL != document_language ) {
947             const char *pos = strchr(document_language, '_');
948             if ( NULL != pos ) {
949                 return Glib::ustring(document_language, pos - document_language);
950             }
951         }
952     }
954     if ( NULL == document_language )
955         return Glib::ustring();
956     return document_language;
959 /* Object modification root handler */
961 void
962 sp_document_request_modified(SPDocument *doc)
964     if (!doc->modified_id) {
965         doc->modified_id = g_idle_add_full(SP_DOCUMENT_UPDATE_PRIORITY, 
966                 sp_document_idle_handler, doc, NULL);
967     }
968     if (!doc->rerouting_handler_id) {
969         doc->rerouting_handler_id = g_idle_add_full(SP_DOCUMENT_REROUTING_PRIORITY, 
970                 sp_document_rerouting_handler, doc, NULL);
971     }
974 void
975 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
977     ctx->ctx.flags = 0;
978     ctx->i2doc = Geom::identity();
979     /* Set up viewport in case svg has it defined as percentages */
980     if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
981         ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
982         ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
983         ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
984         ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
985     } else { // as a last resort, set size to A4
986         ctx->vp.x0 = 0.0;
987         ctx->vp.y0 = 0.0;
988         ctx->vp.x1 = 210 * PX_PER_MM;
989         ctx->vp.y1 = 297 * PX_PER_MM;
990     }
991     ctx->i2vp = Geom::identity();
994 /**
995  * Tries to update the document state based on the modified and
996  * "update required" flags, and return true if the document has
997  * been brought fully up to date.
998  */
999 bool
1000 SPDocument::_updateDocument()
1002     /* Process updates */
1003     if (this->root->uflags || this->root->mflags) {
1004         if (this->root->uflags) {
1005             SPItemCtx ctx;
1006             sp_document_setup_viewport (this, &ctx);
1008             bool saved = sp_document_get_undo_sensitive(this);
1009             sp_document_set_undo_sensitive(this, false);
1011             this->root->updateDisplay((SPCtx *)&ctx, 0);
1013             sp_document_set_undo_sensitive(this, saved);
1014         }
1015         this->_emitModified();
1016     }
1018     return !(this->root->uflags || this->root->mflags);
1022 /**
1023  * Repeatedly works on getting the document updated, since sometimes
1024  * it takes more than one pass to get the document updated.  But it
1025  * usually should not take more than a few loops, and certainly never
1026  * more than 32 iterations.  So we bail out if we hit 32 iterations,
1027  * since this typically indicates we're stuck in an update loop.
1028  */
1029 gint
1030 sp_document_ensure_up_to_date(SPDocument *doc)
1032     // Bring the document up-to-date, specifically via the following:
1033     //   1a) Process all document updates.
1034     //   1b) When completed, process connector routing changes.
1035     //   2a) Process any updates resulting from connector reroutings.
1036     int counter = 32;
1037     for (unsigned int pass = 1; pass <= 2; ++pass) {
1038         // Process document updates.
1039         while (!doc->_updateDocument()) {
1040             if (counter == 0) {
1041                 g_warning("More than 32 iteration while updating document '%s'", doc->uri);
1042                 break;
1043             }
1044             counter--;
1045         }
1046         if (counter == 0)
1047         {
1048             break;
1049         }
1051         // After updates on the first pass we get libavoid to process all the 
1052         // changed objects and provide new routings.  This may cause some objects
1053             // to be modified, hence the second update pass.
1054         if (pass == 1) {
1055             doc->router->processTransaction();
1056         }
1057     }
1058     
1059     if (doc->modified_id) {
1060         /* Remove handler */
1061         g_source_remove(doc->modified_id);
1062         doc->modified_id = 0;
1063     }
1064     if (doc->rerouting_handler_id) {
1065         /* Remove handler */
1066         g_source_remove(doc->rerouting_handler_id);
1067         doc->rerouting_handler_id = 0;
1068     }
1069     return counter>0;
1072 /**
1073  * An idle handler to update the document.  Returns true if
1074  * the document needs further updates.
1075  */
1076 static gint
1077 sp_document_idle_handler(gpointer data)
1079     SPDocument *doc = static_cast<SPDocument *>(data);
1080     if (doc->_updateDocument()) {
1081         doc->modified_id = 0;
1082         return false;
1083     } else {
1084         return true;
1085     }
1088 /**
1089  * An idle handler to reroute connectors in the document.  
1090  */
1091 static gint
1092 sp_document_rerouting_handler(gpointer data)
1094     // Process any queued movement actions and determine new routings for 
1095     // object-avoiding connectors.  Callbacks will be used to update and 
1096     // redraw affected connectors.
1097     SPDocument *doc = static_cast<SPDocument *>(data);
1098     doc->router->processTransaction();
1099     
1100     // We don't need to handle rerouting again until there are further 
1101     // diagram updates.
1102     doc->rerouting_handler_id = 0;
1103     return false;
1106 static bool is_within(Geom::Rect const &area, Geom::Rect const &box)
1108     return area.contains(box);
1111 static bool overlaps(Geom::Rect const &area, Geom::Rect const &box)
1113     return area.intersects(box);
1116 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, Geom::Rect const &area,
1117                                   bool (*test)(Geom::Rect const &, Geom::Rect const &), bool take_insensitive = false)
1119     g_return_val_if_fail(SP_IS_GROUP(group), s);
1121     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1122         if (!SP_IS_ITEM(o)) {
1123             continue;
1124         }
1125         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
1126             s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
1127         } else {
1128             SPItem *child = SP_ITEM(o);
1129             Geom::OptRect box = sp_item_bbox_desktop(child);
1130             if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1131                 s = g_slist_append(s, child);
1132             }
1133         }
1134     }
1136     return s;
1139 /**
1140 Returns true if an item is among the descendants of group (recursively).
1141  */
1142 bool item_is_in_group(SPItem *item, SPGroup *group)
1144     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1145         if (!SP_IS_ITEM(o)) continue;
1146         if (SP_ITEM(o) == item)
1147             return true;
1148         if (SP_IS_GROUP(o))
1149             if (item_is_in_group(item, SP_GROUP(o)))
1150                 return true;
1151     }
1152     return false;
1155 /**
1156 Returns the bottommost item from the list which is at the point, or NULL if none.
1157 */
1158 SPItem*
1159 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
1160                                            Geom::Point const p, bool take_insensitive)
1162     g_return_val_if_fail(group, NULL);
1163     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1164     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1166     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1168         if (!SP_IS_ITEM(o)) continue;
1170         SPItem *item = SP_ITEM(o);
1171         NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
1172         if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1173             && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
1174             if (g_slist_find((GSList *) list, item) != NULL)
1175                 return item;
1176         }
1178         if (SP_IS_GROUP(o)) {
1179             SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
1180             if (found)
1181                 return found;
1182         }
1184     }
1185     return NULL;
1188 /**
1189 Returns the topmost (in z-order) item from the descendants of group (recursively) which
1190 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
1191 non-layer groups or not. Honors take_insensitive on whether to return insensitive
1192 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
1193 upwards in z-order and returns what it has found so far (i.e. the found item is
1194 guaranteed to be lower than upto).
1195  */
1196 SPItem*
1197 find_item_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
1199     SPItem *seen = NULL, *newseen = NULL;
1200     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1201     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1203     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1204         if (!SP_IS_ITEM(o)) continue;
1206         if (upto && SP_ITEM(o) == upto)
1207             break;
1209         if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
1210             // if nothing found yet, recurse into the group
1211             newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
1212             if (newseen) {
1213                 seen = newseen;
1214                 newseen = NULL;
1215             }
1217             if (item_is_in_group(upto, SP_GROUP(o)))
1218                 break;
1220         } else {
1221             SPItem *child = SP_ITEM(o);
1222             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1224             // seen remembers the last (topmost) of items pickable at this point
1225             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1226                 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1227                 seen = child;
1228             }
1229         }
1230     }
1231     return seen;
1234 /**
1235 Returns the topmost non-layer group from the descendants of group which is at point
1236 p, or NULL if none. Recurses into layers but not into groups.
1237  */
1238 SPItem*
1239 find_group_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p)
1241     SPItem *seen = NULL;
1242     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1243     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1245     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1246         if (!SP_IS_ITEM(o)) continue;
1247         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1248             SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1249             if (newseen) {
1250                 seen = newseen;
1251             }
1252         }
1253         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1254             SPItem *child = SP_ITEM(o);
1255             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1257             // seen remembers the last (topmost) of groups pickable at this point
1258             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1259                 seen = child;
1260             }
1261         }
1262     }
1263     return seen;
1266 /*
1267  * Return list of items, contained in box
1268  *
1269  * Assumes box is normalized (and g_asserts it!)
1270  *
1271  */
1273 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1275     g_return_val_if_fail(document != NULL, NULL);
1276     g_return_val_if_fail(document->priv != NULL, NULL);
1278     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
1281 /*
1282  * Return list of items, that the parts of the item contained in box
1283  *
1284  * Assumes box is normalized (and g_asserts it!)
1285  *
1286  */
1288 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1290     g_return_val_if_fail(document != NULL, NULL);
1291     g_return_val_if_fail(document->priv != NULL, NULL);
1293     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1296 GSList *
1297 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<Geom::Point> points)
1299     GSList *items = NULL;
1300     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1302     // When picking along the path, we don't want small objects close together
1303     // (such as hatching strokes) to obscure each other by their deltas,
1304     // so we temporarily set delta to a small value
1305     gdouble saved_delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1306     prefs->setDouble("/options/cursortolerance/value", 0.25);
1308     for(unsigned int i = 0; i < points.size(); i++) {
1309         SPItem *item = sp_document_item_at_point(document, key, points[i],
1310                                                  false, NULL);
1311         if (item && !g_slist_find(items, item))
1312             items = g_slist_prepend (items, item);
1313     }
1315     // and now we restore it back
1316     prefs->setDouble("/options/cursortolerance/value", saved_delta);
1318     return items;
1321 SPItem *
1322 sp_document_item_at_point(SPDocument *document, unsigned const key, Geom::Point const p,
1323                           gboolean const into_groups, SPItem *upto)
1325     g_return_val_if_fail(document != NULL, NULL);
1326     g_return_val_if_fail(document->priv != NULL, NULL);
1328     return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1331 SPItem*
1332 sp_document_group_at_point(SPDocument *document, unsigned int key, Geom::Point const p)
1334     g_return_val_if_fail(document != NULL, NULL);
1335     g_return_val_if_fail(document->priv != NULL, NULL);
1337     return find_group_at_point(key, SP_GROUP(document->root), p);
1341 /* Resource management */
1343 gboolean
1344 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1346     GSList *rlist;
1347     GQuark q = g_quark_from_string(key);
1349     g_return_val_if_fail(document != NULL, FALSE);
1350     g_return_val_if_fail(key != NULL, FALSE);
1351     g_return_val_if_fail(*key != '\0', FALSE);
1352     g_return_val_if_fail(object != NULL, FALSE);
1353     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1355     if (SP_OBJECT_IS_CLONED(object))
1356         return FALSE;
1358     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1359     g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1360     rlist = g_slist_prepend(rlist, object);
1361     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1363     document->priv->resources_changed_signals[q].emit();
1365     return TRUE;
1368 gboolean
1369 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1371     GSList *rlist;
1372     GQuark q = g_quark_from_string(key);
1374     g_return_val_if_fail(document != NULL, FALSE);
1375     g_return_val_if_fail(key != NULL, FALSE);
1376     g_return_val_if_fail(*key != '\0', FALSE);
1377     g_return_val_if_fail(object != NULL, FALSE);
1378     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1380     if (SP_OBJECT_IS_CLONED(object))
1381         return FALSE;
1383     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1384     g_return_val_if_fail(rlist != NULL, FALSE);
1385     g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1386     rlist = g_slist_remove(rlist, object);
1387     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1389     document->priv->resources_changed_signals[q].emit();
1391     return TRUE;
1394 GSList const *
1395 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1397     g_return_val_if_fail(document != NULL, NULL);
1398     g_return_val_if_fail(key != NULL, NULL);
1399     g_return_val_if_fail(*key != '\0', NULL);
1401     return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1404 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1405                                                        gchar const *key,
1406                                                        SPDocument::ResourcesChangedSignal::slot_type slot)
1408     GQuark q = g_quark_from_string(key);
1409     return document->priv->resources_changed_signals[q].connect(slot);
1412 /* Helpers */
1414 gboolean
1415 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1417     g_slist_free((GSList *) value);
1418     return TRUE;
1421 unsigned int
1422 count_objects_recursive(SPObject *obj, unsigned int count)
1424     count++; // obj itself
1426     for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1427         count = count_objects_recursive(i, count);
1428     }
1430     return count;
1433 unsigned int
1434 objects_in_document(SPDocument *document)
1436     return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1439 void
1440 vacuum_document_recursive(SPObject *obj)
1442     if (SP_IS_DEFS(obj)) {
1443         for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1444             /* fixme: some inkscape-internal nodes in the future might not be collectable */
1445             def->requestOrphanCollection();
1446         }
1447     } else {
1448         for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1449             vacuum_document_recursive(i);
1450         }
1451     }
1454 unsigned int
1455 vacuum_document(SPDocument *document)
1457     unsigned int start = objects_in_document(document);
1458     unsigned int end;
1459     unsigned int newend = start;
1461     unsigned int iterations = 0;
1463     do {
1464         end = newend;
1466         vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1467         document->collectOrphans();
1468         iterations++;
1470         newend = objects_in_document(document);
1472     } while (iterations < 100 && newend < end);
1474     return start - newend;
1477 bool SPDocument::isSeeking() const {
1478     return priv->seeking;
1482 /*
1483   Local Variables:
1484   mode:c++
1485   c-file-style:"stroustrup"
1486   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1487   indent-tabs-mode:nil
1488   fill-column:99
1489   End:
1490 */
1491 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :