Code

allow multiple (balanced) calls to add and remove document
[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 "application/application.h"
42 #include "application/editor.h"
43 #include "libnr/nr-matrix-fns.h"
44 #include "xml/repr.h"
45 #include "helper/units.h"
46 #include "inkscape-private.h"
47 #include "inkscape_version.h"
48 #include "sp-object-repr.h"
49 #include "document-private.h"
50 #include "dir-util.h"
51 #include "unit-constants.h"
52 #include "prefs-utils.h"
53 #include "libavoid/router.h"
54 #include "libnr/nr-rect.h"
55 #include "sp-item-group.h"
57 #include "display/nr-arena-item.h"
59 #include "dialogs/rdf.h"
61 #define A4_WIDTH_STR "210mm"
62 #define A4_HEIGHT_STR "297mm"
64 #define SP_DOCUMENT_UPDATE_PRIORITY (G_PRIORITY_HIGH_IDLE - 1)
67 static gint sp_document_idle_handler(gpointer data);
69 gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data);
71 static gint doc_count = 0;
73 SPDocument::SPDocument() {
74     SPDocumentPrivate *p;
76     keepalive = FALSE;
77     virgin    = TRUE;
79     modified_id = 0;
81     rdoc = NULL;
82     rroot = NULL;
83     root = NULL;
84     style_cascade = cr_cascade_new(NULL, NULL, NULL);
86     uri = NULL;
87     base = NULL;
88     name = NULL;
90     _collection_queue = NULL;
92     // Initialise instance of connector router.
93     router = new Avoid::Router();
94     // Don't use the Consolidate moves optimisation.
95     router->ConsolidateMoves = false;
97     p = new SPDocumentPrivate();
99     p->iddef = g_hash_table_new(g_direct_hash, g_direct_equal);
100     p->reprdef = g_hash_table_new(g_direct_hash, g_direct_equal);
102     p->resources = g_hash_table_new(g_str_hash, g_str_equal);
104     p->sensitive = FALSE;
105     p->partial = NULL;
106     p->history_size = 0;
107     p->undo = NULL;
108     p->redo = NULL;
109     p->seeking = false;
111     priv = p;
113     // XXX only for testing!
114     priv->undoStackObservers.add(p->console_output_undo_observer);
117 SPDocument::~SPDocument() {
118     collectOrphans();
120     if (priv) {
121         if (priv->partial) {
122             sp_repr_free_log(priv->partial);
123             priv->partial = NULL;
124         }
126         sp_document_clear_redo(this);
127         sp_document_clear_undo(this);
129         if (root) {
130             root->releaseReferences();
131             sp_object_unref(root);
132             root = NULL;
133         }
135         if (priv->iddef) g_hash_table_destroy(priv->iddef);
136         if (priv->reprdef) g_hash_table_destroy(priv->reprdef);
138         if (rdoc) Inkscape::GC::release(rdoc);
140         /* Free resources */
141         g_hash_table_foreach_remove(priv->resources, sp_document_resource_list_free, this);
142         g_hash_table_destroy(priv->resources);
144         delete priv;
145         priv = NULL;
146     }
148     cr_cascade_unref(style_cascade);
149     style_cascade = NULL;
151     if (name) {
152         g_free(name);
153         name = NULL;
154     }
155     if (base) {
156         g_free(base);
157         base = NULL;
158     }
159     if (uri) {
160         g_free(uri);
161         uri = NULL;
162     }
164     if (modified_id) {
165         gtk_idle_remove(modified_id);
166         modified_id = 0;
167     }
169     _selection_changed_connection.disconnect();
170     _desktop_activated_connection.disconnect();
172     if (keepalive) {
173         inkscape_unref();
174         keepalive = FALSE;
175     }
177     if (router) {
178         delete router;
179         router = NULL;
180     }
182     //delete this->_whiteboard_session_manager;
185 void SPDocument::queueForOrphanCollection(SPObject *object) {
186     g_return_if_fail(object != NULL);
187     g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
189     sp_object_ref(object, NULL);
190     _collection_queue = g_slist_prepend(_collection_queue, object);
193 void SPDocument::collectOrphans() {
194     while (_collection_queue) {
195         GSList *objects=_collection_queue;
196         _collection_queue = NULL;
197         for ( GSList *iter=objects ; iter ; iter = iter->next ) {
198             SPObject *object=reinterpret_cast<SPObject *>(iter->data);
199             object->collectOrphan();
200             sp_object_unref(object, NULL);
201         }
202         g_slist_free(objects);
203     }
206 void SPDocument::reset_key (void *dummy)
208     actionkey = NULL;
211 SPDocument *
212 sp_document_create(Inkscape::XML::Document *rdoc,
213                    gchar const *uri,
214                    gchar const *base,
215                    gchar const *name,
216                    unsigned int keepalive)
218     SPDocument *document;
219     Inkscape::XML::Node *rroot;
220     Inkscape::Version sodipodi_version;
222     rroot = rdoc->root();
224     document = new SPDocument();
226     document->keepalive = keepalive;
228     document->rdoc = rdoc;
229     document->rroot = rroot;
231 #ifndef WIN32
232     prepend_current_dir_if_relative(&(document->uri), uri);
233 #else
234     // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
235     document->uri = uri? g_strdup(uri) : NULL;
236 #endif
238     // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
239     // which is why we use g_get_current_dir() in calculating the abs path above
240     //This is NULL for a new document
241     if (base)
242         document->base = g_strdup(base);
243     else
244         document->base = NULL;
245     document->name = g_strdup(name);
247     document->root = sp_object_repr_build_tree(document, rroot);
249     sodipodi_version = SP_ROOT(document->root)->version.sodipodi;
251     /* fixme: Not sure about this, but lets assume ::build updates */
252     rroot->setAttribute("sodipodi:version", SODIPODI_VERSION);
253     rroot->setAttribute("inkscape:version", INKSCAPE_VERSION);
254     /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
256     /* Quick hack 2 - get default image size into document */
257     if (!rroot->attribute("width")) rroot->setAttribute("width", A4_WIDTH_STR);
258     if (!rroot->attribute("height")) rroot->setAttribute("height", A4_HEIGHT_STR);
259     /* End of quick hack 2 */
261     /* Quick hack 3 - Set uri attributes */
262     if (uri) {
263         rroot->setAttribute("sodipodi:docname", uri);
264     }
265     /* End of quick hack 3 */
267     // creating namedview
268     if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
269         // if there's none in the document already,
270         Inkscape::XML::Node *r = NULL;
271         Inkscape::XML::Node *rnew = NULL;
272         r = inkscape_get_repr(INKSCAPE, "template.base");
273         // see if there's a template with id="base" in the preferences
274         if (!r) {
275             // if there's none, create an empty element
276             rnew = rdoc->createElement("sodipodi:namedview");
277             rnew->setAttribute("id", "base");
278         } else {
279             // otherwise, take from preferences
280             rnew = r->duplicate(rroot->document());
281         }
282         // insert into the document
283         rroot->addChild(rnew, NULL);
284         // clean up
285         Inkscape::GC::release(rnew);
286     }
288     /* Defs */
289     if (!SP_ROOT(document->root)->defs) {
290         Inkscape::XML::Node *r;
291         r = rdoc->createElement("svg:defs");
292         rroot->addChild(r, NULL);
293         Inkscape::GC::release(r);
294         g_assert(SP_ROOT(document->root)->defs);
295     }
297     /* Default RDF */
298     rdf_set_defaults( document );
300     if (keepalive) {
301         inkscape_ref();
302     }
304     sp_document_set_undo_sensitive(document, true);
306     // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
307     if (!Inkscape::NSApplication::Application::getNewGui()) {
308         g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
309                          G_CALLBACK(sp_document_reset_key), document);
310         g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
311                          G_CALLBACK(sp_document_reset_key), document);
312     } else {
313         document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
314         document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
315     }
317     return document;
320 /**
321  * Fetches document from URI, or creates new, if NULL; public document
322  * appears in document list.
323  */
324 SPDocument *
325 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
327     SPDocument *doc;
328     Inkscape::XML::Document *rdoc;
329     gchar *base = NULL;
330     gchar *name = NULL;
332     if (uri) {
333         Inkscape::XML::Node *rroot;
334         gchar *s, *p;
335         /* Try to fetch repr from file */
336         rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
337         /* If file cannot be loaded, return NULL without warning */
338         if (rdoc == NULL) return NULL;
339         rroot = rdoc->root();
340         /* If xml file is not svg, return NULL without warning */
341         /* fixme: destroy document */
342         if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
343         s = g_strdup(uri);
344         p = strrchr(s, '/');
345         if (p) {
346             name = g_strdup(p + 1);
347             p[1] = '\0';
348             base = g_strdup(s);
349         } else {
350             base = NULL;
351             name = g_strdup(uri);
352         }
353         g_free(s);
354     } else {
355         rdoc = sp_repr_document_new("svg:svg");
356     }
358     if (make_new) {
359         base = NULL;
360         uri = NULL;
361         name = g_strdup_printf(_("New document %d"), ++doc_count);
362     }
364     //# These should be set by now
365     g_assert(name);
367     doc = sp_document_create(rdoc, uri, base, name, keepalive);
369     g_free(base);
370     g_free(name);
372     return doc;
375 SPDocument *
376 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
378     SPDocument *doc;
379     Inkscape::XML::Document *rdoc;
380     Inkscape::XML::Node *rroot;
381     gchar *name;
383     rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
385     /* If it cannot be loaded, return NULL without warning */
386     if (rdoc == NULL) return NULL;
388     rroot = rdoc->root();
389     /* If xml file is not svg, return NULL without warning */
390     /* fixme: destroy document */
391     if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
393     name = g_strdup_printf(_("Memory document %d"), ++doc_count);
395     doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
397     return doc;
400 SPDocument *sp_document_new_dummy() {
401     SPDocument *document = new SPDocument();
402     return document;
405 SPDocument *
406 sp_document_ref(SPDocument *doc)
408     g_return_val_if_fail(doc != NULL, NULL);
409     Inkscape::GC::anchor(doc);
410     return doc;
413 SPDocument *
414 sp_document_unref(SPDocument *doc)
416     g_return_val_if_fail(doc != NULL, NULL);
417     Inkscape::GC::release(doc);
418     return NULL;
421 gdouble sp_document_width(SPDocument *document)
423     g_return_val_if_fail(document != NULL, 0.0);
424     g_return_val_if_fail(document->priv != NULL, 0.0);
425     g_return_val_if_fail(document->root != NULL, 0.0);
427     return SP_ROOT(document->root)->width.computed;
430 void
431 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
433     SPRoot *root = SP_ROOT(document->root);
435     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
436         root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
437     } else { // set to width=
438         root->width.computed = sp_units_get_pixels (width, *unit);
439         /* SVG does not support meters as a unit, so we must translate meters to
440          * cm when writing */
441         if (!strcmp(unit->abbr, "m")) {
442             root->width.value = 100*width;
443             root->width.unit = SVGLength::CM;
444         } else {
445             root->width.value = width;
446             root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
447         }
448     }
450     SP_OBJECT (root)->updateRepr();
453 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
455     SPRoot *root = SP_ROOT(document->root);
457     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
458         root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
459     } else { // set to height=
460         root->height.computed = sp_units_get_pixels (height, *unit);
461         /* SVG does not support meters as a unit, so we must translate meters to
462          * cm when writing */
463         if (!strcmp(unit->abbr, "m")) {
464             root->height.value = 100*height;
465             root->height.unit = SVGLength::CM;
466         } else {
467             root->height.value = height;
468             root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
469         }
470     }
472     SP_OBJECT (root)->updateRepr();
475 gdouble sp_document_height(SPDocument *document)
477     g_return_val_if_fail(document != NULL, 0.0);
478     g_return_val_if_fail(document->priv != NULL, 0.0);
479     g_return_val_if_fail(document->root != NULL, 0.0);
481     return SP_ROOT(document->root)->height.computed;
484 /**
485  * Given an NRRect that may, for example, correspond to the bbox of an object
486  * this function fits the canvas to that rect by resizing the canvas
487  * and translating the document root into position.
488  */
489 void SPDocument::fitToRect(NRRect const & rect)
491     g_return_if_fail(!nr_rect_d_test_empty(&rect));
492     
493     gdouble w = rect.x1 - rect.x0;
494     gdouble h = rect.y1 - rect.y0;
495     gdouble old_height = sp_document_height(this);
496     SPUnit unit = sp_unit_get_by_id(SP_UNIT_PX);
497     sp_document_set_width(this, w, &unit);
498     sp_document_set_height(this, h, &unit);
500     NR::translate tr = NR::translate::translate(-rect.x0,-(rect.y0 + (h - old_height)));
501     static_cast<SPGroup *>(root)->translateChildItems(tr);
504 void sp_document_set_uri(SPDocument *document, gchar const *uri)
506     g_return_if_fail(document != NULL);
508     if (document->name) {
509         g_free(document->name);
510         document->name = NULL;
511     }
512     if (document->base) {
513         g_free(document->base);
514         document->base = NULL;
515     }
516     if (document->uri) {
517         g_free(document->uri);
518         document->uri = NULL;
519     }
521     if (uri) {
523 #ifndef WIN32
524         prepend_current_dir_if_relative(&(document->uri), uri);
525 #else
526         // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
527         document->uri = g_strdup(uri);
528 #endif
530         /* fixme: Think, what this means for images (Lauris) */
531         document->base = g_path_get_dirname(document->uri);
532         document->name = g_path_get_basename(document->uri);
534     } else {
535         document->uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
536         document->base = NULL;
537         document->name = g_strdup(document->uri);
538     }
540     // Update saveable repr attributes.
541     Inkscape::XML::Node *repr = sp_document_repr_root(document);
542     // changing uri in the document repr must not be not undoable
543     bool saved = sp_document_get_undo_sensitive(document);
544     sp_document_set_undo_sensitive(document, false);
546     repr->setAttribute("sodipodi:docname", document->name);
547     sp_document_set_undo_sensitive(document, saved);
549     document->priv->uri_set_signal.emit(document->uri);
552 void
553 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
555     g_return_if_fail(doc != NULL);
557     doc->priv->resized_signal.emit(width, height);
560 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
562     return priv->modified_signal.connect(slot);
565 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
567     return priv->uri_set_signal.connect(slot);
570 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
572     return priv->resized_signal.connect(slot);
575 sigc::connection
576 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
578     return priv->_reconstruction_start_signal.connect(slot);
581 void
582 SPDocument::emitReconstructionStart(void)
584     // printf("Starting Reconstruction\n");
585     priv->_reconstruction_start_signal.emit();
586     return;
589 sigc::connection
590 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type  slot)
592     return priv->_reconstruction_finish_signal.connect(slot);
595 void
596 SPDocument::emitReconstructionFinish(void)
598     // printf("Finishing Reconstruction\n");
599     priv->_reconstruction_finish_signal.emit();
600     return;
603 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
605     return priv->commit_signal.connect(slot);
610 void SPDocument::_emitModified() {
611     static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
612     root->emitModified(0);
613     priv->modified_signal.emit(flags);
616 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
617     GQuark idq = g_quark_from_string(id);
619     if (object) {
620         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
621         g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
622     } else {
623         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
624         g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
625     }
627     SPDocumentPrivate::IDChangedSignalMap::iterator pos;
629     pos = priv->id_changed_signals.find(idq);
630     if ( pos != priv->id_changed_signals.end() ) {
631         if (!(*pos).second.empty()) {
632             (*pos).second.emit(object);
633         } else { // discard unused signal
634             priv->id_changed_signals.erase(pos);
635         }
636     }
639 void
640 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
642         this->priv->undoStackObservers.add(observer);
645 void
646 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
648         this->priv->undoStackObservers.remove(observer);
651 SPObject *SPDocument::getObjectById(gchar const *id) {
652     g_return_val_if_fail(id != NULL, NULL);
654     GQuark idq = g_quark_from_string(id);
655     return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
658 sigc::connection SPDocument::connectIdChanged(gchar const *id,
659                                               SPDocument::IDChangedSignal::slot_type slot)
661     return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
664 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
665     if (object) {
666         g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
667         g_hash_table_insert(priv->reprdef, repr, object);
668     } else {
669         g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
670         g_hash_table_remove(priv->reprdef, repr);
671     }
674 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
675     g_return_val_if_fail(repr != NULL, NULL);
676     return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
679 Glib::ustring SPDocument::getLanguage() {
680     gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
681     if (document_language) {
682         while (isspace(*document_language))
683             document_language++;
684     }
685     if ( !document_language || 0 == *document_language) {
686         // retrieve system language
687         document_language = getenv("LC_ALL");
688         if ( NULL == document_language || *document_language == 0 ) {
689             document_language = getenv ("LC_MESSAGES");
690         }
691         if ( NULL == document_language || *document_language == 0 ) {
692             document_language = getenv ("LANG");
693         }
694         
695         if ( NULL != document_language ) {
696             gchar *pos = strchr(document_language, '_');
697             if ( NULL != pos ) {
698                 return Glib::ustring(document_language, pos - document_language);
699             }
700         }
701     }
703     if ( NULL == document_language )
704         return Glib::ustring();
705     return document_language;
708 /* Object modification root handler */
710 void
711 sp_document_request_modified(SPDocument *doc)
713     if (!doc->modified_id) {
714         doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
715     }
718 void
719 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
721     ctx->ctx.flags = 0;
722     ctx->i2doc = NR::identity();
723     /* Set up viewport in case svg has it defined as percentages */
724     if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
725         ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
726         ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
727         ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
728         ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
729     } else { // as a last resort, set size to A4
730         ctx->vp.x0 = 0.0;
731         ctx->vp.y0 = 0.0;
732         ctx->vp.x1 = 210 * PX_PER_MM;
733         ctx->vp.y1 = 297 * PX_PER_MM;
734     }
735     ctx->i2vp = NR::identity();
738 /**
739  * Tries to update the document state based on the modified and 
740  * "update required" flags, and return true if the document has
741  * been brought fully up to date.
742  */
743 bool
744 SPDocument::_updateDocument()
746     /* Process updates */
747     if (this->root->uflags || this->root->mflags) {
748         if (this->root->uflags) {
749             SPItemCtx ctx;
750             sp_document_setup_viewport (this, &ctx);
752             bool saved = sp_document_get_undo_sensitive(this);
753             sp_document_set_undo_sensitive(this, false);
755             this->root->updateDisplay((SPCtx *)&ctx, 0);
757             sp_document_set_undo_sensitive(this, saved);
758         }
759         this->_emitModified();
760     }
762     return !(this->root->uflags || this->root->mflags);
766 /**
767  * Repeatedly works on getting the document updated, since sometimes
768  * it takes more than one pass to get the document updated.  But it
769  * usually should not take more than a few loops, and certainly never
770  * more than 32 iterations.  So we bail out if we hit 32 iterations,
771  * since this typically indicates we're stuck in an update loop.
772  */
773 gint
774 sp_document_ensure_up_to_date(SPDocument *doc)
776     int counter = 32;
777     while (!doc->_updateDocument()) {
778         if (counter == 0) {
779             g_warning("More than 32 iteration while updating document '%s'", doc->uri);
780             break;
781         }
782         counter--;
783     }
785     if (doc->modified_id) {
786         /* Remove handler */
787         gtk_idle_remove(doc->modified_id);
788         doc->modified_id = 0;
789     }
790     return counter>0;
793 /**
794  * An idle handler to update the document.  Returns true if
795  * the document needs further updates.
796  */
797 static gint
798 sp_document_idle_handler(gpointer data)
800     SPDocument *doc = static_cast<SPDocument *>(data);
801     if (doc->_updateDocument()) {
802         doc->modified_id = 0;
803         return false;
804     } else {
805         return true;
806     }
809 static bool is_within(NR::Rect const &area, NR::Rect const &box)
811     return area.contains(box);
814 static bool overlaps(NR::Rect const &area, NR::Rect const &box)
816     return area.intersects(box);
819 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, NR::Rect const &area,
820                                   bool (*test)(NR::Rect const &, NR::Rect const &), bool take_insensitive = false)
822     g_return_val_if_fail(SP_IS_GROUP(group), s);
824     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
825         if (!SP_IS_ITEM(o)) {
826             continue;
827         }
828         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
829             s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
830         } else {
831             SPItem *child = SP_ITEM(o);
832             NR::Maybe<NR::Rect> box = sp_item_bbox_desktop(child);
833             if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
834                 s = g_slist_append(s, child);
835             }
836         }
837     }
839     return s;
842 /**
843 Returns true if an item is among the descendants of group (recursively).
844  */
845 bool item_is_in_group(SPItem *item, SPGroup *group)
847     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
848         if (!SP_IS_ITEM(o)) continue;
849         if (SP_ITEM(o) == item)
850             return true;
851         if (SP_IS_GROUP(o))
852             if (item_is_in_group(item, SP_GROUP(o)))
853                 return true;
854     }
855     return false;
858 /**
859 Returns the bottommost item from the list which is at the point, or NULL if none.
860 */
861 SPItem*
862 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
863                                            NR::Point const p, bool take_insensitive)
865     g_return_val_if_fail(group, NULL);
867     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
869     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
871         if (!SP_IS_ITEM(o)) continue;
873         SPItem *item = SP_ITEM(o);
874         NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
875         if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
876             && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
877             if (g_slist_find((GSList *) list, item) != NULL)
878                 return item;
879         }
881         if (SP_IS_GROUP(o)) {
882             SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
883             if (found)
884                 return found;
885         }
887     }
888     return NULL;
891 /**
892 Returns the topmost (in z-order) item from the descendants of group (recursively) which
893 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
894 non-layer groups or not. Honors take_insensitive on whether to return insensitive
895 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
896 upwards in z-order and returns what it has found so far (i.e. the found item is
897 guaranteed to be lower than upto).
898  */
899 SPItem*
900 find_item_at_point(unsigned int dkey, SPGroup *group, NR::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
902     SPItem *seen = NULL, *newseen = NULL;
904     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
906     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
907         if (!SP_IS_ITEM(o)) continue;
909         if (upto && SP_ITEM(o) == upto)
910             break;
912         if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
913             // if nothing found yet, recurse into the group
914             newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
915             if (newseen) {
916                 seen = newseen;
917                 newseen = NULL;
918             }
920             if (item_is_in_group(upto, SP_GROUP(o)))
921                 break;
923         } else {
924             SPItem *child = SP_ITEM(o);
925             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
927             // seen remembers the last (topmost) of items pickable at this point
928             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
929                 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
930                 seen = child;
931             }
932         }
933     }
934     return seen;
937 /**
938 Returns the topmost non-layer group from the descendants of group which is at point
939 p, or NULL if none. Recurses into layers but not into groups.
940  */
941 SPItem*
942 find_group_at_point(unsigned int dkey, SPGroup *group, NR::Point const p)
944     SPItem *seen = NULL;
946     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
948     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
949         if (!SP_IS_ITEM(o)) continue;
950         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
951             SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
952             if (newseen) {
953                 seen = newseen;
954             }
955         }
956         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
957             SPItem *child = SP_ITEM(o);
958             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
960             // seen remembers the last (topmost) of groups pickable at this point
961             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
962                 seen = child;
963             }
964         }
965     }
966     return seen;
969 /*
970  * Return list of items, contained in box
971  *
972  * Assumes box is normalized (and g_asserts it!)
973  *
974  */
976 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
978     g_return_val_if_fail(document != NULL, NULL);
979     g_return_val_if_fail(document->priv != NULL, NULL);
981     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
984 /*
985  * Return list of items, that the parts of the item contained in box
986  *
987  * Assumes box is normalized (and g_asserts it!)
988  *
989  */
991 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
993     g_return_val_if_fail(document != NULL, NULL);
994     g_return_val_if_fail(document->priv != NULL, NULL);
996     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
999 SPItem *
1000 sp_document_item_at_point(SPDocument *document, unsigned const key, NR::Point const p,
1001                           gboolean const into_groups, SPItem *upto)
1003     g_return_val_if_fail(document != NULL, NULL);
1004     g_return_val_if_fail(document->priv != NULL, NULL);
1006     return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1009 SPItem*
1010 sp_document_group_at_point(SPDocument *document, unsigned int key, NR::Point const p)
1012     g_return_val_if_fail(document != NULL, NULL);
1013     g_return_val_if_fail(document->priv != NULL, NULL);
1015     return find_group_at_point(key, SP_GROUP(document->root), p);
1019 /* Resource management */
1021 gboolean
1022 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1024     GSList *rlist;
1025     GQuark q = g_quark_from_string(key);
1027     g_return_val_if_fail(document != NULL, FALSE);
1028     g_return_val_if_fail(key != NULL, FALSE);
1029     g_return_val_if_fail(*key != '\0', FALSE);
1030     g_return_val_if_fail(object != NULL, FALSE);
1031     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1033     if (SP_OBJECT_IS_CLONED(object))
1034         return FALSE;
1036     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1037     g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1038     rlist = g_slist_prepend(rlist, object);
1039     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1041     document->priv->resources_changed_signals[q].emit();
1043     return TRUE;
1046 gboolean
1047 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1049     GSList *rlist;
1050     GQuark q = g_quark_from_string(key);
1052     g_return_val_if_fail(document != NULL, FALSE);
1053     g_return_val_if_fail(key != NULL, FALSE);
1054     g_return_val_if_fail(*key != '\0', FALSE);
1055     g_return_val_if_fail(object != NULL, FALSE);
1056     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1058     if (SP_OBJECT_IS_CLONED(object))
1059         return FALSE;
1061     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1062     g_return_val_if_fail(rlist != NULL, FALSE);
1063     g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1064     rlist = g_slist_remove(rlist, object);
1065     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1067     document->priv->resources_changed_signals[q].emit();
1069     return TRUE;
1072 GSList const *
1073 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1075     g_return_val_if_fail(document != NULL, NULL);
1076     g_return_val_if_fail(key != NULL, NULL);
1077     g_return_val_if_fail(*key != '\0', NULL);
1079     return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1082 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1083                                                        gchar const *key,
1084                                                        SPDocument::ResourcesChangedSignal::slot_type slot)
1086     GQuark q = g_quark_from_string(key);
1087     return document->priv->resources_changed_signals[q].connect(slot);
1090 /* Helpers */
1092 gboolean
1093 sp_document_resource_list_free(gpointer key, gpointer value, gpointer data)
1095     g_slist_free((GSList *) value);
1096     return TRUE;
1099 unsigned int
1100 count_objects_recursive(SPObject *obj, unsigned int count)
1102     count++; // obj itself
1104     for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1105         count = count_objects_recursive(i, count);
1106     }
1108     return count;
1111 unsigned int
1112 objects_in_document(SPDocument *document)
1114     return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1117 void
1118 vacuum_document_recursive(SPObject *obj)
1120     if (SP_IS_DEFS(obj)) {
1121         for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1122             /* fixme: some inkscape-internal nodes in the future might not be collectable */
1123             def->requestOrphanCollection();
1124         }
1125     } else {
1126         for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1127             vacuum_document_recursive(i);
1128         }
1129     }
1132 unsigned int
1133 vacuum_document(SPDocument *document)
1135     unsigned int start = objects_in_document(document);
1136     unsigned int end;
1137     unsigned int newend = start;
1139     unsigned int iterations = 0;
1141     do {
1142         end = newend;
1144         vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1145         document->collectOrphans();
1146         iterations++;
1148         newend = objects_in_document(document);
1150     } while (iterations < 100 && newend < end);
1152     return start - newend;
1155 bool SPDocument::isSeeking() const {
1156     return priv->seeking;
1160 /*
1161   Local Variables:
1162   mode:c++
1163   c-file-style:"stroustrup"
1164   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1165   indent-tabs-mode:nil
1166   fill-column:99
1167   End:
1168 */
1169 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :