Code

Move files from the src/dialogs/ directory to the places where they
[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 <string>
42 #include <cstring>
44 #include "application/application.h"
45 #include "application/editor.h"
46 #include "desktop.h"
47 #include "dir-util.h"
48 #include "display/nr-arena-item.h"
49 #include "document-private.h"
50 #include "helper/units.h"
51 #include "inkscape-private.h"
52 #include "inkscape-version.h"
53 #include "libavoid/router.h"
54 #include "persp3d.h"
55 #include "preferences.h"
56 #include "profile-manager.h"
57 #include "rdf.h"
58 #include "sp-item-group.h"
59 #include "sp-namedview.h"
60 #include "sp-object-repr.h"
61 #include "transf_mat_3x4.h"
62 #include "unit-constants.h"
63 #include "xml/repr.h"
65 #define SP_DOCUMENT_UPDATE_PRIORITY (G_PRIORITY_HIGH_IDLE - 1)
68 static gint sp_document_idle_handler(gpointer data);
70 gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data);
72 static gint doc_count = 0;
74 static unsigned long next_serial = 0;
76 SPDocument::SPDocument() :
77     keepalive(FALSE),
78     virgin(TRUE),
79     modified_since_save(FALSE),
80     rdoc(0),
81     rroot(0),
82     root(0),
83     style_cascade(cr_cascade_new(NULL, NULL, NULL)),
84     uri(0),
85     base(0),
86     name(0),
87     priv(0), // reset in ctor
88     actionkey(0),
89     modified_id(0),
90     profileManager(0), // deferred until after other initialization
91     router(new Avoid::Router()),
92     perspectives(0),
93     current_persp3d(0),
94     _collection_queue(0),
95     oldSignalsConnected(false)
96 {
97     // Don't use the Consolidate moves optimisation.
98     router->ConsolidateMoves = false;
100     SPDocumentPrivate *p = new SPDocumentPrivate();
102     p->serial = next_serial++;
104     p->iddef = g_hash_table_new(g_direct_hash, g_direct_equal);
105     p->reprdef = g_hash_table_new(g_direct_hash, g_direct_equal);
107     p->resources = g_hash_table_new(g_str_hash, g_str_equal);
109     p->sensitive = FALSE;
110     p->partial = NULL;
111     p->history_size = 0;
112     p->undo = NULL;
113     p->redo = NULL;
114     p->seeking = false;
116     priv = p;
118     // Once things are set, hook in the manager
119     profileManager = new Inkscape::ProfileManager(this);
121     // XXX only for testing!
122     priv->undoStackObservers.add(p->console_output_undo_observer);
125 SPDocument::~SPDocument() {
126     collectOrphans();
128     // kill/unhook this first
129     if ( profileManager ) {
130         delete profileManager;
131         profileManager = 0;
132     }
134     if (priv) {
135         if (priv->partial) {
136             sp_repr_free_log(priv->partial);
137             priv->partial = NULL;
138         }
140         sp_document_clear_redo(this);
141         sp_document_clear_undo(this);
143         if (root) {
144             root->releaseReferences();
145             sp_object_unref(root);
146             root = NULL;
147         }
149         if (priv->iddef) g_hash_table_destroy(priv->iddef);
150         if (priv->reprdef) g_hash_table_destroy(priv->reprdef);
152         if (rdoc) Inkscape::GC::release(rdoc);
154         /* Free resources */
155         g_hash_table_foreach_remove(priv->resources, sp_document_resource_list_free, this);
156         g_hash_table_destroy(priv->resources);
158         delete priv;
159         priv = NULL;
160     }
162     cr_cascade_unref(style_cascade);
163     style_cascade = NULL;
165     if (name) {
166         g_free(name);
167         name = NULL;
168     }
169     if (base) {
170         g_free(base);
171         base = NULL;
172     }
173     if (uri) {
174         g_free(uri);
175         uri = NULL;
176     }
178     if (modified_id) {
179         gtk_idle_remove(modified_id);
180         modified_id = 0;
181     }
183     if (oldSignalsConnected) {
184         g_signal_handlers_disconnect_by_func(G_OBJECT(INKSCAPE),
185                                              reinterpret_cast<gpointer>(sp_document_reset_key),
186                                              static_cast<gpointer>(this));
187     } else {
188         _selection_changed_connection.disconnect();
189         _desktop_activated_connection.disconnect();
190     }
192     if (keepalive) {
193         inkscape_unref();
194         keepalive = FALSE;
195     }
197     if (router) {
198         delete router;
199         router = NULL;
200     }
202     //delete this->_whiteboard_session_manager;
206 void SPDocument::add_persp3d (Persp3D * const /*persp*/)
208     SPDefs *defs = SP_ROOT(this->root)->defs;
209     for (SPObject *i = sp_object_first_child(SP_OBJECT(defs)); i != NULL; i = SP_OBJECT_NEXT(i) ) {
210         if (SP_IS_PERSP3D(i)) {
211             g_print ("Encountered a Persp3D in defs\n");
212         }
213     }
215     g_print ("Adding Persp3D to defs\n");
216     persp3d_create_xml_element (this);
219 void SPDocument::remove_persp3d (Persp3D * const /*persp*/)
221     // TODO: Delete the repr, maybe perform a check if any boxes are still linked to the perspective.
222     //       Anything else?
223     g_print ("Please implement deletion of perspectives here.\n");
226 unsigned long SPDocument::serial() const {
227     return priv->serial;
230 void SPDocument::queueForOrphanCollection(SPObject *object) {
231     g_return_if_fail(object != NULL);
232     g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
234     sp_object_ref(object, NULL);
235     _collection_queue = g_slist_prepend(_collection_queue, object);
238 void SPDocument::collectOrphans() {
239     while (_collection_queue) {
240         GSList *objects=_collection_queue;
241         _collection_queue = NULL;
242         for ( GSList *iter=objects ; iter ; iter = iter->next ) {
243             SPObject *object=reinterpret_cast<SPObject *>(iter->data);
244             object->collectOrphan();
245             sp_object_unref(object, NULL);
246         }
247         g_slist_free(objects);
248     }
251 void SPDocument::reset_key (void */*dummy*/)
253     actionkey = NULL;
256 SPDocument *
257 sp_document_create(Inkscape::XML::Document *rdoc,
258                    gchar const *uri,
259                    gchar const *base,
260                    gchar const *name,
261                    unsigned int keepalive)
263     SPDocument *document;
264     Inkscape::XML::Node *rroot;
265     Inkscape::Version sodipodi_version;
266     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
268     rroot = rdoc->root();
270     document = new SPDocument();
272     document->keepalive = keepalive;
274     document->rdoc = rdoc;
275     document->rroot = rroot;
277 #ifndef WIN32
278     prepend_current_dir_if_relative(&(document->uri), uri);
279 #else
280     // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
281     document->uri = uri? g_strdup(uri) : NULL;
282 #endif
284     // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
285     // which is why we use g_get_current_dir() in calculating the abs path above
286     //This is NULL for a new document
287     if (base)
288         document->base = g_strdup(base);
289     else
290         document->base = NULL;
291     document->name = g_strdup(name);
293     document->root = sp_object_repr_build_tree(document, rroot);
295     sodipodi_version = SP_ROOT(document->root)->version.sodipodi;
297     /* fixme: Not sure about this, but lets assume ::build updates */
298     rroot->setAttribute("sodipodi:version", SODIPODI_VERSION);
299     rroot->setAttribute("inkscape:version", Inkscape::version_string);
300     /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
302     /* Quick hack 2 - get default image size into document */
303     if (!rroot->attribute("width")) rroot->setAttribute("width", "100%");
304     if (!rroot->attribute("height")) rroot->setAttribute("height", "100%");
305     /* End of quick hack 2 */
307     /* Quick hack 3 - Set uri attributes */
308     if (uri) {
309         rroot->setAttribute("sodipodi:docname", uri);
310     }
311     /* End of quick hack 3 */
313     /* Eliminate obsolete sodipodi:docbase, for privacy reasons */
314     rroot->setAttribute("sodipodi:docbase", NULL);
315     
316     /* Eliminate any claim to adhere to a profile, as we don't try to */
317     rroot->setAttribute("baseProfile", NULL);
319     // creating namedview
320     if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
321         // if there's none in the document already,
322         Inkscape::XML::Node *rnew = NULL;
323         
324         rnew = rdoc->createElement("sodipodi:namedview");
325         //rnew->setAttribute("id", "base");
327         // Add namedview data from the preferences
328         // we can't use getAllEntries because this could produce non-SVG doubles
329         Glib::ustring pagecolor = prefs->getString("/template/base/pagecolor");
330         if (!pagecolor.empty()) {
331             rnew->setAttribute("pagecolor", pagecolor.data());
332         }
333         Glib::ustring bordercolor = prefs->getString("/template/base/bordercolor");
334         if (!bordercolor.empty()) {
335             rnew->setAttribute("bordercolor", bordercolor.data());
336         }
337         sp_repr_set_svg_double(rnew, "borderopacity",
338             prefs->getDouble("/template/base/borderopacity", 1.0));
339         sp_repr_set_svg_double(rnew, "objecttolerance",
340             prefs->getDouble("/template/base/objecttolerance", 10.0));
341         sp_repr_set_svg_double(rnew, "gridtolerance",
342             prefs->getDouble("/template/base/gridtolerance", 10.0));
343         sp_repr_set_svg_double(rnew, "guidetolerance",
344             prefs->getDouble("/template/base/guidetolerance", 10.0));
345         sp_repr_set_svg_double(rnew, "inkscape:pageopacity",
346             prefs->getDouble("/template/base/inkscape:pageopacity", 0.0));
347         sp_repr_set_int(rnew, "inkscape:pageshadow",
348             prefs->getInt("/template/base/inkscape:pageshadow", 2));
349         sp_repr_set_int(rnew, "inkscape:window-width",
350             prefs->getInt("/template/base/inkscape:window-width", 640));
351         sp_repr_set_int(rnew, "inkscape:window-height",
352             prefs->getInt("/template/base/inkscape:window-height", 480));
353         
354         // insert into the document
355         rroot->addChild(rnew, NULL);
356         // clean up
357         Inkscape::GC::release(rnew);
358     }
360     /* Defs */
361     if (!SP_ROOT(document->root)->defs) {
362         Inkscape::XML::Node *r;
363         r = rdoc->createElement("svg:defs");
364         rroot->addChild(r, NULL);
365         Inkscape::GC::release(r);
366         g_assert(SP_ROOT(document->root)->defs);
367     }
369     /* Default RDF */
370     rdf_set_defaults( document );
372     if (keepalive) {
373         inkscape_ref();
374     }
376     // Remark: Here, we used to create a "currentpersp3d" element in the document defs.
377     // But this is probably a bad idea since we need to adapt it for every change of selection, which will
378     // completely clutter the undo history. Maybe rather save it to prefs on exit and re-read it on startup?
380     document->current_persp3d = persp3d_document_first_persp(document);
381     if (!document->current_persp3d) {
382         document->current_persp3d = persp3d_create_xml_element (document);
383     }
385     sp_document_set_undo_sensitive(document, true);
387     // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
388     if (!Inkscape::NSApplication::Application::getNewGui()) {
389         g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
390                          G_CALLBACK(sp_document_reset_key), document);
391         g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
392                          G_CALLBACK(sp_document_reset_key), document);
393         document->oldSignalsConnected = true;
394     } else {
395         document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
396         document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
397         document->oldSignalsConnected = false;
398     }
400     return document;
403 /**
404  * Fetches document from URI, or creates new, if NULL; public document
405  * appears in document list.
406  */
407 SPDocument *
408 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
410     SPDocument *doc;
411     Inkscape::XML::Document *rdoc;
412     gchar *base = NULL;
413     gchar *name = NULL;
415     if (uri) {
416         Inkscape::XML::Node *rroot;
417         gchar *s, *p;
418         /* Try to fetch repr from file */
419         rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
420         /* If file cannot be loaded, return NULL without warning */
421         if (rdoc == NULL) return NULL;
422         rroot = rdoc->root();
423         /* If xml file is not svg, return NULL without warning */
424         /* fixme: destroy document */
425         if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
426         s = g_strdup(uri);
427         p = strrchr(s, '/');
428         if (p) {
429             name = g_strdup(p + 1);
430             p[1] = '\0';
431             base = g_strdup(s);
432         } else {
433             base = NULL;
434             name = g_strdup(uri);
435         }
436         g_free(s);
437     } else {
438         rdoc = sp_repr_document_new("svg:svg");
439     }
441     if (make_new) {
442         base = NULL;
443         uri = NULL;
444         name = g_strdup_printf(_("New document %d"), ++doc_count);
445     }
447     //# These should be set by now
448     g_assert(name);
450     doc = sp_document_create(rdoc, uri, base, name, keepalive);
452     g_free(base);
453     g_free(name);
455     return doc;
458 SPDocument *
459 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
461     SPDocument *doc;
462     Inkscape::XML::Document *rdoc;
463     Inkscape::XML::Node *rroot;
464     gchar *name;
466     rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
468     /* If it cannot be loaded, return NULL without warning */
469     if (rdoc == NULL) return NULL;
471     rroot = rdoc->root();
472     /* If xml file is not svg, return NULL without warning */
473     /* fixme: destroy document */
474     if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
476     name = g_strdup_printf(_("Memory document %d"), ++doc_count);
478     doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
480     return doc;
483 SPDocument *
484 sp_document_ref(SPDocument *doc)
486     g_return_val_if_fail(doc != NULL, NULL);
487     Inkscape::GC::anchor(doc);
488     return doc;
491 SPDocument *
492 sp_document_unref(SPDocument *doc)
494     g_return_val_if_fail(doc != NULL, NULL);
495     Inkscape::GC::release(doc);
496     return NULL;
499 gdouble sp_document_width(SPDocument *document)
501     g_return_val_if_fail(document != NULL, 0.0);
502     g_return_val_if_fail(document->priv != NULL, 0.0);
503     g_return_val_if_fail(document->root != NULL, 0.0);
505     SPRoot *root = SP_ROOT(document->root);
507     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set)
508         return root->viewBox.x1 - root->viewBox.x0;
509     return root->width.computed;
512 void
513 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
515     SPRoot *root = SP_ROOT(document->root);
517     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
518         root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
519     } else { // set to width=
520         gdouble old_computed = root->width.computed;
521         root->width.computed = sp_units_get_pixels (width, *unit);
522         /* SVG does not support meters as a unit, so we must translate meters to
523          * cm when writing */
524         if (!strcmp(unit->abbr, "m")) {
525             root->width.value = 100*width;
526             root->width.unit = SVGLength::CM;
527         } else {
528             root->width.value = width;
529             root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
530         }
532         if (root->viewBox_set)
533             root->viewBox.x1 = root->viewBox.x0 + (root->width.computed / old_computed) * (root->viewBox.x1 - root->viewBox.x0);
534     }
536     SP_OBJECT (root)->updateRepr();
539 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
541     SPRoot *root = SP_ROOT(document->root);
543     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
544         root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
545     } else { // set to height=
546         gdouble old_computed = root->height.computed;
547         root->height.computed = sp_units_get_pixels (height, *unit);
548         /* SVG does not support meters as a unit, so we must translate meters to
549          * cm when writing */
550         if (!strcmp(unit->abbr, "m")) {
551             root->height.value = 100*height;
552             root->height.unit = SVGLength::CM;
553         } else {
554             root->height.value = height;
555             root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
556         }
558         if (root->viewBox_set)
559             root->viewBox.y1 = root->viewBox.y0 + (root->height.computed / old_computed) * (root->viewBox.y1 - root->viewBox.y0);
560     }
562     SP_OBJECT (root)->updateRepr();
565 gdouble sp_document_height(SPDocument *document)
567     g_return_val_if_fail(document != NULL, 0.0);
568     g_return_val_if_fail(document->priv != NULL, 0.0);
569     g_return_val_if_fail(document->root != NULL, 0.0);
571     SPRoot *root = SP_ROOT(document->root);
573     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set)
574         return root->viewBox.y1 - root->viewBox.y0;
575     return root->height.computed;
578 Geom::Point sp_document_dimensions(SPDocument *doc)
580     return Geom::Point(sp_document_width(doc), sp_document_height(doc));
583 /**
584  * Given a Geom::Rect that may, for example, correspond to the bbox of an object,
585  * this function fits the canvas to that rect by resizing the canvas
586  * and translating the document root into position.
587  */
588 void SPDocument::fitToRect(Geom::Rect const &rect)
590     double const w = rect.width();
591     double const h = rect.height();
593     double const old_height = sp_document_height(this);
594     SPUnit const &px(sp_unit_get_by_id(SP_UNIT_PX));
595     sp_document_set_width(this, w, &px);
596     sp_document_set_height(this, h, &px);
598     Geom::Translate const tr(Geom::Point(0, (old_height - h))
599                              - to_2geom(rect.min()));
600     SP_GROUP(root)->translateChildItems(tr);
601     SPNamedView *nv = sp_document_namedview(this, 0);
602     if(nv) {
603         Geom::Translate tr2(-rect.min());
604         nv->translateGuides(tr2);
606         // update the viewport so the drawing appears to stay where it was
607         nv->scrollAllDesktops(-tr2[0], tr2[1], false);
608     }
611 void sp_document_set_uri(SPDocument *document, gchar const *uri)
613     g_return_if_fail(document != NULL);
615     if (document->name) {
616         g_free(document->name);
617         document->name = NULL;
618     }
619     if (document->base) {
620         g_free(document->base);
621         document->base = NULL;
622     }
623     if (document->uri) {
624         g_free(document->uri);
625         document->uri = NULL;
626     }
628     if (uri) {
630 #ifndef WIN32
631         prepend_current_dir_if_relative(&(document->uri), uri);
632 #else
633         // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
634         document->uri = g_strdup(uri);
635 #endif
637         /* fixme: Think, what this means for images (Lauris) */
638         document->base = g_path_get_dirname(document->uri);
639         document->name = g_path_get_basename(document->uri);
641     } else {
642         document->uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
643         document->base = NULL;
644         document->name = g_strdup(document->uri);
645     }
647     // Update saveable repr attributes.
648     Inkscape::XML::Node *repr = sp_document_repr_root(document);
649     // changing uri in the document repr must not be not undoable
650     bool saved = sp_document_get_undo_sensitive(document);
651     sp_document_set_undo_sensitive(document, false);
653     repr->setAttribute("sodipodi:docname", document->name);
654     sp_document_set_undo_sensitive(document, saved);
656     document->priv->uri_set_signal.emit(document->uri);
659 void
660 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
662     g_return_if_fail(doc != NULL);
664     doc->priv->resized_signal.emit(width, height);
667 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
669     return priv->modified_signal.connect(slot);
672 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
674     return priv->uri_set_signal.connect(slot);
677 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
679     return priv->resized_signal.connect(slot);
682 sigc::connection
683 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
685     return priv->_reconstruction_start_signal.connect(slot);
688 void
689 SPDocument::emitReconstructionStart(void)
691     // printf("Starting Reconstruction\n");
692     priv->_reconstruction_start_signal.emit();
693     return;
696 sigc::connection
697 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type  slot)
699     return priv->_reconstruction_finish_signal.connect(slot);
702 void
703 SPDocument::emitReconstructionFinish(void)
705     // printf("Finishing Reconstruction\n");
706     priv->_reconstruction_finish_signal.emit();
707     return;
710 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
712     return priv->commit_signal.connect(slot);
717 void SPDocument::_emitModified() {
718     static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
719     root->emitModified(0);
720     priv->modified_signal.emit(flags);
723 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
724     GQuark idq = g_quark_from_string(id);
726     if (object) {
727         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
728         g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
729     } else {
730         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
731         g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
732     }
734     SPDocumentPrivate::IDChangedSignalMap::iterator pos;
736     pos = priv->id_changed_signals.find(idq);
737     if ( pos != priv->id_changed_signals.end() ) {
738         if (!(*pos).second.empty()) {
739             (*pos).second.emit(object);
740         } else { // discard unused signal
741             priv->id_changed_signals.erase(pos);
742         }
743     }
746 void
747 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
749     this->priv->undoStackObservers.add(observer);
752 void
753 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
755     this->priv->undoStackObservers.remove(observer);
758 SPObject *SPDocument::getObjectById(gchar const *id) {
759     g_return_val_if_fail(id != NULL, NULL);
761     GQuark idq = g_quark_from_string(id);
762     return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
765 sigc::connection SPDocument::connectIdChanged(gchar const *id,
766                                               SPDocument::IDChangedSignal::slot_type slot)
768     return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
771 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
772     if (object) {
773         g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
774         g_hash_table_insert(priv->reprdef, repr, object);
775     } else {
776         g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
777         g_hash_table_remove(priv->reprdef, repr);
778     }
781 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
782     g_return_val_if_fail(repr != NULL, NULL);
783     return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
786 Glib::ustring SPDocument::getLanguage() {
787     gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
788     if (document_language) {
789         while (isspace(*document_language))
790             document_language++;
791     }
792     if ( !document_language || 0 == *document_language) {
793         // retrieve system language
794         document_language = getenv("LC_ALL");
795         if ( NULL == document_language || *document_language == 0 ) {
796             document_language = getenv ("LC_MESSAGES");
797         }
798         if ( NULL == document_language || *document_language == 0 ) {
799             document_language = getenv ("LANG");
800         }
802         if ( NULL != document_language ) {
803             gchar *pos = strchr(document_language, '_');
804             if ( NULL != pos ) {
805                 return Glib::ustring(document_language, pos - document_language);
806             }
807         }
808     }
810     if ( NULL == document_language )
811         return Glib::ustring();
812     return document_language;
815 /* Object modification root handler */
817 void
818 sp_document_request_modified(SPDocument *doc)
820     if (!doc->modified_id) {
821         doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
822     }
825 void
826 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
828     ctx->ctx.flags = 0;
829     ctx->i2doc = Geom::identity();
830     /* Set up viewport in case svg has it defined as percentages */
831     if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
832         ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
833         ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
834         ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
835         ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
836     } else { // as a last resort, set size to A4
837         ctx->vp.x0 = 0.0;
838         ctx->vp.y0 = 0.0;
839         ctx->vp.x1 = 210 * PX_PER_MM;
840         ctx->vp.y1 = 297 * PX_PER_MM;
841     }
842     ctx->i2vp = Geom::identity();
845 /**
846  * Tries to update the document state based on the modified and
847  * "update required" flags, and return true if the document has
848  * been brought fully up to date.
849  */
850 bool
851 SPDocument::_updateDocument()
853     /* Process updates */
854     if (this->root->uflags || this->root->mflags) {
855         if (this->root->uflags) {
856             SPItemCtx ctx;
857             sp_document_setup_viewport (this, &ctx);
859             bool saved = sp_document_get_undo_sensitive(this);
860             sp_document_set_undo_sensitive(this, false);
862             this->root->updateDisplay((SPCtx *)&ctx, 0);
864             sp_document_set_undo_sensitive(this, saved);
865         }
866         this->_emitModified();
867     }
869     return !(this->root->uflags || this->root->mflags);
873 /**
874  * Repeatedly works on getting the document updated, since sometimes
875  * it takes more than one pass to get the document updated.  But it
876  * usually should not take more than a few loops, and certainly never
877  * more than 32 iterations.  So we bail out if we hit 32 iterations,
878  * since this typically indicates we're stuck in an update loop.
879  */
880 gint
881 sp_document_ensure_up_to_date(SPDocument *doc)
883     int counter = 32;
884     while (!doc->_updateDocument()) {
885         if (counter == 0) {
886             g_warning("More than 32 iteration while updating document '%s'", doc->uri);
887             break;
888         }
889         counter--;
890     }
892     if (doc->modified_id) {
893         /* Remove handler */
894         gtk_idle_remove(doc->modified_id);
895         doc->modified_id = 0;
896     }
897     return counter>0;
900 /**
901  * An idle handler to update the document.  Returns true if
902  * the document needs further updates.
903  */
904 static gint
905 sp_document_idle_handler(gpointer data)
907     SPDocument *doc = static_cast<SPDocument *>(data);
908     if (doc->_updateDocument()) {
909         doc->modified_id = 0;
910         return false;
911     } else {
912         return true;
913     }
916 static bool is_within(Geom::Rect const &area, Geom::Rect const &box)
918     return area.contains(box);
921 static bool overlaps(Geom::Rect const &area, Geom::Rect const &box)
923     return area.intersects(box);
926 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, Geom::Rect const &area,
927                                   bool (*test)(Geom::Rect const &, Geom::Rect const &), bool take_insensitive = false)
929     g_return_val_if_fail(SP_IS_GROUP(group), s);
931     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
932         if (!SP_IS_ITEM(o)) {
933             continue;
934         }
935         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
936             s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
937         } else {
938             SPItem *child = SP_ITEM(o);
939             Geom::OptRect box = sp_item_bbox_desktop(child);
940             if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
941                 s = g_slist_append(s, child);
942             }
943         }
944     }
946     return s;
949 /**
950 Returns true if an item is among the descendants of group (recursively).
951  */
952 bool item_is_in_group(SPItem *item, SPGroup *group)
954     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
955         if (!SP_IS_ITEM(o)) continue;
956         if (SP_ITEM(o) == item)
957             return true;
958         if (SP_IS_GROUP(o))
959             if (item_is_in_group(item, SP_GROUP(o)))
960                 return true;
961     }
962     return false;
965 /**
966 Returns the bottommost item from the list which is at the point, or NULL if none.
967 */
968 SPItem*
969 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
970                                            Geom::Point const p, bool take_insensitive)
972     g_return_val_if_fail(group, NULL);
973     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
974     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
976     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
978         if (!SP_IS_ITEM(o)) continue;
980         SPItem *item = SP_ITEM(o);
981         NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
982         if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
983             && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
984             if (g_slist_find((GSList *) list, item) != NULL)
985                 return item;
986         }
988         if (SP_IS_GROUP(o)) {
989             SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
990             if (found)
991                 return found;
992         }
994     }
995     return NULL;
998 /**
999 Returns the topmost (in z-order) item from the descendants of group (recursively) which
1000 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
1001 non-layer groups or not. Honors take_insensitive on whether to return insensitive
1002 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
1003 upwards in z-order and returns what it has found so far (i.e. the found item is
1004 guaranteed to be lower than upto).
1005  */
1006 SPItem*
1007 find_item_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
1009     SPItem *seen = NULL, *newseen = NULL;
1010     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1011     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1013     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1014         if (!SP_IS_ITEM(o)) continue;
1016         if (upto && SP_ITEM(o) == upto)
1017             break;
1019         if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
1020             // if nothing found yet, recurse into the group
1021             newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
1022             if (newseen) {
1023                 seen = newseen;
1024                 newseen = NULL;
1025             }
1027             if (item_is_in_group(upto, SP_GROUP(o)))
1028                 break;
1030         } else {
1031             SPItem *child = SP_ITEM(o);
1032             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1034             // seen remembers the last (topmost) of items pickable at this point
1035             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1036                 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1037                 seen = child;
1038             }
1039         }
1040     }
1041     return seen;
1044 /**
1045 Returns the topmost non-layer group from the descendants of group which is at point
1046 p, or NULL if none. Recurses into layers but not into groups.
1047  */
1048 SPItem*
1049 find_group_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p)
1051     SPItem *seen = NULL;
1052     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1053     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1055     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1056         if (!SP_IS_ITEM(o)) continue;
1057         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1058             SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1059             if (newseen) {
1060                 seen = newseen;
1061             }
1062         }
1063         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1064             SPItem *child = SP_ITEM(o);
1065             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1067             // seen remembers the last (topmost) of groups pickable at this point
1068             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1069                 seen = child;
1070             }
1071         }
1072     }
1073     return seen;
1076 /*
1077  * Return list of items, contained in box
1078  *
1079  * Assumes box is normalized (and g_asserts it!)
1080  *
1081  */
1083 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1085     g_return_val_if_fail(document != NULL, NULL);
1086     g_return_val_if_fail(document->priv != NULL, NULL);
1088     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
1091 /*
1092  * Return list of items, that the parts of the item contained in box
1093  *
1094  * Assumes box is normalized (and g_asserts it!)
1095  *
1096  */
1098 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1100     g_return_val_if_fail(document != NULL, NULL);
1101     g_return_val_if_fail(document->priv != NULL, NULL);
1103     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1106 GSList *
1107 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<Geom::Point> points)
1109     GSList *items = NULL;
1110     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1112     // When picking along the path, we don't want small objects close together
1113     // (such as hatching strokes) to obscure each other by their deltas,
1114     // so we temporarily set delta to a small value
1115     gdouble saved_delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1116     prefs->setDouble("/options/cursortolerance/value", 0.25);
1118     for(unsigned int i = 0; i < points.size(); i++) {
1119         SPItem *item = sp_document_item_at_point(document, key, points[i],
1120                                                  false, NULL);
1121         if (item && !g_slist_find(items, item))
1122             items = g_slist_prepend (items, item);
1123     }
1125     // and now we restore it back
1126     prefs->setDouble("/options/cursortolerance/value", saved_delta);
1128     return items;
1131 SPItem *
1132 sp_document_item_at_point(SPDocument *document, unsigned const key, Geom::Point const p,
1133                           gboolean const into_groups, SPItem *upto)
1135     g_return_val_if_fail(document != NULL, NULL);
1136     g_return_val_if_fail(document->priv != NULL, NULL);
1138     return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1141 SPItem*
1142 sp_document_group_at_point(SPDocument *document, unsigned int key, Geom::Point const p)
1144     g_return_val_if_fail(document != NULL, NULL);
1145     g_return_val_if_fail(document->priv != NULL, NULL);
1147     return find_group_at_point(key, SP_GROUP(document->root), p);
1151 /* Resource management */
1153 gboolean
1154 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1156     GSList *rlist;
1157     GQuark q = g_quark_from_string(key);
1159     g_return_val_if_fail(document != NULL, FALSE);
1160     g_return_val_if_fail(key != NULL, FALSE);
1161     g_return_val_if_fail(*key != '\0', FALSE);
1162     g_return_val_if_fail(object != NULL, FALSE);
1163     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1165     if (SP_OBJECT_IS_CLONED(object))
1166         return FALSE;
1168     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1169     g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1170     rlist = g_slist_prepend(rlist, object);
1171     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1173     document->priv->resources_changed_signals[q].emit();
1175     return TRUE;
1178 gboolean
1179 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1181     GSList *rlist;
1182     GQuark q = g_quark_from_string(key);
1184     g_return_val_if_fail(document != NULL, FALSE);
1185     g_return_val_if_fail(key != NULL, FALSE);
1186     g_return_val_if_fail(*key != '\0', FALSE);
1187     g_return_val_if_fail(object != NULL, FALSE);
1188     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1190     if (SP_OBJECT_IS_CLONED(object))
1191         return FALSE;
1193     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1194     g_return_val_if_fail(rlist != NULL, FALSE);
1195     g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1196     rlist = g_slist_remove(rlist, object);
1197     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1199     document->priv->resources_changed_signals[q].emit();
1201     return TRUE;
1204 GSList const *
1205 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1207     g_return_val_if_fail(document != NULL, NULL);
1208     g_return_val_if_fail(key != NULL, NULL);
1209     g_return_val_if_fail(*key != '\0', NULL);
1211     return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1214 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1215                                                        gchar const *key,
1216                                                        SPDocument::ResourcesChangedSignal::slot_type slot)
1218     GQuark q = g_quark_from_string(key);
1219     return document->priv->resources_changed_signals[q].connect(slot);
1222 /* Helpers */
1224 gboolean
1225 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1227     g_slist_free((GSList *) value);
1228     return TRUE;
1231 unsigned int
1232 count_objects_recursive(SPObject *obj, unsigned int count)
1234     count++; // obj itself
1236     for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1237         count = count_objects_recursive(i, count);
1238     }
1240     return count;
1243 unsigned int
1244 objects_in_document(SPDocument *document)
1246     return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1249 void
1250 vacuum_document_recursive(SPObject *obj)
1252     if (SP_IS_DEFS(obj)) {
1253         for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1254             /* fixme: some inkscape-internal nodes in the future might not be collectable */
1255             def->requestOrphanCollection();
1256         }
1257     } else {
1258         for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1259             vacuum_document_recursive(i);
1260         }
1261     }
1264 unsigned int
1265 vacuum_document(SPDocument *document)
1267     unsigned int start = objects_in_document(document);
1268     unsigned int end;
1269     unsigned int newend = start;
1271     unsigned int iterations = 0;
1273     do {
1274         end = newend;
1276         vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1277         document->collectOrphans();
1278         iterations++;
1280         newend = objects_in_document(document);
1282     } while (iterations < 100 && newend < end);
1284     return start - newend;
1287 bool SPDocument::isSeeking() const {
1288     return priv->seeking;
1292 /*
1293   Local Variables:
1294   mode:c++
1295   c-file-style:"stroustrup"
1296   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1297   indent-tabs-mode:nil
1298   fill-column:99
1299   End:
1300 */
1301 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :