Code

Correcting initialization order in ctor.
[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"
64 #include "xml/rebase-hrefs.h"
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(0),
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         sp_document_clear_redo(this);
154         sp_document_clear_undo(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>(sp_document_reset_key),
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     }
215     //delete this->_whiteboard_session_manager;
218 Persp3D *
219 SPDocument::getCurrentPersp3D() {
220     // Check if current_persp3d is still valid
221     std::vector<Persp3D*> plist;
222     getPerspectivesInDefs(plist);
223     for (unsigned int i = 0; i < plist.size(); ++i) {
224         if (current_persp3d == plist[i])
225             return current_persp3d;
226     }
228     // If not, return the first perspective in defs (which may be NULL of none exists)
229     current_persp3d = persp3d_document_first_persp (this);
231     return current_persp3d;
234 Persp3DImpl *
235 SPDocument::getCurrentPersp3DImpl() {
236     return current_persp3d_impl;
239 void
240 SPDocument::setCurrentPersp3D(Persp3D * const persp) {
241     current_persp3d = persp;
242     //current_persp3d_impl = persp->perspective_impl;
245 void
246 SPDocument::getPerspectivesInDefs(std::vector<Persp3D*> &list) {
247     SPDefs *defs = SP_ROOT(this->root)->defs;
248     for (SPObject *i = sp_object_first_child(SP_OBJECT(defs)); i != NULL; i = SP_OBJECT_NEXT(i) ) {
249         if (SP_IS_PERSP3D(i))
250             list.push_back(SP_PERSP3D(i));
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 = NULL;
294 SPDocument *
295 sp_document_create(Inkscape::XML::Document *rdoc,
296                    gchar const *uri,
297                    gchar const *base,
298                    gchar const *name,
299                    unsigned int keepalive)
301     SPDocument *document;
302     Inkscape::XML::Node *rroot;
303     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
305     rroot = rdoc->root();
307     document = new SPDocument();
309     document->keepalive = keepalive;
311     document->rdoc = rdoc;
312     document->rroot = rroot;
314 #ifndef WIN32
315     document->uri = prepend_current_dir_if_relative(uri);
316 #else
317     // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
318     document->uri = uri? g_strdup(uri) : NULL;
319 #endif
321     // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
322     // which is why we use g_get_current_dir() in calculating the abs path above
323     //This is NULL for a new document
324     if (base)
325         document->base = g_strdup(base);
326     else
327         document->base = NULL;
328     document->name = g_strdup(name);
330     document->root = sp_object_repr_build_tree(document, rroot);
332     /* fixme: Not sure about this, but lets assume ::build updates */
333     rroot->setAttribute("inkscape:version", Inkscape::version_string);
334     /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
336     /* Quick hack 2 - get default image size into document */
337     if (!rroot->attribute("width")) rroot->setAttribute("width", "100%");
338     if (!rroot->attribute("height")) rroot->setAttribute("height", "100%");
339     /* End of quick hack 2 */
341     /* Quick hack 3 - Set uri attributes */
342     if (uri) {
343         rroot->setAttribute("sodipodi:docname", uri);
344     }
345     /* End of quick hack 3 */
347     /* Eliminate obsolete sodipodi:docbase, for privacy reasons */
348     rroot->setAttribute("sodipodi:docbase", NULL);
350     /* Eliminate any claim to adhere to a profile, as we don't try to */
351     rroot->setAttribute("baseProfile", NULL);
353     // creating namedview
354     if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
355         // if there's none in the document already,
356         Inkscape::XML::Node *rnew = NULL;
358         rnew = rdoc->createElement("sodipodi:namedview");
359         //rnew->setAttribute("id", "base");
361         // Add namedview data from the preferences
362         // we can't use getAllEntries because this could produce non-SVG doubles
363         Glib::ustring pagecolor = prefs->getString("/template/base/pagecolor");
364         if (!pagecolor.empty()) {
365             rnew->setAttribute("pagecolor", pagecolor.data());
366         }
367         Glib::ustring bordercolor = prefs->getString("/template/base/bordercolor");
368         if (!bordercolor.empty()) {
369             rnew->setAttribute("bordercolor", bordercolor.data());
370         }
371         sp_repr_set_svg_double(rnew, "borderopacity",
372             prefs->getDouble("/template/base/borderopacity", 1.0));
373         sp_repr_set_svg_double(rnew, "objecttolerance",
374             prefs->getDouble("/template/base/objecttolerance", 10.0));
375         sp_repr_set_svg_double(rnew, "gridtolerance",
376             prefs->getDouble("/template/base/gridtolerance", 10.0));
377         sp_repr_set_svg_double(rnew, "guidetolerance",
378             prefs->getDouble("/template/base/guidetolerance", 10.0));
379         sp_repr_set_svg_double(rnew, "inkscape:pageopacity",
380             prefs->getDouble("/template/base/inkscape:pageopacity", 0.0));
381         sp_repr_set_int(rnew, "inkscape:pageshadow",
382             prefs->getInt("/template/base/inkscape:pageshadow", 2));
383         sp_repr_set_int(rnew, "inkscape:window-width",
384             prefs->getInt("/template/base/inkscape:window-width", 640));
385         sp_repr_set_int(rnew, "inkscape:window-height",
386             prefs->getInt("/template/base/inkscape:window-height", 480));
388         // insert into the document
389         rroot->addChild(rnew, NULL);
390         // clean up
391         Inkscape::GC::release(rnew);
392     }
394     /* Defs */
395     if (!SP_ROOT(document->root)->defs) {
396         Inkscape::XML::Node *r;
397         r = rdoc->createElement("svg:defs");
398         rroot->addChild(r, NULL);
399         Inkscape::GC::release(r);
400         g_assert(SP_ROOT(document->root)->defs);
401     }
403     /* Default RDF */
404     rdf_set_defaults( document );
406     if (keepalive) {
407         inkscape_ref();
408     }
410     // Check if the document already has a perspective (e.g., when opening an existing
411     // document). If not, create a new one and set it as the current perspective.
412     document->setCurrentPersp3D(persp3d_document_first_persp(document));
413     if (!document->getCurrentPersp3D()) {
414         //document->setCurrentPersp3D(persp3d_create_xml_element (document));
415         Persp3DImpl *persp_impl = new Persp3DImpl();
416         document->setCurrentPersp3DImpl(persp_impl);
417     }
419     sp_document_set_undo_sensitive(document, true);
421     // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
422     if (!Inkscape::NSApplication::Application::getNewGui()) {
423         g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
424                          G_CALLBACK(sp_document_reset_key), document);
425         g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
426                          G_CALLBACK(sp_document_reset_key), document);
427         document->oldSignalsConnected = true;
428     } else {
429         document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
430         document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
431         document->oldSignalsConnected = false;
432     }
434     return document;
437 /**
438  * Fetches document from URI, or creates new, if NULL; public document
439  * appears in document list.
440  */
441 SPDocument *
442 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
444     SPDocument *doc;
445     Inkscape::XML::Document *rdoc;
446     gchar *base = NULL;
447     gchar *name = NULL;
449     if (uri) {
450         Inkscape::XML::Node *rroot;
451         gchar *s, *p;
452         /* Try to fetch repr from file */
453         rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
454         /* If file cannot be loaded, return NULL without warning */
455         if (rdoc == NULL) return NULL;
456         rroot = rdoc->root();
457         /* If xml file is not svg, return NULL without warning */
458         /* fixme: destroy document */
459         if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
460         s = g_strdup(uri);
461         p = strrchr(s, '/');
462         if (p) {
463             name = g_strdup(p + 1);
464             p[1] = '\0';
465             base = g_strdup(s);
466         } else {
467             base = NULL;
468             name = g_strdup(uri);
469         }
470         g_free(s);
471     } else {
472         rdoc = sp_repr_document_new("svg:svg");
473     }
475     if (make_new) {
476         base = NULL;
477         uri = NULL;
478         name = g_strdup_printf(_("New document %d"), ++doc_count);
479     }
481     //# These should be set by now
482     g_assert(name);
484     doc = sp_document_create(rdoc, uri, base, name, keepalive);
486     g_free(base);
487     g_free(name);
489     return doc;
492 SPDocument *
493 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
495     SPDocument *doc;
496     Inkscape::XML::Document *rdoc;
497     Inkscape::XML::Node *rroot;
498     gchar *name;
500     rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
502     /* If it cannot be loaded, return NULL without warning */
503     if (rdoc == NULL) return NULL;
505     rroot = rdoc->root();
506     /* If xml file is not svg, return NULL without warning */
507     /* fixme: destroy document */
508     if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
510     name = g_strdup_printf(_("Memory document %d"), ++doc_count);
512     doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
514     return doc;
517 SPDocument *
518 sp_document_ref(SPDocument *doc)
520     g_return_val_if_fail(doc != NULL, NULL);
521     Inkscape::GC::anchor(doc);
522     return doc;
525 SPDocument *
526 sp_document_unref(SPDocument *doc)
528     g_return_val_if_fail(doc != NULL, NULL);
529     Inkscape::GC::release(doc);
530     return NULL;
533 gdouble sp_document_width(SPDocument *document)
535     g_return_val_if_fail(document != NULL, 0.0);
536     g_return_val_if_fail(document->priv != NULL, 0.0);
537     g_return_val_if_fail(document->root != NULL, 0.0);
539     SPRoot *root = SP_ROOT(document->root);
541     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set)
542         return root->viewBox.x1 - root->viewBox.x0;
543     return root->width.computed;
546 void
547 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
549     SPRoot *root = SP_ROOT(document->root);
551     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
552         root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
553     } else { // set to width=
554         gdouble old_computed = root->width.computed;
555         root->width.computed = sp_units_get_pixels (width, *unit);
556         /* SVG does not support meters as a unit, so we must translate meters to
557          * cm when writing */
558         if (!strcmp(unit->abbr, "m")) {
559             root->width.value = 100*width;
560             root->width.unit = SVGLength::CM;
561         } else {
562             root->width.value = width;
563             root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
564         }
566         if (root->viewBox_set)
567             root->viewBox.x1 = root->viewBox.x0 + (root->width.computed / old_computed) * (root->viewBox.x1 - root->viewBox.x0);
568     }
570     SP_OBJECT (root)->updateRepr();
573 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
575     SPRoot *root = SP_ROOT(document->root);
577     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
578         root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
579     } else { // set to height=
580         gdouble old_computed = root->height.computed;
581         root->height.computed = sp_units_get_pixels (height, *unit);
582         /* SVG does not support meters as a unit, so we must translate meters to
583          * cm when writing */
584         if (!strcmp(unit->abbr, "m")) {
585             root->height.value = 100*height;
586             root->height.unit = SVGLength::CM;
587         } else {
588             root->height.value = height;
589             root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
590         }
592         if (root->viewBox_set)
593             root->viewBox.y1 = root->viewBox.y0 + (root->height.computed / old_computed) * (root->viewBox.y1 - root->viewBox.y0);
594     }
596     SP_OBJECT (root)->updateRepr();
599 gdouble sp_document_height(SPDocument *document)
601     g_return_val_if_fail(document != NULL, 0.0);
602     g_return_val_if_fail(document->priv != NULL, 0.0);
603     g_return_val_if_fail(document->root != NULL, 0.0);
605     SPRoot *root = SP_ROOT(document->root);
607     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set)
608         return root->viewBox.y1 - root->viewBox.y0;
609     return root->height.computed;
612 Geom::Point sp_document_dimensions(SPDocument *doc)
614     return Geom::Point(sp_document_width(doc), sp_document_height(doc));
617 /**
618  * Given a Geom::Rect that may, for example, correspond to the bbox of an object,
619  * this function fits the canvas to that rect by resizing the canvas
620  * and translating the document root into position.
621  */
622 void SPDocument::fitToRect(Geom::Rect const &rect)
624     double const w = rect.width();
625     double const h = rect.height();
627     double const old_height = sp_document_height(this);
628     SPUnit const &px(sp_unit_get_by_id(SP_UNIT_PX));
629     sp_document_set_width(this, w, &px);
630     sp_document_set_height(this, h, &px);
632     Geom::Translate const tr(Geom::Point(0, (old_height - h))
633                              - to_2geom(rect.min()));
634     SP_GROUP(root)->translateChildItems(tr);
635     SPNamedView *nv = sp_document_namedview(this, 0);
636     if(nv) {
637         Geom::Translate tr2(-rect.min());
638         nv->translateGuides(tr2);
640         // update the viewport so the drawing appears to stay where it was
641         nv->scrollAllDesktops(-tr2[0], tr2[1], false);
642     }
645 static void
646 do_change_uri(SPDocument *const document, gchar const *const filename, bool const rebase)
648     g_return_if_fail(document != NULL);
650     gchar *new_base;
651     gchar *new_name;
652     gchar *new_uri;
653     if (filename) {
655 #ifndef WIN32
656         new_uri = prepend_current_dir_if_relative(filename);
657 #else
658         // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
659         new_uri = g_strdup(filename);
660 #endif
662         new_base = g_path_get_dirname(new_uri);
663         new_name = g_path_get_basename(new_uri);
664     } else {
665         new_uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
666         new_base = NULL;
667         new_name = g_strdup(document->uri);
668     }
670     // Update saveable repr attributes.
671     Inkscape::XML::Node *repr = sp_document_repr_root(document);
673     // Changing uri in the document repr must not be not undoable.
674     bool const saved = sp_document_get_undo_sensitive(document);
675     sp_document_set_undo_sensitive(document, false);
677     if (rebase) {
678         Inkscape::XML::rebase_hrefs(document, new_base, true);
679     }
681     repr->setAttribute("sodipodi:docname", document->name);
682     sp_document_set_undo_sensitive(document, saved);
685     g_free(document->name);
686     g_free(document->base);
687     g_free(document->uri);
688     document->name = new_name;
689     document->base = new_base;
690     document->uri = new_uri;
692     document->priv->uri_set_signal.emit(document->uri);
695 /**
696  * Sets base, name and uri members of \a document.  Doesn't update
697  * any relative hrefs in the document: thus, this is primarily for
698  * newly-created documents.
699  *
700  * \see sp_document_change_uri_and_hrefs
701  */
702 void sp_document_set_uri(SPDocument *document, gchar const *filename)
704     g_return_if_fail(document != NULL);
706     do_change_uri(document, filename, false);
709 /**
710  * Changes the base, name and uri members of \a document, and updates any
711  * relative hrefs in the document to be relative to the new base.
712  *
713  * \see sp_document_set_uri
714  */
715 void sp_document_change_uri_and_hrefs(SPDocument *document, gchar const *filename)
717     g_return_if_fail(document != NULL);
719     do_change_uri(document, filename, true);
722 void
723 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
725     g_return_if_fail(doc != NULL);
727     doc->priv->resized_signal.emit(width, height);
730 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
732     return priv->modified_signal.connect(slot);
735 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
737     return priv->uri_set_signal.connect(slot);
740 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
742     return priv->resized_signal.connect(slot);
745 sigc::connection
746 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
748     return priv->_reconstruction_start_signal.connect(slot);
751 void
752 SPDocument::emitReconstructionStart(void)
754     // printf("Starting Reconstruction\n");
755     priv->_reconstruction_start_signal.emit();
756     return;
759 sigc::connection
760 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type  slot)
762     return priv->_reconstruction_finish_signal.connect(slot);
765 void
766 SPDocument::emitReconstructionFinish(void)
768     // printf("Finishing Reconstruction\n");
769     priv->_reconstruction_finish_signal.emit();
771 /**    
772     // Reference to the old persp3d object is invalid after reconstruction.
773     initialize_current_persp3d();
774     
775     return;
776 **/
779 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
781     return priv->commit_signal.connect(slot);
786 void SPDocument::_emitModified() {
787     static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
788     root->emitModified(0);
789     priv->modified_signal.emit(flags);
792 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
793     GQuark idq = g_quark_from_string(id);
795     if (object) {
796         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
797         g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
798     } else {
799         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
800         g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
801     }
803     SPDocumentPrivate::IDChangedSignalMap::iterator pos;
805     pos = priv->id_changed_signals.find(idq);
806     if ( pos != priv->id_changed_signals.end() ) {
807         if (!(*pos).second.empty()) {
808             (*pos).second.emit(object);
809         } else { // discard unused signal
810             priv->id_changed_signals.erase(pos);
811         }
812     }
815 void
816 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
818     this->priv->undoStackObservers.add(observer);
821 void
822 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
824     this->priv->undoStackObservers.remove(observer);
827 SPObject *SPDocument::getObjectById(gchar const *id) {
828     g_return_val_if_fail(id != NULL, NULL);
830     GQuark idq = g_quark_from_string(id);
831     return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
834 sigc::connection SPDocument::connectIdChanged(gchar const *id,
835                                               SPDocument::IDChangedSignal::slot_type slot)
837     return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
840 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
841     if (object) {
842         g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
843         g_hash_table_insert(priv->reprdef, repr, object);
844     } else {
845         g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
846         g_hash_table_remove(priv->reprdef, repr);
847     }
850 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
851     g_return_val_if_fail(repr != NULL, NULL);
852     return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
855 Glib::ustring SPDocument::getLanguage() {
856     gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
857     if (document_language) {
858         while (isspace(*document_language))
859             document_language++;
860     }
861     if ( !document_language || 0 == *document_language) {
862         // retrieve system language
863         document_language = getenv("LC_ALL");
864         if ( NULL == document_language || *document_language == 0 ) {
865             document_language = getenv ("LC_MESSAGES");
866         }
867         if ( NULL == document_language || *document_language == 0 ) {
868             document_language = getenv ("LANG");
869         }
871         if ( NULL != document_language ) {
872             const char *pos = strchr(document_language, '_');
873             if ( NULL != pos ) {
874                 return Glib::ustring(document_language, pos - document_language);
875             }
876         }
877     }
879     if ( NULL == document_language )
880         return Glib::ustring();
881     return document_language;
884 /* Object modification root handler */
886 void
887 sp_document_request_modified(SPDocument *doc)
889     if (!doc->modified_id) {
890         doc->modified_id = g_idle_add_full(SP_DOCUMENT_UPDATE_PRIORITY, 
891                 sp_document_idle_handler, doc, NULL);
892     }
893     if (!doc->rerouting_handler_id) {
894         doc->rerouting_handler_id = g_idle_add_full(SP_DOCUMENT_REROUTING_PRIORITY, 
895                 sp_document_rerouting_handler, doc, NULL);
896     }
899 void
900 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
902     ctx->ctx.flags = 0;
903     ctx->i2doc = Geom::identity();
904     /* Set up viewport in case svg has it defined as percentages */
905     if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
906         ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
907         ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
908         ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
909         ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
910     } else { // as a last resort, set size to A4
911         ctx->vp.x0 = 0.0;
912         ctx->vp.y0 = 0.0;
913         ctx->vp.x1 = 210 * PX_PER_MM;
914         ctx->vp.y1 = 297 * PX_PER_MM;
915     }
916     ctx->i2vp = Geom::identity();
919 /**
920  * Tries to update the document state based on the modified and
921  * "update required" flags, and return true if the document has
922  * been brought fully up to date.
923  */
924 bool
925 SPDocument::_updateDocument()
927     /* Process updates */
928     if (this->root->uflags || this->root->mflags) {
929         if (this->root->uflags) {
930             SPItemCtx ctx;
931             sp_document_setup_viewport (this, &ctx);
933             bool saved = sp_document_get_undo_sensitive(this);
934             sp_document_set_undo_sensitive(this, false);
936             this->root->updateDisplay((SPCtx *)&ctx, 0);
938             sp_document_set_undo_sensitive(this, saved);
939         }
940         this->_emitModified();
941     }
943     return !(this->root->uflags || this->root->mflags);
947 /**
948  * Repeatedly works on getting the document updated, since sometimes
949  * it takes more than one pass to get the document updated.  But it
950  * usually should not take more than a few loops, and certainly never
951  * more than 32 iterations.  So we bail out if we hit 32 iterations,
952  * since this typically indicates we're stuck in an update loop.
953  */
954 gint
955 sp_document_ensure_up_to_date(SPDocument *doc)
957     // Bring the document up-to-date, specifically via the following:
958     //   1a) Process all document updates.
959     //   1b) When completed, process connector routing changes.
960     //   2a) Process any updates resulting from connector reroutings.
961     int counter = 32;
962     for (unsigned int pass = 1; pass <= 2; ++pass) {
963         // Process document updates.
964         while (!doc->_updateDocument()) {
965             if (counter == 0) {
966                 g_warning("More than 32 iteration while updating document '%s'", doc->uri);
967                 break;
968             }
969             counter--;
970         }
971         if (counter == 0)
972         {
973             break;
974         }
976         // After updates on the first pass we get libavoid to process all the 
977         // changed objects and provide new routings.  This may cause some objects
978             // to be modified, hence the second update pass.
979         if (pass == 1) {
980             doc->router->processTransaction();
981         }
982     }
983     
984     if (doc->modified_id) {
985         /* Remove handler */
986         g_source_remove(doc->modified_id);
987         doc->modified_id = 0;
988     }
989     if (doc->rerouting_handler_id) {
990         /* Remove handler */
991         g_source_remove(doc->rerouting_handler_id);
992         doc->rerouting_handler_id = 0;
993     }
994     return counter>0;
997 /**
998  * An idle handler to update the document.  Returns true if
999  * the document needs further updates.
1000  */
1001 static gint
1002 sp_document_idle_handler(gpointer data)
1004     SPDocument *doc = static_cast<SPDocument *>(data);
1005     if (doc->_updateDocument()) {
1006         doc->modified_id = 0;
1007         return false;
1008     } else {
1009         return true;
1010     }
1013 /**
1014  * An idle handler to reroute connectors in the document.  
1015  */
1016 static gint
1017 sp_document_rerouting_handler(gpointer data)
1019     // Process any queued movement actions and determine new routings for 
1020     // object-avoiding connectors.  Callbacks will be used to update and 
1021     // redraw affected connectors.
1022     SPDocument *doc = static_cast<SPDocument *>(data);
1023     doc->router->processTransaction();
1024     
1025     // We don't need to handle rerouting again until there are further 
1026     // diagram updates.
1027     doc->rerouting_handler_id = 0;
1028     return false;
1031 static bool is_within(Geom::Rect const &area, Geom::Rect const &box)
1033     return area.contains(box);
1036 static bool overlaps(Geom::Rect const &area, Geom::Rect const &box)
1038     return area.intersects(box);
1041 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, Geom::Rect const &area,
1042                                   bool (*test)(Geom::Rect const &, Geom::Rect const &), bool take_insensitive = false)
1044     g_return_val_if_fail(SP_IS_GROUP(group), s);
1046     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1047         if (!SP_IS_ITEM(o)) {
1048             continue;
1049         }
1050         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
1051             s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
1052         } else {
1053             SPItem *child = SP_ITEM(o);
1054             Geom::OptRect box = sp_item_bbox_desktop(child);
1055             if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1056                 s = g_slist_append(s, child);
1057             }
1058         }
1059     }
1061     return s;
1064 /**
1065 Returns true if an item is among the descendants of group (recursively).
1066  */
1067 bool item_is_in_group(SPItem *item, SPGroup *group)
1069     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1070         if (!SP_IS_ITEM(o)) continue;
1071         if (SP_ITEM(o) == item)
1072             return true;
1073         if (SP_IS_GROUP(o))
1074             if (item_is_in_group(item, SP_GROUP(o)))
1075                 return true;
1076     }
1077     return false;
1080 /**
1081 Returns the bottommost item from the list which is at the point, or NULL if none.
1082 */
1083 SPItem*
1084 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
1085                                            Geom::Point const p, bool take_insensitive)
1087     g_return_val_if_fail(group, NULL);
1088     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1089     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1091     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1093         if (!SP_IS_ITEM(o)) continue;
1095         SPItem *item = SP_ITEM(o);
1096         NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
1097         if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1098             && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
1099             if (g_slist_find((GSList *) list, item) != NULL)
1100                 return item;
1101         }
1103         if (SP_IS_GROUP(o)) {
1104             SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
1105             if (found)
1106                 return found;
1107         }
1109     }
1110     return NULL;
1113 /**
1114 Returns the topmost (in z-order) item from the descendants of group (recursively) which
1115 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
1116 non-layer groups or not. Honors take_insensitive on whether to return insensitive
1117 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
1118 upwards in z-order and returns what it has found so far (i.e. the found item is
1119 guaranteed to be lower than upto).
1120  */
1121 SPItem*
1122 find_item_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
1124     SPItem *seen = NULL, *newseen = NULL;
1125     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1126     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1128     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1129         if (!SP_IS_ITEM(o)) continue;
1131         if (upto && SP_ITEM(o) == upto)
1132             break;
1134         if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
1135             // if nothing found yet, recurse into the group
1136             newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
1137             if (newseen) {
1138                 seen = newseen;
1139                 newseen = NULL;
1140             }
1142             if (item_is_in_group(upto, SP_GROUP(o)))
1143                 break;
1145         } else {
1146             SPItem *child = SP_ITEM(o);
1147             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1149             // seen remembers the last (topmost) of items pickable at this point
1150             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1151                 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1152                 seen = child;
1153             }
1154         }
1155     }
1156     return seen;
1159 /**
1160 Returns the topmost non-layer group from the descendants of group which is at point
1161 p, or NULL if none. Recurses into layers but not into groups.
1162  */
1163 SPItem*
1164 find_group_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p)
1166     SPItem *seen = NULL;
1167     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1168     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1170     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1171         if (!SP_IS_ITEM(o)) continue;
1172         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1173             SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1174             if (newseen) {
1175                 seen = newseen;
1176             }
1177         }
1178         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1179             SPItem *child = SP_ITEM(o);
1180             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1182             // seen remembers the last (topmost) of groups pickable at this point
1183             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1184                 seen = child;
1185             }
1186         }
1187     }
1188     return seen;
1191 /*
1192  * Return list of items, contained in box
1193  *
1194  * Assumes box is normalized (and g_asserts it!)
1195  *
1196  */
1198 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1200     g_return_val_if_fail(document != NULL, NULL);
1201     g_return_val_if_fail(document->priv != NULL, NULL);
1203     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
1206 /*
1207  * Return list of items, that the parts of the item contained in box
1208  *
1209  * Assumes box is normalized (and g_asserts it!)
1210  *
1211  */
1213 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1215     g_return_val_if_fail(document != NULL, NULL);
1216     g_return_val_if_fail(document->priv != NULL, NULL);
1218     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1221 GSList *
1222 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<Geom::Point> points)
1224     GSList *items = NULL;
1225     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1227     // When picking along the path, we don't want small objects close together
1228     // (such as hatching strokes) to obscure each other by their deltas,
1229     // so we temporarily set delta to a small value
1230     gdouble saved_delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1231     prefs->setDouble("/options/cursortolerance/value", 0.25);
1233     for(unsigned int i = 0; i < points.size(); i++) {
1234         SPItem *item = sp_document_item_at_point(document, key, points[i],
1235                                                  false, NULL);
1236         if (item && !g_slist_find(items, item))
1237             items = g_slist_prepend (items, item);
1238     }
1240     // and now we restore it back
1241     prefs->setDouble("/options/cursortolerance/value", saved_delta);
1243     return items;
1246 SPItem *
1247 sp_document_item_at_point(SPDocument *document, unsigned const key, Geom::Point const p,
1248                           gboolean const into_groups, SPItem *upto)
1250     g_return_val_if_fail(document != NULL, NULL);
1251     g_return_val_if_fail(document->priv != NULL, NULL);
1253     return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1256 SPItem*
1257 sp_document_group_at_point(SPDocument *document, unsigned int key, Geom::Point const p)
1259     g_return_val_if_fail(document != NULL, NULL);
1260     g_return_val_if_fail(document->priv != NULL, NULL);
1262     return find_group_at_point(key, SP_GROUP(document->root), p);
1266 /* Resource management */
1268 gboolean
1269 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1271     GSList *rlist;
1272     GQuark q = g_quark_from_string(key);
1274     g_return_val_if_fail(document != NULL, FALSE);
1275     g_return_val_if_fail(key != NULL, FALSE);
1276     g_return_val_if_fail(*key != '\0', FALSE);
1277     g_return_val_if_fail(object != NULL, FALSE);
1278     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1280     if (SP_OBJECT_IS_CLONED(object))
1281         return FALSE;
1283     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1284     g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1285     rlist = g_slist_prepend(rlist, object);
1286     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1288     document->priv->resources_changed_signals[q].emit();
1290     return TRUE;
1293 gboolean
1294 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1296     GSList *rlist;
1297     GQuark q = g_quark_from_string(key);
1299     g_return_val_if_fail(document != NULL, FALSE);
1300     g_return_val_if_fail(key != NULL, FALSE);
1301     g_return_val_if_fail(*key != '\0', FALSE);
1302     g_return_val_if_fail(object != NULL, FALSE);
1303     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1305     if (SP_OBJECT_IS_CLONED(object))
1306         return FALSE;
1308     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1309     g_return_val_if_fail(rlist != NULL, FALSE);
1310     g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1311     rlist = g_slist_remove(rlist, object);
1312     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1314     document->priv->resources_changed_signals[q].emit();
1316     return TRUE;
1319 GSList const *
1320 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1322     g_return_val_if_fail(document != NULL, NULL);
1323     g_return_val_if_fail(key != NULL, NULL);
1324     g_return_val_if_fail(*key != '\0', NULL);
1326     return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1329 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1330                                                        gchar const *key,
1331                                                        SPDocument::ResourcesChangedSignal::slot_type slot)
1333     GQuark q = g_quark_from_string(key);
1334     return document->priv->resources_changed_signals[q].connect(slot);
1337 /* Helpers */
1339 gboolean
1340 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1342     g_slist_free((GSList *) value);
1343     return TRUE;
1346 unsigned int
1347 count_objects_recursive(SPObject *obj, unsigned int count)
1349     count++; // obj itself
1351     for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1352         count = count_objects_recursive(i, count);
1353     }
1355     return count;
1358 unsigned int
1359 objects_in_document(SPDocument *document)
1361     return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1364 void
1365 vacuum_document_recursive(SPObject *obj)
1367     if (SP_IS_DEFS(obj)) {
1368         for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1369             /* fixme: some inkscape-internal nodes in the future might not be collectable */
1370             def->requestOrphanCollection();
1371         }
1372     } else {
1373         for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1374             vacuum_document_recursive(i);
1375         }
1376     }
1379 unsigned int
1380 vacuum_document(SPDocument *document)
1382     unsigned int start = objects_in_document(document);
1383     unsigned int end;
1384     unsigned int newend = start;
1386     unsigned int iterations = 0;
1388     do {
1389         end = newend;
1391         vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1392         document->collectOrphans();
1393         iterations++;
1395         newend = objects_in_document(document);
1397     } while (iterations < 100 && newend < end);
1399     return start - newend;
1402 bool SPDocument::isSeeking() const {
1403     return priv->seeking;
1407 /*
1408   Local Variables:
1409   mode:c++
1410   c-file-style:"stroustrup"
1411   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1412   indent-tabs-mode:nil
1413   fill-column:99
1414   End:
1415 */
1416 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :