Code

Revert recent refactoring changes by johnce because they break the build, which canno...
[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 #define SP_DOCUMENT_UPDATE_PRIORITY (G_PRIORITY_HIGH_IDLE - 1)
69 static gint sp_document_idle_handler(gpointer data);
71 gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data);
73 static gint doc_count = 0;
75 static unsigned long next_serial = 0;
77 SPDocument::SPDocument() :
78     keepalive(FALSE),
79     virgin(TRUE),
80     modified_since_save(FALSE),
81     rdoc(0),
82     rroot(0),
83     root(0),
84     style_cascade(cr_cascade_new(NULL, NULL, NULL)),
85     uri(0),
86     base(0),
87     name(0),
88     priv(0), // reset in ctor
89     actionkey(0),
90     modified_id(0),
91     profileManager(0), // deferred until after other initialization
92     router(new Avoid::Router()),
93     perspectives(0),
94     current_persp3d(0),
95     _collection_queue(0),
96     oldSignalsConnected(false)
97 {
98     // Don't use the Consolidate moves optimisation.
99     router->ConsolidateMoves = false;
101     SPDocumentPrivate *p = new SPDocumentPrivate();
103     p->serial = next_serial++;
105     p->iddef = g_hash_table_new(g_direct_hash, g_direct_equal);
106     p->reprdef = g_hash_table_new(g_direct_hash, g_direct_equal);
108     p->resources = g_hash_table_new(g_str_hash, g_str_equal);
110     p->sensitive = FALSE;
111     p->partial = NULL;
112     p->history_size = 0;
113     p->undo = NULL;
114     p->redo = NULL;
115     p->seeking = false;
117     priv = p;
119     // Once things are set, hook in the manager
120     profileManager = new Inkscape::ProfileManager(this);
122     // XXX only for testing!
123     priv->undoStackObservers.add(p->console_output_undo_observer);
126 SPDocument::~SPDocument() {
127     collectOrphans();
129     // kill/unhook this first
130     if ( profileManager ) {
131         delete profileManager;
132         profileManager = 0;
133     }
135     if (priv) {
136         if (priv->partial) {
137             sp_repr_free_log(priv->partial);
138             priv->partial = NULL;
139         }
141         sp_document_clear_redo(this);
142         sp_document_clear_undo(this);
144         if (root) {
145             root->releaseReferences();
146             sp_object_unref(root);
147             root = NULL;
148         }
150         if (priv->iddef) g_hash_table_destroy(priv->iddef);
151         if (priv->reprdef) g_hash_table_destroy(priv->reprdef);
153         if (rdoc) Inkscape::GC::release(rdoc);
155         /* Free resources */
156         g_hash_table_foreach_remove(priv->resources, sp_document_resource_list_free, this);
157         g_hash_table_destroy(priv->resources);
159         delete priv;
160         priv = NULL;
161     }
163     cr_cascade_unref(style_cascade);
164     style_cascade = NULL;
166     if (name) {
167         g_free(name);
168         name = NULL;
169     }
170     if (base) {
171         g_free(base);
172         base = NULL;
173     }
174     if (uri) {
175         g_free(uri);
176         uri = NULL;
177     }
179     if (modified_id) {
180         gtk_idle_remove(modified_id);
181         modified_id = 0;
182     }
184     if (oldSignalsConnected) {
185         g_signal_handlers_disconnect_by_func(G_OBJECT(INKSCAPE),
186                                              reinterpret_cast<gpointer>(sp_document_reset_key),
187                                              static_cast<gpointer>(this));
188     } else {
189         _selection_changed_connection.disconnect();
190         _desktop_activated_connection.disconnect();
191     }
193     if (keepalive) {
194         inkscape_unref();
195         keepalive = FALSE;
196     }
198     if (router) {
199         delete router;
200         router = NULL;
201     }
203     //delete this->_whiteboard_session_manager;
207 void SPDocument::add_persp3d (Persp3D * const /*persp*/)
209     SPDefs *defs = SP_ROOT(this->root)->defs;
210     for (SPObject *i = sp_object_first_child(SP_OBJECT(defs)); i != NULL; i = SP_OBJECT_NEXT(i) ) {
211         if (SP_IS_PERSP3D(i)) {
212             g_print ("Encountered a Persp3D in defs\n");
213         }
214     }
216     g_print ("Adding Persp3D to defs\n");
217     persp3d_create_xml_element (this);
220 void SPDocument::remove_persp3d (Persp3D * const /*persp*/)
222     // TODO: Delete the repr, maybe perform a check if any boxes are still linked to the perspective.
223     //       Anything else?
224     g_print ("Please implement deletion of perspectives here.\n");
227 unsigned long SPDocument::serial() const {
228     return priv->serial;
231 void SPDocument::queueForOrphanCollection(SPObject *object) {
232     g_return_if_fail(object != NULL);
233     g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
235     sp_object_ref(object, NULL);
236     _collection_queue = g_slist_prepend(_collection_queue, object);
239 void SPDocument::collectOrphans() {
240     while (_collection_queue) {
241         GSList *objects=_collection_queue;
242         _collection_queue = NULL;
243         for ( GSList *iter=objects ; iter ; iter = iter->next ) {
244             SPObject *object=reinterpret_cast<SPObject *>(iter->data);
245             object->collectOrphan();
246             sp_object_unref(object, NULL);
247         }
248         g_slist_free(objects);
249     }
252 void SPDocument::reset_key (void */*dummy*/)
254     actionkey = NULL;
257 SPDocument *
258 sp_document_create(Inkscape::XML::Document *rdoc,
259                    gchar const *uri,
260                    gchar const *base,
261                    gchar const *name,
262                    unsigned int keepalive)
264     SPDocument *document;
265     Inkscape::XML::Node *rroot;
266     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
268     rroot = rdoc->root();
270     document = new SPDocument();
272     document->keepalive = keepalive;
274     document->rdoc = rdoc;
275     document->rroot = rroot;
277 #ifndef WIN32
278     document->uri = prepend_current_dir_if_relative(uri);
279 #else
280     // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
281     document->uri = uri? g_strdup(uri) : NULL;
282 #endif
284     // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
285     // which is why we use g_get_current_dir() in calculating the abs path above
286     //This is NULL for a new document
287     if (base)
288         document->base = g_strdup(base);
289     else
290         document->base = NULL;
291     document->name = g_strdup(name);
293     document->root = sp_object_repr_build_tree(document, rroot);
295     /* fixme: Not sure about this, but lets assume ::build updates */
296     rroot->setAttribute("inkscape:version", Inkscape::version_string);
297     /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
299     /* Quick hack 2 - get default image size into document */
300     if (!rroot->attribute("width")) rroot->setAttribute("width", "100%");
301     if (!rroot->attribute("height")) rroot->setAttribute("height", "100%");
302     /* End of quick hack 2 */
304     /* Quick hack 3 - Set uri attributes */
305     if (uri) {
306         rroot->setAttribute("sodipodi:docname", uri);
307     }
308     /* End of quick hack 3 */
310     /* Eliminate obsolete sodipodi:docbase, for privacy reasons */
311     rroot->setAttribute("sodipodi:docbase", NULL);
313     /* Eliminate any claim to adhere to a profile, as we don't try to */
314     rroot->setAttribute("baseProfile", NULL);
316     // creating namedview
317     if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
318         // if there's none in the document already,
319         Inkscape::XML::Node *rnew = NULL;
321         rnew = rdoc->createElement("sodipodi:namedview");
322         //rnew->setAttribute("id", "base");
324         // Add namedview data from the preferences
325         // we can't use getAllEntries because this could produce non-SVG doubles
326         Glib::ustring pagecolor = prefs->getString("/template/base/pagecolor");
327         if (!pagecolor.empty()) {
328             rnew->setAttribute("pagecolor", pagecolor.data());
329         }
330         Glib::ustring bordercolor = prefs->getString("/template/base/bordercolor");
331         if (!bordercolor.empty()) {
332             rnew->setAttribute("bordercolor", bordercolor.data());
333         }
334         sp_repr_set_svg_double(rnew, "borderopacity",
335             prefs->getDouble("/template/base/borderopacity", 1.0));
336         sp_repr_set_svg_double(rnew, "objecttolerance",
337             prefs->getDouble("/template/base/objecttolerance", 10.0));
338         sp_repr_set_svg_double(rnew, "gridtolerance",
339             prefs->getDouble("/template/base/gridtolerance", 10.0));
340         sp_repr_set_svg_double(rnew, "guidetolerance",
341             prefs->getDouble("/template/base/guidetolerance", 10.0));
342         sp_repr_set_svg_double(rnew, "inkscape:pageopacity",
343             prefs->getDouble("/template/base/inkscape:pageopacity", 0.0));
344         sp_repr_set_int(rnew, "inkscape:pageshadow",
345             prefs->getInt("/template/base/inkscape:pageshadow", 2));
346         sp_repr_set_int(rnew, "inkscape:window-width",
347             prefs->getInt("/template/base/inkscape:window-width", 640));
348         sp_repr_set_int(rnew, "inkscape:window-height",
349             prefs->getInt("/template/base/inkscape:window-height", 480));
351         // insert into the document
352         rroot->addChild(rnew, NULL);
353         // clean up
354         Inkscape::GC::release(rnew);
355     }
357     /* Defs */
358     if (!SP_ROOT(document->root)->defs) {
359         Inkscape::XML::Node *r;
360         r = rdoc->createElement("svg:defs");
361         rroot->addChild(r, NULL);
362         Inkscape::GC::release(r);
363         g_assert(SP_ROOT(document->root)->defs);
364     }
366     /* Default RDF */
367     rdf_set_defaults( document );
369     if (keepalive) {
370         inkscape_ref();
371     }
373     // Remark: Here, we used to create a "currentpersp3d" element in the document defs.
374     // But this is probably a bad idea since we need to adapt it for every change of selection, which will
375     // completely clutter the undo history. Maybe rather save it to prefs on exit and re-read it on startup?
377     document->current_persp3d = persp3d_document_first_persp(document);
378     if (!document->current_persp3d) {
379         document->current_persp3d = persp3d_create_xml_element (document);
380     }
382     sp_document_set_undo_sensitive(document, true);
384     // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
385     if (!Inkscape::NSApplication::Application::getNewGui()) {
386         g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
387                          G_CALLBACK(sp_document_reset_key), document);
388         g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
389                          G_CALLBACK(sp_document_reset_key), document);
390         document->oldSignalsConnected = true;
391     } else {
392         document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
393         document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
394         document->oldSignalsConnected = false;
395     }
397     return document;
400 /**
401  * Fetches document from URI, or creates new, if NULL; public document
402  * appears in document list.
403  */
404 SPDocument *
405 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
407     SPDocument *doc;
408     Inkscape::XML::Document *rdoc;
409     gchar *base = NULL;
410     gchar *name = NULL;
412     if (uri) {
413         Inkscape::XML::Node *rroot;
414         gchar *s, *p;
415         /* Try to fetch repr from file */
416         rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
417         /* If file cannot be loaded, return NULL without warning */
418         if (rdoc == NULL) return NULL;
419         rroot = rdoc->root();
420         /* If xml file is not svg, return NULL without warning */
421         /* fixme: destroy document */
422         if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
423         s = g_strdup(uri);
424         p = strrchr(s, '/');
425         if (p) {
426             name = g_strdup(p + 1);
427             p[1] = '\0';
428             base = g_strdup(s);
429         } else {
430             base = NULL;
431             name = g_strdup(uri);
432         }
433         g_free(s);
434     } else {
435         rdoc = sp_repr_document_new("svg:svg");
436     }
438     if (make_new) {
439         base = NULL;
440         uri = NULL;
441         name = g_strdup_printf(_("New document %d"), ++doc_count);
442     }
444     //# These should be set by now
445     g_assert(name);
447     doc = sp_document_create(rdoc, uri, base, name, keepalive);
449     g_free(base);
450     g_free(name);
452     return doc;
455 SPDocument *
456 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
458     SPDocument *doc;
459     Inkscape::XML::Document *rdoc;
460     Inkscape::XML::Node *rroot;
461     gchar *name;
463     rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
465     /* If it cannot be loaded, return NULL without warning */
466     if (rdoc == NULL) return NULL;
468     rroot = rdoc->root();
469     /* If xml file is not svg, return NULL without warning */
470     /* fixme: destroy document */
471     if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
473     name = g_strdup_printf(_("Memory document %d"), ++doc_count);
475     doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
477     return doc;
480 SPDocument *
481 sp_document_ref(SPDocument *doc)
483     g_return_val_if_fail(doc != NULL, NULL);
484     Inkscape::GC::anchor(doc);
485     return doc;
488 SPDocument *
489 sp_document_unref(SPDocument *doc)
491     g_return_val_if_fail(doc != NULL, NULL);
492     Inkscape::GC::release(doc);
493     return NULL;
496 gdouble sp_document_width(SPDocument *document)
498     g_return_val_if_fail(document != NULL, 0.0);
499     g_return_val_if_fail(document->priv != NULL, 0.0);
500     g_return_val_if_fail(document->root != NULL, 0.0);
502     SPRoot *root = SP_ROOT(document->root);
504     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set)
505         return root->viewBox.x1 - root->viewBox.x0;
506     return root->width.computed;
509 void
510 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
512     SPRoot *root = SP_ROOT(document->root);
514     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
515         root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
516     } else { // set to width=
517         gdouble old_computed = root->width.computed;
518         root->width.computed = sp_units_get_pixels (width, *unit);
519         /* SVG does not support meters as a unit, so we must translate meters to
520          * cm when writing */
521         if (!strcmp(unit->abbr, "m")) {
522             root->width.value = 100*width;
523             root->width.unit = SVGLength::CM;
524         } else {
525             root->width.value = width;
526             root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
527         }
529         if (root->viewBox_set)
530             root->viewBox.x1 = root->viewBox.x0 + (root->width.computed / old_computed) * (root->viewBox.x1 - root->viewBox.x0);
531     }
533     SP_OBJECT (root)->updateRepr();
536 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
538     SPRoot *root = SP_ROOT(document->root);
540     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
541         root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
542     } else { // set to height=
543         gdouble old_computed = root->height.computed;
544         root->height.computed = sp_units_get_pixels (height, *unit);
545         /* SVG does not support meters as a unit, so we must translate meters to
546          * cm when writing */
547         if (!strcmp(unit->abbr, "m")) {
548             root->height.value = 100*height;
549             root->height.unit = SVGLength::CM;
550         } else {
551             root->height.value = height;
552             root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
553         }
555         if (root->viewBox_set)
556             root->viewBox.y1 = root->viewBox.y0 + (root->height.computed / old_computed) * (root->viewBox.y1 - root->viewBox.y0);
557     }
559     SP_OBJECT (root)->updateRepr();
562 gdouble sp_document_height(SPDocument *document)
564     g_return_val_if_fail(document != NULL, 0.0);
565     g_return_val_if_fail(document->priv != NULL, 0.0);
566     g_return_val_if_fail(document->root != NULL, 0.0);
568     SPRoot *root = SP_ROOT(document->root);
570     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set)
571         return root->viewBox.y1 - root->viewBox.y0;
572     return root->height.computed;
575 Geom::Point sp_document_dimensions(SPDocument *doc)
577     return Geom::Point(sp_document_width(doc), sp_document_height(doc));
580 /**
581  * Given a Geom::Rect that may, for example, correspond to the bbox of an object,
582  * this function fits the canvas to that rect by resizing the canvas
583  * and translating the document root into position.
584  */
585 void SPDocument::fitToRect(Geom::Rect const &rect)
587     double const w = rect.width();
588     double const h = rect.height();
590     double const old_height = sp_document_height(this);
591     SPUnit const &px(sp_unit_get_by_id(SP_UNIT_PX));
592     sp_document_set_width(this, w, &px);
593     sp_document_set_height(this, h, &px);
595     Geom::Translate const tr(Geom::Point(0, (old_height - h))
596                              - to_2geom(rect.min()));
597     SP_GROUP(root)->translateChildItems(tr);
598     SPNamedView *nv = sp_document_namedview(this, 0);
599     if(nv) {
600         Geom::Translate tr2(-rect.min());
601         nv->translateGuides(tr2);
603         // update the viewport so the drawing appears to stay where it was
604         nv->scrollAllDesktops(-tr2[0], tr2[1], false);
605     }
608 static void
609 do_change_uri(SPDocument *const document, gchar const *const filename, bool const rebase)
611     g_return_if_fail(document != NULL);
613     gchar *new_base;
614     gchar *new_name;
615     gchar *new_uri;
616     if (filename) {
618 #ifndef WIN32
619         new_uri = prepend_current_dir_if_relative(filename);
620 #else
621         // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
622         new_uri = g_strdup(filename);
623 #endif
625         new_base = g_path_get_dirname(new_uri);
626         new_name = g_path_get_basename(new_uri);
627     } else {
628         new_uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
629         new_base = NULL;
630         new_name = g_strdup(document->uri);
631     }
633     // Update saveable repr attributes.
634     Inkscape::XML::Node *repr = sp_document_repr_root(document);
636     // Changing uri in the document repr must not be not undoable.
637     bool const saved = sp_document_get_undo_sensitive(document);
638     sp_document_set_undo_sensitive(document, false);
640     if (rebase) {
641         Inkscape::XML::rebase_hrefs(document, new_base, true);
642     }
644     repr->setAttribute("sodipodi:docname", document->name);
645     sp_document_set_undo_sensitive(document, saved);
648     g_free(document->name);
649     g_free(document->base);
650     g_free(document->uri);
651     document->name = new_name;
652     document->base = new_base;
653     document->uri = new_uri;
655     document->priv->uri_set_signal.emit(document->uri);
658 /**
659  * Sets base, name and uri members of \a document.  Doesn't update
660  * any relative hrefs in the document: thus, this is primarily for
661  * newly-created documents.
662  *
663  * \see sp_document_change_uri_and_hrefs
664  */
665 void sp_document_set_uri(SPDocument *document, gchar const *filename)
667     g_return_if_fail(document != NULL);
669     do_change_uri(document, filename, false);
672 /**
673  * Changes the base, name and uri members of \a document, and updates any
674  * relative hrefs in the document to be relative to the new base.
675  *
676  * \see sp_document_set_uri
677  */
678 void sp_document_change_uri_and_hrefs(SPDocument *document, gchar const *filename)
680     g_return_if_fail(document != NULL);
682     do_change_uri(document, filename, true);
685 void
686 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
688     g_return_if_fail(doc != NULL);
690     doc->priv->resized_signal.emit(width, height);
693 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
695     return priv->modified_signal.connect(slot);
698 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
700     return priv->uri_set_signal.connect(slot);
703 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
705     return priv->resized_signal.connect(slot);
708 sigc::connection
709 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
711     return priv->_reconstruction_start_signal.connect(slot);
714 void
715 SPDocument::emitReconstructionStart(void)
717     // printf("Starting Reconstruction\n");
718     priv->_reconstruction_start_signal.emit();
719     return;
722 sigc::connection
723 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type  slot)
725     return priv->_reconstruction_finish_signal.connect(slot);
728 void
729 SPDocument::emitReconstructionFinish(void)
731     // printf("Finishing Reconstruction\n");
732     priv->_reconstruction_finish_signal.emit();
733     return;
736 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
738     return priv->commit_signal.connect(slot);
743 void SPDocument::_emitModified() {
744     static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
745     root->emitModified(0);
746     priv->modified_signal.emit(flags);
749 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
750     GQuark idq = g_quark_from_string(id);
752     if (object) {
753         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
754         g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
755     } else {
756         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
757         g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
758     }
760     SPDocumentPrivate::IDChangedSignalMap::iterator pos;
762     pos = priv->id_changed_signals.find(idq);
763     if ( pos != priv->id_changed_signals.end() ) {
764         if (!(*pos).second.empty()) {
765             (*pos).second.emit(object);
766         } else { // discard unused signal
767             priv->id_changed_signals.erase(pos);
768         }
769     }
772 void
773 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
775     this->priv->undoStackObservers.add(observer);
778 void
779 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
781     this->priv->undoStackObservers.remove(observer);
784 SPObject *SPDocument::getObjectById(gchar const *id) {
785     g_return_val_if_fail(id != NULL, NULL);
787     GQuark idq = g_quark_from_string(id);
788     return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
791 sigc::connection SPDocument::connectIdChanged(gchar const *id,
792                                               SPDocument::IDChangedSignal::slot_type slot)
794     return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
797 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
798     if (object) {
799         g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
800         g_hash_table_insert(priv->reprdef, repr, object);
801     } else {
802         g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
803         g_hash_table_remove(priv->reprdef, repr);
804     }
807 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
808     g_return_val_if_fail(repr != NULL, NULL);
809     return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
812 Glib::ustring SPDocument::getLanguage() {
813     gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
814     if (document_language) {
815         while (isspace(*document_language))
816             document_language++;
817     }
818     if ( !document_language || 0 == *document_language) {
819         // retrieve system language
820         document_language = getenv("LC_ALL");
821         if ( NULL == document_language || *document_language == 0 ) {
822             document_language = getenv ("LC_MESSAGES");
823         }
824         if ( NULL == document_language || *document_language == 0 ) {
825             document_language = getenv ("LANG");
826         }
828         if ( NULL != document_language ) {
829             const char *pos = strchr(document_language, '_');
830             if ( NULL != pos ) {
831                 return Glib::ustring(document_language, pos - document_language);
832             }
833         }
834     }
836     if ( NULL == document_language )
837         return Glib::ustring();
838     return document_language;
841 /* Object modification root handler */
843 void
844 sp_document_request_modified(SPDocument *doc)
846     if (!doc->modified_id) {
847         doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
848     }
851 void
852 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
854     ctx->ctx.flags = 0;
855     ctx->i2doc = Geom::identity();
856     /* Set up viewport in case svg has it defined as percentages */
857     if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
858         ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
859         ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
860         ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
861         ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
862     } else { // as a last resort, set size to A4
863         ctx->vp.x0 = 0.0;
864         ctx->vp.y0 = 0.0;
865         ctx->vp.x1 = 210 * PX_PER_MM;
866         ctx->vp.y1 = 297 * PX_PER_MM;
867     }
868     ctx->i2vp = Geom::identity();
871 /**
872  * Tries to update the document state based on the modified and
873  * "update required" flags, and return true if the document has
874  * been brought fully up to date.
875  */
876 bool
877 SPDocument::_updateDocument()
879     /* Process updates */
880     if (this->root->uflags || this->root->mflags) {
881         if (this->root->uflags) {
882             SPItemCtx ctx;
883             sp_document_setup_viewport (this, &ctx);
885             bool saved = sp_document_get_undo_sensitive(this);
886             sp_document_set_undo_sensitive(this, false);
888             this->root->updateDisplay((SPCtx *)&ctx, 0);
890             sp_document_set_undo_sensitive(this, saved);
891         }
892         this->_emitModified();
893     }
895     return !(this->root->uflags || this->root->mflags);
899 /**
900  * Repeatedly works on getting the document updated, since sometimes
901  * it takes more than one pass to get the document updated.  But it
902  * usually should not take more than a few loops, and certainly never
903  * more than 32 iterations.  So we bail out if we hit 32 iterations,
904  * since this typically indicates we're stuck in an update loop.
905  */
906 gint
907 sp_document_ensure_up_to_date(SPDocument *doc)
909     int counter = 32;
910     while (!doc->_updateDocument()) {
911         if (counter == 0) {
912             g_warning("More than 32 iteration while updating document '%s'", doc->uri);
913             break;
914         }
915         counter--;
916     }
918     if (doc->modified_id) {
919         /* Remove handler */
920         gtk_idle_remove(doc->modified_id);
921         doc->modified_id = 0;
922     }
923     return counter>0;
926 /**
927  * An idle handler to update the document.  Returns true if
928  * the document needs further updates.
929  */
930 static gint
931 sp_document_idle_handler(gpointer data)
933     SPDocument *doc = static_cast<SPDocument *>(data);
934     if (doc->_updateDocument()) {
935         doc->modified_id = 0;
936         return false;
937     } else {
938         return true;
939     }
942 static bool is_within(Geom::Rect const &area, Geom::Rect const &box)
944     return area.contains(box);
947 static bool overlaps(Geom::Rect const &area, Geom::Rect const &box)
949     return area.intersects(box);
952 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, Geom::Rect const &area,
953                                   bool (*test)(Geom::Rect const &, Geom::Rect const &), bool take_insensitive = false)
955     g_return_val_if_fail(SP_IS_GROUP(group), s);
957     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
958         if (!SP_IS_ITEM(o)) {
959             continue;
960         }
961         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
962             s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
963         } else {
964             SPItem *child = SP_ITEM(o);
965             Geom::OptRect box = sp_item_bbox_desktop(child);
966             if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
967                 s = g_slist_append(s, child);
968             }
969         }
970     }
972     return s;
975 /**
976 Returns true if an item is among the descendants of group (recursively).
977  */
978 bool item_is_in_group(SPItem *item, SPGroup *group)
980     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
981         if (!SP_IS_ITEM(o)) continue;
982         if (SP_ITEM(o) == item)
983             return true;
984         if (SP_IS_GROUP(o))
985             if (item_is_in_group(item, SP_GROUP(o)))
986                 return true;
987     }
988     return false;
991 /**
992 Returns the bottommost item from the list which is at the point, or NULL if none.
993 */
994 SPItem*
995 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
996                                            Geom::Point const p, bool take_insensitive)
998     g_return_val_if_fail(group, NULL);
999     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1000     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1002     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1004         if (!SP_IS_ITEM(o)) continue;
1006         SPItem *item = SP_ITEM(o);
1007         NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
1008         if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1009             && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
1010             if (g_slist_find((GSList *) list, item) != NULL)
1011                 return item;
1012         }
1014         if (SP_IS_GROUP(o)) {
1015             SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
1016             if (found)
1017                 return found;
1018         }
1020     }
1021     return NULL;
1024 /**
1025 Returns the topmost (in z-order) item from the descendants of group (recursively) which
1026 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
1027 non-layer groups or not. Honors take_insensitive on whether to return insensitive
1028 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
1029 upwards in z-order and returns what it has found so far (i.e. the found item is
1030 guaranteed to be lower than upto).
1031  */
1032 SPItem*
1033 find_item_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
1035     SPItem *seen = NULL, *newseen = NULL;
1036     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1037     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1039     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1040         if (!SP_IS_ITEM(o)) continue;
1042         if (upto && SP_ITEM(o) == upto)
1043             break;
1045         if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
1046             // if nothing found yet, recurse into the group
1047             newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
1048             if (newseen) {
1049                 seen = newseen;
1050                 newseen = NULL;
1051             }
1053             if (item_is_in_group(upto, SP_GROUP(o)))
1054                 break;
1056         } else {
1057             SPItem *child = SP_ITEM(o);
1058             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1060             // seen remembers the last (topmost) of items pickable at this point
1061             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1062                 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1063                 seen = child;
1064             }
1065         }
1066     }
1067     return seen;
1070 /**
1071 Returns the topmost non-layer group from the descendants of group which is at point
1072 p, or NULL if none. Recurses into layers but not into groups.
1073  */
1074 SPItem*
1075 find_group_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p)
1077     SPItem *seen = NULL;
1078     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1079     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1081     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1082         if (!SP_IS_ITEM(o)) continue;
1083         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1084             SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1085             if (newseen) {
1086                 seen = newseen;
1087             }
1088         }
1089         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1090             SPItem *child = SP_ITEM(o);
1091             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1093             // seen remembers the last (topmost) of groups pickable at this point
1094             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1095                 seen = child;
1096             }
1097         }
1098     }
1099     return seen;
1102 /*
1103  * Return list of items, contained in box
1104  *
1105  * Assumes box is normalized (and g_asserts it!)
1106  *
1107  */
1109 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1111     g_return_val_if_fail(document != NULL, NULL);
1112     g_return_val_if_fail(document->priv != NULL, NULL);
1114     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
1117 /*
1118  * Return list of items, that the parts of the item contained in box
1119  *
1120  * Assumes box is normalized (and g_asserts it!)
1121  *
1122  */
1124 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1126     g_return_val_if_fail(document != NULL, NULL);
1127     g_return_val_if_fail(document->priv != NULL, NULL);
1129     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1132 GSList *
1133 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<Geom::Point> points)
1135     GSList *items = NULL;
1136     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1138     // When picking along the path, we don't want small objects close together
1139     // (such as hatching strokes) to obscure each other by their deltas,
1140     // so we temporarily set delta to a small value
1141     gdouble saved_delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1142     prefs->setDouble("/options/cursortolerance/value", 0.25);
1144     for(unsigned int i = 0; i < points.size(); i++) {
1145         SPItem *item = sp_document_item_at_point(document, key, points[i],
1146                                                  false, NULL);
1147         if (item && !g_slist_find(items, item))
1148             items = g_slist_prepend (items, item);
1149     }
1151     // and now we restore it back
1152     prefs->setDouble("/options/cursortolerance/value", saved_delta);
1154     return items;
1157 SPItem *
1158 sp_document_item_at_point(SPDocument *document, unsigned const key, Geom::Point const p,
1159                           gboolean const into_groups, SPItem *upto)
1161     g_return_val_if_fail(document != NULL, NULL);
1162     g_return_val_if_fail(document->priv != NULL, NULL);
1164     return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1167 SPItem*
1168 sp_document_group_at_point(SPDocument *document, unsigned int key, Geom::Point const p)
1170     g_return_val_if_fail(document != NULL, NULL);
1171     g_return_val_if_fail(document->priv != NULL, NULL);
1173     return find_group_at_point(key, SP_GROUP(document->root), p);
1177 /* Resource management */
1179 gboolean
1180 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1182     GSList *rlist;
1183     GQuark q = g_quark_from_string(key);
1185     g_return_val_if_fail(document != NULL, FALSE);
1186     g_return_val_if_fail(key != NULL, FALSE);
1187     g_return_val_if_fail(*key != '\0', FALSE);
1188     g_return_val_if_fail(object != NULL, FALSE);
1189     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1191     if (SP_OBJECT_IS_CLONED(object))
1192         return FALSE;
1194     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1195     g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1196     rlist = g_slist_prepend(rlist, object);
1197     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1199     document->priv->resources_changed_signals[q].emit();
1201     return TRUE;
1204 gboolean
1205 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1207     GSList *rlist;
1208     GQuark q = g_quark_from_string(key);
1210     g_return_val_if_fail(document != NULL, FALSE);
1211     g_return_val_if_fail(key != NULL, FALSE);
1212     g_return_val_if_fail(*key != '\0', FALSE);
1213     g_return_val_if_fail(object != NULL, FALSE);
1214     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1216     if (SP_OBJECT_IS_CLONED(object))
1217         return FALSE;
1219     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1220     g_return_val_if_fail(rlist != NULL, FALSE);
1221     g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1222     rlist = g_slist_remove(rlist, object);
1223     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1225     document->priv->resources_changed_signals[q].emit();
1227     return TRUE;
1230 GSList const *
1231 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1233     g_return_val_if_fail(document != NULL, NULL);
1234     g_return_val_if_fail(key != NULL, NULL);
1235     g_return_val_if_fail(*key != '\0', NULL);
1237     return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1240 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1241                                                        gchar const *key,
1242                                                        SPDocument::ResourcesChangedSignal::slot_type slot)
1244     GQuark q = g_quark_from_string(key);
1245     return document->priv->resources_changed_signals[q].connect(slot);
1248 /* Helpers */
1250 gboolean
1251 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1253     g_slist_free((GSList *) value);
1254     return TRUE;
1257 unsigned int
1258 count_objects_recursive(SPObject *obj, unsigned int count)
1260     count++; // obj itself
1262     for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1263         count = count_objects_recursive(i, count);
1264     }
1266     return count;
1269 unsigned int
1270 objects_in_document(SPDocument *document)
1272     return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1275 void
1276 vacuum_document_recursive(SPObject *obj)
1278     if (SP_IS_DEFS(obj)) {
1279         for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1280             /* fixme: some inkscape-internal nodes in the future might not be collectable */
1281             def->requestOrphanCollection();
1282         }
1283     } else {
1284         for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1285             vacuum_document_recursive(i);
1286         }
1287     }
1290 unsigned int
1291 vacuum_document(SPDocument *document)
1293     unsigned int start = objects_in_document(document);
1294     unsigned int end;
1295     unsigned int newend = start;
1297     unsigned int iterations = 0;
1299     do {
1300         end = newend;
1302         vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1303         document->collectOrphans();
1304         iterations++;
1306         newend = objects_in_document(document);
1308     } while (iterations < 100 && newend < end);
1310     return start - newend;
1313 bool SPDocument::isSeeking() const {
1314     return priv->seeking;
1318 /*
1319   Local Variables:
1320   mode:c++
1321   c-file-style:"stroustrup"
1322   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1323   indent-tabs-mode:nil
1324   fill-column:99
1325   End:
1326 */
1327 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :