Code

Added descriptions to Undo/Redo commands in the menus
[inkscape.git] / src / document.cpp
1 #define __SP_DOCUMENT_C__
3 /** \file
4  * SPDocument manipulation
5  *
6  * Authors:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   MenTaLguY <mental@rydia.net>
9  *   bulia byak <buliabyak@users.sf.net>
10  *
11  * Copyright (C) 2004-2005 MenTaLguY
12  * Copyright (C) 1999-2002 Lauris Kaplinski
13  * Copyright (C) 2000-2001 Ximian, Inc.
14  *
15  * Released under GNU GPL, read the file 'COPYING' for more information
16  */
18 /** \class SPDocument
19  * SPDocument serves as the container of both model trees (agnostic XML
20  * and typed object tree), and implements all of the document-level
21  * functionality used by the program. Many document level operations, like
22  * load, save, print, export and so on, use SPDocument as their basic datatype.
23  *
24  * SPDocument implements undo and redo stacks and an id-based object
25  * dictionary.  Thanks to unique id attributes, the latter can be used to
26  * map from the XML tree back to the object tree.
27  *
28  * SPDocument performs the basic operations needed for asynchronous
29  * update notification (SPObject ::modified virtual method), and implements
30  * the 'modified' signal, as well.
31  */
34 #define noSP_DOCUMENT_DEBUG_IDLE
35 #define noSP_DOCUMENT_DEBUG_UNDO
37 #ifdef HAVE_CONFIG_H
38 # include "config.h"
39 #endif
40 #include <gtk/gtkmain.h>
41 #include "application/application.h"
42 #include "application/editor.h"
43 #include "libnr/nr-matrix-fns.h"
44 #include "xml/repr.h"
45 #include "helper/units.h"
46 #include "inkscape-private.h"
47 #include "inkscape_version.h"
48 #include "sp-object-repr.h"
49 #include "document-private.h"
50 #include "dir-util.h"
51 #include "unit-constants.h"
52 #include "prefs-utils.h"
53 #include "libavoid/router.h"
54 #include "libnr/nr-rect.h"
55 #include "sp-item-group.h"
57 #include "display/nr-arena-item.h"
59 #include "dialogs/rdf.h"
61 #define A4_WIDTH_STR "210mm"
62 #define A4_HEIGHT_STR "297mm"
64 #define SP_DOCUMENT_UPDATE_PRIORITY (G_PRIORITY_HIGH_IDLE - 1)
67 static gint sp_document_idle_handler(gpointer data);
69 gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data);
71 static gint doc_count = 0;
73 SPDocument::SPDocument() {
74     SPDocumentPrivate *p;
76     keepalive = FALSE;
77     virgin    = TRUE;
79     modified_id = 0;
81     rdoc = NULL;
82     rroot = NULL;
83     root = NULL;
84     style_cascade = cr_cascade_new(NULL, NULL, NULL);
86     uri = NULL;
87     base = NULL;
88     name = NULL;
90     _collection_queue = NULL;
92     // Initialise instance of connector router.
93     router = new Avoid::Router();
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     p->undoStackObservers.add(p->event_log);
109     p->event_log.setDocument(this);
111     priv = p;
113     // XXX only for testing!
114     priv->undoStackObservers.add(p->console_output_undo_observer);
117 SPDocument::~SPDocument() {
118     collectOrphans();
120     if (priv) {
121         inkscape_remove_document(this);
123         if (priv->partial) {
124             sp_repr_free_log(priv->partial);
125             priv->partial = NULL;
126         }
128         sp_document_clear_redo(this);
129         sp_document_clear_undo(this);
131         if (root) {
132             sp_object_invoke_release(root);
133             sp_object_unref(root);
134             root = NULL;
135         }
137         if (priv->iddef) g_hash_table_destroy(priv->iddef);
138         if (priv->reprdef) g_hash_table_destroy(priv->reprdef);
140         if (rdoc) Inkscape::GC::release(rdoc);
142         /* Free resources */
143         g_hash_table_foreach_remove(priv->resources, sp_document_resource_list_free, this);
144         g_hash_table_destroy(priv->resources);
146         delete priv;
147         priv = NULL;
148     }
150     cr_cascade_unref(style_cascade);
151     style_cascade = NULL;
153     if (name) {
154         g_free(name);
155         name = NULL;
156     }
157     if (base) {
158         g_free(base);
159         base = NULL;
160     }
161     if (uri) {
162         g_free(uri);
163         uri = NULL;
164     }
166     if (modified_id) {
167         gtk_idle_remove(modified_id);
168         modified_id = 0;
169     }
171     _selection_changed_connection.disconnect();
172     _desktop_activated_connection.disconnect();
174     if (keepalive) {
175         inkscape_unref();
176         keepalive = FALSE;
177     }
179     if (router) {
180         delete router;
181         router = NULL;
182     }
184     //delete this->_whiteboard_session_manager;
187 void SPDocument::queueForOrphanCollection(SPObject *object) {
188     g_return_if_fail(object != NULL);
189     g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
191     sp_object_ref(object, NULL);
192     _collection_queue = g_slist_prepend(_collection_queue, object);
195 void SPDocument::collectOrphans() {
196     while (_collection_queue) {
197         GSList *objects=_collection_queue;
198         _collection_queue = NULL;
199         for ( GSList *iter=objects ; iter ; iter = iter->next ) {
200             SPObject *object=reinterpret_cast<SPObject *>(iter->data);
201             object->collectOrphan();
202             sp_object_unref(object, NULL);
203         }
204         g_slist_free(objects);
205     }
208 void SPDocument::reset_key (void *dummy)
210     actionkey = NULL;
213 SPDocument *
214 sp_document_create(Inkscape::XML::Document *rdoc,
215                    gchar const *uri,
216                    gchar const *base,
217                    gchar const *name,
218                    unsigned int keepalive)
220     SPDocument *document;
221     Inkscape::XML::Node *rroot;
222     Inkscape::Version sodipodi_version;
224     rroot = sp_repr_document_root(rdoc);
226     document = new SPDocument();
228     document->keepalive = keepalive;
230     document->rdoc = rdoc;
231     document->rroot = rroot;
233 #ifndef WIN32
234     prepend_current_dir_if_relative(&(document->uri), uri);
235 #else
236     // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
237     document->uri = uri? g_strdup(uri) : NULL;
238 #endif
240     // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
241     // which is why we use g_get_current_dir() in calculating the abs path above
242     //This is NULL for a new document
243     if (base)
244         document->base = g_strdup(base);
245     else
246         document->base = NULL;
247     document->name = g_strdup(name);
249     document->root = sp_object_repr_build_tree(document, rroot);
251     sodipodi_version = SP_ROOT(document->root)->version.sodipodi;
253     /* fixme: Not sure about this, but lets assume ::build updates */
254     rroot->setAttribute("sodipodi:version", SODIPODI_VERSION);
255     rroot->setAttribute("inkscape:version", INKSCAPE_VERSION);
256     /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
258     /* Quick hack 2 - get default image size into document */
259     if (!rroot->attribute("width")) rroot->setAttribute("width", A4_WIDTH_STR);
260     if (!rroot->attribute("height")) rroot->setAttribute("height", A4_HEIGHT_STR);
261     /* End of quick hack 2 */
263     /* Quick hack 3 - Set uri attributes */
264     if (uri) {
265         /* fixme: Think, what this means for images (Lauris) */
266         rroot->setAttribute("sodipodi:docname", uri);
267         if (document->base)
268             rroot->setAttribute("sodipodi:docbase", document->base);
269     }
270     /* End of quick hack 3 */
272     // creating namedview
273     if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
274         // if there's none in the document already,
275         Inkscape::XML::Node *r = NULL;
276         Inkscape::XML::Node *rnew = NULL;
277         r = inkscape_get_repr(INKSCAPE, "template.base");
278         // see if there's a template with id="base" in the preferences
279         if (!r) {
280             // if there's none, create an empty element
281             rnew = sp_repr_new("sodipodi:namedview");
282             rnew->setAttribute("id", "base");
283         } else {
284             // otherwise, take from preferences
285             rnew = r->duplicate();
286         }
287         // insert into the document
288         rroot->addChild(rnew, NULL);
289         // clean up
290         Inkscape::GC::release(rnew);
291     }
293     /* Defs */
294     if (!SP_ROOT(document->root)->defs) {
295         Inkscape::XML::Node *r;
296         r = sp_repr_new("svg:defs");
297         rroot->addChild(r, NULL);
298         Inkscape::GC::release(r);
299         g_assert(SP_ROOT(document->root)->defs);
300     }
302     /* Default RDF */
303     rdf_set_defaults( document );
305     if (keepalive) {
306         inkscape_ref();
307     }
309     sp_document_set_undo_sensitive(document, TRUE);
311     // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
312     if (!Inkscape::NSApplication::Application::getNewGui()) {
313         g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
314                          G_CALLBACK(sp_document_reset_key), document);
315         g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
316                          G_CALLBACK(sp_document_reset_key), document);
317     } else {
318         document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
319         document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
320     }
321     inkscape_add_document(document);
323     return document;
326 /**
327  * Fetches document from URI, or creates new, if NULL; public document
328  * appears in document list.
329  */
330 SPDocument *
331 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
333     SPDocument *doc;
334     Inkscape::XML::Document *rdoc;
335     gchar *base = NULL;
336     gchar *name = NULL;
338     if (uri) {
339         Inkscape::XML::Node *rroot;
340         gchar *s, *p;
341         /* Try to fetch repr from file */
342         rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
343         /* If file cannot be loaded, return NULL without warning */
344         if (rdoc == NULL) return NULL;
345         rroot = sp_repr_document_root(rdoc);
346         /* If xml file is not svg, return NULL without warning */
347         /* fixme: destroy document */
348         if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
349         s = g_strdup(uri);
350         p = strrchr(s, '/');
351         if (p) {
352             name = g_strdup(p + 1);
353             p[1] = '\0';
354             base = g_strdup(s);
355         } else {
356             base = NULL;
357             name = g_strdup(uri);
358         }
359         g_free(s);
360     } else {
361         rdoc = sp_repr_document_new("svg:svg");
362     }
364     if (make_new) {
365         base = NULL;
366         uri = NULL;
367         name = g_strdup_printf(_("New document %d"), ++doc_count);
368     }
370     //# These should be set by now
371     g_assert(name);
373     doc = sp_document_create(rdoc, uri, base, name, keepalive);
375     g_free(base);
376     g_free(name);
378     return doc;
381 SPDocument *
382 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
384     SPDocument *doc;
385     Inkscape::XML::Document *rdoc;
386     Inkscape::XML::Node *rroot;
387     gchar *name;
389     rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
391     /* If it cannot be loaded, return NULL without warning */
392     if (rdoc == NULL) return NULL;
394     rroot = sp_repr_document_root(rdoc);
395     /* If xml file is not svg, return NULL without warning */
396     /* fixme: destroy document */
397     if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
399     name = g_strdup_printf(_("Memory document %d"), ++doc_count);
401     doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
403     return doc;
406 SPDocument *sp_document_new_dummy() {
407     SPDocument *document = new SPDocument();
408     inkscape_add_document(document);
409     return document;
412 SPDocument *
413 sp_document_ref(SPDocument *doc)
415     g_return_val_if_fail(doc != NULL, NULL);
416     Inkscape::GC::anchor(doc);
417     return doc;
420 SPDocument *
421 sp_document_unref(SPDocument *doc)
423     g_return_val_if_fail(doc != NULL, NULL);
424     Inkscape::GC::release(doc);
425     return NULL;
428 gdouble sp_document_width(SPDocument *document)
430     g_return_val_if_fail(document != NULL, 0.0);
431     g_return_val_if_fail(document->priv != NULL, 0.0);
432     g_return_val_if_fail(document->root != NULL, 0.0);
434     return SP_ROOT(document->root)->width.computed;
437 void
438 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
440     SPRoot *root = SP_ROOT(document->root);
442     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
443         root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
444     } else { // set to width=
445         root->width.computed = sp_units_get_pixels (width, *unit);
446         /* SVG does not support meters as a unit, so we must translate meters to
447          * cm when writing */
448         if (!strcmp(unit->abbr, "m")) {
449             root->width.value = 100*width;
450             root->width.unit = SVGLength::CM;
451         } else {
452             root->width.value = width;
453             root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
454         }
455     }
457     SP_OBJECT (root)->updateRepr();
460 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
462     SPRoot *root = SP_ROOT(document->root);
464     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
465         root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
466     } else { // set to height=
467         root->height.computed = sp_units_get_pixels (height, *unit);
468         /* SVG does not support meters as a unit, so we must translate meters to
469          * cm when writing */
470         if (!strcmp(unit->abbr, "m")) {
471             root->height.value = 100*height;
472             root->height.unit = SVGLength::CM;
473         } else {
474             root->height.value = height;
475             root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
476         }
477     }
479     SP_OBJECT (root)->updateRepr();
482 gdouble sp_document_height(SPDocument *document)
484     g_return_val_if_fail(document != NULL, 0.0);
485     g_return_val_if_fail(document->priv != NULL, 0.0);
486     g_return_val_if_fail(document->root != NULL, 0.0);
488     return SP_ROOT(document->root)->height.computed;
491 /**
492  * Given an NRRect that may, for example, correspond to the bbox of an object
493  * this function fits the canvas to that rect by resizing the canvas
494  * and translating the document root into position.
495  */
496 void SPDocument::fitToRect(NRRect const & rect)
498     g_return_if_fail(!empty(rect));
499     
500     gdouble w = rect.x1 - rect.x0;
501     gdouble h = rect.y1 - rect.y0;
502     gdouble old_height = sp_document_height(this);
503     SPUnit unit = sp_unit_get_by_id(SP_UNIT_PX);
504     sp_document_set_width(this, w, &unit);
505     sp_document_set_height(this, h, &unit);
507     NR::translate tr = NR::translate::translate(-rect.x0,-(rect.y0 + (h - old_height)));
508     static_cast<SPGroup *>(root)->translateChildItems(tr);
511 void sp_document_set_uri(SPDocument *document, gchar const *uri)
513     g_return_if_fail(document != NULL);
515     if (document->name) {
516         g_free(document->name);
517         document->name = NULL;
518     }
519     if (document->base) {
520         g_free(document->base);
521         document->base = NULL;
522     }
523     if (document->uri) {
524         g_free(document->uri);
525         document->uri = NULL;
526     }
528     if (uri) {
530 #ifndef WIN32
531         prepend_current_dir_if_relative(&(document->uri), uri);
532 #else
533         // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
534         document->uri = g_strdup(uri);
535 #endif
537         /* fixme: Think, what this means for images (Lauris) */
538         document->base = g_path_get_dirname(document->uri);
539         document->name = g_path_get_basename(document->uri);
541     } else {
542         document->uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
543         document->base = NULL;
544         document->name = g_strdup(document->uri);
545     }
547     // Update saveable repr attributes.
548     Inkscape::XML::Node *repr = sp_document_repr_root(document);
549     // changing uri in the document repr must not be not undoable
550     gboolean saved = sp_document_get_undo_sensitive(document);
551     sp_document_set_undo_sensitive(document, FALSE);
552     if (document->base)
553         repr->setAttribute("sodipodi:docbase", document->base);
555     repr->setAttribute("sodipodi:docname", document->name);
556     sp_document_set_undo_sensitive(document, saved);
558     document->priv->uri_set_signal.emit(document->uri);
561 void
562 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
564     g_return_if_fail(doc != NULL);
566     doc->priv->resized_signal.emit(width, height);
569 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
571     return priv->modified_signal.connect(slot);
574 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
576     return priv->uri_set_signal.connect(slot);
579 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
581     return priv->resized_signal.connect(slot);
584 sigc::connection
585 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
587     return priv->_reconstruction_start_signal.connect(slot);
590 void
591 SPDocument::emitReconstructionStart(void)
593     // printf("Starting Reconstruction\n");
594     priv->_reconstruction_start_signal.emit();
595     return;
598 sigc::connection
599 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type  slot)
601     return priv->_reconstruction_finish_signal.connect(slot);
604 void
605 SPDocument::emitReconstructionFinish(void)
607     // printf("Finishing Reconstruction\n");
608     priv->_reconstruction_finish_signal.emit();
609     return;
613 void SPDocument::_emitModified() {
614     static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
615     root->emitModified(0);
616     priv->modified_signal.emit(flags);
619 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
620     GQuark idq = g_quark_from_string(id);
622     if (object) {
623         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
624         g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
625     } else {
626         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
627         g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
628     }
630     SPDocumentPrivate::IDChangedSignalMap::iterator pos;
632     pos = priv->id_changed_signals.find(idq);
633     if ( pos != priv->id_changed_signals.end() ) {
634         if (!(*pos).second.empty()) {
635             (*pos).second.emit(object);
636         } else { // discard unused signal
637             priv->id_changed_signals.erase(pos);
638         }
639     }
642 void
643 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
645         this->priv->undoStackObservers.add(observer);
648 void
649 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
651         this->priv->undoStackObservers.remove(observer);
654 Inkscape::EventLog&
655 SPDocument::getEventLog() const
657   return priv->event_log;
660 SPObject *SPDocument::getObjectById(gchar const *id) {
661     g_return_val_if_fail(id != NULL, NULL);
663     GQuark idq = g_quark_from_string(id);
664     return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
667 sigc::connection SPDocument::connectIdChanged(gchar const *id,
668                                               SPDocument::IDChangedSignal::slot_type slot)
670     return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
673 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
674     if (object) {
675         g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
676         g_hash_table_insert(priv->reprdef, repr, object);
677     } else {
678         g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
679         g_hash_table_remove(priv->reprdef, repr);
680     }
683 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
684     g_return_val_if_fail(repr != NULL, NULL);
685     return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
688 Glib::ustring SPDocument::getLanguage() {
689     gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
690     if (document_language) {
691         while (isspace(*document_language))
692             document_language++;
693     }
694     if ( !document_language || 0 == *document_language) {
695         // retrieve system language
696         document_language = getenv("LC_ALL");
697         if ( NULL == document_language || *document_language == 0 ) {
698             document_language = getenv ("LC_MESSAGES");
699         }
700         if ( NULL == document_language || *document_language == 0 ) {
701             document_language = getenv ("LANG");
702         }
703         
704         if ( NULL != document_language ) {
705             gchar *pos = strchr(document_language, '_');
706             if ( NULL != pos ) {
707                 return Glib::ustring(document_language, pos - document_language);
708             }
709         }
710     }
712     if ( NULL == document_language )
713         return Glib::ustring();
714     return document_language;
717 /* Object modification root handler */
719 void
720 sp_document_request_modified(SPDocument *doc)
722     if (!doc->modified_id) {
723         doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
724     }
727 void
728 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
730     ctx->ctx.flags = 0;
731     ctx->i2doc = NR::identity();
732     /* Set up viewport in case svg has it defined as percentages */
733     if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
734         ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
735         ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
736         ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
737         ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
738     } else { // as a last resort, set size to A4
739         ctx->vp.x0 = 0.0;
740         ctx->vp.y0 = 0.0;
741         ctx->vp.x1 = 210 * PX_PER_MM;
742         ctx->vp.y1 = 297 * PX_PER_MM;
743     }
744     ctx->i2vp = NR::identity();
747 gint
748 sp_document_ensure_up_to_date(SPDocument *doc)
750     int lc;
751     lc = 32;
752     while (doc->root->uflags || doc->root->mflags) {
753         lc -= 1;
754         if (lc < 0) {
755             g_warning("More than 32 iterations while updating document '%s'", doc->uri);
756             if (doc->modified_id) {
757                 /* Remove handler */
758                 gtk_idle_remove(doc->modified_id);
759                 doc->modified_id = 0;
760             }
761             return FALSE;
762         }
763         /* Process updates */
764         if (doc->root->uflags) {
765             SPItemCtx ctx;
766             sp_document_setup_viewport (doc, &ctx);
767             doc->root->updateDisplay((SPCtx *)&ctx, 0);
768         }
769         doc->_emitModified();
770     }
771     if (doc->modified_id) {
772         /* Remove handler */
773         gtk_idle_remove(doc->modified_id);
774         doc->modified_id = 0;
775     }
776     return TRUE;
779 static gint
780 sp_document_idle_handler(gpointer data)
782     SPDocument *doc;
783     int repeat;
785     doc = static_cast<SPDocument *>(data);
787 #ifdef SP_DOCUMENT_DEBUG_IDLE
788     g_print("->\n");
789 #endif
791     /* Process updates */
792     if (doc->root->uflags) {
793         SPItemCtx ctx;
794         sp_document_setup_viewport (doc, &ctx);
796         gboolean saved = sp_document_get_undo_sensitive(doc);
797         sp_document_set_undo_sensitive(doc, FALSE);
799         doc->root->updateDisplay((SPCtx *)&ctx, 0);
801         sp_document_set_undo_sensitive(doc, saved);
802         /* if (doc->root->uflags & SP_OBJECT_MODIFIED_FLAG) return TRUE; */
803     }
805     doc->_emitModified();
807     repeat = (doc->root->uflags || doc->root->mflags);
808     if (!repeat) doc->modified_id = 0;
809     return repeat;
812 static bool is_within(NR::Rect const &area, NR::Rect const &box)
814     return area.contains(box);
817 static bool overlaps(NR::Rect const &area, NR::Rect const &box)
819     return area.intersects(box);
822 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, NR::Rect const &area,
823                                   bool (*test)(NR::Rect const &, NR::Rect const &), bool take_insensitive = false)
825     g_return_val_if_fail(SP_IS_GROUP(group), s);
827     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
828         if (!SP_IS_ITEM(o)) {
829             continue;
830         }
831         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
832             s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
833         } else {
834             SPItem *child = SP_ITEM(o);
835             NR::Rect box = sp_item_bbox_desktop(child);
836             if (test(area, box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
837                 s = g_slist_append(s, child);
838             }
839         }
840     }
842     return s;
845 /**
846 Returns true if an item is among the descendants of group (recursively).
847  */
848 bool item_is_in_group(SPItem *item, SPGroup *group)
850     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
851         if (!SP_IS_ITEM(o)) continue;
852         if (SP_ITEM(o) == item)
853             return true;
854         if (SP_IS_GROUP(o))
855             if (item_is_in_group(item, SP_GROUP(o)))
856                 return true;
857     }
858     return false;
861 /**
862 Returns the bottommost item from the list which is at the point, or NULL if none.
863 */
864 SPItem*
865 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
866                                            NR::Point const p, bool take_insensitive)
868     g_return_val_if_fail(group, NULL);
870     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
872     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
874         if (!SP_IS_ITEM(o)) continue;
876         SPItem *item = SP_ITEM(o);
877         NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
878         if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
879             && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
880             if (g_slist_find((GSList *) list, item) != NULL)
881                 return item;
882         }
884         if (SP_IS_GROUP(o)) {
885             SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
886             if (found)
887                 return found;
888         }
890     }
891     return NULL;
894 /**
895 Returns the topmost (in z-order) item from the descendants of group (recursively) which
896 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
897 non-layer groups or not. Honors take_insensitive on whether to return insensitive
898 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
899 upwards in z-order and returns what it has found so far (i.e. the found item is
900 guaranteed to be lower than upto).
901  */
902 SPItem*
903 find_item_at_point(unsigned int dkey, SPGroup *group, NR::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
905     SPItem *seen = NULL, *newseen = NULL;
907     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
909     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
910         if (!SP_IS_ITEM(o)) continue;
912         if (upto && SP_ITEM(o) == upto)
913             break;
915         if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
916             // if nothing found yet, recurse into the group
917             newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
918             if (newseen) {
919                 seen = newseen;
920                 newseen = NULL;
921             }
923             if (item_is_in_group(upto, SP_GROUP(o)))
924                 break;
926         } else {
927             SPItem *child = SP_ITEM(o);
928             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
930             // seen remembers the last (topmost) of items pickable at this point
931             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
932                 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
933                 seen = child;
934             }
935         }
936     }
937     return seen;
940 /**
941 Returns the topmost non-layer group from the descendants of group which is at point
942 p, or NULL if none. Recurses into layers but not into groups.
943  */
944 SPItem*
945 find_group_at_point(unsigned int dkey, SPGroup *group, NR::Point const p)
947     SPItem *seen = NULL;
949     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
951     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
952         if (!SP_IS_ITEM(o)) continue;
953         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
954             SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
955             if (newseen) {
956                 seen = newseen;
957             }
958         }
959         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
960             SPItem *child = SP_ITEM(o);
961             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
963             // seen remembers the last (topmost) of groups pickable at this point
964             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
965                 seen = child;
966             }
967         }
968     }
969     return seen;
972 /*
973  * Return list of items, contained in box
974  *
975  * Assumes box is normalized (and g_asserts it!)
976  *
977  */
979 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
981     g_return_val_if_fail(document != NULL, NULL);
982     g_return_val_if_fail(document->priv != NULL, NULL);
984     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
987 /*
988  * Return list of items, that the parts of the item contained in box
989  *
990  * Assumes box is normalized (and g_asserts it!)
991  *
992  */
994 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
996     g_return_val_if_fail(document != NULL, NULL);
997     g_return_val_if_fail(document->priv != NULL, NULL);
999     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1002 SPItem *
1003 sp_document_item_at_point(SPDocument *document, unsigned const key, NR::Point const p,
1004                           gboolean const into_groups, SPItem *upto)
1006     g_return_val_if_fail(document != NULL, NULL);
1007     g_return_val_if_fail(document->priv != NULL, NULL);
1009     return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1012 SPItem*
1013 sp_document_group_at_point(SPDocument *document, unsigned int key, NR::Point const p)
1015     g_return_val_if_fail(document != NULL, NULL);
1016     g_return_val_if_fail(document->priv != NULL, NULL);
1018     return find_group_at_point(key, SP_GROUP(document->root), p);
1022 /* Resource management */
1024 gboolean
1025 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1027     GSList *rlist;
1028     GQuark q = g_quark_from_string(key);
1030     g_return_val_if_fail(document != NULL, FALSE);
1031     g_return_val_if_fail(key != NULL, FALSE);
1032     g_return_val_if_fail(*key != '\0', FALSE);
1033     g_return_val_if_fail(object != NULL, FALSE);
1034     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1036     if (SP_OBJECT_IS_CLONED(object))
1037         return FALSE;
1039     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1040     g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1041     rlist = g_slist_prepend(rlist, object);
1042     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1044     document->priv->resources_changed_signals[q].emit();
1046     return TRUE;
1049 gboolean
1050 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1052     GSList *rlist;
1053     GQuark q = g_quark_from_string(key);
1055     g_return_val_if_fail(document != NULL, FALSE);
1056     g_return_val_if_fail(key != NULL, FALSE);
1057     g_return_val_if_fail(*key != '\0', FALSE);
1058     g_return_val_if_fail(object != NULL, FALSE);
1059     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1061     if (SP_OBJECT_IS_CLONED(object))
1062         return FALSE;
1064     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1065     g_return_val_if_fail(rlist != NULL, FALSE);
1066     g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1067     rlist = g_slist_remove(rlist, object);
1068     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1070     document->priv->resources_changed_signals[q].emit();
1072     return TRUE;
1075 GSList const *
1076 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1078     g_return_val_if_fail(document != NULL, NULL);
1079     g_return_val_if_fail(key != NULL, NULL);
1080     g_return_val_if_fail(*key != '\0', NULL);
1082     return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1085 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1086                                                        gchar const *key,
1087                                                        SPDocument::ResourcesChangedSignal::slot_type slot)
1089     GQuark q = g_quark_from_string(key);
1090     return document->priv->resources_changed_signals[q].connect(slot);
1093 /* Helpers */
1095 gboolean
1096 sp_document_resource_list_free(gpointer key, gpointer value, gpointer data)
1098     g_slist_free((GSList *) value);
1099     return TRUE;
1102 unsigned int
1103 count_objects_recursive(SPObject *obj, unsigned int count)
1105     count++; // obj itself
1107     for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1108         count = count_objects_recursive(i, count);
1109     }
1111     return count;
1114 unsigned int
1115 objects_in_document(SPDocument *document)
1117     return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1120 void
1121 vacuum_document_recursive(SPObject *obj)
1123     if (SP_IS_DEFS(obj)) {
1124         for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1125             /* fixme: some inkscape-internal nodes in the future might not be collectable */
1126             def->requestOrphanCollection();
1127         }
1128     } else {
1129         for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1130             vacuum_document_recursive(i);
1131         }
1132     }
1135 unsigned int
1136 vacuum_document(SPDocument *document)
1138     unsigned int start = objects_in_document(document);
1139     unsigned int end;
1140     unsigned int newend = start;
1142     unsigned int iterations = 0;
1144     do {
1145         end = newend;
1147         vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1148         document->collectOrphans();
1149         iterations++;
1151         newend = objects_in_document(document);
1153     } while (iterations < 100 && newend < end);
1155     return start - newend;
1159 /*
1160   Local Variables:
1161   mode:c++
1162   c-file-style:"stroustrup"
1163   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1164   indent-tabs-mode:nil
1165   fill-column:99
1166   End:
1167 */
1168 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :