Code

Warning cleanup
[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"
56 #include "perspective3d.h"
57 #include "profile-manager.h"
59 #include "display/nr-arena-item.h"
61 #include "dialogs/rdf.h"
63 #define A4_WIDTH_STR "210mm"
64 #define A4_HEIGHT_STR "297mm"
66 #define SP_DOCUMENT_UPDATE_PRIORITY (G_PRIORITY_HIGH_IDLE - 1)
69 static gint sp_document_idle_handler(gpointer data);
71 gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data);
73 static gint doc_count = 0;
75 static unsigned long next_serial = 0;
77 SPDocument::SPDocument() {
78     SPDocumentPrivate *p;
80     keepalive = FALSE;
81     virgin    = TRUE;
83     modified_id = 0;
85     rdoc = NULL;
86     rroot = NULL;
87     root = NULL;
88     style_cascade = cr_cascade_new(NULL, NULL, NULL);
90     uri = NULL;
91     base = NULL;
92     name = NULL;
94     _collection_queue = NULL;
96     // Initialise instance of connector router.
97     router = new Avoid::Router();
98     // Don't use the Consolidate moves optimisation.
99     router->ConsolidateMoves = false;
101     perspectives = NULL;
103     /* Create an initial perspective, make it current and append it to the list of existing perspectives */
104     current_perspective = new Box3D::Perspective3D (
105                               // VP in x-direction
106                               Box3D::VanishingPoint( NR::Point(-50.0, 600.0),
107                                                      NR::Point( -1.0,   0.0), Box3D::VP_FINITE),
108                               // VP in y-direction
109                               Box3D::VanishingPoint( NR::Point(500.0,1000.0),
110                                                      NR::Point(  0.0,   1.0), Box3D::VP_INFINITE),
111                               // VP in z-direction
112                               Box3D::VanishingPoint( NR::Point(700.0, 600.0),
113                                                      NR::Point(sqrt(3.0),1.0), Box3D::VP_FINITE),
114                               this);
116     add_perspective (current_perspective);    
118     p = new SPDocumentPrivate();
120     p->serial = next_serial++;
122     p->iddef = g_hash_table_new(g_direct_hash, g_direct_equal);
123     p->reprdef = g_hash_table_new(g_direct_hash, g_direct_equal);
125     p->resources = g_hash_table_new(g_str_hash, g_str_equal);
127     p->sensitive = FALSE;
128     p->partial = NULL;
129     p->history_size = 0;
130     p->undo = NULL;
131     p->redo = NULL;
132     p->seeking = false;
134     priv = p;
136     // Once things are set, hook in the manager
137     profileManager = new Inkscape::ProfileManager(this);
139     // XXX only for testing!
140     priv->undoStackObservers.add(p->console_output_undo_observer);
143 SPDocument::~SPDocument() {
144     collectOrphans();
146     // kill/unhook this first
147     if ( profileManager ) {
148         delete profileManager;
149         profileManager = 0;
150     }
152     if (priv) {
153         if (priv->partial) {
154             sp_repr_free_log(priv->partial);
155             priv->partial = NULL;
156         }
158         sp_document_clear_redo(this);
159         sp_document_clear_undo(this);
161         if (root) {
162             root->releaseReferences();
163             sp_object_unref(root);
164             root = NULL;
165         }
167         if (priv->iddef) g_hash_table_destroy(priv->iddef);
168         if (priv->reprdef) g_hash_table_destroy(priv->reprdef);
170         if (rdoc) Inkscape::GC::release(rdoc);
172         /* Free resources */
173         g_hash_table_foreach_remove(priv->resources, sp_document_resource_list_free, this);
174         g_hash_table_destroy(priv->resources);
176         delete priv;
177         priv = NULL;
178     }
180     cr_cascade_unref(style_cascade);
181     style_cascade = NULL;
183     if (name) {
184         g_free(name);
185         name = NULL;
186     }
187     if (base) {
188         g_free(base);
189         base = NULL;
190     }
191     if (uri) {
192         g_free(uri);
193         uri = NULL;
194     }
196     if (modified_id) {
197         gtk_idle_remove(modified_id);
198         modified_id = 0;
199     }
201     _selection_changed_connection.disconnect();
202     _desktop_activated_connection.disconnect();
204     if (keepalive) {
205         inkscape_unref();
206         keepalive = FALSE;
207     }
209     if (router) {
210         delete router;
211         router = NULL;
212     }
214     //delete this->_whiteboard_session_manager;
216     current_perspective = NULL;
217     // TODO: Do we have to delete the perspectives?
218     /***
219     for (GSList *i = perspectives; i != NULL; ++i) {
220         delete ((Box3D::Perspective3D *) i->data);
221     }
222     g_slist_free (perspectives);
223     ***/
226 void SPDocument::add_perspective (Box3D::Perspective3D * const persp)
228     // FIXME: Should we handle the case that the perspectives have equal VPs but are not identical?
229     //        If so, we need to take care of relinking the boxes, etc.
230     if (persp == NULL || g_slist_find (perspectives, persp)) return;
231     perspectives = g_slist_prepend (perspectives, persp);
234 void SPDocument::remove_perspective (Box3D::Perspective3D * const persp)
236     if (persp == NULL || !g_slist_find (perspectives, persp)) return;
237     perspectives = g_slist_remove (perspectives, persp);
240 // find an existing perspective whose VPs are equal to those of persp
241 Box3D::Perspective3D * SPDocument::find_perspective (const Box3D::Perspective3D * persp)
243     for (GSList *p = perspectives; p != NULL; p = p->next) {
244         if (*((Box3D::Perspective3D *) p->data) == *persp) {
245             return ((Box3D::Perspective3D *) p->data);
246         }
247     }
248     return NULL; // perspective was not found
251 Box3D::Perspective3D * SPDocument::get_persp_of_box (const SP3DBox *box)
253     for (GSList *p = perspectives; p != NULL; p = p->next) {
254         if (((Box3D::Perspective3D *) p->data)->has_box (box))
255             return (Box3D::Perspective3D *) p->data;
256     }
257     g_warning ("Stray 3D box!\n");
258     g_assert_not_reached();
261 Box3D::Perspective3D * SPDocument::get_persp_of_VP (const Box3D::VanishingPoint *vp)
263     Box3D::Perspective3D *persp;
264     for (GSList *p = perspectives; p != NULL; p = p->next) {
265         persp = (Box3D::Perspective3D *) p->data;
266         // we compare the pointers, not the position/state of the VPs; is this correct?
267         if (persp->get_vanishing_point (Box3D::X) == vp ||
268             persp->get_vanishing_point (Box3D::Y) == vp ||
269             persp->get_vanishing_point (Box3D::Z) == vp)
270             return persp;
271     }
273     g_warning ("Stray vanishing point!\n");
274     g_assert_not_reached();
277 unsigned long SPDocument::serial() const {
278     return priv->serial;
281 void SPDocument::queueForOrphanCollection(SPObject *object) {
282     g_return_if_fail(object != NULL);
283     g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
285     sp_object_ref(object, NULL);
286     _collection_queue = g_slist_prepend(_collection_queue, object);
289 void SPDocument::collectOrphans() {
290     while (_collection_queue) {
291         GSList *objects=_collection_queue;
292         _collection_queue = NULL;
293         for ( GSList *iter=objects ; iter ; iter = iter->next ) {
294             SPObject *object=reinterpret_cast<SPObject *>(iter->data);
295             object->collectOrphan();
296             sp_object_unref(object, NULL);
297         }
298         g_slist_free(objects);
299     }
302 void SPDocument::reset_key (void */*dummy*/)
304     actionkey = NULL;
307 SPDocument *
308 sp_document_create(Inkscape::XML::Document *rdoc,
309                    gchar const *uri,
310                    gchar const *base,
311                    gchar const *name,
312                    unsigned int keepalive)
314     SPDocument *document;
315     Inkscape::XML::Node *rroot;
316     Inkscape::Version sodipodi_version;
318     rroot = rdoc->root();
320     document = new SPDocument();
322     document->keepalive = keepalive;
324     document->rdoc = rdoc;
325     document->rroot = rroot;
327 #ifndef WIN32
328     prepend_current_dir_if_relative(&(document->uri), uri);
329 #else
330     // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
331     document->uri = uri? g_strdup(uri) : NULL;
332 #endif
334     // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
335     // which is why we use g_get_current_dir() in calculating the abs path above
336     //This is NULL for a new document
337     if (base)
338         document->base = g_strdup(base);
339     else
340         document->base = NULL;
341     document->name = g_strdup(name);
343     document->root = sp_object_repr_build_tree(document, rroot);
345     sodipodi_version = SP_ROOT(document->root)->version.sodipodi;
347     /* fixme: Not sure about this, but lets assume ::build updates */
348     rroot->setAttribute("sodipodi:version", SODIPODI_VERSION);
349     rroot->setAttribute("inkscape:version", INKSCAPE_VERSION);
350     /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
352     /* Quick hack 2 - get default image size into document */
353     if (!rroot->attribute("width")) rroot->setAttribute("width", A4_WIDTH_STR);
354     if (!rroot->attribute("height")) rroot->setAttribute("height", A4_HEIGHT_STR);
355     /* End of quick hack 2 */
357     /* Quick hack 3 - Set uri attributes */
358     if (uri) {
359         rroot->setAttribute("sodipodi:docname", uri);
360     }
361     /* End of quick hack 3 */
363     // creating namedview
364     if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
365         // if there's none in the document already,
366         Inkscape::XML::Node *r = NULL;
367         Inkscape::XML::Node *rnew = NULL;
368         r = inkscape_get_repr(INKSCAPE, "template.base");
369         // see if there's a template with id="base" in the preferences
370         if (!r) {
371             // if there's none, create an empty element
372             rnew = rdoc->createElement("sodipodi:namedview");
373             rnew->setAttribute("id", "base");
374         } else {
375             // otherwise, take from preferences
376             rnew = r->duplicate(rroot->document());
377         }
378         // insert into the document
379         rroot->addChild(rnew, NULL);
380         // clean up
381         Inkscape::GC::release(rnew);
382     }
384     /* Defs */
385     if (!SP_ROOT(document->root)->defs) {
386         Inkscape::XML::Node *r;
387         r = rdoc->createElement("svg:defs");
388         rroot->addChild(r, NULL);
389         Inkscape::GC::release(r);
390         g_assert(SP_ROOT(document->root)->defs);
391     }
393     /* Default RDF */
394     rdf_set_defaults( document );
396     if (keepalive) {
397         inkscape_ref();
398     }
400     sp_document_set_undo_sensitive(document, true);
402     // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
403     if (!Inkscape::NSApplication::Application::getNewGui()) {
404         g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
405                          G_CALLBACK(sp_document_reset_key), document);
406         g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
407                          G_CALLBACK(sp_document_reset_key), document);
408     } else {
409         document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
410         document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
411     }
413     return document;
416 /**
417  * Fetches document from URI, or creates new, if NULL; public document
418  * appears in document list.
419  */
420 SPDocument *
421 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
423     SPDocument *doc;
424     Inkscape::XML::Document *rdoc;
425     gchar *base = NULL;
426     gchar *name = NULL;
428     if (uri) {
429         Inkscape::XML::Node *rroot;
430         gchar *s, *p;
431         /* Try to fetch repr from file */
432         rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
433         /* If file cannot be loaded, return NULL without warning */
434         if (rdoc == NULL) return NULL;
435         rroot = rdoc->root();
436         /* If xml file is not svg, return NULL without warning */
437         /* fixme: destroy document */
438         if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
439         s = g_strdup(uri);
440         p = strrchr(s, '/');
441         if (p) {
442             name = g_strdup(p + 1);
443             p[1] = '\0';
444             base = g_strdup(s);
445         } else {
446             base = NULL;
447             name = g_strdup(uri);
448         }
449         g_free(s);
450     } else {
451         rdoc = sp_repr_document_new("svg:svg");
452     }
454     if (make_new) {
455         base = NULL;
456         uri = NULL;
457         name = g_strdup_printf(_("New document %d"), ++doc_count);
458     }
460     //# These should be set by now
461     g_assert(name);
463     doc = sp_document_create(rdoc, uri, base, name, keepalive);
465     g_free(base);
466     g_free(name);
468     return doc;
471 SPDocument *
472 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
474     SPDocument *doc;
475     Inkscape::XML::Document *rdoc;
476     Inkscape::XML::Node *rroot;
477     gchar *name;
479     rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
481     /* If it cannot be loaded, return NULL without warning */
482     if (rdoc == NULL) return NULL;
484     rroot = rdoc->root();
485     /* If xml file is not svg, return NULL without warning */
486     /* fixme: destroy document */
487     if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
489     name = g_strdup_printf(_("Memory document %d"), ++doc_count);
491     doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
493     return doc;
496 SPDocument *
497 sp_document_ref(SPDocument *doc)
499     g_return_val_if_fail(doc != NULL, NULL);
500     Inkscape::GC::anchor(doc);
501     return doc;
504 SPDocument *
505 sp_document_unref(SPDocument *doc)
507     g_return_val_if_fail(doc != NULL, NULL);
508     Inkscape::GC::release(doc);
509     return NULL;
512 gdouble sp_document_width(SPDocument *document)
514     g_return_val_if_fail(document != NULL, 0.0);
515     g_return_val_if_fail(document->priv != NULL, 0.0);
516     g_return_val_if_fail(document->root != NULL, 0.0);
518     return SP_ROOT(document->root)->width.computed;
521 void
522 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
524     SPRoot *root = SP_ROOT(document->root);
526     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
527         root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
528     } else { // set to width=
529         root->width.computed = sp_units_get_pixels (width, *unit);
530         /* SVG does not support meters as a unit, so we must translate meters to
531          * cm when writing */
532         if (!strcmp(unit->abbr, "m")) {
533             root->width.value = 100*width;
534             root->width.unit = SVGLength::CM;
535         } else {
536             root->width.value = width;
537             root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
538         }
539     }
541     SP_OBJECT (root)->updateRepr();
544 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
546     SPRoot *root = SP_ROOT(document->root);
548     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
549         root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
550     } else { // set to height=
551         root->height.computed = sp_units_get_pixels (height, *unit);
552         /* SVG does not support meters as a unit, so we must translate meters to
553          * cm when writing */
554         if (!strcmp(unit->abbr, "m")) {
555             root->height.value = 100*height;
556             root->height.unit = SVGLength::CM;
557         } else {
558             root->height.value = height;
559             root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
560         }
561     }
563     SP_OBJECT (root)->updateRepr();
566 gdouble sp_document_height(SPDocument *document)
568     g_return_val_if_fail(document != NULL, 0.0);
569     g_return_val_if_fail(document->priv != NULL, 0.0);
570     g_return_val_if_fail(document->root != NULL, 0.0);
572     return SP_ROOT(document->root)->height.computed;
575 /**
576  * Given an NR::Rect that may, for example, correspond to the bbox of an object,
577  * this function fits the canvas to that rect by resizing the canvas
578  * and translating the document root into position.
579  */
580 void SPDocument::fitToRect(NR::Rect const &rect)
582     g_return_if_fail(!rect.isEmpty());
584     using NR::X; using NR::Y;
585     double const w = rect.extent(X);
586     double const h = rect.extent(Y);
588     double const old_height = sp_document_height(this);
589     SPUnit const &px(sp_unit_get_by_id(SP_UNIT_PX));
590     sp_document_set_width(this, w, &px);
591     sp_document_set_height(this, h, &px);
593     NR::translate const tr(NR::Point(0, (old_height - h))
594                            - rect.min());
595     SP_GROUP(root)->translateChildItems(tr);
598 void sp_document_set_uri(SPDocument *document, gchar const *uri)
600     g_return_if_fail(document != NULL);
602     if (document->name) {
603         g_free(document->name);
604         document->name = NULL;
605     }
606     if (document->base) {
607         g_free(document->base);
608         document->base = NULL;
609     }
610     if (document->uri) {
611         g_free(document->uri);
612         document->uri = NULL;
613     }
615     if (uri) {
617 #ifndef WIN32
618         prepend_current_dir_if_relative(&(document->uri), uri);
619 #else
620         // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
621         document->uri = g_strdup(uri);
622 #endif
624         /* fixme: Think, what this means for images (Lauris) */
625         document->base = g_path_get_dirname(document->uri);
626         document->name = g_path_get_basename(document->uri);
628     } else {
629         document->uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
630         document->base = NULL;
631         document->name = g_strdup(document->uri);
632     }
634     // Update saveable repr attributes.
635     Inkscape::XML::Node *repr = sp_document_repr_root(document);
636     // changing uri in the document repr must not be not undoable
637     bool saved = sp_document_get_undo_sensitive(document);
638     sp_document_set_undo_sensitive(document, false);
640     repr->setAttribute("sodipodi:docname", document->name);
641     sp_document_set_undo_sensitive(document, saved);
643     document->priv->uri_set_signal.emit(document->uri);
646 void
647 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
649     g_return_if_fail(doc != NULL);
651     doc->priv->resized_signal.emit(width, height);
654 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
656     return priv->modified_signal.connect(slot);
659 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
661     return priv->uri_set_signal.connect(slot);
664 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
666     return priv->resized_signal.connect(slot);
669 sigc::connection
670 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
672     return priv->_reconstruction_start_signal.connect(slot);
675 void
676 SPDocument::emitReconstructionStart(void)
678     // printf("Starting Reconstruction\n");
679     priv->_reconstruction_start_signal.emit();
680     return;
683 sigc::connection
684 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type  slot)
686     return priv->_reconstruction_finish_signal.connect(slot);
689 void
690 SPDocument::emitReconstructionFinish(void)
692     // printf("Finishing Reconstruction\n");
693     priv->_reconstruction_finish_signal.emit();
694     return;
697 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
699     return priv->commit_signal.connect(slot);
704 void SPDocument::_emitModified() {
705     static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
706     root->emitModified(0);
707     priv->modified_signal.emit(flags);
710 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
711     GQuark idq = g_quark_from_string(id);
713     if (object) {
714         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
715         g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
716     } else {
717         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
718         g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
719     }
721     SPDocumentPrivate::IDChangedSignalMap::iterator pos;
723     pos = priv->id_changed_signals.find(idq);
724     if ( pos != priv->id_changed_signals.end() ) {
725         if (!(*pos).second.empty()) {
726             (*pos).second.emit(object);
727         } else { // discard unused signal
728             priv->id_changed_signals.erase(pos);
729         }
730     }
733 void
734 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
736         this->priv->undoStackObservers.add(observer);
739 void
740 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
742         this->priv->undoStackObservers.remove(observer);
745 SPObject *SPDocument::getObjectById(gchar const *id) {
746     g_return_val_if_fail(id != NULL, NULL);
748     GQuark idq = g_quark_from_string(id);
749     return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
752 sigc::connection SPDocument::connectIdChanged(gchar const *id,
753                                               SPDocument::IDChangedSignal::slot_type slot)
755     return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
758 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
759     if (object) {
760         g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
761         g_hash_table_insert(priv->reprdef, repr, object);
762     } else {
763         g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
764         g_hash_table_remove(priv->reprdef, repr);
765     }
768 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
769     g_return_val_if_fail(repr != NULL, NULL);
770     return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
773 Glib::ustring SPDocument::getLanguage() {
774     gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
775     if (document_language) {
776         while (isspace(*document_language))
777             document_language++;
778     }
779     if ( !document_language || 0 == *document_language) {
780         // retrieve system language
781         document_language = getenv("LC_ALL");
782         if ( NULL == document_language || *document_language == 0 ) {
783             document_language = getenv ("LC_MESSAGES");
784         }
785         if ( NULL == document_language || *document_language == 0 ) {
786             document_language = getenv ("LANG");
787         }
788         
789         if ( NULL != document_language ) {
790             gchar *pos = strchr(document_language, '_');
791             if ( NULL != pos ) {
792                 return Glib::ustring(document_language, pos - document_language);
793             }
794         }
795     }
797     if ( NULL == document_language )
798         return Glib::ustring();
799     return document_language;
802 /* Object modification root handler */
804 void
805 sp_document_request_modified(SPDocument *doc)
807     if (!doc->modified_id) {
808         doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
809     }
812 void
813 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
815     ctx->ctx.flags = 0;
816     ctx->i2doc = NR::identity();
817     /* Set up viewport in case svg has it defined as percentages */
818     if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
819         ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
820         ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
821         ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
822         ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
823     } else { // as a last resort, set size to A4
824         ctx->vp.x0 = 0.0;
825         ctx->vp.y0 = 0.0;
826         ctx->vp.x1 = 210 * PX_PER_MM;
827         ctx->vp.y1 = 297 * PX_PER_MM;
828     }
829     ctx->i2vp = NR::identity();
832 /**
833  * Tries to update the document state based on the modified and 
834  * "update required" flags, and return true if the document has
835  * been brought fully up to date.
836  */
837 bool
838 SPDocument::_updateDocument()
840     /* Process updates */
841     if (this->root->uflags || this->root->mflags) {
842         if (this->root->uflags) {
843             SPItemCtx ctx;
844             sp_document_setup_viewport (this, &ctx);
846             bool saved = sp_document_get_undo_sensitive(this);
847             sp_document_set_undo_sensitive(this, false);
849             this->root->updateDisplay((SPCtx *)&ctx, 0);
851             sp_document_set_undo_sensitive(this, saved);
852         }
853         this->_emitModified();
854     }
856     return !(this->root->uflags || this->root->mflags);
860 /**
861  * Repeatedly works on getting the document updated, since sometimes
862  * it takes more than one pass to get the document updated.  But it
863  * usually should not take more than a few loops, and certainly never
864  * more than 32 iterations.  So we bail out if we hit 32 iterations,
865  * since this typically indicates we're stuck in an update loop.
866  */
867 gint
868 sp_document_ensure_up_to_date(SPDocument *doc)
870     int counter = 32;
871     while (!doc->_updateDocument()) {
872         if (counter == 0) {
873             g_warning("More than 32 iteration while updating document '%s'", doc->uri);
874             break;
875         }
876         counter--;
877     }
879     if (doc->modified_id) {
880         /* Remove handler */
881         gtk_idle_remove(doc->modified_id);
882         doc->modified_id = 0;
883     }
884     return counter>0;
887 /**
888  * An idle handler to update the document.  Returns true if
889  * the document needs further updates.
890  */
891 static gint
892 sp_document_idle_handler(gpointer data)
894     SPDocument *doc = static_cast<SPDocument *>(data);
895     if (doc->_updateDocument()) {
896         doc->modified_id = 0;
897         return false;
898     } else {
899         return true;
900     }
903 static bool is_within(NR::Rect const &area, NR::Rect const &box)
905     return area.contains(box);
908 static bool overlaps(NR::Rect const &area, NR::Rect const &box)
910     return area.intersects(box);
913 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, NR::Rect const &area,
914                                   bool (*test)(NR::Rect const &, NR::Rect const &), bool take_insensitive = false)
916     g_return_val_if_fail(SP_IS_GROUP(group), s);
918     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
919         if (!SP_IS_ITEM(o)) {
920             continue;
921         }
922         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
923             s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
924         } else {
925             SPItem *child = SP_ITEM(o);
926             NR::Maybe<NR::Rect> box = sp_item_bbox_desktop(child);
927             if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
928                 s = g_slist_append(s, child);
929             }
930         }
931     }
933     return s;
936 /**
937 Returns true if an item is among the descendants of group (recursively).
938  */
939 bool item_is_in_group(SPItem *item, SPGroup *group)
941     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
942         if (!SP_IS_ITEM(o)) continue;
943         if (SP_ITEM(o) == item)
944             return true;
945         if (SP_IS_GROUP(o))
946             if (item_is_in_group(item, SP_GROUP(o)))
947                 return true;
948     }
949     return false;
952 /**
953 Returns the bottommost item from the list which is at the point, or NULL if none.
954 */
955 SPItem*
956 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
957                                            NR::Point const p, bool take_insensitive)
959     g_return_val_if_fail(group, NULL);
961     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
963     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
965         if (!SP_IS_ITEM(o)) continue;
967         SPItem *item = SP_ITEM(o);
968         NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
969         if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
970             && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
971             if (g_slist_find((GSList *) list, item) != NULL)
972                 return item;
973         }
975         if (SP_IS_GROUP(o)) {
976             SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
977             if (found)
978                 return found;
979         }
981     }
982     return NULL;
985 /**
986 Returns the topmost (in z-order) item from the descendants of group (recursively) which
987 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
988 non-layer groups or not. Honors take_insensitive on whether to return insensitive
989 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
990 upwards in z-order and returns what it has found so far (i.e. the found item is
991 guaranteed to be lower than upto).
992  */
993 SPItem*
994 find_item_at_point(unsigned int dkey, SPGroup *group, NR::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
996     SPItem *seen = NULL, *newseen = NULL;
998     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
1000     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1001         if (!SP_IS_ITEM(o)) continue;
1003         if (upto && SP_ITEM(o) == upto)
1004             break;
1006         if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
1007             // if nothing found yet, recurse into the group
1008             newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
1009             if (newseen) {
1010                 seen = newseen;
1011                 newseen = NULL;
1012             }
1014             if (item_is_in_group(upto, SP_GROUP(o)))
1015                 break;
1017         } else {
1018             SPItem *child = SP_ITEM(o);
1019             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1021             // seen remembers the last (topmost) of items pickable at this point
1022             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1023                 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1024                 seen = child;
1025             }
1026         }
1027     }
1028     return seen;
1031 /**
1032 Returns the topmost non-layer group from the descendants of group which is at point
1033 p, or NULL if none. Recurses into layers but not into groups.
1034  */
1035 SPItem*
1036 find_group_at_point(unsigned int dkey, SPGroup *group, NR::Point const p)
1038     SPItem *seen = NULL;
1040     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
1042     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1043         if (!SP_IS_ITEM(o)) continue;
1044         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1045             SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1046             if (newseen) {
1047                 seen = newseen;
1048             }
1049         }
1050         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1051             SPItem *child = SP_ITEM(o);
1052             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1054             // seen remembers the last (topmost) of groups pickable at this point
1055             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1056                 seen = child;
1057             }
1058         }
1059     }
1060     return seen;
1063 /*
1064  * Return list of items, contained in box
1065  *
1066  * Assumes box is normalized (and g_asserts it!)
1067  *
1068  */
1070 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
1072     g_return_val_if_fail(document != NULL, NULL);
1073     g_return_val_if_fail(document->priv != NULL, NULL);
1075     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
1078 /*
1079  * Return list of items, that the parts of the item contained in box
1080  *
1081  * Assumes box is normalized (and g_asserts it!)
1082  *
1083  */
1085 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
1087     g_return_val_if_fail(document != NULL, NULL);
1088     g_return_val_if_fail(document->priv != NULL, NULL);
1090     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1093 GSList *
1094 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<NR::Point> points)
1096     GSList *items = NULL;
1098     // When picking along the path, we don't want small objects close together 
1099     // (such as hatching strokes) to obscure each other by their deltas, 
1100     // so we temporarily set delta to a small value
1101     gdouble saved_delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
1102     prefs_set_double_attribute ("options.cursortolerance", "value", 0.25);
1104     for(unsigned int i = 0; i < points.size(); i++) {
1105         SPItem *item = sp_document_item_at_point(document, key, points[i],
1106                                          false, NULL);
1107         if (item && !g_slist_find(items, item))
1108             items = g_slist_prepend (items, item);
1109     }
1111     // and now we restore it back
1112     prefs_set_double_attribute ("options.cursortolerance", "value", saved_delta);
1114     return items;
1117 SPItem *
1118 sp_document_item_at_point(SPDocument *document, unsigned const key, NR::Point const p,
1119                           gboolean const into_groups, SPItem *upto)
1121     g_return_val_if_fail(document != NULL, NULL);
1122     g_return_val_if_fail(document->priv != NULL, NULL);
1124     return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1127 SPItem*
1128 sp_document_group_at_point(SPDocument *document, unsigned int key, NR::Point const p)
1130     g_return_val_if_fail(document != NULL, NULL);
1131     g_return_val_if_fail(document->priv != NULL, NULL);
1133     return find_group_at_point(key, SP_GROUP(document->root), p);
1137 /* Resource management */
1139 gboolean
1140 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1142     GSList *rlist;
1143     GQuark q = g_quark_from_string(key);
1145     g_return_val_if_fail(document != NULL, FALSE);
1146     g_return_val_if_fail(key != NULL, FALSE);
1147     g_return_val_if_fail(*key != '\0', FALSE);
1148     g_return_val_if_fail(object != NULL, FALSE);
1149     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1151     if (SP_OBJECT_IS_CLONED(object))
1152         return FALSE;
1154     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1155     g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1156     rlist = g_slist_prepend(rlist, object);
1157     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1159     document->priv->resources_changed_signals[q].emit();
1161     return TRUE;
1164 gboolean
1165 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1167     GSList *rlist;
1168     GQuark q = g_quark_from_string(key);
1170     g_return_val_if_fail(document != NULL, FALSE);
1171     g_return_val_if_fail(key != NULL, FALSE);
1172     g_return_val_if_fail(*key != '\0', FALSE);
1173     g_return_val_if_fail(object != NULL, FALSE);
1174     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1176     if (SP_OBJECT_IS_CLONED(object))
1177         return FALSE;
1179     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1180     g_return_val_if_fail(rlist != NULL, FALSE);
1181     g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1182     rlist = g_slist_remove(rlist, object);
1183     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1185     document->priv->resources_changed_signals[q].emit();
1187     return TRUE;
1190 GSList const *
1191 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1193     g_return_val_if_fail(document != NULL, NULL);
1194     g_return_val_if_fail(key != NULL, NULL);
1195     g_return_val_if_fail(*key != '\0', NULL);
1197     return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1200 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1201                                                        gchar const *key,
1202                                                        SPDocument::ResourcesChangedSignal::slot_type slot)
1204     GQuark q = g_quark_from_string(key);
1205     return document->priv->resources_changed_signals[q].connect(slot);
1208 /* Helpers */
1210 gboolean
1211 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1213     g_slist_free((GSList *) value);
1214     return TRUE;
1217 unsigned int
1218 count_objects_recursive(SPObject *obj, unsigned int count)
1220     count++; // obj itself
1222     for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1223         count = count_objects_recursive(i, count);
1224     }
1226     return count;
1229 unsigned int
1230 objects_in_document(SPDocument *document)
1232     return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1235 void
1236 vacuum_document_recursive(SPObject *obj)
1238     if (SP_IS_DEFS(obj)) {
1239         for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1240             /* fixme: some inkscape-internal nodes in the future might not be collectable */
1241             def->requestOrphanCollection();
1242         }
1243     } else {
1244         for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1245             vacuum_document_recursive(i);
1246         }
1247     }
1250 unsigned int
1251 vacuum_document(SPDocument *document)
1253     unsigned int start = objects_in_document(document);
1254     unsigned int end;
1255     unsigned int newend = start;
1257     unsigned int iterations = 0;
1259     do {
1260         end = newend;
1262         vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1263         document->collectOrphans();
1264         iterations++;
1266         newend = objects_in_document(document);
1268     } while (iterations < 100 && newend < end);
1270     return start - newend;
1273 bool SPDocument::isSeeking() const {
1274     return priv->seeking;
1278 /*
1279   Local Variables:
1280   mode:c++
1281   c-file-style:"stroustrup"
1282   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1283   indent-tabs-mode:nil
1284   fill-column:99
1285   End:
1286 */
1287 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :