Code

clean left warning on revision 12272
[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::Version sodipodi_version;
267     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
269     rroot = rdoc->root();
271     document = new SPDocument();
273     document->keepalive = keepalive;
275     document->rdoc = rdoc;
276     document->rroot = rroot;
278 #ifndef WIN32
279     document->uri = prepend_current_dir_if_relative(uri);
280 #else
281     // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
282     document->uri = uri? g_strdup(uri) : NULL;
283 #endif
285     // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
286     // which is why we use g_get_current_dir() in calculating the abs path above
287     //This is NULL for a new document
288     if (base)
289         document->base = g_strdup(base);
290     else
291         document->base = NULL;
292     document->name = g_strdup(name);
294     document->root = sp_object_repr_build_tree(document, rroot);
296     sodipodi_version = SP_ROOT(document->root)->version.sodipodi;
298     /* fixme: Not sure about this, but lets assume ::build updates */
299     rroot->setAttribute("sodipodi:version", SODIPODI_VERSION);
300     rroot->setAttribute("inkscape:version", Inkscape::version_string);
301     /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
303     /* Quick hack 2 - get default image size into document */
304     if (!rroot->attribute("width")) rroot->setAttribute("width", "100%");
305     if (!rroot->attribute("height")) rroot->setAttribute("height", "100%");
306     /* End of quick hack 2 */
308     /* Quick hack 3 - Set uri attributes */
309     if (uri) {
310         rroot->setAttribute("sodipodi:docname", uri);
311     }
312     /* End of quick hack 3 */
314     /* Eliminate obsolete sodipodi:docbase, for privacy reasons */
315     rroot->setAttribute("sodipodi:docbase", NULL);
316     
317     /* Eliminate any claim to adhere to a profile, as we don't try to */
318     rroot->setAttribute("baseProfile", NULL);
320     // creating namedview
321     if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
322         // if there's none in the document already,
323         Inkscape::XML::Node *rnew = NULL;
324         
325         rnew = rdoc->createElement("sodipodi:namedview");
326         //rnew->setAttribute("id", "base");
328         // Add namedview data from the preferences
329         // we can't use getAllEntries because this could produce non-SVG doubles
330         Glib::ustring pagecolor = prefs->getString("/template/base/pagecolor");
331         if (!pagecolor.empty()) {
332             rnew->setAttribute("pagecolor", pagecolor.data());
333         }
334         Glib::ustring bordercolor = prefs->getString("/template/base/bordercolor");
335         if (!bordercolor.empty()) {
336             rnew->setAttribute("bordercolor", bordercolor.data());
337         }
338         sp_repr_set_svg_double(rnew, "borderopacity",
339             prefs->getDouble("/template/base/borderopacity", 1.0));
340         sp_repr_set_svg_double(rnew, "objecttolerance",
341             prefs->getDouble("/template/base/objecttolerance", 10.0));
342         sp_repr_set_svg_double(rnew, "gridtolerance",
343             prefs->getDouble("/template/base/gridtolerance", 10.0));
344         sp_repr_set_svg_double(rnew, "guidetolerance",
345             prefs->getDouble("/template/base/guidetolerance", 10.0));
346         sp_repr_set_svg_double(rnew, "inkscape:pageopacity",
347             prefs->getDouble("/template/base/inkscape:pageopacity", 0.0));
348         sp_repr_set_int(rnew, "inkscape:pageshadow",
349             prefs->getInt("/template/base/inkscape:pageshadow", 2));
350         sp_repr_set_int(rnew, "inkscape:window-width",
351             prefs->getInt("/template/base/inkscape:window-width", 640));
352         sp_repr_set_int(rnew, "inkscape:window-height",
353             prefs->getInt("/template/base/inkscape:window-height", 480));
354         
355         // insert into the document
356         rroot->addChild(rnew, NULL);
357         // clean up
358         Inkscape::GC::release(rnew);
359     }
361     /* Defs */
362     if (!SP_ROOT(document->root)->defs) {
363         Inkscape::XML::Node *r;
364         r = rdoc->createElement("svg:defs");
365         rroot->addChild(r, NULL);
366         Inkscape::GC::release(r);
367         g_assert(SP_ROOT(document->root)->defs);
368     }
370     /* Default RDF */
371     rdf_set_defaults( document );
373     if (keepalive) {
374         inkscape_ref();
375     }
377     // Remark: Here, we used to create a "currentpersp3d" element in the document defs.
378     // But this is probably a bad idea since we need to adapt it for every change of selection, which will
379     // completely clutter the undo history. Maybe rather save it to prefs on exit and re-read it on startup?
381     document->current_persp3d = persp3d_document_first_persp(document);
382     if (!document->current_persp3d) {
383         document->current_persp3d = persp3d_create_xml_element (document);
384     }
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);
675     
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     return;
740 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
742     return priv->commit_signal.connect(slot);
747 void SPDocument::_emitModified() {
748     static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
749     root->emitModified(0);
750     priv->modified_signal.emit(flags);
753 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
754     GQuark idq = g_quark_from_string(id);
756     if (object) {
757         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
758         g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
759     } else {
760         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
761         g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
762     }
764     SPDocumentPrivate::IDChangedSignalMap::iterator pos;
766     pos = priv->id_changed_signals.find(idq);
767     if ( pos != priv->id_changed_signals.end() ) {
768         if (!(*pos).second.empty()) {
769             (*pos).second.emit(object);
770         } else { // discard unused signal
771             priv->id_changed_signals.erase(pos);
772         }
773     }
776 void
777 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
779     this->priv->undoStackObservers.add(observer);
782 void
783 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
785     this->priv->undoStackObservers.remove(observer);
788 SPObject *SPDocument::getObjectById(gchar const *id) {
789     g_return_val_if_fail(id != NULL, NULL);
791     GQuark idq = g_quark_from_string(id);
792     return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
795 sigc::connection SPDocument::connectIdChanged(gchar const *id,
796                                               SPDocument::IDChangedSignal::slot_type slot)
798     return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
801 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
802     if (object) {
803         g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
804         g_hash_table_insert(priv->reprdef, repr, object);
805     } else {
806         g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
807         g_hash_table_remove(priv->reprdef, repr);
808     }
811 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
812     g_return_val_if_fail(repr != NULL, NULL);
813     return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
816 Glib::ustring SPDocument::getLanguage() {
817     gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
818     if (document_language) {
819         while (isspace(*document_language))
820             document_language++;
821     }
822     if ( !document_language || 0 == *document_language) {
823         // retrieve system language
824         document_language = getenv("LC_ALL");
825         if ( NULL == document_language || *document_language == 0 ) {
826             document_language = getenv ("LC_MESSAGES");
827         }
828         if ( NULL == document_language || *document_language == 0 ) {
829             document_language = getenv ("LANG");
830         }
832         if ( NULL != document_language ) {
833             const char *pos = strchr(document_language, '_');
834             if ( NULL != pos ) {
835                 return Glib::ustring(document_language, pos - document_language);
836             }
837         }
838     }
840     if ( NULL == document_language )
841         return Glib::ustring();
842     return document_language;
845 /* Object modification root handler */
847 void
848 sp_document_request_modified(SPDocument *doc)
850     if (!doc->modified_id) {
851         doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
852     }
855 void
856 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
858     ctx->ctx.flags = 0;
859     ctx->i2doc = Geom::identity();
860     /* Set up viewport in case svg has it defined as percentages */
861     if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
862         ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
863         ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
864         ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
865         ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
866     } else { // as a last resort, set size to A4
867         ctx->vp.x0 = 0.0;
868         ctx->vp.y0 = 0.0;
869         ctx->vp.x1 = 210 * PX_PER_MM;
870         ctx->vp.y1 = 297 * PX_PER_MM;
871     }
872     ctx->i2vp = Geom::identity();
875 /**
876  * Tries to update the document state based on the modified and
877  * "update required" flags, and return true if the document has
878  * been brought fully up to date.
879  */
880 bool
881 SPDocument::_updateDocument()
883     /* Process updates */
884     if (this->root->uflags || this->root->mflags) {
885         if (this->root->uflags) {
886             SPItemCtx ctx;
887             sp_document_setup_viewport (this, &ctx);
889             bool saved = sp_document_get_undo_sensitive(this);
890             sp_document_set_undo_sensitive(this, false);
892             this->root->updateDisplay((SPCtx *)&ctx, 0);
894             sp_document_set_undo_sensitive(this, saved);
895         }
896         this->_emitModified();
897     }
899     return !(this->root->uflags || this->root->mflags);
903 /**
904  * Repeatedly works on getting the document updated, since sometimes
905  * it takes more than one pass to get the document updated.  But it
906  * usually should not take more than a few loops, and certainly never
907  * more than 32 iterations.  So we bail out if we hit 32 iterations,
908  * since this typically indicates we're stuck in an update loop.
909  */
910 gint
911 sp_document_ensure_up_to_date(SPDocument *doc)
913     int counter = 32;
914     while (!doc->_updateDocument()) {
915         if (counter == 0) {
916             g_warning("More than 32 iteration while updating document '%s'", doc->uri);
917             break;
918         }
919         counter--;
920     }
922     if (doc->modified_id) {
923         /* Remove handler */
924         gtk_idle_remove(doc->modified_id);
925         doc->modified_id = 0;
926     }
927     return counter>0;
930 /**
931  * An idle handler to update the document.  Returns true if
932  * the document needs further updates.
933  */
934 static gint
935 sp_document_idle_handler(gpointer data)
937     SPDocument *doc = static_cast<SPDocument *>(data);
938     if (doc->_updateDocument()) {
939         doc->modified_id = 0;
940         return false;
941     } else {
942         return true;
943     }
946 static bool is_within(Geom::Rect const &area, Geom::Rect const &box)
948     return area.contains(box);
951 static bool overlaps(Geom::Rect const &area, Geom::Rect const &box)
953     return area.intersects(box);
956 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, Geom::Rect const &area,
957                                   bool (*test)(Geom::Rect const &, Geom::Rect const &), bool take_insensitive = false)
959     g_return_val_if_fail(SP_IS_GROUP(group), s);
961     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
962         if (!SP_IS_ITEM(o)) {
963             continue;
964         }
965         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
966             s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
967         } else {
968             SPItem *child = SP_ITEM(o);
969             Geom::OptRect box = sp_item_bbox_desktop(child);
970             if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
971                 s = g_slist_append(s, child);
972             }
973         }
974     }
976     return s;
979 /**
980 Returns true if an item is among the descendants of group (recursively).
981  */
982 bool item_is_in_group(SPItem *item, SPGroup *group)
984     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
985         if (!SP_IS_ITEM(o)) continue;
986         if (SP_ITEM(o) == item)
987             return true;
988         if (SP_IS_GROUP(o))
989             if (item_is_in_group(item, SP_GROUP(o)))
990                 return true;
991     }
992     return false;
995 /**
996 Returns the bottommost item from the list which is at the point, or NULL if none.
997 */
998 SPItem*
999 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
1000                                            Geom::Point const p, bool take_insensitive)
1002     g_return_val_if_fail(group, NULL);
1003     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1004     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1006     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1008         if (!SP_IS_ITEM(o)) continue;
1010         SPItem *item = SP_ITEM(o);
1011         NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
1012         if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1013             && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
1014             if (g_slist_find((GSList *) list, item) != NULL)
1015                 return item;
1016         }
1018         if (SP_IS_GROUP(o)) {
1019             SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
1020             if (found)
1021                 return found;
1022         }
1024     }
1025     return NULL;
1028 /**
1029 Returns the topmost (in z-order) item from the descendants of group (recursively) which
1030 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
1031 non-layer groups or not. Honors take_insensitive on whether to return insensitive
1032 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
1033 upwards in z-order and returns what it has found so far (i.e. the found item is
1034 guaranteed to be lower than upto).
1035  */
1036 SPItem*
1037 find_item_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
1039     SPItem *seen = NULL, *newseen = NULL;
1040     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1041     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1043     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1044         if (!SP_IS_ITEM(o)) continue;
1046         if (upto && SP_ITEM(o) == upto)
1047             break;
1049         if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
1050             // if nothing found yet, recurse into the group
1051             newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
1052             if (newseen) {
1053                 seen = newseen;
1054                 newseen = NULL;
1055             }
1057             if (item_is_in_group(upto, SP_GROUP(o)))
1058                 break;
1060         } else {
1061             SPItem *child = SP_ITEM(o);
1062             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1064             // seen remembers the last (topmost) of items pickable at this point
1065             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1066                 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1067                 seen = child;
1068             }
1069         }
1070     }
1071     return seen;
1074 /**
1075 Returns the topmost non-layer group from the descendants of group which is at point
1076 p, or NULL if none. Recurses into layers but not into groups.
1077  */
1078 SPItem*
1079 find_group_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p)
1081     SPItem *seen = NULL;
1082     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1083     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1085     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1086         if (!SP_IS_ITEM(o)) continue;
1087         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1088             SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1089             if (newseen) {
1090                 seen = newseen;
1091             }
1092         }
1093         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1094             SPItem *child = SP_ITEM(o);
1095             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1097             // seen remembers the last (topmost) of groups pickable at this point
1098             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1099                 seen = child;
1100             }
1101         }
1102     }
1103     return seen;
1106 /*
1107  * Return list of items, contained in box
1108  *
1109  * Assumes box is normalized (and g_asserts it!)
1110  *
1111  */
1113 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1115     g_return_val_if_fail(document != NULL, NULL);
1116     g_return_val_if_fail(document->priv != NULL, NULL);
1118     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
1121 /*
1122  * Return list of items, that the parts of the item contained in box
1123  *
1124  * Assumes box is normalized (and g_asserts it!)
1125  *
1126  */
1128 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1130     g_return_val_if_fail(document != NULL, NULL);
1131     g_return_val_if_fail(document->priv != NULL, NULL);
1133     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1136 GSList *
1137 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<Geom::Point> points)
1139     GSList *items = NULL;
1140     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1142     // When picking along the path, we don't want small objects close together
1143     // (such as hatching strokes) to obscure each other by their deltas,
1144     // so we temporarily set delta to a small value
1145     gdouble saved_delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1146     prefs->setDouble("/options/cursortolerance/value", 0.25);
1148     for(unsigned int i = 0; i < points.size(); i++) {
1149         SPItem *item = sp_document_item_at_point(document, key, points[i],
1150                                                  false, NULL);
1151         if (item && !g_slist_find(items, item))
1152             items = g_slist_prepend (items, item);
1153     }
1155     // and now we restore it back
1156     prefs->setDouble("/options/cursortolerance/value", saved_delta);
1158     return items;
1161 SPItem *
1162 sp_document_item_at_point(SPDocument *document, unsigned const key, Geom::Point const p,
1163                           gboolean const into_groups, SPItem *upto)
1165     g_return_val_if_fail(document != NULL, NULL);
1166     g_return_val_if_fail(document->priv != NULL, NULL);
1168     return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1171 SPItem*
1172 sp_document_group_at_point(SPDocument *document, unsigned int key, Geom::Point const p)
1174     g_return_val_if_fail(document != NULL, NULL);
1175     g_return_val_if_fail(document->priv != NULL, NULL);
1177     return find_group_at_point(key, SP_GROUP(document->root), p);
1181 /* Resource management */
1183 gboolean
1184 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1186     GSList *rlist;
1187     GQuark q = g_quark_from_string(key);
1189     g_return_val_if_fail(document != NULL, FALSE);
1190     g_return_val_if_fail(key != NULL, FALSE);
1191     g_return_val_if_fail(*key != '\0', FALSE);
1192     g_return_val_if_fail(object != NULL, FALSE);
1193     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1195     if (SP_OBJECT_IS_CLONED(object))
1196         return FALSE;
1198     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1199     g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1200     rlist = g_slist_prepend(rlist, object);
1201     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1203     document->priv->resources_changed_signals[q].emit();
1205     return TRUE;
1208 gboolean
1209 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1211     GSList *rlist;
1212     GQuark q = g_quark_from_string(key);
1214     g_return_val_if_fail(document != NULL, FALSE);
1215     g_return_val_if_fail(key != NULL, FALSE);
1216     g_return_val_if_fail(*key != '\0', FALSE);
1217     g_return_val_if_fail(object != NULL, FALSE);
1218     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1220     if (SP_OBJECT_IS_CLONED(object))
1221         return FALSE;
1223     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1224     g_return_val_if_fail(rlist != NULL, FALSE);
1225     g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1226     rlist = g_slist_remove(rlist, object);
1227     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1229     document->priv->resources_changed_signals[q].emit();
1231     return TRUE;
1234 GSList const *
1235 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1237     g_return_val_if_fail(document != NULL, NULL);
1238     g_return_val_if_fail(key != NULL, NULL);
1239     g_return_val_if_fail(*key != '\0', NULL);
1241     return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1244 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1245                                                        gchar const *key,
1246                                                        SPDocument::ResourcesChangedSignal::slot_type slot)
1248     GQuark q = g_quark_from_string(key);
1249     return document->priv->resources_changed_signals[q].connect(slot);
1252 /* Helpers */
1254 gboolean
1255 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1257     g_slist_free((GSList *) value);
1258     return TRUE;
1261 unsigned int
1262 count_objects_recursive(SPObject *obj, unsigned int count)
1264     count++; // obj itself
1266     for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1267         count = count_objects_recursive(i, count);
1268     }
1270     return count;
1273 unsigned int
1274 objects_in_document(SPDocument *document)
1276     return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1279 void
1280 vacuum_document_recursive(SPObject *obj)
1282     if (SP_IS_DEFS(obj)) {
1283         for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1284             /* fixme: some inkscape-internal nodes in the future might not be collectable */
1285             def->requestOrphanCollection();
1286         }
1287     } else {
1288         for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1289             vacuum_document_recursive(i);
1290         }
1291     }
1294 unsigned int
1295 vacuum_document(SPDocument *document)
1297     unsigned int start = objects_in_document(document);
1298     unsigned int end;
1299     unsigned int newend = start;
1301     unsigned int iterations = 0;
1303     do {
1304         end = newend;
1306         vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1307         document->collectOrphans();
1308         iterations++;
1310         newend = objects_in_document(document);
1312     } while (iterations < 100 && newend < end);
1314     return start - newend;
1317 bool SPDocument::isSeeking() const {
1318     return priv->seeking;
1322 /*
1323   Local Variables:
1324   mode:c++
1325   c-file-style:"stroustrup"
1326   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1327   indent-tabs-mode:nil
1328   fill-column:99
1329   End:
1330 */
1331 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :