Code

SVG 1.1 Conditional Processing Module rendering support (<switch> element, requiredRe...
[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-transform.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();
95     p = new SPDocumentPrivate();
97     p->iddef = g_hash_table_new(g_direct_hash, g_direct_equal);
98     p->reprdef = g_hash_table_new(g_direct_hash, g_direct_equal);
100     p->resources = g_hash_table_new(g_str_hash, g_str_equal);
102     p->sensitive = FALSE;
103     p->partial = NULL;
104     p->history_size = 0;
105     p->undo = NULL;
106     p->redo = NULL;
108     priv = p;
111 SPDocument::~SPDocument() {
112     collectOrphans();
114     if (priv) {
115         inkscape_remove_document(this);
117         if (priv->partial) {
118             sp_repr_free_log(priv->partial);
119             priv->partial = NULL;
120         }
122         sp_document_clear_redo(this);
123         sp_document_clear_undo(this);
125         if (root) {
126             sp_object_invoke_release(root);
127             g_object_unref(G_OBJECT(root));
128             root = NULL;
129         }
131         if (priv->iddef) g_hash_table_destroy(priv->iddef);
132         if (priv->reprdef) g_hash_table_destroy(priv->reprdef);
134         if (rdoc) Inkscape::GC::release(rdoc);
136         /* Free resources */
137         g_hash_table_foreach_remove(priv->resources, sp_document_resource_list_free, this);
138         g_hash_table_destroy(priv->resources);
140         delete priv;
141         priv = NULL;
142     }
144     cr_cascade_unref(style_cascade);
145     style_cascade = NULL;
147     if (name) {
148         g_free(name);
149         name = NULL;
150     }
151     if (base) {
152         g_free(base);
153         base = NULL;
154     }
155     if (uri) {
156         g_free(uri);
157         uri = NULL;
158     }
160     if (modified_id) {
161         gtk_idle_remove(modified_id);
162         modified_id = 0;
163     }
165     _selection_changed_connection.disconnect();
166     _desktop_activated_connection.disconnect();
168     if (keepalive) {
169         inkscape_unref();
170         keepalive = FALSE;
171     }
173     if (router) {
174         delete router;
175         router = NULL;
176     }
178     //delete this->_whiteboard_session_manager;
181 void SPDocument::queueForOrphanCollection(SPObject *object) {
182     g_return_if_fail(object != NULL);
183     g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
185     sp_object_ref(object, NULL);
186     _collection_queue = g_slist_prepend(_collection_queue, object);
189 void SPDocument::collectOrphans() {
190     while (_collection_queue) {
191         GSList *objects=_collection_queue;
192         _collection_queue = NULL;
193         for ( GSList *iter=objects ; iter ; iter = iter->next ) {
194             SPObject *object=reinterpret_cast<SPObject *>(iter->data);
195             object->collectOrphan();
196             sp_object_unref(object, NULL);
197         }
198         g_slist_free(objects);
199     }
202 void SPDocument::reset_key (void *dummy)
204     actionkey = NULL;
207 static SPDocument *
208 sp_document_create(Inkscape::XML::Document *rdoc,
209                    gchar const *uri,
210                    gchar const *base,
211                    gchar const *name,
212                    unsigned int keepalive)
214     SPDocument *document;
215     Inkscape::XML::Node *rroot;
216     Inkscape::Version sodipodi_version;
218     rroot = sp_repr_document_root(rdoc);
220     document = new SPDocument();
222     document->keepalive = keepalive;
224     document->rdoc = rdoc;
225     document->rroot = rroot;
227 #ifndef WIN32
228     prepend_current_dir_if_relative(&(document->uri), uri);
229 #else
230     // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
231     document->uri = uri? g_strdup(uri) : NULL;
232 #endif
234     // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
235     // which is why we use g_get_current_dir() in calculating the abs path above
236     //This is NULL for a new document
237     if (base)
238         document->base = g_strdup(base);
239     else
240         document->base = NULL;
241     document->name = g_strdup(name);
243     document->root = sp_object_repr_build_tree(document, rroot);
245     sodipodi_version = SP_ROOT(document->root)->version.sodipodi;
247     /* fixme: Not sure about this, but lets assume ::build updates */
248     rroot->setAttribute("sodipodi:version", SODIPODI_VERSION);
249     rroot->setAttribute("inkscape:version", INKSCAPE_VERSION);
250     /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
252     /* Quick hack 2 - get default image size into document */
253     if (!rroot->attribute("width")) rroot->setAttribute("width", A4_WIDTH_STR);
254     if (!rroot->attribute("height")) rroot->setAttribute("height", A4_HEIGHT_STR);
255     /* End of quick hack 2 */
257     /* Quick hack 3 - Set uri attributes */
258     if (uri) {
259         /* fixme: Think, what this means for images (Lauris) */
260         rroot->setAttribute("sodipodi:docname", uri);
261         if (document->base)
262             rroot->setAttribute("sodipodi:docbase", document->base);
263     }
264     /* End of quick hack 3 */
266     // creating namedview
267     if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
268         // if there's none in the document already,
269         Inkscape::XML::Node *r = NULL;
270         Inkscape::XML::Node *rnew = NULL;
271         r = inkscape_get_repr(INKSCAPE, "template.base");
272         // see if there's a template with id="base" in the preferences
273         if (!r) {
274             // if there's none, create an empty element
275             rnew = sp_repr_new("sodipodi:namedview");
276             rnew->setAttribute("id", "base");
277         } else {
278             // otherwise, take from preferences
279             rnew = r->duplicate();
280         }
281         // insert into the document
282         rroot->addChild(rnew, NULL);
283         // clean up
284         Inkscape::GC::release(rnew);
285     }
287     /* Defs */
288     if (!SP_ROOT(document->root)->defs) {
289         Inkscape::XML::Node *r;
290         r = sp_repr_new("svg:defs");
291         rroot->addChild(r, NULL);
292         Inkscape::GC::release(r);
293         g_assert(SP_ROOT(document->root)->defs);
294     }
296     /* Default RDF */
297     rdf_set_defaults( document );
299     if (keepalive) {
300         inkscape_ref();
301     }
303     sp_document_set_undo_sensitive(document, TRUE);
305     // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
306     if (!Inkscape::NSApplication::Application::getNewGui()) {
307         g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
308                          G_CALLBACK(sp_document_reset_key), document);
309         g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
310                          G_CALLBACK(sp_document_reset_key), document);
311     } else {
312         document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
313         document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
314     }
315     inkscape_add_document(document);
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 = sp_repr_document_root(rdoc);
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 = sp_repr_document_root(rdoc);
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     inkscape_add_document(document);
403     return document;
406 SPDocument *
407 sp_document_ref(SPDocument *doc)
409     g_return_val_if_fail(doc != NULL, NULL);
410     Inkscape::GC::anchor(doc);
411     return doc;
414 SPDocument *
415 sp_document_unref(SPDocument *doc)
417     g_return_val_if_fail(doc != NULL, NULL);
418     Inkscape::GC::release(doc);
419     return NULL;
422 gdouble sp_document_width(SPDocument *document)
424     g_return_val_if_fail(document != NULL, 0.0);
425     g_return_val_if_fail(document->priv != NULL, 0.0);
426     g_return_val_if_fail(document->root != NULL, 0.0);
428     return SP_ROOT(document->root)->width.computed;
431 void
432 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
434     SPRoot *root = SP_ROOT(document->root);
436     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
437         root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
438     } else { // set to width=
439         root->width.computed = sp_units_get_pixels (width, *unit);
440         /* SVG does not support meters as a unit, so we must translate meters to
441          * cm when writing */
442         if (!strcmp(unit->abbr, "m")) {
443             root->width.value = 100*width;
444             root->width.unit = SVGLength::CM;
445         } else {
446             root->width.value = width;
447             root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
448         }
449     }
451     SP_OBJECT (root)->updateRepr();
454 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
456     SPRoot *root = SP_ROOT(document->root);
458     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
459         root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
460     } else { // set to height=
461         root->height.computed = sp_units_get_pixels (height, *unit);
462         /* SVG does not support meters as a unit, so we must translate meters to
463          * cm when writing */
464         if (!strcmp(unit->abbr, "m")) {
465             root->height.value = 100*height;
466             root->height.unit = SVGLength::CM;
467         } else {
468             root->height.value = height;
469             root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
470         }
471     }
473     SP_OBJECT (root)->updateRepr();
476 gdouble sp_document_height(SPDocument *document)
478     g_return_val_if_fail(document != NULL, 0.0);
479     g_return_val_if_fail(document->priv != NULL, 0.0);
480     g_return_val_if_fail(document->root != NULL, 0.0);
482     return SP_ROOT(document->root)->height.computed;
485 /**
486  * Given an NRRect that may, for example, correspond to the bbox of an object
487  * this function fits the canvas to that rect by resizing the canvas
488  * and translating the document root into position.
489  */
490 void SPDocument::fitToRect(NRRect const & rect)
492     g_return_if_fail(!empty(rect));
493     
494     gdouble w = rect.x1 - rect.x0;
495     gdouble h = rect.y1 - rect.y0;
496     gdouble old_height = sp_document_height(this);
497     SPUnit unit = sp_unit_get_by_id(SP_UNIT_PX);
498     sp_document_set_width(this, w, &unit);
499     sp_document_set_height(this, h, &unit);
501     NR::translate tr = NR::translate::translate(-rect.x0,-(rect.y0 + (h - old_height)));
502     sp_item_move_rel((SPItem *) root, tr);
505 void sp_document_set_uri(SPDocument *document, gchar const *uri)
507     g_return_if_fail(document != NULL);
509     if (document->name) {
510         g_free(document->name);
511         document->name = NULL;
512     }
513     if (document->base) {
514         g_free(document->base);
515         document->base = NULL;
516     }
517     if (document->uri) {
518         g_free(document->uri);
519         document->uri = NULL;
520     }
522     if (uri) {
524 #ifndef WIN32
525         prepend_current_dir_if_relative(&(document->uri), uri);
526 #else
527         // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
528         document->uri = g_strdup(uri);
529 #endif
531         /* fixme: Think, what this means for images (Lauris) */
532         document->base = g_path_get_dirname(document->uri);
533         document->name = g_path_get_basename(document->uri);
535     } else {
536         document->uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
537         document->base = NULL;
538         document->name = g_strdup(document->uri);
539     }
541     // Update saveable repr attributes.
542     Inkscape::XML::Node *repr = sp_document_repr_root(document);
543     // changing uri in the document repr must not be not undoable
544     gboolean saved = sp_document_get_undo_sensitive(document);
545     sp_document_set_undo_sensitive(document, FALSE);
546     if (document->base)
547         repr->setAttribute("sodipodi:docbase", document->base);
549     repr->setAttribute("sodipodi:docname", document->name);
550     sp_document_set_undo_sensitive(document, saved);
552     document->priv->uri_set_signal.emit(document->uri);
555 void
556 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
558     g_return_if_fail(doc != NULL);
560     doc->priv->resized_signal.emit(width, height);
563 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
565     return priv->modified_signal.connect(slot);
568 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
570     return priv->uri_set_signal.connect(slot);
573 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
575     return priv->resized_signal.connect(slot);
578 sigc::connection
579 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
581     return priv->_reconstruction_start_signal.connect(slot);
584 void
585 SPDocument::emitReconstructionStart(void)
587     // printf("Starting Reconstruction\n");
588     priv->_reconstruction_start_signal.emit();
589     return;
592 sigc::connection
593 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type  slot)
595     return priv->_reconstruction_finish_signal.connect(slot);
598 void
599 SPDocument::emitReconstructionFinish(void)
601     // printf("Finishing Reconstruction\n");
602     priv->_reconstruction_finish_signal.emit();
603     return;
607 void SPDocument::_emitModified() {
608     static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
609     root->emitModified(0);
610     priv->modified_signal.emit(flags);
613 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
614     GQuark idq = g_quark_from_string(id);
616     if (object) {
617         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
618         g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
619     } else {
620         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
621         g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
622     }
624     SPDocumentPrivate::IDChangedSignalMap::iterator pos;
626     pos = priv->id_changed_signals.find(idq);
627     if ( pos != priv->id_changed_signals.end() ) {
628         if (!(*pos).second.empty()) {
629             (*pos).second.emit(object);
630         } else { // discard unused signal
631             priv->id_changed_signals.erase(pos);
632         }
633     }
636 void
637 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
639         this->priv->undoStackObservers.add(observer);
642 void
643 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
645         this->priv->undoStackObservers.remove(observer);
648 SPObject *SPDocument::getObjectById(gchar const *id) {
649     g_return_val_if_fail(id != NULL, NULL);
651     GQuark idq = g_quark_from_string(id);
652     return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
655 sigc::connection SPDocument::connectIdChanged(gchar const *id,
656                                               SPDocument::IDChangedSignal::slot_type slot)
658     return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
661 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
662     if (object) {
663         g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
664         g_hash_table_insert(priv->reprdef, repr, object);
665     } else {
666         g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
667         g_hash_table_remove(priv->reprdef, repr);
668     }
671 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
672     g_return_val_if_fail(repr != NULL, NULL);
673     return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
676 Glib::ustring SPDocument::getLanguage() {
677     gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
678     if (document_language) {
679         while (isspace(*document_language))
680             document_language++;
681     }
682     if ( !document_language || 0 == *document_language) {
683         // retrieve system language
684         document_language = getenv("LC_ALL");
685         if ( NULL == document_language || *document_language == 0 ) {
686             document_language = getenv ("LC_MESSAGES");
687         }
688         if ( NULL == document_language || *document_language == 0 ) {
689             document_language = getenv ("LANG");
690         }
691         
692         if ( NULL != document_language ) {
693             gchar *pos = strchr(document_language, '_');
694             if ( NULL != pos ) {
695                 return Glib::ustring(document_language, pos - document_language);
696             }
697         }
698     }
700     if ( NULL == document_language )
701         return Glib::ustring();
702     return document_language;
705 /* Object modification root handler */
707 void
708 sp_document_request_modified(SPDocument *doc)
710     if (!doc->modified_id) {
711         doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
712     }
715 void
716 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
718     ctx->ctx.flags = 0;
719     ctx->i2doc = NR::identity();
720     /* Set up viewport in case svg has it defined as percentages */
721     if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
722         ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
723         ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
724         ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
725         ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
726     } else { // as a last resort, set size to A4
727         ctx->vp.x0 = 0.0;
728         ctx->vp.y0 = 0.0;
729         ctx->vp.x1 = 210 * PX_PER_MM;
730         ctx->vp.y1 = 297 * PX_PER_MM;
731     }
732     ctx->i2vp = NR::identity();
735 gint
736 sp_document_ensure_up_to_date(SPDocument *doc)
738     int lc;
739     lc = 32;
740     while (doc->root->uflags || doc->root->mflags) {
741         lc -= 1;
742         if (lc < 0) {
743             g_warning("More than 32 iterations while updating document '%s'", doc->uri);
744             if (doc->modified_id) {
745                 /* Remove handler */
746                 gtk_idle_remove(doc->modified_id);
747                 doc->modified_id = 0;
748             }
749             return FALSE;
750         }
751         /* Process updates */
752         if (doc->root->uflags) {
753             SPItemCtx ctx;
754             sp_document_setup_viewport (doc, &ctx);
755             doc->root->updateDisplay((SPCtx *)&ctx, 0);
756         }
757         doc->_emitModified();
758     }
759     if (doc->modified_id) {
760         /* Remove handler */
761         gtk_idle_remove(doc->modified_id);
762         doc->modified_id = 0;
763     }
764     return TRUE;
767 static gint
768 sp_document_idle_handler(gpointer data)
770     SPDocument *doc;
771     int repeat;
773     doc = static_cast<SPDocument *>(data);
775 #ifdef SP_DOCUMENT_DEBUG_IDLE
776     g_print("->\n");
777 #endif
779     /* Process updates */
780     if (doc->root->uflags) {
781         SPItemCtx ctx;
782         sp_document_setup_viewport (doc, &ctx);
784         gboolean saved = sp_document_get_undo_sensitive(doc);
785         sp_document_set_undo_sensitive(doc, FALSE);
787         doc->root->updateDisplay((SPCtx *)&ctx, 0);
789         sp_document_set_undo_sensitive(doc, saved);
790         /* if (doc->root->uflags & SP_OBJECT_MODIFIED_FLAG) return TRUE; */
791     }
793     doc->_emitModified();
795     repeat = (doc->root->uflags || doc->root->mflags);
796     if (!repeat) doc->modified_id = 0;
797     return repeat;
800 static bool is_within(NR::Rect const &area, NR::Rect const &box)
802     return area.contains(box);
805 static bool overlaps(NR::Rect const &area, NR::Rect const &box)
807     return area.intersects(box);
810 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, NR::Rect const &area,
811                                   bool (*test)(NR::Rect const &, NR::Rect const &), bool take_insensitive = false)
813     g_return_val_if_fail(SP_IS_GROUP(group), s);
815     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
816         if (!SP_IS_ITEM(o)) {
817             continue;
818         }
819         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
820             s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
821         } else {
822             SPItem *child = SP_ITEM(o);
823             NR::Rect box = sp_item_bbox_desktop(child);
824             if (test(area, box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
825                 s = g_slist_append(s, child);
826             }
827         }
828     }
830     return s;
833 /**
834 Returns true if an item is among the descendants of group (recursively).
835  */
836 bool item_is_in_group(SPItem *item, SPGroup *group)
838     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
839         if (!SP_IS_ITEM(o)) continue;
840         if (SP_ITEM(o) == item)
841             return true;
842         if (SP_IS_GROUP(o))
843             if (item_is_in_group(item, SP_GROUP(o)))
844                 return true;
845     }
846     return false;
849 /**
850 Returns the bottommost item from the list which is at the point, or NULL if none.
851 */
852 SPItem*
853 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
854                                            NR::Point const p, bool take_insensitive)
856     g_return_val_if_fail(group, NULL);
858     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
860     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
862         if (!SP_IS_ITEM(o)) continue;
864         SPItem *item = SP_ITEM(o);
865         NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
866         if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
867             && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
868             if (g_slist_find((GSList *) list, item) != NULL)
869                 return item;
870         }
872         if (SP_IS_GROUP(o)) {
873             SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
874             if (found)
875                 return found;
876         }
878     }
879     return NULL;
882 /**
883 Returns the topmost (in z-order) item from the descendants of group (recursively) which
884 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
885 non-layer groups or not. Honors take_insensitive on whether to return insensitive
886 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
887 upwards in z-order and returns what it has found so far (i.e. the found item is
888 guaranteed to be lower than upto).
889  */
890 SPItem*
891 find_item_at_point(unsigned int dkey, SPGroup *group, NR::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
893     SPItem *seen = NULL, *newseen = NULL;
895     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
897     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
898         if (!SP_IS_ITEM(o)) continue;
900         if (upto && SP_ITEM(o) == upto)
901             break;
903         if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
904             // if nothing found yet, recurse into the group
905             newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
906             if (newseen) {
907                 seen = newseen;
908                 newseen = NULL;
909             }
911             if (item_is_in_group(upto, SP_GROUP(o)))
912                 break;
914         } else {
915             SPItem *child = SP_ITEM(o);
916             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
918             // seen remembers the last (topmost) of items pickable at this point
919             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
920                 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
921                 seen = child;
922             }
923         }
924     }
925     return seen;
928 /**
929 Returns the topmost non-layer group from the descendants of group which is at point
930 p, or NULL if none. Recurses into layers but not into groups.
931  */
932 SPItem*
933 find_group_at_point(unsigned int dkey, SPGroup *group, NR::Point const p)
935     SPItem *seen = NULL;
937     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
939     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
940         if (!SP_IS_ITEM(o)) continue;
941         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
942             SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
943             if (newseen) {
944                 seen = newseen;
945             }
946         }
947         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
948             SPItem *child = SP_ITEM(o);
949             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
951             // seen remembers the last (topmost) of groups pickable at this point
952             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
953                 seen = child;
954             }
955         }
956     }
957     return seen;
960 /*
961  * Return list of items, contained in box
962  *
963  * Assumes box is normalized (and g_asserts it!)
964  *
965  */
967 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
969     g_return_val_if_fail(document != NULL, NULL);
970     g_return_val_if_fail(document->priv != NULL, NULL);
972     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
975 /*
976  * Return list of items, that the parts of the item contained in box
977  *
978  * Assumes box is normalized (and g_asserts it!)
979  *
980  */
982 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
984     g_return_val_if_fail(document != NULL, NULL);
985     g_return_val_if_fail(document->priv != NULL, NULL);
987     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
990 SPItem *
991 sp_document_item_at_point(SPDocument *document, unsigned const key, NR::Point const p,
992                           gboolean const into_groups, SPItem *upto)
994     g_return_val_if_fail(document != NULL, NULL);
995     g_return_val_if_fail(document->priv != NULL, NULL);
997     return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1000 SPItem*
1001 sp_document_group_at_point(SPDocument *document, unsigned int key, NR::Point const p)
1003     g_return_val_if_fail(document != NULL, NULL);
1004     g_return_val_if_fail(document->priv != NULL, NULL);
1006     return find_group_at_point(key, SP_GROUP(document->root), p);
1010 /* Resource management */
1012 gboolean
1013 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1015     GSList *rlist;
1016     GQuark q = g_quark_from_string(key);
1018     g_return_val_if_fail(document != NULL, FALSE);
1019     g_return_val_if_fail(key != NULL, FALSE);
1020     g_return_val_if_fail(*key != '\0', FALSE);
1021     g_return_val_if_fail(object != NULL, FALSE);
1022     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1024     if (SP_OBJECT_IS_CLONED(object))
1025         return FALSE;
1027     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1028     g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1029     rlist = g_slist_prepend(rlist, object);
1030     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1032     document->priv->resources_changed_signals[q].emit();
1034     return TRUE;
1037 gboolean
1038 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1040     GSList *rlist;
1041     GQuark q = g_quark_from_string(key);
1043     g_return_val_if_fail(document != NULL, FALSE);
1044     g_return_val_if_fail(key != NULL, FALSE);
1045     g_return_val_if_fail(*key != '\0', FALSE);
1046     g_return_val_if_fail(object != NULL, FALSE);
1047     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1049     if (SP_OBJECT_IS_CLONED(object))
1050         return FALSE;
1052     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1053     g_return_val_if_fail(rlist != NULL, FALSE);
1054     g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1055     rlist = g_slist_remove(rlist, object);
1056     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1058     document->priv->resources_changed_signals[q].emit();
1060     return TRUE;
1063 GSList const *
1064 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1066     g_return_val_if_fail(document != NULL, NULL);
1067     g_return_val_if_fail(key != NULL, NULL);
1068     g_return_val_if_fail(*key != '\0', NULL);
1070     return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1073 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1074                                                        gchar const *key,
1075                                                        SPDocument::ResourcesChangedSignal::slot_type slot)
1077     GQuark q = g_quark_from_string(key);
1078     return document->priv->resources_changed_signals[q].connect(slot);
1081 /* Helpers */
1083 gboolean
1084 sp_document_resource_list_free(gpointer key, gpointer value, gpointer data)
1086     g_slist_free((GSList *) value);
1087     return TRUE;
1090 unsigned int
1091 count_objects_recursive(SPObject *obj, unsigned int count)
1093     count++; // obj itself
1095     for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1096         count = count_objects_recursive(i, count);
1097     }
1099     return count;
1102 unsigned int
1103 objects_in_document(SPDocument *document)
1105     return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1108 void
1109 vacuum_document_recursive(SPObject *obj)
1111     if (SP_IS_DEFS(obj)) {
1112         for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1113             /* fixme: some inkscape-internal nodes in the future might not be collectable */
1114             def->requestOrphanCollection();
1115         }
1116     } else {
1117         for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1118             vacuum_document_recursive(i);
1119         }
1120     }
1123 unsigned int
1124 vacuum_document(SPDocument *document)
1126     unsigned int start = objects_in_document(document);
1127     unsigned int end;
1128     unsigned int newend = start;
1130     unsigned int iterations = 0;
1132     do {
1133         end = newend;
1135         vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1136         document->collectOrphans();
1137         iterations++;
1139         newend = objects_in_document(document);
1141     } while (iterations < 100 && newend < end);
1143     return start - newend;
1147 /*
1148   Local Variables:
1149   mode:c++
1150   c-file-style:"stroustrup"
1151   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1152   indent-tabs-mode:nil
1153   fill-column:99
1154   End:
1155 */
1156 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :