Code

Merge and cleanup of GSoC C++-ification project.
[inkscape.git] / src / document.cpp
1 /** \file
2  * SPDocument manipulation
3  *
4  * Authors:
5  *   Lauris Kaplinski <lauris@kaplinski.com>
6  *   MenTaLguY <mental@rydia.net>
7  *   bulia byak <buliabyak@users.sf.net>
8  *   Jon A. Cruz <jon@joncruz.org>
9  *   Abhishek Sharma
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 "desktop.h"
45 #include "dir-util.h"
46 #include "display/nr-arena-item.h"
47 #include "document-private.h"
48 #include "helper/units.h"
49 #include "inkscape-private.h"
50 #include "inkscape-version.h"
51 #include "libavoid/router.h"
52 #include "persp3d.h"
53 #include "preferences.h"
54 #include "profile-manager.h"
55 #include "rdf.h"
56 #include "sp-item-group.h"
57 #include "sp-namedview.h"
58 #include "sp-object-repr.h"
59 #include "transf_mat_3x4.h"
60 #include "unit-constants.h"
61 #include "xml/repr.h"
62 #include "xml/rebase-hrefs.h"
64 using Inkscape::DocumentUndo;
66 // Higher number means lower priority.
67 #define SP_DOCUMENT_UPDATE_PRIORITY (G_PRIORITY_HIGH_IDLE - 2)
69 // Should have a lower priority than SP_DOCUMENT_UPDATE_PRIORITY,
70 // since we want it to happen when there are no more updates.
71 #define SP_DOCUMENT_REROUTING_PRIORITY (G_PRIORITY_HIGH_IDLE - 1)
74 static gint sp_document_idle_handler(gpointer data);
75 static gint sp_document_rerouting_handler(gpointer data);
77 gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data);
79 static gint doc_count = 0;
81 static unsigned long next_serial = 0;
83 SPDocument::SPDocument() :
84     keepalive(FALSE),
85     virgin(TRUE),
86     modified_since_save(FALSE),
87     rdoc(0),
88     rroot(0),
89     root(0),
90     style_cascade(cr_cascade_new(NULL, NULL, NULL)),
91     uri(0),
92     base(0),
93     name(0),
94     priv(0), // reset in ctor
95     actionkey(),
96     modified_id(0),
97     rerouting_handler_id(0),
98     profileManager(0), // deferred until after other initialization
99     router(new Avoid::Router(Avoid::PolyLineRouting|Avoid::OrthogonalRouting)),
100     _collection_queue(0),
101     oldSignalsConnected(false),
102     current_persp3d(0)
104     // Penalise libavoid for choosing paths with needless extra segments.
105     // This results in much better looking orthogonal connector paths.
106     router->setRoutingPenalty(Avoid::segmentPenalty);
108     SPDocumentPrivate *p = new SPDocumentPrivate();
110     p->serial = next_serial++;
112     p->iddef = g_hash_table_new(g_direct_hash, g_direct_equal);
113     p->reprdef = g_hash_table_new(g_direct_hash, g_direct_equal);
115     p->resources = g_hash_table_new(g_str_hash, g_str_equal);
117     p->sensitive = FALSE;
118     p->partial = NULL;
119     p->history_size = 0;
120     p->undo = NULL;
121     p->redo = NULL;
122     p->seeking = false;
124     priv = p;
126     // Once things are set, hook in the manager
127     profileManager = new Inkscape::ProfileManager(this);
129     // XXX only for testing!
130     priv->undoStackObservers.add(p->console_output_undo_observer);
133 SPDocument::~SPDocument() {
134     collectOrphans();
136     // kill/unhook this first
137     if ( profileManager ) {
138         delete profileManager;
139         profileManager = 0;
140     }
142     if (router) {
143         delete router;
144         router = NULL;
145     }
147     if (priv) {
148         if (priv->partial) {
149             sp_repr_free_log(priv->partial);
150             priv->partial = NULL;
151         }
153         DocumentUndo::clearRedo(this);
154         DocumentUndo::clearUndo(this);
156         if (root) {
157             root->releaseReferences();
158             sp_object_unref(root);
159             root = NULL;
160         }
162         if (priv->iddef) g_hash_table_destroy(priv->iddef);
163         if (priv->reprdef) g_hash_table_destroy(priv->reprdef);
165         if (rdoc) Inkscape::GC::release(rdoc);
167         /* Free resources */
168         g_hash_table_foreach_remove(priv->resources, sp_document_resource_list_free, this);
169         g_hash_table_destroy(priv->resources);
171         delete priv;
172         priv = NULL;
173     }
175     cr_cascade_unref(style_cascade);
176     style_cascade = NULL;
178     if (name) {
179         g_free(name);
180         name = NULL;
181     }
182     if (base) {
183         g_free(base);
184         base = NULL;
185     }
186     if (uri) {
187         g_free(uri);
188         uri = NULL;
189     }
191     if (modified_id) {
192         g_source_remove(modified_id);
193         modified_id = 0;
194     }
196     if (rerouting_handler_id) {
197         g_source_remove(rerouting_handler_id);
198         rerouting_handler_id = 0;
199     }
201     if (oldSignalsConnected) {
202         g_signal_handlers_disconnect_by_func(G_OBJECT(INKSCAPE),
203                                              reinterpret_cast<gpointer>(DocumentUndo::resetKey),
204                                              static_cast<gpointer>(this));
205     } else {
206         _selection_changed_connection.disconnect();
207         _desktop_activated_connection.disconnect();
208     }
210     if (keepalive) {
211         inkscape_unref();
212         keepalive = FALSE;
213     }
214     //delete this->_whiteboard_session_manager;
217 Persp3D *
218 SPDocument::getCurrentPersp3D() {
219     // Check if current_persp3d is still valid
220     std::vector<Persp3D*> plist;
221     getPerspectivesInDefs(plist);
222     for (unsigned int i = 0; i < plist.size(); ++i) {
223         if (current_persp3d == plist[i])
224             return current_persp3d;
225     }
227     // If not, return the first perspective in defs (which may be NULL of none exists)
228     current_persp3d = persp3d_document_first_persp (this);
230     return current_persp3d;
233 Persp3DImpl *
234 SPDocument::getCurrentPersp3DImpl() {
235     return current_persp3d_impl;
238 void
239 SPDocument::setCurrentPersp3D(Persp3D * const persp) {
240     current_persp3d = persp;
241     //current_persp3d_impl = persp->perspective_impl;
244 void SPDocument::getPerspectivesInDefs(std::vector<Persp3D*> &list) const
246     SPDefs *defs = SP_ROOT(this->root)->defs;
247     for (SPObject *i = defs->firstChild(); i; i = i->getNext() ) {
248         if (SP_IS_PERSP3D(i)) {
249             list.push_back(SP_PERSP3D(i));
250         }
251     }
254 /**
255 void SPDocument::initialize_current_persp3d()
257     this->current_persp3d = persp3d_document_first_persp(this);
258     if (!this->current_persp3d) {
259         this->current_persp3d = persp3d_create_xml_element(this);
260     }
262 **/
264 unsigned long SPDocument::serial() const {
265     return priv->serial;
268 void SPDocument::queueForOrphanCollection(SPObject *object) {
269     g_return_if_fail(object != NULL);
270     g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
272     sp_object_ref(object, NULL);
273     _collection_queue = g_slist_prepend(_collection_queue, object);
276 void SPDocument::collectOrphans() {
277     while (_collection_queue) {
278         GSList *objects=_collection_queue;
279         _collection_queue = NULL;
280         for ( GSList *iter=objects ; iter ; iter = iter->next ) {
281             SPObject *object=reinterpret_cast<SPObject *>(iter->data);
282             object->collectOrphan();
283             sp_object_unref(object, NULL);
284         }
285         g_slist_free(objects);
286     }
289 void SPDocument::reset_key (void */*dummy*/)
291     actionkey.clear();
294 SPDocument *SPDocument::createDoc(Inkscape::XML::Document *rdoc,
295                                   gchar const *uri,
296                                   gchar const *base,
297                                   gchar const *name,
298                                   unsigned int keepalive)
300     SPDocument *document = new SPDocument();
302     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
303     Inkscape::XML::Node *rroot = rdoc->root();
305     document->keepalive = keepalive;
307     document->rdoc = rdoc;
308     document->rroot = rroot;
310 #ifndef WIN32
311     document->uri = prepend_current_dir_if_relative(uri);
312 #else
313     // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
314     document->uri = uri? g_strdup(uri) : NULL;
315 #endif
317     // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
318     // which is why we use g_get_current_dir() in calculating the abs path above
319     //This is NULL for a new document
320     if (base) {
321         document->base = g_strdup(base);
322     } else {
323         document->base = NULL;
324     }
325     document->name = g_strdup(name);
327     document->root = sp_object_repr_build_tree(document, rroot);
329     /* fixme: Not sure about this, but lets assume ::build updates */
330     rroot->setAttribute("inkscape:version", Inkscape::version_string);
331     /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
333     /* Quick hack 2 - get default image size into document */
334     if (!rroot->attribute("width")) rroot->setAttribute("width", "100%");
335     if (!rroot->attribute("height")) rroot->setAttribute("height", "100%");
336     /* End of quick hack 2 */
338     /* Quick hack 3 - Set uri attributes */
339     if (uri) {
340         rroot->setAttribute("sodipodi:docname", uri);
341     }
342     /* End of quick hack 3 */
344     /* Eliminate obsolete sodipodi:docbase, for privacy reasons */
345     rroot->setAttribute("sodipodi:docbase", NULL);
347     /* Eliminate any claim to adhere to a profile, as we don't try to */
348     rroot->setAttribute("baseProfile", NULL);
350     // creating namedview
351     if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
352         // if there's none in the document already,
353         Inkscape::XML::Node *rnew = NULL;
355         rnew = rdoc->createElement("sodipodi:namedview");
356         //rnew->setAttribute("id", "base");
358         // Add namedview data from the preferences
359         // we can't use getAllEntries because this could produce non-SVG doubles
360         Glib::ustring pagecolor = prefs->getString("/template/base/pagecolor");
361         if (!pagecolor.empty()) {
362             rnew->setAttribute("pagecolor", pagecolor.data());
363         }
364         Glib::ustring bordercolor = prefs->getString("/template/base/bordercolor");
365         if (!bordercolor.empty()) {
366             rnew->setAttribute("bordercolor", bordercolor.data());
367         }
368         sp_repr_set_svg_double(rnew, "borderopacity",
369             prefs->getDouble("/template/base/borderopacity", 1.0));
370         sp_repr_set_svg_double(rnew, "objecttolerance",
371             prefs->getDouble("/template/base/objecttolerance", 10.0));
372         sp_repr_set_svg_double(rnew, "gridtolerance",
373             prefs->getDouble("/template/base/gridtolerance", 10.0));
374         sp_repr_set_svg_double(rnew, "guidetolerance",
375             prefs->getDouble("/template/base/guidetolerance", 10.0));
376         sp_repr_set_svg_double(rnew, "inkscape:pageopacity",
377             prefs->getDouble("/template/base/inkscape:pageopacity", 0.0));
378         sp_repr_set_int(rnew, "inkscape:pageshadow",
379             prefs->getInt("/template/base/inkscape:pageshadow", 2));
380         sp_repr_set_int(rnew, "inkscape:window-width",
381             prefs->getInt("/template/base/inkscape:window-width", 640));
382         sp_repr_set_int(rnew, "inkscape:window-height",
383             prefs->getInt("/template/base/inkscape:window-height", 480));
385         // insert into the document
386         rroot->addChild(rnew, NULL);
387         // clean up
388         Inkscape::GC::release(rnew);
389     }
391     /* Defs */
392     if (!SP_ROOT(document->root)->defs) {
393         Inkscape::XML::Node *r;
394         r = rdoc->createElement("svg:defs");
395         rroot->addChild(r, NULL);
396         Inkscape::GC::release(r);
397         g_assert(SP_ROOT(document->root)->defs);
398     }
400     /* Default RDF */
401     rdf_set_defaults( document );
403     if (keepalive) {
404         inkscape_ref();
405     }
407     // Check if the document already has a perspective (e.g., when opening an existing
408     // document). If not, create a new one and set it as the current perspective.
409     document->setCurrentPersp3D(persp3d_document_first_persp(document));
410     if (!document->getCurrentPersp3D()) {
411         //document->setCurrentPersp3D(persp3d_create_xml_element (document));
412         Persp3DImpl *persp_impl = new Persp3DImpl();
413         document->setCurrentPersp3DImpl(persp_impl);
414     }
416     DocumentUndo::setUndoSensitive(document, true);
418     // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
419     g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
420                      G_CALLBACK(DocumentUndo::resetKey), document);
421     g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
422                      G_CALLBACK(DocumentUndo::resetKey), document);
423     document->oldSignalsConnected = true;
425     return document;
428 /**
429  * Fetches document from URI, or creates new, if NULL; public document
430  * appears in document list.
431  */
432 SPDocument *SPDocument::createNewDoc(gchar const *uri, unsigned int keepalive, bool make_new)
434     SPDocument *doc;
435     Inkscape::XML::Document *rdoc;
436     gchar *base = NULL;
437     gchar *name = NULL;
439     if (uri) {
440         Inkscape::XML::Node *rroot;
441         gchar *s, *p;
442         /* Try to fetch repr from file */
443         rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
444         /* If file cannot be loaded, return NULL without warning */
445         if (rdoc == NULL) return NULL;
446         rroot = rdoc->root();
447         /* If xml file is not svg, return NULL without warning */
448         /* fixme: destroy document */
449         if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
450         s = g_strdup(uri);
451         p = strrchr(s, '/');
452         if (p) {
453             name = g_strdup(p + 1);
454             p[1] = '\0';
455             base = g_strdup(s);
456         } else {
457             base = NULL;
458             name = g_strdup(uri);
459         }
460         g_free(s);
461     } else {
462         rdoc = sp_repr_document_new("svg:svg");
463     }
465     if (make_new) {
466         base = NULL;
467         uri = NULL;
468         name = g_strdup_printf(_("New document %d"), ++doc_count);
469     }
471     //# These should be set by now
472     g_assert(name);
474     doc = createDoc(rdoc, uri, base, name, keepalive);
476     g_free(base);
477     g_free(name);
479     return doc;
482 SPDocument *SPDocument::createNewDocFromMem(gchar const *buffer, gint length, unsigned int keepalive)
484     SPDocument *doc;
485     Inkscape::XML::Document *rdoc;
486     Inkscape::XML::Node *rroot;
487     gchar *name;
489     rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
491     /* If it cannot be loaded, return NULL without warning */
492     if (rdoc == NULL) return NULL;
494     rroot = rdoc->root();
495     /* If xml file is not svg, return NULL without warning */
496     /* fixme: destroy document */
497     if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
499     name = g_strdup_printf(_("Memory document %d"), ++doc_count);
501     doc = createDoc(rdoc, NULL, NULL, name, keepalive);
503     return doc;
506 SPDocument *SPDocument::doRef()
508     Inkscape::GC::anchor(this);
509     return this;
512 SPDocument *SPDocument::doUnref()
514     Inkscape::GC::release(this);
515     return NULL;
518 gdouble SPDocument::getWidth() const
520     g_return_val_if_fail(this->priv != NULL, 0.0);
521     g_return_val_if_fail(this->root != NULL, 0.0);
523     SPRoot *root = SP_ROOT(this->root);
525     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set)
526         return root->viewBox.x1 - root->viewBox.x0;
527     return root->width.computed;
530 void SPDocument::setWidth(gdouble width, const SPUnit *unit)
532     SPRoot *root = SP_ROOT(this->root);
534     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
535         root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
536     } else { // set to width=
537         gdouble old_computed = root->width.computed;
538         root->width.computed = sp_units_get_pixels (width, *unit);
539         /* SVG does not support meters as a unit, so we must translate meters to
540          * cm when writing */
541         if (!strcmp(unit->abbr, "m")) {
542             root->width.value = 100*width;
543             root->width.unit = SVGLength::CM;
544         } else {
545             root->width.value = width;
546             root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
547         }
549         if (root->viewBox_set)
550             root->viewBox.x1 = root->viewBox.x0 + (root->width.computed / old_computed) * (root->viewBox.x1 - root->viewBox.x0);
551     }
553     SP_OBJECT (root)->updateRepr();
556 void SPDocument::setHeight(gdouble height, const SPUnit *unit)
558     SPRoot *root = SP_ROOT(this->root);
560     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
561         root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
562     } else { // set to height=
563         gdouble old_computed = root->height.computed;
564         root->height.computed = sp_units_get_pixels (height, *unit);
565         /* SVG does not support meters as a unit, so we must translate meters to
566          * cm when writing */
567         if (!strcmp(unit->abbr, "m")) {
568             root->height.value = 100*height;
569             root->height.unit = SVGLength::CM;
570         } else {
571             root->height.value = height;
572             root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
573         }
575         if (root->viewBox_set)
576             root->viewBox.y1 = root->viewBox.y0 + (root->height.computed / old_computed) * (root->viewBox.y1 - root->viewBox.y0);
577     }
579     SP_OBJECT (root)->updateRepr();
582 gdouble SPDocument::getHeight() const
584     g_return_val_if_fail(this->priv != NULL, 0.0);
585     g_return_val_if_fail(this->root != NULL, 0.0);
587     SPRoot *root = SP_ROOT(this->root);
589     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set)
590         return root->viewBox.y1 - root->viewBox.y0;
591     return root->height.computed;
594 Geom::Point SPDocument::getDimensions() const
596     return Geom::Point(getWidth(), getHeight());
599 /**
600  * Given a Geom::Rect that may, for example, correspond to the bbox of an object,
601  * this function fits the canvas to that rect by resizing the canvas
602  * and translating the document root into position.
603  * \param rect fit document size to this
604  * \param with_margins add margins to rect, by taking margins from this
605  *        document's namedview (<sodipodi:namedview> "fit-margin-..."
606  *        attributes, and "units")
607  */
608 void SPDocument::fitToRect(Geom::Rect const &rect, bool with_margins)
610     double const w = rect.width();
611     double const h = rect.height();
613     double const old_height = getHeight();
614     SPUnit const &px(sp_unit_get_by_id(SP_UNIT_PX));
615     
616     /* in px */
617     double margin_top = 0.0;
618     double margin_left = 0.0;
619     double margin_right = 0.0;
620     double margin_bottom = 0.0;
621     
622     SPNamedView *nv = sp_document_namedview(this, 0);
623     
624     if (with_margins && nv) {
625         if (nv != NULL) {
626             gchar const * const units_abbr = nv->getAttribute("units");
627             SPUnit const *margin_units = NULL;
628             if (units_abbr != NULL) {
629                 margin_units = sp_unit_get_by_abbreviation(units_abbr);
630             }
631             if (margin_units == NULL) {
632                 margin_units = &px;
633             }
634             margin_top = nv->getMarginLength("fit-margin-top",margin_units, &px, w, h, false);
635             margin_top = nv->getMarginLength("fit-margin-left",margin_units, &px, w, h, true);
636             margin_top = nv->getMarginLength("fit-margin-right",margin_units, &px, w, h, true);
637             margin_top = nv->getMarginLength("fit-margin-bottom",margin_units, &px, w, h, false);
638         }
639     }
640     
641     Geom::Rect const rect_with_margins(
642             rect.min() - Geom::Point(margin_left, margin_bottom),
643             rect.max() + Geom::Point(margin_right, margin_top));
644     
645     
646     setWidth(rect_with_margins.width(), &px);
647     setHeight(rect_with_margins.height(), &px);
649     Geom::Translate const tr(
650             Geom::Point(0, old_height - rect_with_margins.height())
651             - to_2geom(rect_with_margins.min()));
652     SP_GROUP(root)->translateChildItems(tr);
654     if(nv) {
655         Geom::Translate tr2(-rect_with_margins.min());
656         nv->translateGuides(tr2);
658         // update the viewport so the drawing appears to stay where it was
659         nv->scrollAllDesktops(-tr2[0], tr2[1], false);
660     }
663 void SPDocument::setBase( gchar const* base )
665     if (this->base) {
666         g_free(this->base);
667         this->base = 0;
668     }
669     if (base) {
670         this->base = g_strdup(base);
671     }
674 void SPDocument::do_change_uri(gchar const *const filename, bool const rebase)
676     gchar *new_base = 0;
677     gchar *new_name = 0;
678     gchar *new_uri = 0;
679     if (filename) {
681 #ifndef WIN32
682         new_uri = prepend_current_dir_if_relative(filename);
683 #else
684         // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
685         new_uri = g_strdup(filename);
686 #endif
688         new_base = g_path_get_dirname(new_uri);
689         new_name = g_path_get_basename(new_uri);
690     } else {
691         new_uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
692         new_base = NULL;
693         new_name = g_strdup(this->uri);
694     }
696     // Update saveable repr attributes.
697     Inkscape::XML::Node *repr = getReprRoot();
699     // Changing uri in the document repr must not be not undoable.
700     bool const saved = DocumentUndo::getUndoSensitive(this);
701     DocumentUndo::setUndoSensitive(this, false);
703     if (rebase) {
704         Inkscape::XML::rebase_hrefs(this, new_base, true);
705     }
707     repr->setAttribute("sodipodi:docname", this->name);
708     DocumentUndo::setUndoSensitive(this, saved);
711     g_free(this->name);
712     g_free(this->base);
713     g_free(this->uri);
714     this->name = new_name;
715     this->base = new_base;
716     this->uri = new_uri;
718     this->priv->uri_set_signal.emit(this->uri);
721 /**
722  * Sets base, name and uri members of \a document.  Doesn't update
723  * any relative hrefs in the document: thus, this is primarily for
724  * newly-created documents.
725  *
726  * \see sp_document_change_uri_and_hrefs
727  */
728 void SPDocument::setUri(gchar const *filename)
730     do_change_uri(filename, false);
733 /**
734  * Changes the base, name and uri members of \a document, and updates any
735  * relative hrefs in the document to be relative to the new base.
736  *
737  * \see sp_document_set_uri
738  */
739 void SPDocument::changeUriAndHrefs(gchar const *filename)
741     do_change_uri(filename, true);
744 void SPDocument::emitResizedSignal(gdouble width, gdouble height)
746     this->priv->resized_signal.emit(width, height);
749 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
751     return priv->modified_signal.connect(slot);
754 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
756     return priv->uri_set_signal.connect(slot);
759 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
761     return priv->resized_signal.connect(slot);
764 sigc::connection
765 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
767     return priv->_reconstruction_start_signal.connect(slot);
770 void
771 SPDocument::emitReconstructionStart(void)
773     // printf("Starting Reconstruction\n");
774     priv->_reconstruction_start_signal.emit();
775     return;
778 sigc::connection
779 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type  slot)
781     return priv->_reconstruction_finish_signal.connect(slot);
784 void
785 SPDocument::emitReconstructionFinish(void)
787     // printf("Finishing Reconstruction\n");
788     priv->_reconstruction_finish_signal.emit();
790 /**    
791     // Reference to the old persp3d object is invalid after reconstruction.
792     initialize_current_persp3d();
793     
794     return;
795 **/
798 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
800     return priv->commit_signal.connect(slot);
805 void SPDocument::_emitModified() {
806     static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
807     root->emitModified(0);
808     priv->modified_signal.emit(flags);
811 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
812     GQuark idq = g_quark_from_string(id);
814     if (object) {
815         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
816         g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
817     } else {
818         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
819         g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
820     }
822     SPDocumentPrivate::IDChangedSignalMap::iterator pos;
824     pos = priv->id_changed_signals.find(idq);
825     if ( pos != priv->id_changed_signals.end() ) {
826         if (!(*pos).second.empty()) {
827             (*pos).second.emit(object);
828         } else { // discard unused signal
829             priv->id_changed_signals.erase(pos);
830         }
831     }
834 void
835 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
837     this->priv->undoStackObservers.add(observer);
840 void
841 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
843     this->priv->undoStackObservers.remove(observer);
846 SPObject *SPDocument::getObjectById(gchar const *id) const
848     g_return_val_if_fail(id != NULL, NULL);
850     GQuark idq = g_quark_from_string(id);
851     return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
854 sigc::connection SPDocument::connectIdChanged(gchar const *id,
855                                               SPDocument::IDChangedSignal::slot_type slot)
857     return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
860 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object)
862     if (object) {
863         g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
864         g_hash_table_insert(priv->reprdef, repr, object);
865     } else {
866         g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
867         g_hash_table_remove(priv->reprdef, repr);
868     }
871 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) const
873     g_return_val_if_fail(repr != NULL, NULL);
874     return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
877 Glib::ustring SPDocument::getLanguage() const
879     gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
880     if (document_language) {
881         while (isspace(*document_language))
882             document_language++;
883     }
884     if ( !document_language || 0 == *document_language) {
885         // retrieve system language
886         document_language = getenv("LC_ALL");
887         if ( NULL == document_language || *document_language == 0 ) {
888             document_language = getenv ("LC_MESSAGES");
889         }
890         if ( NULL == document_language || *document_language == 0 ) {
891             document_language = getenv ("LANG");
892         }
894         if ( NULL != document_language ) {
895             const char *pos = strchr(document_language, '_');
896             if ( NULL != pos ) {
897                 return Glib::ustring(document_language, pos - document_language);
898             }
899         }
900     }
902     if ( NULL == document_language )
903         return Glib::ustring();
904     return document_language;
907 /* Object modification root handler */
909 void SPDocument::requestModified()
911     if (!modified_id) {
912         modified_id = g_idle_add_full(SP_DOCUMENT_UPDATE_PRIORITY, 
913                 sp_document_idle_handler, this, NULL);
914     }
915     if (!rerouting_handler_id) {
916         rerouting_handler_id = g_idle_add_full(SP_DOCUMENT_REROUTING_PRIORITY, 
917                 sp_document_rerouting_handler, this, NULL);
918     }
921 void
922 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
924     ctx->ctx.flags = 0;
925     ctx->i2doc = Geom::identity();
926     /* Set up viewport in case svg has it defined as percentages */
927     if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
928         ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
929         ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
930         ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
931         ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
932     } else { // as a last resort, set size to A4
933         ctx->vp.x0 = 0.0;
934         ctx->vp.y0 = 0.0;
935         ctx->vp.x1 = 210 * PX_PER_MM;
936         ctx->vp.y1 = 297 * PX_PER_MM;
937     }
938     ctx->i2vp = Geom::identity();
941 /**
942  * Tries to update the document state based on the modified and
943  * "update required" flags, and return true if the document has
944  * been brought fully up to date.
945  */
946 bool
947 SPDocument::_updateDocument()
949     /* Process updates */
950     if (this->root->uflags || this->root->mflags) {
951         if (this->root->uflags) {
952             SPItemCtx ctx;
953             sp_document_setup_viewport (this, &ctx);
955             bool saved = DocumentUndo::getUndoSensitive(this);
956             DocumentUndo::setUndoSensitive(this, false);
958             this->root->updateDisplay((SPCtx *)&ctx, 0);
960             DocumentUndo::setUndoSensitive(this, saved);
961         }
962         this->_emitModified();
963     }
965     return !(this->root->uflags || this->root->mflags);
969 /**
970  * Repeatedly works on getting the document updated, since sometimes
971  * it takes more than one pass to get the document updated.  But it
972  * usually should not take more than a few loops, and certainly never
973  * more than 32 iterations.  So we bail out if we hit 32 iterations,
974  * since this typically indicates we're stuck in an update loop.
975  */
976 gint SPDocument::ensureUpToDate()
978     // Bring the document up-to-date, specifically via the following:
979     //   1a) Process all document updates.
980     //   1b) When completed, process connector routing changes.
981     //   2a) Process any updates resulting from connector reroutings.
982     int counter = 32;
983     for (unsigned int pass = 1; pass <= 2; ++pass) {
984         // Process document updates.
985         while (!_updateDocument()) {
986             if (counter == 0) {
987                 g_warning("More than 32 iteration while updating document '%s'", uri);
988                 break;
989             }
990             counter--;
991         }
992         if (counter == 0)
993         {
994             break;
995         }
997         // After updates on the first pass we get libavoid to process all the 
998         // changed objects and provide new routings.  This may cause some objects
999             // to be modified, hence the second update pass.
1000         if (pass == 1) {
1001             router->processTransaction();
1002         }
1003     }
1004     
1005     if (modified_id) {
1006         // Remove handler
1007         g_source_remove(modified_id);
1008         modified_id = 0;
1009     }
1010     if (rerouting_handler_id) {
1011         // Remove handler
1012         g_source_remove(rerouting_handler_id);
1013         rerouting_handler_id = 0;
1014     }
1015     return counter>0;
1018 /**
1019  * An idle handler to update the document.  Returns true if
1020  * the document needs further updates.
1021  */
1022 static gint
1023 sp_document_idle_handler(gpointer data)
1025     SPDocument *doc = static_cast<SPDocument *>(data);
1026     if (doc->_updateDocument()) {
1027         doc->modified_id = 0;
1028         return false;
1029     } else {
1030         return true;
1031     }
1034 /**
1035  * An idle handler to reroute connectors in the document.  
1036  */
1037 static gint
1038 sp_document_rerouting_handler(gpointer data)
1040     // Process any queued movement actions and determine new routings for 
1041     // object-avoiding connectors.  Callbacks will be used to update and 
1042     // redraw affected connectors.
1043     SPDocument *doc = static_cast<SPDocument *>(data);
1044     doc->router->processTransaction();
1045     
1046     // We don't need to handle rerouting again until there are further 
1047     // diagram updates.
1048     doc->rerouting_handler_id = 0;
1049     return false;
1052 static bool is_within(Geom::Rect const &area, Geom::Rect const &box)
1054     return area.contains(box);
1057 static bool overlaps(Geom::Rect const &area, Geom::Rect const &box)
1059     return area.intersects(box);
1062 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, Geom::Rect const &area,
1063                                   bool (*test)(Geom::Rect const &, Geom::Rect const &), bool take_insensitive = false)
1065     g_return_val_if_fail(SP_IS_GROUP(group), s);
1067     for ( SPObject *o = group->firstChild() ; o ; o = o->getNext() ) {
1068         if ( SP_IS_ITEM(o) ) {
1069             if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
1070                 s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
1071             } else {
1072                 SPItem *child = SP_ITEM(o);
1073                 Geom::OptRect box = child->getBboxDesktop();
1074                 if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1075                     s = g_slist_append(s, child);
1076                 }
1077             }
1078         }
1079     }
1081     return s;
1084 /**
1085 Returns true if an item is among the descendants of group (recursively).
1086  */
1087 bool item_is_in_group(SPItem *item, SPGroup *group)
1089     bool inGroup = false;
1090     for ( SPObject *o = group->firstChild() ; o && !inGroup; o = o->getNext() ) {
1091         if ( SP_IS_ITEM(o) ) {
1092             if (SP_ITEM(o) == item) {
1093                 inGroup = true;
1094             } else if ( SP_IS_GROUP(o) ) {
1095                 inGroup = item_is_in_group(item, SP_GROUP(o));
1096             }
1097         }
1098     }
1099     return inGroup;
1102 SPItem *SPDocument::getItemFromListAtPointBottom(unsigned int dkey, SPGroup *group, GSList const *list,Geom::Point const p, bool take_insensitive)
1104     g_return_val_if_fail(group, NULL);
1105     SPItem *bottomMost = 0;
1107     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1108     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1110     for ( SPObject *o = group->firstChild() ; o && !bottomMost; o = o->getNext() ) {
1111         if ( SP_IS_ITEM(o) ) {
1112             SPItem *item = SP_ITEM(o);
1113             NRArenaItem *arenaitem = item->get_arenaitem(dkey);
1114             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1115                 && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
1116                 if (g_slist_find((GSList *) list, item) != NULL) {
1117                     bottomMost = item;
1118                 }
1119             }
1121             if ( !bottomMost && SP_IS_GROUP(o) ) {
1122                 // return null if not found:
1123                 bottomMost = getItemFromListAtPointBottom(dkey, SP_GROUP(o), list, p, take_insensitive);
1124             }
1125         }
1126     }
1127     return bottomMost;
1130 /**
1131 Returns the topmost (in z-order) item from the descendants of group (recursively) which
1132 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
1133 non-layer groups or not. Honors take_insensitive on whether to return insensitive
1134 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
1135 upwards in z-order and returns what it has found so far (i.e. the found item is
1136 guaranteed to be lower than upto).
1137  */
1138 SPItem *find_item_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
1140     SPItem *seen = NULL;
1141     SPItem *newseen = NULL;
1142     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1143     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1145     for ( SPObject *o = group->firstChild() ; o ; o = o->getNext() ) {
1146         if (!SP_IS_ITEM(o)) {
1147             continue;
1148         }
1150         if (upto && SP_ITEM(o) == upto) {
1151             break;
1152         }
1154         if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
1155             // if nothing found yet, recurse into the group
1156             newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
1157             if (newseen) {
1158                 seen = newseen;
1159                 newseen = NULL;
1160             }
1162             if (item_is_in_group(upto, SP_GROUP(o))) {
1163                 break;
1164             }
1165         } else {
1166             SPItem *child = SP_ITEM(o);
1167             NRArenaItem *arenaitem = child->get_arenaitem(dkey);
1169             // seen remembers the last (topmost) of items pickable at this point
1170             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1171                 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1172                 seen = child;
1173             }
1174         }
1175     }
1176     return seen;
1179 /**
1180 Returns the topmost non-layer group from the descendants of group which is at point
1181 p, or NULL if none. Recurses into layers but not into groups.
1182  */
1183 SPItem *find_group_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p)
1185     SPItem *seen = NULL;
1186     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1187     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1189     for ( SPObject *o = group->firstChild() ; o ; o = o->getNext() ) {
1190         if (!SP_IS_ITEM(o)) {
1191             continue;
1192         }
1193         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1194             SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1195             if (newseen) {
1196                 seen = newseen;
1197             }
1198         }
1199         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1200             SPItem *child = SP_ITEM(o);
1201             NRArenaItem *arenaitem = child->get_arenaitem(dkey);
1203             // seen remembers the last (topmost) of groups pickable at this point
1204             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1205                 seen = child;
1206             }
1207         }
1208     }
1209     return seen;
1212 /*
1213  * Return list of items, contained in box
1214  *
1215  * Assumes box is normalized (and g_asserts it!)
1216  *
1217  */
1218 GSList *SPDocument::getItemsInBox(unsigned int dkey, Geom::Rect const &box) const
1220     g_return_val_if_fail(this->priv != NULL, NULL);
1222     return find_items_in_area(NULL, SP_GROUP(this->root), dkey, box, is_within);
1225 /*
1226  * Return list of items, that the parts of the item contained in box
1227  *
1228  * Assumes box is normalized (and g_asserts it!)
1229  *
1230  */
1232 GSList *SPDocument::getItemsPartiallyInBox(unsigned int dkey, Geom::Rect const &box) const
1234     g_return_val_if_fail(this->priv != NULL, NULL);
1236     return find_items_in_area(NULL, SP_GROUP(this->root), dkey, box, overlaps);
1239 GSList *SPDocument::getItemsAtPoints(unsigned const key, std::vector<Geom::Point> points) const
1241     GSList *items = NULL;
1242     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1244     // When picking along the path, we don't want small objects close together
1245     // (such as hatching strokes) to obscure each other by their deltas,
1246     // so we temporarily set delta to a small value
1247     gdouble saved_delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1248     prefs->setDouble("/options/cursortolerance/value", 0.25);
1250     for(unsigned int i = 0; i < points.size(); i++) {
1251         SPItem *item = getItemAtPoint(key, points[i],
1252                                                  false, NULL);
1253         if (item && !g_slist_find(items, item))
1254             items = g_slist_prepend (items, item);
1255     }
1257     // and now we restore it back
1258     prefs->setDouble("/options/cursortolerance/value", saved_delta);
1260     return items;
1263 SPItem *SPDocument::getItemAtPoint( unsigned const key, Geom::Point const p,
1264                                     gboolean const into_groups, SPItem *upto) const
1266     g_return_val_if_fail(this->priv != NULL, NULL);
1268     return find_item_at_point(key, SP_GROUP(this->root), p, into_groups, false, upto);
1271 SPItem *SPDocument::getGroupAtPoint(unsigned int key, Geom::Point const p) const
1273     g_return_val_if_fail(this->priv != NULL, NULL);
1275     return find_group_at_point(key, SP_GROUP(this->root), p);
1279 // Resource management
1281 bool SPDocument::addResource(gchar const *key, SPObject *object)
1283     g_return_val_if_fail(key != NULL, false);
1284     g_return_val_if_fail(*key != '\0', false);
1285     g_return_val_if_fail(object != NULL, false);
1286     g_return_val_if_fail(SP_IS_OBJECT(object), false);
1288     bool result = false;
1290     if ( !object->cloned ) {
1291         GSList *rlist = (GSList*)g_hash_table_lookup(priv->resources, key);
1292         g_return_val_if_fail(!g_slist_find(rlist, object), false);
1293         rlist = g_slist_prepend(rlist, object);
1294         g_hash_table_insert(priv->resources, (gpointer) key, rlist);
1296         GQuark q = g_quark_from_string(key);
1297         priv->resources_changed_signals[q].emit();
1299         result = true;
1300     }
1302     return result;
1305 bool SPDocument::removeResource(gchar const *key, SPObject *object)
1307     g_return_val_if_fail(key != NULL, false);
1308     g_return_val_if_fail(*key != '\0', false);
1309     g_return_val_if_fail(object != NULL, false);
1310     g_return_val_if_fail(SP_IS_OBJECT(object), false);
1312     bool result = false;
1314     if ( !object->cloned ) {
1315         GSList *rlist = (GSList*)g_hash_table_lookup(priv->resources, key);
1316         g_return_val_if_fail(rlist != NULL, false);
1317         g_return_val_if_fail(g_slist_find(rlist, object), false);
1318         rlist = g_slist_remove(rlist, object);
1319         g_hash_table_insert(priv->resources, (gpointer) key, rlist);
1321         GQuark q = g_quark_from_string(key);
1322         priv->resources_changed_signals[q].emit();
1324         result = true;
1325     }
1327     return result;
1330 GSList const *SPDocument::getResourceList(gchar const *key) const
1332     g_return_val_if_fail(key != NULL, NULL);
1333     g_return_val_if_fail(*key != '\0', NULL);
1335     return (GSList*)g_hash_table_lookup(this->priv->resources, key);
1338 sigc::connection SPDocument::connectResourcesChanged(gchar const *key,
1339                                                      SPDocument::ResourcesChangedSignal::slot_type slot)
1341     GQuark q = g_quark_from_string(key);
1342     return this->priv->resources_changed_signals[q].connect(slot);
1345 /* Helpers */
1347 gboolean
1348 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1350     g_slist_free((GSList *) value);
1351     return TRUE;
1354 unsigned int count_objects_recursive(SPObject *obj, unsigned int count)
1356     count++; // obj itself
1358     for ( SPObject *i = obj->firstChild(); i; i = i->getNext() ) {
1359         count = count_objects_recursive(i, count);
1360     }
1362     return count;
1365 unsigned int objects_in_document(SPDocument *document)
1367     return count_objects_recursive(document->getRoot(), 0);
1370 void vacuum_document_recursive(SPObject *obj)
1372     if (SP_IS_DEFS(obj)) {
1373         for ( SPObject *def = obj->firstChild(); def; def = def->getNext()) {
1374             // fixme: some inkscape-internal nodes in the future might not be collectable
1375             def->requestOrphanCollection();
1376         }
1377     } else {
1378         for ( SPObject *i = obj->firstChild(); i; i = i->getNext() ) {
1379             vacuum_document_recursive(i);
1380         }
1381     }
1384 unsigned int SPDocument::vacuumDocument()
1386     unsigned int start = objects_in_document(this);
1387     unsigned int end = start;
1388     unsigned int newend = start;
1390     unsigned int iterations = 0;
1392     do {
1393         end = newend;
1395         vacuum_document_recursive(root);
1396         this->collectOrphans();
1397         iterations++;
1399         newend = objects_in_document(this);
1401     } while (iterations < 100 && newend < end);
1403     return start - newend;
1406 bool SPDocument::isSeeking() const {
1407     return priv->seeking;
1411 /*
1412   Local Variables:
1413   mode:c++
1414   c-file-style:"stroustrup"
1415   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1416   indent-tabs-mode:nil
1417   fill-column:99
1418   End:
1419 */
1420 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :