Code

Merging in from trunk
[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 void SPDocument::initialize_current_persp3d()
229     this->current_persp3d = persp3d_document_first_persp(this);
230     if (!this->current_persp3d) {
231         this->current_persp3d = persp3d_create_xml_element(this);
232     }
235 unsigned long SPDocument::serial() const {
236     return priv->serial;
239 void SPDocument::queueForOrphanCollection(SPObject *object) {
240     g_return_if_fail(object != NULL);
241     g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
243     sp_object_ref(object, NULL);
244     _collection_queue = g_slist_prepend(_collection_queue, object);
247 void SPDocument::collectOrphans() {
248     while (_collection_queue) {
249         GSList *objects=_collection_queue;
250         _collection_queue = NULL;
251         for ( GSList *iter=objects ; iter ; iter = iter->next ) {
252             SPObject *object=reinterpret_cast<SPObject *>(iter->data);
253             object->collectOrphan();
254             sp_object_unref(object, NULL);
255         }
256         g_slist_free(objects);
257     }
260 void SPDocument::reset_key (void */*dummy*/)
262     actionkey = NULL;
265 SPDocument *
266 sp_document_create(Inkscape::XML::Document *rdoc,
267                    gchar const *uri,
268                    gchar const *base,
269                    gchar const *name,
270                    unsigned int keepalive)
272     SPDocument *document;
273     Inkscape::XML::Node *rroot;
274     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
276     rroot = rdoc->root();
278     document = new SPDocument();
280     document->keepalive = keepalive;
282     document->rdoc = rdoc;
283     document->rroot = rroot;
285 #ifndef WIN32
286     document->uri = prepend_current_dir_if_relative(uri);
287 #else
288     // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
289     document->uri = uri? g_strdup(uri) : NULL;
290 #endif
292     // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
293     // which is why we use g_get_current_dir() in calculating the abs path above
294     //This is NULL for a new document
295     if (base)
296         document->base = g_strdup(base);
297     else
298         document->base = NULL;
299     document->name = g_strdup(name);
301     document->root = sp_object_repr_build_tree(document, rroot);
303     /* fixme: Not sure about this, but lets assume ::build updates */
304     rroot->setAttribute("inkscape:version", Inkscape::version_string);
305     /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
307     /* Quick hack 2 - get default image size into document */
308     if (!rroot->attribute("width")) rroot->setAttribute("width", "100%");
309     if (!rroot->attribute("height")) rroot->setAttribute("height", "100%");
310     /* End of quick hack 2 */
312     /* Quick hack 3 - Set uri attributes */
313     if (uri) {
314         rroot->setAttribute("sodipodi:docname", uri);
315     }
316     /* End of quick hack 3 */
318     /* Eliminate obsolete sodipodi:docbase, for privacy reasons */
319     rroot->setAttribute("sodipodi:docbase", NULL);
321     /* Eliminate any claim to adhere to a profile, as we don't try to */
322     rroot->setAttribute("baseProfile", NULL);
324     // creating namedview
325     if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
326         // if there's none in the document already,
327         Inkscape::XML::Node *rnew = NULL;
329         rnew = rdoc->createElement("sodipodi:namedview");
330         //rnew->setAttribute("id", "base");
332         // Add namedview data from the preferences
333         // we can't use getAllEntries because this could produce non-SVG doubles
334         Glib::ustring pagecolor = prefs->getString("/template/base/pagecolor");
335         if (!pagecolor.empty()) {
336             rnew->setAttribute("pagecolor", pagecolor.data());
337         }
338         Glib::ustring bordercolor = prefs->getString("/template/base/bordercolor");
339         if (!bordercolor.empty()) {
340             rnew->setAttribute("bordercolor", bordercolor.data());
341         }
342         sp_repr_set_svg_double(rnew, "borderopacity",
343             prefs->getDouble("/template/base/borderopacity", 1.0));
344         sp_repr_set_svg_double(rnew, "objecttolerance",
345             prefs->getDouble("/template/base/objecttolerance", 10.0));
346         sp_repr_set_svg_double(rnew, "gridtolerance",
347             prefs->getDouble("/template/base/gridtolerance", 10.0));
348         sp_repr_set_svg_double(rnew, "guidetolerance",
349             prefs->getDouble("/template/base/guidetolerance", 10.0));
350         sp_repr_set_svg_double(rnew, "inkscape:pageopacity",
351             prefs->getDouble("/template/base/inkscape:pageopacity", 0.0));
352         sp_repr_set_int(rnew, "inkscape:pageshadow",
353             prefs->getInt("/template/base/inkscape:pageshadow", 2));
354         sp_repr_set_int(rnew, "inkscape:window-width",
355             prefs->getInt("/template/base/inkscape:window-width", 640));
356         sp_repr_set_int(rnew, "inkscape:window-height",
357             prefs->getInt("/template/base/inkscape:window-height", 480));
359         // insert into the document
360         rroot->addChild(rnew, NULL);
361         // clean up
362         Inkscape::GC::release(rnew);
363     }
365     /* Defs */
366     if (!SP_ROOT(document->root)->defs) {
367         Inkscape::XML::Node *r;
368         r = rdoc->createElement("svg:defs");
369         rroot->addChild(r, NULL);
370         Inkscape::GC::release(r);
371         g_assert(SP_ROOT(document->root)->defs);
372     }
374     /* Default RDF */
375     rdf_set_defaults( document );
377     if (keepalive) {
378         inkscape_ref();
379     }
381     // Remark: Here, we used to create a "currentpersp3d" element in the document defs.
382     // But this is probably a bad idea since we need to adapt it for every change of selection, which will
383     // completely clutter the undo history. Maybe rather save it to prefs on exit and re-read it on startup?
384     document->initialize_current_persp3d();
386     sp_document_set_undo_sensitive(document, true);
388     // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
389     if (!Inkscape::NSApplication::Application::getNewGui()) {
390         g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
391                          G_CALLBACK(sp_document_reset_key), document);
392         g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
393                          G_CALLBACK(sp_document_reset_key), document);
394         document->oldSignalsConnected = true;
395     } else {
396         document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
397         document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
398         document->oldSignalsConnected = false;
399     }
401     return document;
404 /**
405  * Fetches document from URI, or creates new, if NULL; public document
406  * appears in document list.
407  */
408 SPDocument *
409 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
411     SPDocument *doc;
412     Inkscape::XML::Document *rdoc;
413     gchar *base = NULL;
414     gchar *name = NULL;
416     if (uri) {
417         Inkscape::XML::Node *rroot;
418         gchar *s, *p;
419         /* Try to fetch repr from file */
420         rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
421         /* If file cannot be loaded, return NULL without warning */
422         if (rdoc == NULL) return NULL;
423         rroot = rdoc->root();
424         /* If xml file is not svg, return NULL without warning */
425         /* fixme: destroy document */
426         if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
427         s = g_strdup(uri);
428         p = strrchr(s, '/');
429         if (p) {
430             name = g_strdup(p + 1);
431             p[1] = '\0';
432             base = g_strdup(s);
433         } else {
434             base = NULL;
435             name = g_strdup(uri);
436         }
437         g_free(s);
438     } else {
439         rdoc = sp_repr_document_new("svg:svg");
440     }
442     if (make_new) {
443         base = NULL;
444         uri = NULL;
445         name = g_strdup_printf(_("New document %d"), ++doc_count);
446     }
448     //# These should be set by now
449     g_assert(name);
451     doc = sp_document_create(rdoc, uri, base, name, keepalive);
453     g_free(base);
454     g_free(name);
456     return doc;
459 SPDocument *
460 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
462     SPDocument *doc;
463     Inkscape::XML::Document *rdoc;
464     Inkscape::XML::Node *rroot;
465     gchar *name;
467     rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
469     /* If it cannot be loaded, return NULL without warning */
470     if (rdoc == NULL) return NULL;
472     rroot = rdoc->root();
473     /* If xml file is not svg, return NULL without warning */
474     /* fixme: destroy document */
475     if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
477     name = g_strdup_printf(_("Memory document %d"), ++doc_count);
479     doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
481     return doc;
484 SPDocument *
485 sp_document_ref(SPDocument *doc)
487     g_return_val_if_fail(doc != NULL, NULL);
488     Inkscape::GC::anchor(doc);
489     return doc;
492 SPDocument *
493 sp_document_unref(SPDocument *doc)
495     g_return_val_if_fail(doc != NULL, NULL);
496     Inkscape::GC::release(doc);
497     return NULL;
500 gdouble sp_document_width(SPDocument *document)
502     g_return_val_if_fail(document != NULL, 0.0);
503     g_return_val_if_fail(document->priv != NULL, 0.0);
504     g_return_val_if_fail(document->root != NULL, 0.0);
506     SPRoot *root = SP_ROOT(document->root);
508     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set)
509         return root->viewBox.x1 - root->viewBox.x0;
510     return root->width.computed;
513 void
514 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
516     SPRoot *root = SP_ROOT(document->root);
518     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
519         root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
520     } else { // set to width=
521         gdouble old_computed = root->width.computed;
522         root->width.computed = sp_units_get_pixels (width, *unit);
523         /* SVG does not support meters as a unit, so we must translate meters to
524          * cm when writing */
525         if (!strcmp(unit->abbr, "m")) {
526             root->width.value = 100*width;
527             root->width.unit = SVGLength::CM;
528         } else {
529             root->width.value = width;
530             root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
531         }
533         if (root->viewBox_set)
534             root->viewBox.x1 = root->viewBox.x0 + (root->width.computed / old_computed) * (root->viewBox.x1 - root->viewBox.x0);
535     }
537     SP_OBJECT (root)->updateRepr();
540 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
542     SPRoot *root = SP_ROOT(document->root);
544     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
545         root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
546     } else { // set to height=
547         gdouble old_computed = root->height.computed;
548         root->height.computed = sp_units_get_pixels (height, *unit);
549         /* SVG does not support meters as a unit, so we must translate meters to
550          * cm when writing */
551         if (!strcmp(unit->abbr, "m")) {
552             root->height.value = 100*height;
553             root->height.unit = SVGLength::CM;
554         } else {
555             root->height.value = height;
556             root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
557         }
559         if (root->viewBox_set)
560             root->viewBox.y1 = root->viewBox.y0 + (root->height.computed / old_computed) * (root->viewBox.y1 - root->viewBox.y0);
561     }
563     SP_OBJECT (root)->updateRepr();
566 gdouble sp_document_height(SPDocument *document)
568     g_return_val_if_fail(document != NULL, 0.0);
569     g_return_val_if_fail(document->priv != NULL, 0.0);
570     g_return_val_if_fail(document->root != NULL, 0.0);
572     SPRoot *root = SP_ROOT(document->root);
574     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set)
575         return root->viewBox.y1 - root->viewBox.y0;
576     return root->height.computed;
579 Geom::Point sp_document_dimensions(SPDocument *doc)
581     return Geom::Point(sp_document_width(doc), sp_document_height(doc));
584 /**
585  * Given a Geom::Rect that may, for example, correspond to the bbox of an object,
586  * this function fits the canvas to that rect by resizing the canvas
587  * and translating the document root into position.
588  */
589 void SPDocument::fitToRect(Geom::Rect const &rect)
591     double const w = rect.width();
592     double const h = rect.height();
594     double const old_height = sp_document_height(this);
595     SPUnit const &px(sp_unit_get_by_id(SP_UNIT_PX));
596     sp_document_set_width(this, w, &px);
597     sp_document_set_height(this, h, &px);
599     Geom::Translate const tr(Geom::Point(0, (old_height - h))
600                              - to_2geom(rect.min()));
601     SP_GROUP(root)->translateChildItems(tr);
602     SPNamedView *nv = sp_document_namedview(this, 0);
603     if(nv) {
604         Geom::Translate tr2(-rect.min());
605         nv->translateGuides(tr2);
607         // update the viewport so the drawing appears to stay where it was
608         nv->scrollAllDesktops(-tr2[0], tr2[1], false);
609     }
612 static void
613 do_change_uri(SPDocument *const document, gchar const *const filename, bool const rebase)
615     g_return_if_fail(document != NULL);
617     gchar *new_base;
618     gchar *new_name;
619     gchar *new_uri;
620     if (filename) {
622 #ifndef WIN32
623         new_uri = prepend_current_dir_if_relative(filename);
624 #else
625         // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
626         new_uri = g_strdup(filename);
627 #endif
629         new_base = g_path_get_dirname(new_uri);
630         new_name = g_path_get_basename(new_uri);
631     } else {
632         new_uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
633         new_base = NULL;
634         new_name = g_strdup(document->uri);
635     }
637     // Update saveable repr attributes.
638     Inkscape::XML::Node *repr = sp_document_repr_root(document);
640     // Changing uri in the document repr must not be not undoable.
641     bool const saved = sp_document_get_undo_sensitive(document);
642     sp_document_set_undo_sensitive(document, false);
644     if (rebase) {
645         Inkscape::XML::rebase_hrefs(document, new_base, true);
646     }
648     repr->setAttribute("sodipodi:docname", document->name);
649     sp_document_set_undo_sensitive(document, saved);
652     g_free(document->name);
653     g_free(document->base);
654     g_free(document->uri);
655     document->name = new_name;
656     document->base = new_base;
657     document->uri = new_uri;
659     document->priv->uri_set_signal.emit(document->uri);
662 /**
663  * Sets base, name and uri members of \a document.  Doesn't update
664  * any relative hrefs in the document: thus, this is primarily for
665  * newly-created documents.
666  *
667  * \see sp_document_change_uri_and_hrefs
668  */
669 void sp_document_set_uri(SPDocument *document, gchar const *filename)
671     g_return_if_fail(document != NULL);
673     do_change_uri(document, filename, false);
676 /**
677  * Changes the base, name and uri members of \a document, and updates any
678  * relative hrefs in the document to be relative to the new base.
679  *
680  * \see sp_document_set_uri
681  */
682 void sp_document_change_uri_and_hrefs(SPDocument *document, gchar const *filename)
684     g_return_if_fail(document != NULL);
686     do_change_uri(document, filename, true);
689 void
690 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
692     g_return_if_fail(doc != NULL);
694     doc->priv->resized_signal.emit(width, height);
697 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
699     return priv->modified_signal.connect(slot);
702 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
704     return priv->uri_set_signal.connect(slot);
707 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
709     return priv->resized_signal.connect(slot);
712 sigc::connection
713 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
715     return priv->_reconstruction_start_signal.connect(slot);
718 void
719 SPDocument::emitReconstructionStart(void)
721     // printf("Starting Reconstruction\n");
722     priv->_reconstruction_start_signal.emit();
723     return;
726 sigc::connection
727 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type  slot)
729     return priv->_reconstruction_finish_signal.connect(slot);
732 void
733 SPDocument::emitReconstructionFinish(void)
735     // printf("Finishing Reconstruction\n");
736     priv->_reconstruction_finish_signal.emit();
737     
738     // Reference to the old persp3d object is invalid after reconstruction.
739     initialize_current_persp3d();
740     
741     return;
744 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
746     return priv->commit_signal.connect(slot);
751 void SPDocument::_emitModified() {
752     static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
753     root->emitModified(0);
754     priv->modified_signal.emit(flags);
757 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
758     GQuark idq = g_quark_from_string(id);
760     if (object) {
761         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
762         g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
763     } else {
764         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
765         g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
766     }
768     SPDocumentPrivate::IDChangedSignalMap::iterator pos;
770     pos = priv->id_changed_signals.find(idq);
771     if ( pos != priv->id_changed_signals.end() ) {
772         if (!(*pos).second.empty()) {
773             (*pos).second.emit(object);
774         } else { // discard unused signal
775             priv->id_changed_signals.erase(pos);
776         }
777     }
780 void
781 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
783     this->priv->undoStackObservers.add(observer);
786 void
787 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
789     this->priv->undoStackObservers.remove(observer);
792 SPObject *SPDocument::getObjectById(gchar const *id) {
793     g_return_val_if_fail(id != NULL, NULL);
795     GQuark idq = g_quark_from_string(id);
796     return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
799 sigc::connection SPDocument::connectIdChanged(gchar const *id,
800                                               SPDocument::IDChangedSignal::slot_type slot)
802     return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
805 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
806     if (object) {
807         g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
808         g_hash_table_insert(priv->reprdef, repr, object);
809     } else {
810         g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
811         g_hash_table_remove(priv->reprdef, repr);
812     }
815 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
816     g_return_val_if_fail(repr != NULL, NULL);
817     return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
820 Glib::ustring SPDocument::getLanguage() {
821     gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
822     if (document_language) {
823         while (isspace(*document_language))
824             document_language++;
825     }
826     if ( !document_language || 0 == *document_language) {
827         // retrieve system language
828         document_language = getenv("LC_ALL");
829         if ( NULL == document_language || *document_language == 0 ) {
830             document_language = getenv ("LC_MESSAGES");
831         }
832         if ( NULL == document_language || *document_language == 0 ) {
833             document_language = getenv ("LANG");
834         }
836         if ( NULL != document_language ) {
837             const char *pos = strchr(document_language, '_');
838             if ( NULL != pos ) {
839                 return Glib::ustring(document_language, pos - document_language);
840             }
841         }
842     }
844     if ( NULL == document_language )
845         return Glib::ustring();
846     return document_language;
849 /* Object modification root handler */
851 void
852 sp_document_request_modified(SPDocument *doc)
854     if (!doc->modified_id) {
855         doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
856     }
859 void
860 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
862     ctx->ctx.flags = 0;
863     ctx->i2doc = Geom::identity();
864     /* Set up viewport in case svg has it defined as percentages */
865     if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
866         ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
867         ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
868         ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
869         ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
870     } else { // as a last resort, set size to A4
871         ctx->vp.x0 = 0.0;
872         ctx->vp.y0 = 0.0;
873         ctx->vp.x1 = 210 * PX_PER_MM;
874         ctx->vp.y1 = 297 * PX_PER_MM;
875     }
876     ctx->i2vp = Geom::identity();
879 /**
880  * Tries to update the document state based on the modified and
881  * "update required" flags, and return true if the document has
882  * been brought fully up to date.
883  */
884 bool
885 SPDocument::_updateDocument()
887     /* Process updates */
888     if (this->root->uflags || this->root->mflags) {
889         if (this->root->uflags) {
890             SPItemCtx ctx;
891             sp_document_setup_viewport (this, &ctx);
893             bool saved = sp_document_get_undo_sensitive(this);
894             sp_document_set_undo_sensitive(this, false);
896             this->root->updateDisplay((SPCtx *)&ctx, 0);
898             sp_document_set_undo_sensitive(this, saved);
899         }
900         this->_emitModified();
901     }
903     return !(this->root->uflags || this->root->mflags);
907 /**
908  * Repeatedly works on getting the document updated, since sometimes
909  * it takes more than one pass to get the document updated.  But it
910  * usually should not take more than a few loops, and certainly never
911  * more than 64 iterations.  So we bail out if we hit 64 iterations,
912  * since this typically indicates we're stuck in an update loop.
913  */
914 gint
915 sp_document_ensure_up_to_date(SPDocument *doc)
917     int counter = 64;
918     while (!doc->_updateDocument()) {
919         if (counter == 0) {
920             g_warning("More than 64 iteration while updating document '%s'", doc->uri? doc->uri:"<unknown URI, probably clipboard>");
921             break;
922         }
923         counter--;
924     }
926     if (doc->modified_id) {
927         /* Remove handler */
928         gtk_idle_remove(doc->modified_id);
929         doc->modified_id = 0;
930     }
931     return counter>0;
934 /**
935  * An idle handler to update the document.  Returns true if
936  * the document needs further updates.
937  */
938 static gint
939 sp_document_idle_handler(gpointer data)
941     SPDocument *doc = static_cast<SPDocument *>(data);
942     if (doc->_updateDocument()) {
943         doc->modified_id = 0;
944         return false;
945     } else {
946         return true;
947     }
950 static bool is_within(Geom::Rect const &area, Geom::Rect const &box)
952     return area.contains(box);
955 static bool overlaps(Geom::Rect const &area, Geom::Rect const &box)
957     return area.intersects(box);
960 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, Geom::Rect const &area,
961                                   bool (*test)(Geom::Rect const &, Geom::Rect const &), bool take_insensitive = false)
963     g_return_val_if_fail(SP_IS_GROUP(group), s);
965     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
966         if (!SP_IS_ITEM(o)) {
967             continue;
968         }
969         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
970             s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
971         } else {
972             SPItem *child = SP_ITEM(o);
973             Geom::OptRect box = sp_item_bbox_desktop(child);
974             if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
975                 s = g_slist_append(s, child);
976             }
977         }
978     }
980     return s;
983 /**
984 Returns true if an item is among the descendants of group (recursively).
985  */
986 bool item_is_in_group(SPItem *item, SPGroup *group)
988     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
989         if (!SP_IS_ITEM(o)) continue;
990         if (SP_ITEM(o) == item)
991             return true;
992         if (SP_IS_GROUP(o))
993             if (item_is_in_group(item, SP_GROUP(o)))
994                 return true;
995     }
996     return false;
999 /**
1000 Returns the bottommost item from the list which is at the point, or NULL if none.
1001 */
1002 SPItem*
1003 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
1004                                            Geom::Point const p, bool take_insensitive)
1006     g_return_val_if_fail(group, NULL);
1007     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1008     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1010     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1012         if (!SP_IS_ITEM(o)) continue;
1014         SPItem *item = SP_ITEM(o);
1015         NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
1016         if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1017             && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
1018             if (g_slist_find((GSList *) list, item) != NULL)
1019                 return item;
1020         }
1022         if (SP_IS_GROUP(o)) {
1023             SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
1024             if (found)
1025                 return found;
1026         }
1028     }
1029     return NULL;
1032 /**
1033 Returns the topmost (in z-order) item from the descendants of group (recursively) which
1034 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
1035 non-layer groups or not. Honors take_insensitive on whether to return insensitive
1036 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
1037 upwards in z-order and returns what it has found so far (i.e. the found item is
1038 guaranteed to be lower than upto).
1039  */
1040 SPItem*
1041 find_item_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
1043     SPItem *seen = NULL, *newseen = NULL;
1044     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1045     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1047     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1048         if (!SP_IS_ITEM(o)) continue;
1050         if (upto && SP_ITEM(o) == upto)
1051             break;
1053         if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
1054             // if nothing found yet, recurse into the group
1055             newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
1056             if (newseen) {
1057                 seen = newseen;
1058                 newseen = NULL;
1059             }
1061             if (item_is_in_group(upto, SP_GROUP(o)))
1062                 break;
1064         } else {
1065             SPItem *child = SP_ITEM(o);
1066             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1068             // seen remembers the last (topmost) of items pickable at this point
1069             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1070                 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1071                 seen = child;
1072             }
1073         }
1074     }
1075     return seen;
1078 /**
1079 Returns the topmost non-layer group from the descendants of group which is at point
1080 p, or NULL if none. Recurses into layers but not into groups.
1081  */
1082 SPItem*
1083 find_group_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p)
1085     SPItem *seen = NULL;
1086     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1087     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1089     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1090         if (!SP_IS_ITEM(o)) continue;
1091         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1092             SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1093             if (newseen) {
1094                 seen = newseen;
1095             }
1096         }
1097         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1098             SPItem *child = SP_ITEM(o);
1099             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1101             // seen remembers the last (topmost) of groups pickable at this point
1102             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1103                 seen = child;
1104             }
1105         }
1106     }
1107     return seen;
1110 /*
1111  * Return list of items, contained in box
1112  *
1113  * Assumes box is normalized (and g_asserts it!)
1114  *
1115  */
1117 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1119     g_return_val_if_fail(document != NULL, NULL);
1120     g_return_val_if_fail(document->priv != NULL, NULL);
1122     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
1125 /*
1126  * Return list of items, that the parts of the item contained in box
1127  *
1128  * Assumes box is normalized (and g_asserts it!)
1129  *
1130  */
1132 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1134     g_return_val_if_fail(document != NULL, NULL);
1135     g_return_val_if_fail(document->priv != NULL, NULL);
1137     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1140 GSList *
1141 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<Geom::Point> points)
1143     GSList *items = NULL;
1144     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1146     // When picking along the path, we don't want small objects close together
1147     // (such as hatching strokes) to obscure each other by their deltas,
1148     // so we temporarily set delta to a small value
1149     gdouble saved_delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1150     prefs->setDouble("/options/cursortolerance/value", 0.25);
1152     for(unsigned int i = 0; i < points.size(); i++) {
1153         SPItem *item = sp_document_item_at_point(document, key, points[i],
1154                                                  false, NULL);
1155         if (item && !g_slist_find(items, item))
1156             items = g_slist_prepend (items, item);
1157     }
1159     // and now we restore it back
1160     prefs->setDouble("/options/cursortolerance/value", saved_delta);
1162     return items;
1165 SPItem *
1166 sp_document_item_at_point(SPDocument *document, unsigned const key, Geom::Point const p,
1167                           gboolean const into_groups, SPItem *upto)
1169     g_return_val_if_fail(document != NULL, NULL);
1170     g_return_val_if_fail(document->priv != NULL, NULL);
1172     return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1175 SPItem*
1176 sp_document_group_at_point(SPDocument *document, unsigned int key, Geom::Point const p)
1178     g_return_val_if_fail(document != NULL, NULL);
1179     g_return_val_if_fail(document->priv != NULL, NULL);
1181     return find_group_at_point(key, SP_GROUP(document->root), p);
1185 /* Resource management */
1187 gboolean
1188 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1190     GSList *rlist;
1191     GQuark q = g_quark_from_string(key);
1193     g_return_val_if_fail(document != NULL, FALSE);
1194     g_return_val_if_fail(key != NULL, FALSE);
1195     g_return_val_if_fail(*key != '\0', FALSE);
1196     g_return_val_if_fail(object != NULL, FALSE);
1197     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1199     if (SP_OBJECT_IS_CLONED(object))
1200         return FALSE;
1202     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1203     g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1204     rlist = g_slist_prepend(rlist, object);
1205     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1207     document->priv->resources_changed_signals[q].emit();
1209     return TRUE;
1212 gboolean
1213 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1215     GSList *rlist;
1216     GQuark q = g_quark_from_string(key);
1218     g_return_val_if_fail(document != NULL, FALSE);
1219     g_return_val_if_fail(key != NULL, FALSE);
1220     g_return_val_if_fail(*key != '\0', FALSE);
1221     g_return_val_if_fail(object != NULL, FALSE);
1222     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1224     if (SP_OBJECT_IS_CLONED(object))
1225         return FALSE;
1227     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1228     g_return_val_if_fail(rlist != NULL, FALSE);
1229     g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1230     rlist = g_slist_remove(rlist, object);
1231     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1233     document->priv->resources_changed_signals[q].emit();
1235     return TRUE;
1238 GSList const *
1239 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1241     g_return_val_if_fail(document != NULL, NULL);
1242     g_return_val_if_fail(key != NULL, NULL);
1243     g_return_val_if_fail(*key != '\0', NULL);
1245     return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1248 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1249                                                        gchar const *key,
1250                                                        SPDocument::ResourcesChangedSignal::slot_type slot)
1252     GQuark q = g_quark_from_string(key);
1253     return document->priv->resources_changed_signals[q].connect(slot);
1256 /* Helpers */
1258 gboolean
1259 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1261     g_slist_free((GSList *) value);
1262     return TRUE;
1265 unsigned int
1266 count_objects_recursive(SPObject *obj, unsigned int count)
1268     count++; // obj itself
1270     for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1271         count = count_objects_recursive(i, count);
1272     }
1274     return count;
1277 unsigned int
1278 objects_in_document(SPDocument *document)
1280     return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1283 void
1284 vacuum_document_recursive(SPObject *obj)
1286     if (SP_IS_DEFS(obj)) {
1287         for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1288             /* fixme: some inkscape-internal nodes in the future might not be collectable */
1289             def->requestOrphanCollection();
1290         }
1291     } else {
1292         for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1293             vacuum_document_recursive(i);
1294         }
1295     }
1298 unsigned int
1299 vacuum_document(SPDocument *document)
1301     unsigned int start = objects_in_document(document);
1302     unsigned int end;
1303     unsigned int newend = start;
1305     unsigned int iterations = 0;
1307     do {
1308         end = newend;
1310         vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1311         document->collectOrphans();
1312         iterations++;
1314         newend = objects_in_document(document);
1316     } while (iterations < 100 && newend < end);
1318     return start - newend;
1321 bool SPDocument::isSeeking() const {
1322     return priv->seeking;
1326 /*
1327   Local Variables:
1328   mode:c++
1329   c-file-style:"stroustrup"
1330   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1331   indent-tabs-mode:nil
1332   fill-column:99
1333   End:
1334 */
1335 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :