Code

prevent fit canvas button from expanding
[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 /* Object modification root handler */
678 void
679 sp_document_request_modified(SPDocument *doc)
681     if (!doc->modified_id) {
682         doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
683     }
686 void
687 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
689     ctx->ctx.flags = 0;
690     ctx->i2doc = NR::identity();
691     /* Set up viewport in case svg has it defined as percentages */
692     if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
693         ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
694         ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
695         ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
696         ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
697     } else { // as a last resort, set size to A4
698         ctx->vp.x0 = 0.0;
699         ctx->vp.y0 = 0.0;
700         ctx->vp.x1 = 210 * PX_PER_MM;
701         ctx->vp.y1 = 297 * PX_PER_MM;
702     }
703     ctx->i2vp = NR::identity();
706 gint
707 sp_document_ensure_up_to_date(SPDocument *doc)
709     int lc;
710     lc = 32;
711     while (doc->root->uflags || doc->root->mflags) {
712         lc -= 1;
713         if (lc < 0) {
714             g_warning("More than 32 iterations while updating document '%s'", doc->uri);
715             if (doc->modified_id) {
716                 /* Remove handler */
717                 gtk_idle_remove(doc->modified_id);
718                 doc->modified_id = 0;
719             }
720             return FALSE;
721         }
722         /* Process updates */
723         if (doc->root->uflags) {
724             SPItemCtx ctx;
725             sp_document_setup_viewport (doc, &ctx);
726             doc->root->updateDisplay((SPCtx *)&ctx, 0);
727         }
728         doc->_emitModified();
729     }
730     if (doc->modified_id) {
731         /* Remove handler */
732         gtk_idle_remove(doc->modified_id);
733         doc->modified_id = 0;
734     }
735     return TRUE;
738 static gint
739 sp_document_idle_handler(gpointer data)
741     SPDocument *doc;
742     int repeat;
744     doc = static_cast<SPDocument *>(data);
746 #ifdef SP_DOCUMENT_DEBUG_IDLE
747     g_print("->\n");
748 #endif
750     /* Process updates */
751     if (doc->root->uflags) {
752         SPItemCtx ctx;
753         sp_document_setup_viewport (doc, &ctx);
755         gboolean saved = sp_document_get_undo_sensitive(doc);
756         sp_document_set_undo_sensitive(doc, FALSE);
758         doc->root->updateDisplay((SPCtx *)&ctx, 0);
760         sp_document_set_undo_sensitive(doc, saved);
761         /* if (doc->root->uflags & SP_OBJECT_MODIFIED_FLAG) return TRUE; */
762     }
764     doc->_emitModified();
766     repeat = (doc->root->uflags || doc->root->mflags);
767     if (!repeat) doc->modified_id = 0;
768     return repeat;
771 static bool is_within(NR::Rect const &area, NR::Rect const &box)
773     return area.contains(box);
776 static bool overlaps(NR::Rect const &area, NR::Rect const &box)
778     return area.intersects(box);
781 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, NR::Rect const &area,
782                                   bool (*test)(NR::Rect const &, NR::Rect const &), bool take_insensitive = false)
784     g_return_val_if_fail(SP_IS_GROUP(group), s);
786     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
787         if (!SP_IS_ITEM(o)) {
788             continue;
789         }
790         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
791             s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
792         } else {
793             SPItem *child = SP_ITEM(o);
794             NR::Rect box = sp_item_bbox_desktop(child);
795             if (test(area, box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
796                 s = g_slist_append(s, child);
797             }
798         }
799     }
801     return s;
804 /**
805 Returns true if an item is among the descendants of group (recursively).
806  */
807 bool item_is_in_group(SPItem *item, SPGroup *group)
809     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
810         if (!SP_IS_ITEM(o)) continue;
811         if (SP_ITEM(o) == item)
812             return true;
813         if (SP_IS_GROUP(o))
814             if (item_is_in_group(item, SP_GROUP(o)))
815                 return true;
816     }
817     return false;
820 /**
821 Returns the bottommost item from the list which is at the point, or NULL if none.
822 */
823 SPItem*
824 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
825                                            NR::Point const p, bool take_insensitive)
827     g_return_val_if_fail(group, NULL);
829     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
831     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
833         if (!SP_IS_ITEM(o)) continue;
835         SPItem *item = SP_ITEM(o);
836         NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
837         if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
838             && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
839             if (g_slist_find((GSList *) list, item) != NULL)
840                 return item;
841         }
843         if (SP_IS_GROUP(o)) {
844             SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
845             if (found)
846                 return found;
847         }
849     }
850     return NULL;
853 /**
854 Returns the topmost (in z-order) item from the descendants of group (recursively) which
855 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
856 non-layer groups or not. Honors take_insensitive on whether to return insensitive
857 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
858 upwards in z-order and returns what it has found so far (i.e. the found item is
859 guaranteed to be lower than upto).
860  */
861 SPItem*
862 find_item_at_point(unsigned int dkey, SPGroup *group, NR::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
864     SPItem *seen = NULL, *newseen = NULL;
866     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
868     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
869         if (!SP_IS_ITEM(o)) continue;
871         if (upto && SP_ITEM(o) == upto)
872             break;
874         if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
875             // if nothing found yet, recurse into the group
876             newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
877             if (newseen) {
878                 seen = newseen;
879                 newseen = NULL;
880             }
882             if (item_is_in_group(upto, SP_GROUP(o)))
883                 break;
885         } else {
886             SPItem *child = SP_ITEM(o);
887             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
889             // seen remembers the last (topmost) of items pickable at this point
890             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
891                 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
892                 seen = child;
893             }
894         }
895     }
896     return seen;
899 /**
900 Returns the topmost non-layer group from the descendants of group which is at point
901 p, or NULL if none. Recurses into layers but not into groups.
902  */
903 SPItem*
904 find_group_at_point(unsigned int dkey, SPGroup *group, NR::Point const p)
906     SPItem *seen = NULL;
908     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
910     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
911         if (!SP_IS_ITEM(o)) continue;
912         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
913             SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
914             if (newseen) {
915                 seen = newseen;
916             }
917         }
918         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
919             SPItem *child = SP_ITEM(o);
920             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
922             // seen remembers the last (topmost) of groups pickable at this point
923             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
924                 seen = child;
925             }
926         }
927     }
928     return seen;
931 /*
932  * Return list of items, contained in box
933  *
934  * Assumes box is normalized (and g_asserts it!)
935  *
936  */
938 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
940     g_return_val_if_fail(document != NULL, NULL);
941     g_return_val_if_fail(document->priv != NULL, NULL);
943     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
946 /*
947  * Return list of items, that the parts of the item contained in box
948  *
949  * Assumes box is normalized (and g_asserts it!)
950  *
951  */
953 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
955     g_return_val_if_fail(document != NULL, NULL);
956     g_return_val_if_fail(document->priv != NULL, NULL);
958     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
961 SPItem *
962 sp_document_item_at_point(SPDocument *document, unsigned const key, NR::Point const p,
963                           gboolean const into_groups, SPItem *upto)
965     g_return_val_if_fail(document != NULL, NULL);
966     g_return_val_if_fail(document->priv != NULL, NULL);
968     return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
971 SPItem*
972 sp_document_group_at_point(SPDocument *document, unsigned int key, NR::Point const p)
974     g_return_val_if_fail(document != NULL, NULL);
975     g_return_val_if_fail(document->priv != NULL, NULL);
977     return find_group_at_point(key, SP_GROUP(document->root), p);
981 /* Resource management */
983 gboolean
984 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
986     GSList *rlist;
987     GQuark q = g_quark_from_string(key);
989     g_return_val_if_fail(document != NULL, FALSE);
990     g_return_val_if_fail(key != NULL, FALSE);
991     g_return_val_if_fail(*key != '\0', FALSE);
992     g_return_val_if_fail(object != NULL, FALSE);
993     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
995     if (SP_OBJECT_IS_CLONED(object))
996         return FALSE;
998     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
999     g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1000     rlist = g_slist_prepend(rlist, object);
1001     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1003     document->priv->resources_changed_signals[q].emit();
1005     return TRUE;
1008 gboolean
1009 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1011     GSList *rlist;
1012     GQuark q = g_quark_from_string(key);
1014     g_return_val_if_fail(document != NULL, FALSE);
1015     g_return_val_if_fail(key != NULL, FALSE);
1016     g_return_val_if_fail(*key != '\0', FALSE);
1017     g_return_val_if_fail(object != NULL, FALSE);
1018     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1020     if (SP_OBJECT_IS_CLONED(object))
1021         return FALSE;
1023     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1024     g_return_val_if_fail(rlist != NULL, FALSE);
1025     g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1026     rlist = g_slist_remove(rlist, object);
1027     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1029     document->priv->resources_changed_signals[q].emit();
1031     return TRUE;
1034 GSList const *
1035 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1037     g_return_val_if_fail(document != NULL, NULL);
1038     g_return_val_if_fail(key != NULL, NULL);
1039     g_return_val_if_fail(*key != '\0', NULL);
1041     return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1044 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1045                                                        gchar const *key,
1046                                                        SPDocument::ResourcesChangedSignal::slot_type slot)
1048     GQuark q = g_quark_from_string(key);
1049     return document->priv->resources_changed_signals[q].connect(slot);
1052 /* Helpers */
1054 gboolean
1055 sp_document_resource_list_free(gpointer key, gpointer value, gpointer data)
1057     g_slist_free((GSList *) value);
1058     return TRUE;
1061 unsigned int
1062 count_objects_recursive(SPObject *obj, unsigned int count)
1064     count++; // obj itself
1066     for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1067         count = count_objects_recursive(i, count);
1068     }
1070     return count;
1073 unsigned int
1074 objects_in_document(SPDocument *document)
1076     return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1079 void
1080 vacuum_document_recursive(SPObject *obj)
1082     if (SP_IS_DEFS(obj)) {
1083         for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1084             /* fixme: some inkscape-internal nodes in the future might not be collectable */
1085             def->requestOrphanCollection();
1086         }
1087     } else {
1088         for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1089             vacuum_document_recursive(i);
1090         }
1091     }
1094 unsigned int
1095 vacuum_document(SPDocument *document)
1097     unsigned int start = objects_in_document(document);
1098     unsigned int end;
1099     unsigned int newend = start;
1101     unsigned int iterations = 0;
1103     do {
1104         end = newend;
1106         vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1107         document->collectOrphans();
1108         iterations++;
1110         newend = objects_in_document(document);
1112     } while (iterations < 100 && newend < end);
1114     return start - newend;
1118 /*
1119   Local Variables:
1120   mode:c++
1121   c-file-style:"stroustrup"
1122   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1123   indent-tabs-mode:nil
1124   fill-column:99
1125   End:
1126 */
1127 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :