Code

* src/document.cpp, src/document.h, src/sp-conn-end-pair.cpp,
[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"
55 #include "display/nr-arena-item.h"
57 #include "dialogs/rdf.h"
59 #define A4_WIDTH_STR "210mm"
60 #define A4_HEIGHT_STR "297mm"
62 #define SP_DOCUMENT_UPDATE_PRIORITY (G_PRIORITY_HIGH_IDLE - 1)
65 static gint sp_document_idle_handler(gpointer data);
67 gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data);
69 static gint doc_count = 0;
71 SPDocument::SPDocument() {
72     SPDocumentPrivate *p;
74     keepalive = FALSE;
75     virgin    = TRUE;
77     modified_id = 0;
79     rdoc = NULL;
80     rroot = NULL;
81     root = NULL;
82     style_cascade = cr_cascade_new(NULL, NULL, NULL);
84     uri = NULL;
85     base = NULL;
86     name = NULL;
88     _collection_queue = NULL;
90     // Initialise instance of connector router.
91     router = new Avoid::Router();
93     p = new SPDocumentPrivate();
95     p->iddef = g_hash_table_new(g_direct_hash, g_direct_equal);
96     p->reprdef = g_hash_table_new(g_direct_hash, g_direct_equal);
98     p->resources = g_hash_table_new(g_str_hash, g_str_equal);
100     p->sensitive = FALSE;
101     p->partial = NULL;
102     p->history_size = 0;
103     p->undo = NULL;
104     p->redo = NULL;
106     priv = p;
109 SPDocument::~SPDocument() {
110     collectOrphans();
112     if (priv) {
113         inkscape_remove_document(this);
115         if (priv->partial) {
116             sp_repr_free_log(priv->partial);
117             priv->partial = NULL;
118         }
120         sp_document_clear_redo(this);
121         sp_document_clear_undo(this);
123         if (root) {
124             sp_object_invoke_release(root);
125             g_object_unref(G_OBJECT(root));
126             root = NULL;
127         }
129         if (priv->iddef) g_hash_table_destroy(priv->iddef);
130         if (priv->reprdef) g_hash_table_destroy(priv->reprdef);
132         if (rdoc) Inkscape::GC::release(rdoc);
134         /* Free resources */
135         g_hash_table_foreach_remove(priv->resources, sp_document_resource_list_free, this);
136         g_hash_table_destroy(priv->resources);
138         delete priv;
139         priv = NULL;
140     }
142     cr_cascade_unref(style_cascade);
143     style_cascade = NULL;
145     if (name) {
146         g_free(name);
147         name = NULL;
148     }
149     if (base) {
150         g_free(base);
151         base = NULL;
152     }
153     if (uri) {
154         g_free(uri);
155         uri = NULL;
156     }
158     if (modified_id) {
159         gtk_idle_remove(modified_id);
160         modified_id = 0;
161     }
163     _selection_changed_connection.disconnect();
164     _desktop_activated_connection.disconnect();
166     if (keepalive) {
167         inkscape_unref();
168         keepalive = FALSE;
169     }
171     if (router) {
172         delete router;
173         router = NULL;
174     }
176     //delete this->_whiteboard_session_manager;
179 void SPDocument::queueForOrphanCollection(SPObject *object) {
180     g_return_if_fail(object != NULL);
181     g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
183     sp_object_ref(object, NULL);
184     _collection_queue = g_slist_prepend(_collection_queue, object);
187 void SPDocument::collectOrphans() {
188     while (_collection_queue) {
189         GSList *objects=_collection_queue;
190         _collection_queue = NULL;
191         for ( GSList *iter=objects ; iter ; iter = iter->next ) {
192             SPObject *object=reinterpret_cast<SPObject *>(iter->data);
193             object->collectOrphan();
194             sp_object_unref(object, NULL);
195         }
196         g_slist_free(objects);
197     }
200 void SPDocument::reset_key (void *dummy)
202     actionkey = NULL;
204     
205 static SPDocument *
206 sp_document_create(Inkscape::XML::Document *rdoc,
207                    gchar const *uri,
208                    gchar const *base,
209                    gchar const *name,
210                    unsigned int keepalive)
212     SPDocument *document;
213     Inkscape::XML::Node *rroot;
214     Inkscape::Version sodipodi_version;
216     rroot = sp_repr_document_root(rdoc);
218     document = new SPDocument();
220     document->keepalive = keepalive;
222     document->rdoc = rdoc;
223     document->rroot = rroot;
225 #ifndef WIN32
226     prepend_current_dir_if_relative(&(document->uri), uri);
227 #else
228     // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
229     document->uri = uri? g_strdup(uri) : NULL;
230 #endif
232     // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
233     // which is why we use g_get_current_dir() in calculating the abs path above
234     //This is NULL for a new document
235     if (base)
236         document->base = g_strdup(base);
237     else
238         document->base = NULL;
239     document->name = g_strdup(name);
241     document->root = sp_object_repr_build_tree(document, rroot);
243     sodipodi_version = SP_ROOT(document->root)->version.sodipodi;
245     /* fixme: Not sure about this, but lets assume ::build updates */
246     rroot->setAttribute("sodipodi:version", SODIPODI_VERSION);
247     rroot->setAttribute("inkscape:version", INKSCAPE_VERSION);
248     /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
250     /* Quick hack 2 - get default image size into document */
251     if (!rroot->attribute("width")) rroot->setAttribute("width", A4_WIDTH_STR);
252     if (!rroot->attribute("height")) rroot->setAttribute("height", A4_HEIGHT_STR);
253     /* End of quick hack 2 */
255     /* Quick hack 3 - Set uri attributes */
256     if (uri) {
257         /* fixme: Think, what this means for images (Lauris) */
258         rroot->setAttribute("sodipodi:docname", uri);
259         if (document->base)
260             rroot->setAttribute("sodipodi:docbase", document->base);
261     }
262     /* End of quick hack 3 */
264     // creating namedview
265     if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
266         // if there's none in the document already,
267         Inkscape::XML::Node *r = NULL;
268         Inkscape::XML::Node *rnew = NULL;
269         r = inkscape_get_repr(INKSCAPE, "template.base");
270         // see if there's a template with id="base" in the preferences
271         if (!r) {
272             // if there's none, create an empty element
273             rnew = sp_repr_new("sodipodi:namedview");
274             rnew->setAttribute("id", "base");
275         } else {
276             // otherwise, take from preferences
277             rnew = r->duplicate();
278         }
279         // insert into the document
280         rroot->addChild(rnew, NULL);
281         // clean up
282         Inkscape::GC::release(rnew);
283     }
285     /* Defs */
286     if (!SP_ROOT(document->root)->defs) {
287         Inkscape::XML::Node *r;
288         r = sp_repr_new("svg:defs");
289         rroot->addChild(r, NULL);
290         Inkscape::GC::release(r);
291         g_assert(SP_ROOT(document->root)->defs);
292     }
294     /* Default RDF */
295     rdf_set_defaults( document );
297     if (keepalive) {
298         inkscape_ref();
299     }
301     sp_document_set_undo_sensitive(document, TRUE);
303     // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
304     if (!Inkscape::NSApplication::Application::getNewGui()) {
305         g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
306                          G_CALLBACK(sp_document_reset_key), document);
307         g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
308                          G_CALLBACK(sp_document_reset_key), document);
309     } else {
310         document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
311         document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
312     }
313     inkscape_add_document(document);
315     return document;
318 /**
319  * Fetches document from URI, or creates new, if NULL; public document 
320  * appears in document list.
321  */
322 SPDocument *
323 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
325     SPDocument *doc;
326     Inkscape::XML::Document *rdoc;
327     gchar *base = NULL;
328     gchar *name = NULL;
330     if (uri) {
331         Inkscape::XML::Node *rroot;
332         gchar *s, *p;
333         /* Try to fetch repr from file */
334         rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
335         /* If file cannot be loaded, return NULL without warning */
336         if (rdoc == NULL) return NULL;
337         rroot = sp_repr_document_root(rdoc);
338         /* If xml file is not svg, return NULL without warning */
339         /* fixme: destroy document */
340         if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
341         s = g_strdup(uri);
342         p = strrchr(s, '/');
343         if (p) {
344             name = g_strdup(p + 1);
345             p[1] = '\0';
346             base = g_strdup(s);
347         } else {
348             base = NULL;
349             name = g_strdup(uri);
350         }
351         g_free(s);
352     } else {
353         rdoc = sp_repr_document_new("svg:svg");
354     }
356     if (make_new) {
357         base = NULL;
358         uri = NULL;
359         name = g_strdup_printf(_("New document %d"), ++doc_count);
360     }
362     //# These should be set by now
363     g_assert(name);
365     doc = sp_document_create(rdoc, uri, base, name, keepalive);
367     g_free(base);
368     g_free(name);
370     return doc;
373 SPDocument *
374 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
376     SPDocument *doc;
377     Inkscape::XML::Document *rdoc;
378     Inkscape::XML::Node *rroot;
379     gchar *name;
381     rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
383     /* If it cannot be loaded, return NULL without warning */
384     if (rdoc == NULL) return NULL;
386     rroot = sp_repr_document_root(rdoc);
387     /* If xml file is not svg, return NULL without warning */
388     /* fixme: destroy document */
389     if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
391     name = g_strdup_printf(_("Memory document %d"), ++doc_count);
393     doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
395     return doc;
398 SPDocument *sp_document_new_dummy() {
399     SPDocument *document = new SPDocument();
400     inkscape_add_document(document);
401     return document;
404 SPDocument *
405 sp_document_ref(SPDocument *doc)
407     g_return_val_if_fail(doc != NULL, NULL);
408     Inkscape::GC::anchor(doc);
409     return doc;
412 SPDocument *
413 sp_document_unref(SPDocument *doc)
415     g_return_val_if_fail(doc != NULL, NULL);
416     Inkscape::GC::release(doc);
417     return NULL;
420 gdouble sp_document_width(SPDocument *document)
422     g_return_val_if_fail(document != NULL, 0.0);
423     g_return_val_if_fail(document->priv != NULL, 0.0);
424     g_return_val_if_fail(document->root != NULL, 0.0);
426     return SP_ROOT(document->root)->width.computed;
429 void
430 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
432     SPRoot *root = SP_ROOT(document->root);
434     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
435         root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
436     } else { // set to width=
437         root->width.computed = sp_units_get_pixels (width, *unit);
438         /* SVG does not support meters as a unit, so we must translate meters to
439          * cm when writing */
440         if (!strcmp(unit->abbr, "m")) {
441             root->width.value = 100*width;
442             root->width.unit = SVGLength::CM;
443         } else {
444             root->width.value = width;
445             root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
446         }
447     }
449     SP_OBJECT (root)->updateRepr();
452 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
454     SPRoot *root = SP_ROOT(document->root);
456     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
457         root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
458     } else { // set to height=
459         root->height.computed = sp_units_get_pixels (height, *unit);
460         /* SVG does not support meters as a unit, so we must translate meters to
461          * cm when writing */
462         if (!strcmp(unit->abbr, "m")) {
463             root->height.value = 100*height;
464             root->height.unit = SVGLength::CM;
465         } else {
466             root->height.value = height;
467             root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
468         }
469     }
471     SP_OBJECT (root)->updateRepr();
474 gdouble sp_document_height(SPDocument *document)
476     g_return_val_if_fail(document != NULL, 0.0);
477     g_return_val_if_fail(document->priv != NULL, 0.0);
478     g_return_val_if_fail(document->root != NULL, 0.0);
480     return SP_ROOT(document->root)->height.computed;
483 void sp_document_set_uri(SPDocument *document, gchar const *uri)
485     g_return_if_fail(document != NULL);
487     if (document->name) {
488         g_free(document->name);
489         document->name = NULL;
490     }
491     if (document->base) {
492         g_free(document->base);
493         document->base = NULL;
494     }
495     if (document->uri) {
496         g_free(document->uri);
497         document->uri = NULL;
498     }
500     if (uri) {
502 #ifndef WIN32
503         prepend_current_dir_if_relative(&(document->uri), uri);
504 #else
505         // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
506         document->uri = g_strdup(uri);
507 #endif
509         /* fixme: Think, what this means for images (Lauris) */
510         document->base = g_path_get_dirname(document->uri);
511         document->name = g_path_get_basename(document->uri);
513     } else {
514         document->uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
515         document->base = NULL;
516         document->name = g_strdup(document->uri);
517     }
519     // Update saveable repr attributes.
520     Inkscape::XML::Node *repr = sp_document_repr_root(document);
521     // changing uri in the document repr must not be not undoable
522     gboolean saved = sp_document_get_undo_sensitive(document);
523     sp_document_set_undo_sensitive(document, FALSE);
524     if (document->base)
525         repr->setAttribute("sodipodi:docbase", document->base);
527     repr->setAttribute("sodipodi:docname", document->name);
528     sp_document_set_undo_sensitive(document, saved);
530     document->priv->uri_set_signal.emit(document->uri);
533 void
534 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
536     g_return_if_fail(doc != NULL);
538     doc->priv->resized_signal.emit(width, height);
541 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
543     return priv->modified_signal.connect(slot);
546 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
548     return priv->uri_set_signal.connect(slot);
551 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
553     return priv->resized_signal.connect(slot);
556 sigc::connection
557 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
559     return priv->_reconstruction_start_signal.connect(slot);
562 void
563 SPDocument::emitReconstructionStart(void)
565     // printf("Starting Reconstruction\n");
566     priv->_reconstruction_start_signal.emit();
567     return;
570 sigc::connection
571 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type  slot)
573     return priv->_reconstruction_finish_signal.connect(slot);
576 void
577 SPDocument::emitReconstructionFinish(void)
579     // printf("Finishing Reconstruction\n");
580     priv->_reconstruction_finish_signal.emit();
581     return;
585 void SPDocument::_emitModified() {
586     static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
587     root->emitModified(0);
588     priv->modified_signal.emit(flags);
591 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
592     GQuark idq = g_quark_from_string(id);
594     if (object) {
595         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
596         g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
597     } else {
598         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
599         g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
600     }
602     SPDocumentPrivate::IDChangedSignalMap::iterator pos;
604     pos = priv->id_changed_signals.find(idq);
605     if ( pos != priv->id_changed_signals.end() ) {
606         if (!(*pos).second.empty()) {
607             (*pos).second.emit(object);
608         } else { // discard unused signal
609             priv->id_changed_signals.erase(pos);
610         }
611     }
614 void
615 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
617         this->priv->undoStackObservers.add(observer);
620 void
621 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
623         this->priv->undoStackObservers.remove(observer);
626 SPObject *SPDocument::getObjectById(gchar const *id) {
627     g_return_val_if_fail(id != NULL, NULL);
629     GQuark idq = g_quark_from_string(id);
630     return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
633 sigc::connection SPDocument::connectIdChanged(gchar const *id,
634                                               SPDocument::IDChangedSignal::slot_type slot)
636     return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
639 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
640     if (object) {
641         g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
642         g_hash_table_insert(priv->reprdef, repr, object);
643     } else {
644         g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
645         g_hash_table_remove(priv->reprdef, repr);
646     }
649 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
650     g_return_val_if_fail(repr != NULL, NULL);
651     return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
654 /* Object modification root handler */
656 void
657 sp_document_request_modified(SPDocument *doc)
659     if (!doc->modified_id) {
660         doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
661     }
664 void
665 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
667     ctx->ctx.flags = 0;
668     ctx->i2doc = NR::identity();
669     /* Set up viewport in case svg has it defined as percentages */
670     if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
671         ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
672         ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
673         ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
674         ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
675     } else { // as a last resort, set size to A4
676         ctx->vp.x0 = 0.0;
677         ctx->vp.y0 = 0.0;
678         ctx->vp.x1 = 210 * PX_PER_MM;
679         ctx->vp.y1 = 297 * PX_PER_MM;
680     }
681     ctx->i2vp = NR::identity();
684 gint
685 sp_document_ensure_up_to_date(SPDocument *doc)
687     int lc;
688     lc = 32;
689     while (doc->root->uflags || doc->root->mflags) {
690         lc -= 1;
691         if (lc < 0) {
692             g_warning("More than 32 iterations while updating document '%s'", doc->uri);
693             if (doc->modified_id) {
694                 /* Remove handler */
695                 gtk_idle_remove(doc->modified_id);
696                 doc->modified_id = 0;
697             }
698             return FALSE;
699         }
700         /* Process updates */
701         if (doc->root->uflags) {
702             SPItemCtx ctx;
703             sp_document_setup_viewport (doc, &ctx);
704             doc->root->updateDisplay((SPCtx *)&ctx, 0);
705         }
706         doc->_emitModified();
707     }
708     if (doc->modified_id) {
709         /* Remove handler */
710         gtk_idle_remove(doc->modified_id);
711         doc->modified_id = 0;
712     }
713     return TRUE;
716 static gint
717 sp_document_idle_handler(gpointer data)
719     SPDocument *doc;
720     int repeat;
722     doc = static_cast<SPDocument *>(data);
724 #ifdef SP_DOCUMENT_DEBUG_IDLE
725     g_print("->\n");
726 #endif
728     /* Process updates */
729     if (doc->root->uflags) {
730         SPItemCtx ctx;
731         sp_document_setup_viewport (doc, &ctx);
733         gboolean saved = sp_document_get_undo_sensitive(doc);
734         sp_document_set_undo_sensitive(doc, FALSE);
736         doc->root->updateDisplay((SPCtx *)&ctx, 0);
738         sp_document_set_undo_sensitive(doc, saved);
739         /* if (doc->root->uflags & SP_OBJECT_MODIFIED_FLAG) return TRUE; */
740     }
742     doc->_emitModified();
744     repeat = (doc->root->uflags || doc->root->mflags);
745     if (!repeat) doc->modified_id = 0;
746     return repeat;
749 static bool is_within(NR::Rect const &area, NR::Rect const &box)
751     return area.contains(box);
754 static bool overlaps(NR::Rect const &area, NR::Rect const &box)
756     return area.intersects(box);
759 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, NR::Rect const &area,
760                                   bool (*test)(NR::Rect const &, NR::Rect const &), bool take_insensitive = false)
762     g_return_val_if_fail(SP_IS_GROUP(group), s);
764     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
765         if (!SP_IS_ITEM(o)) {
766             continue;
767         }
768         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
769             s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
770         } else {
771             SPItem *child = SP_ITEM(o);
772             NR::Rect box = sp_item_bbox_desktop(child);
773             if (test(area, box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
774                 s = g_slist_append(s, child);
775             }
776         }
777     }
779     return s;
782 /**
783 Returns true if an item is among the descendants of group (recursively).
784  */
785 bool item_is_in_group(SPItem *item, SPGroup *group)
787     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
788         if (!SP_IS_ITEM(o)) continue;
789         if (SP_ITEM(o) == item)
790             return true;
791         if (SP_IS_GROUP(o))
792             if (item_is_in_group(item, SP_GROUP(o)))
793                 return true;
794     }
795     return false;
798 /**
799 Returns the bottommost item from the list which is at the point, or NULL if none.
800 */
801 SPItem*
802 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
803                                            NR::Point const p, bool take_insensitive)
805     g_return_val_if_fail(group, NULL);
807     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
809     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
811         if (!SP_IS_ITEM(o)) continue;
813         SPItem *item = SP_ITEM(o);
814         NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
815         if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
816             && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
817             if (g_slist_find((GSList *) list, item) != NULL)
818                 return item;
819         }
821         if (SP_IS_GROUP(o)) {
822             SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
823             if (found)
824                 return found;
825         }
827     }
828     return NULL;
831 /**
832 Returns the topmost (in z-order) item from the descendants of group (recursively) which
833 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
834 non-layer groups or not. Honors take_insensitive on whether to return insensitive
835 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
836 upwards in z-order and returns what it has found so far (i.e. the found item is
837 guaranteed to be lower than upto).
838  */
839 SPItem*
840 find_item_at_point(unsigned int dkey, SPGroup *group, NR::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
842     SPItem *seen = NULL, *newseen = NULL;
844     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
846     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
847         if (!SP_IS_ITEM(o)) continue;
849         if (upto && SP_ITEM(o) == upto)
850             break;
852         if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
853             // if nothing found yet, recurse into the group
854             newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
855             if (newseen) {
856                 seen = newseen;
857                 newseen = NULL;
858             }
860             if (item_is_in_group(upto, SP_GROUP(o)))
861                 break;
863         } else {
864             SPItem *child = SP_ITEM(o);
865             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
867             // seen remembers the last (topmost) of items pickable at this point
868             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
869                 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
870                 seen = child;
871             }
872         }
873     }
874     return seen;
877 /**
878 Returns the topmost non-layer group from the descendants of group which is at point
879 p, or NULL if none. Recurses into layers but not into groups.
880  */
881 SPItem*
882 find_group_at_point(unsigned int dkey, SPGroup *group, NR::Point const p)
884     SPItem *seen = NULL;
886     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
888     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
889         if (!SP_IS_ITEM(o)) continue;
890         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
891             SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
892             if (newseen) {
893                 seen = newseen;
894             }
895         }
896         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
897             SPItem *child = SP_ITEM(o);
898             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
900             // seen remembers the last (topmost) of groups pickable at this point
901             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
902                 seen = child;
903             }
904         }
905     }
906     return seen;
909 /*
910  * Return list of items, contained in box
911  *
912  * Assumes box is normalized (and g_asserts it!)
913  *
914  */
916 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
918     g_return_val_if_fail(document != NULL, NULL);
919     g_return_val_if_fail(document->priv != NULL, NULL);
921     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
924 /*
925  * Return list of items, that the parts of the item contained in box
926  *
927  * Assumes box is normalized (and g_asserts it!)
928  *
929  */
931 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
933     g_return_val_if_fail(document != NULL, NULL);
934     g_return_val_if_fail(document->priv != NULL, NULL);
936     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
939 SPItem *
940 sp_document_item_at_point(SPDocument *document, unsigned const key, NR::Point const p,
941                           gboolean const into_groups, SPItem *upto)
943     g_return_val_if_fail(document != NULL, NULL);
944     g_return_val_if_fail(document->priv != NULL, NULL);
946     return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
949 SPItem*
950 sp_document_group_at_point(SPDocument *document, unsigned int key, NR::Point const p)
952     g_return_val_if_fail(document != NULL, NULL);
953     g_return_val_if_fail(document->priv != NULL, NULL);
955     return find_group_at_point(key, SP_GROUP(document->root), p);
959 /* Resource management */
961 gboolean
962 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
964     GSList *rlist;
965     GQuark q = g_quark_from_string(key);
967     g_return_val_if_fail(document != NULL, FALSE);
968     g_return_val_if_fail(key != NULL, FALSE);
969     g_return_val_if_fail(*key != '\0', FALSE);
970     g_return_val_if_fail(object != NULL, FALSE);
971     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
973     if (SP_OBJECT_IS_CLONED(object))
974         return FALSE;
976     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
977     g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
978     rlist = g_slist_prepend(rlist, object);
979     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
981     document->priv->resources_changed_signals[q].emit();
983     return TRUE;
986 gboolean
987 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
989     GSList *rlist;
990     GQuark q = g_quark_from_string(key);
992     g_return_val_if_fail(document != NULL, FALSE);
993     g_return_val_if_fail(key != NULL, FALSE);
994     g_return_val_if_fail(*key != '\0', FALSE);
995     g_return_val_if_fail(object != NULL, FALSE);
996     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
998     if (SP_OBJECT_IS_CLONED(object))
999         return FALSE;
1001     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1002     g_return_val_if_fail(rlist != NULL, FALSE);
1003     g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1004     rlist = g_slist_remove(rlist, object);
1005     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1007     document->priv->resources_changed_signals[q].emit();
1009     return TRUE;
1012 GSList const *
1013 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1015     g_return_val_if_fail(document != NULL, NULL);
1016     g_return_val_if_fail(key != NULL, NULL);
1017     g_return_val_if_fail(*key != '\0', NULL);
1019     return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1022 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1023                                                        gchar const *key,
1024                                                        SPDocument::ResourcesChangedSignal::slot_type slot)
1026     GQuark q = g_quark_from_string(key);
1027     return document->priv->resources_changed_signals[q].connect(slot);
1030 /* Helpers */
1032 gboolean
1033 sp_document_resource_list_free(gpointer key, gpointer value, gpointer data)
1035     g_slist_free((GSList *) value);
1036     return TRUE;
1039 unsigned int
1040 count_objects_recursive(SPObject *obj, unsigned int count)
1042     count++; // obj itself
1044     for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1045         count = count_objects_recursive(i, count);
1046     }
1048     return count;
1051 unsigned int
1052 objects_in_document(SPDocument *document)
1054     return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1057 void
1058 vacuum_document_recursive(SPObject *obj)
1060     if (SP_IS_DEFS(obj)) {
1061         for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1062             /* fixme: some inkscape-internal nodes in the future might not be collectable */
1063             def->requestOrphanCollection();
1064         }
1065     } else {
1066         for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1067             vacuum_document_recursive(i);
1068         }
1069     }
1072 unsigned int
1073 vacuum_document(SPDocument *document)
1075     unsigned int start = objects_in_document(document);
1076     unsigned int end;
1077     unsigned int newend = start;
1079     unsigned int iterations = 0;
1081     do {
1082         end = newend;
1084         vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1085         document->collectOrphans();
1086         iterations++;
1088         newend = objects_in_document(document);
1090     } while (iterations < 100 && newend < end);
1092     return start - newend;
1096 /*
1097   Local Variables:
1098   mode:c++
1099   c-file-style:"stroustrup"
1100   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1101   indent-tabs-mode:nil
1102   fill-column:99
1103   End:
1104 */
1105 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :