Code

Merge from fe-moved
[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>
43 #include "application/application.h"
44 #include "application/editor.h"
45 #include "xml/repr.h"
46 #include "helper/units.h"
47 #include "inkscape-private.h"
48 #include "inkscape_version.h"
49 #include "sp-object-repr.h"
50 #include "sp-namedview.h"
51 #include "desktop.h"
52 #include "document-private.h"
53 #include "dir-util.h"
54 #include "unit-constants.h"
55 #include "preferences.h"
56 #include "libavoid/router.h"
57 #include "sp-item-group.h"
58 #include "profile-manager.h"
59 #include "persp3d.h"
61 #include "display/nr-arena-item.h"
63 #include "dialogs/rdf.h"
65 #include "transf_mat_3x4.h"
67 #define SP_DOCUMENT_UPDATE_PRIORITY (G_PRIORITY_HIGH_IDLE - 1)
70 static gint sp_document_idle_handler(gpointer data);
72 gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data);
74 static gint doc_count = 0;
76 static unsigned long next_serial = 0;
78 SPDocument::SPDocument() :
79     keepalive(FALSE),
80     virgin(TRUE),
81     modified_since_save(FALSE),
82     rdoc(0),
83     rroot(0),
84     root(0),
85     style_cascade(cr_cascade_new(NULL, NULL, NULL)),
86     uri(0),
87     base(0),
88     name(0),
89     priv(0), // reset in ctor
90     actionkey(0),
91     modified_id(0),
92     profileManager(0), // deferred until after other initialization
93     router(new Avoid::Router()),
94     perspectives(0),
95     current_persp3d(0),
96     _collection_queue(0)
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     _selection_changed_connection.disconnect();
185     _desktop_activated_connection.disconnect();
187     if (keepalive) {
188         inkscape_unref();
189         keepalive = FALSE;
190     }
192     if (router) {
193         delete router;
194         router = NULL;
195     }
197     //delete this->_whiteboard_session_manager;
201 void SPDocument::add_persp3d (Persp3D * const /*persp*/)
203     SPDefs *defs = SP_ROOT(this->root)->defs;
204     for (SPObject *i = sp_object_first_child(SP_OBJECT(defs)); i != NULL; i = SP_OBJECT_NEXT(i) ) {
205         if (SP_IS_PERSP3D(i)) {
206             g_print ("Encountered a Persp3D in defs\n");
207         }
208     }
210     g_print ("Adding Persp3D to defs\n");
211     persp3d_create_xml_element (this);
214 void SPDocument::remove_persp3d (Persp3D * const /*persp*/)
216     // TODO: Delete the repr, maybe perform a check if any boxes are still linked to the perspective.
217     //       Anything else?
218     g_print ("Please implement deletion of perspectives here.\n");
221 unsigned long SPDocument::serial() const {
222     return priv->serial;
225 void SPDocument::queueForOrphanCollection(SPObject *object) {
226     g_return_if_fail(object != NULL);
227     g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
229     sp_object_ref(object, NULL);
230     _collection_queue = g_slist_prepend(_collection_queue, object);
233 void SPDocument::collectOrphans() {
234     while (_collection_queue) {
235         GSList *objects=_collection_queue;
236         _collection_queue = NULL;
237         for ( GSList *iter=objects ; iter ; iter = iter->next ) {
238             SPObject *object=reinterpret_cast<SPObject *>(iter->data);
239             object->collectOrphan();
240             sp_object_unref(object, NULL);
241         }
242         g_slist_free(objects);
243     }
246 void SPDocument::reset_key (void */*dummy*/)
248     actionkey = NULL;
251 SPDocument *
252 sp_document_create(Inkscape::XML::Document *rdoc,
253                    gchar const *uri,
254                    gchar const *base,
255                    gchar const *name,
256                    unsigned int keepalive)
258     SPDocument *document;
259     Inkscape::XML::Node *rroot;
260     Inkscape::Version sodipodi_version;
261     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
263     rroot = rdoc->root();
265     document = new SPDocument();
267     document->keepalive = keepalive;
269     document->rdoc = rdoc;
270     document->rroot = rroot;
272 #ifndef WIN32
273     prepend_current_dir_if_relative(&(document->uri), uri);
274 #else
275     // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
276     document->uri = uri? g_strdup(uri) : NULL;
277 #endif
279     // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
280     // which is why we use g_get_current_dir() in calculating the abs path above
281     //This is NULL for a new document
282     if (base)
283         document->base = g_strdup(base);
284     else
285         document->base = NULL;
286     document->name = g_strdup(name);
288     document->root = sp_object_repr_build_tree(document, rroot);
290     sodipodi_version = SP_ROOT(document->root)->version.sodipodi;
292     /* fixme: Not sure about this, but lets assume ::build updates */
293     rroot->setAttribute("sodipodi:version", SODIPODI_VERSION);
294     rroot->setAttribute("inkscape:version", INKSCAPE_VERSION);
295     /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
297     /* Quick hack 2 - get default image size into document */
298     if (!rroot->attribute("width")) rroot->setAttribute("width", "100%");
299     if (!rroot->attribute("height")) rroot->setAttribute("height", "100%");
300     /* End of quick hack 2 */
302     /* Quick hack 3 - Set uri attributes */
303     if (uri) {
304         rroot->setAttribute("sodipodi:docname", uri);
305     }
306     /* End of quick hack 3 */
308     /* Eliminate obsolete sodipodi:docbase, for privacy reasons */
309     rroot->setAttribute("sodipodi:docbase", NULL);
310     
311     /* Eliminate any claim to adhere to a profile, as we don't try to */
312     rroot->setAttribute("baseProfile", NULL);
314     // creating namedview
315     if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
316         // if there's none in the document already,
317         Inkscape::XML::Node *rnew = NULL;
318         
319         rnew = rdoc->createElement("sodipodi:namedview");
320         //rnew->setAttribute("id", "base");
322         // Add namedview data from the preferences
323         // we can't use getAllEntries because this could produce non-SVG doubles
324         Glib::ustring pagecolor = prefs->getString("/template/base/pagecolor");
325         if (!pagecolor.empty()) {
326             rnew->setAttribute("pagecolor", pagecolor.data());
327         }
328         Glib::ustring bordercolor = prefs->getString("/template/base/pagecolor");
329         if (!bordercolor.empty()) {
330             rnew->setAttribute("bordercolor", bordercolor.data());
331         }
332         sp_repr_set_svg_double(rnew, "borderopacity",
333             prefs->getDouble("/template/base/borderopacity", 1.0));
334         sp_repr_set_svg_double(rnew, "objecttolerance",
335             prefs->getDouble("/template/base/objecttolerance", 10.0));
336         sp_repr_set_svg_double(rnew, "gridtolerance",
337             prefs->getDouble("/template/base/gridtolerance", 10.0));
338         sp_repr_set_svg_double(rnew, "guidetolerance",
339             prefs->getDouble("/template/base/guidetolerance", 10.0));
340         sp_repr_set_svg_double(rnew, "inkscape:pageopacity",
341             prefs->getDouble("/template/base/inkscape:pageopacity", 0.0));
342         sp_repr_set_int(rnew, "inkscape:pageshadow",
343             prefs->getInt("/template/base/inkscape:pageshadow", 2));
344         sp_repr_set_int(rnew, "inkscape:window-width",
345             prefs->getInt("/template/base/inkscape:window-width", 640));
346         sp_repr_set_int(rnew, "inkscape:window-height",
347             prefs->getInt("/template/base/inkscape:window-height", 480));
348         
349         // insert into the document
350         rroot->addChild(rnew, NULL);
351         // clean up
352         Inkscape::GC::release(rnew);
353     }
355     /* Defs */
356     if (!SP_ROOT(document->root)->defs) {
357         Inkscape::XML::Node *r;
358         r = rdoc->createElement("svg:defs");
359         rroot->addChild(r, NULL);
360         Inkscape::GC::release(r);
361         g_assert(SP_ROOT(document->root)->defs);
362     }
364     /* Default RDF */
365     rdf_set_defaults( document );
367     if (keepalive) {
368         inkscape_ref();
369     }
371     // Remark: Here, we used to create a "currentpersp3d" element in the document defs.
372     // But this is probably a bad idea since we need to adapt it for every change of selection, which will
373     // completely clutter the undo history. Maybe rather save it to prefs on exit and re-read it on startup?
375     document->current_persp3d = persp3d_document_first_persp(document);
376     if (!document->current_persp3d) {
377         document->current_persp3d = persp3d_create_xml_element (document);
378     }
380     sp_document_set_undo_sensitive(document, true);
382     // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
383     if (!Inkscape::NSApplication::Application::getNewGui()) {
384         g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
385                          G_CALLBACK(sp_document_reset_key), document);
386         g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
387                          G_CALLBACK(sp_document_reset_key), document);
388     } else {
389         document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
390         document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
391     }
393     return document;
396 /**
397  * Fetches document from URI, or creates new, if NULL; public document
398  * appears in document list.
399  */
400 SPDocument *
401 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
403     SPDocument *doc;
404     Inkscape::XML::Document *rdoc;
405     gchar *base = NULL;
406     gchar *name = NULL;
408     if (uri) {
409         Inkscape::XML::Node *rroot;
410         gchar *s, *p;
411         /* Try to fetch repr from file */
412         rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
413         /* If file cannot be loaded, return NULL without warning */
414         if (rdoc == NULL) return NULL;
415         rroot = rdoc->root();
416         /* If xml file is not svg, return NULL without warning */
417         /* fixme: destroy document */
418         if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
419         s = g_strdup(uri);
420         p = strrchr(s, '/');
421         if (p) {
422             name = g_strdup(p + 1);
423             p[1] = '\0';
424             base = g_strdup(s);
425         } else {
426             base = NULL;
427             name = g_strdup(uri);
428         }
429         g_free(s);
430     } else {
431         rdoc = sp_repr_document_new("svg:svg");
432     }
434     if (make_new) {
435         base = NULL;
436         uri = NULL;
437         name = g_strdup_printf(_("New document %d"), ++doc_count);
438     }
440     //# These should be set by now
441     g_assert(name);
443     doc = sp_document_create(rdoc, uri, base, name, keepalive);
445     g_free(base);
446     g_free(name);
448     return doc;
451 SPDocument *
452 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
454     SPDocument *doc;
455     Inkscape::XML::Document *rdoc;
456     Inkscape::XML::Node *rroot;
457     gchar *name;
459     rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
461     /* If it cannot be loaded, return NULL without warning */
462     if (rdoc == NULL) return NULL;
464     rroot = rdoc->root();
465     /* If xml file is not svg, return NULL without warning */
466     /* fixme: destroy document */
467     if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
469     name = g_strdup_printf(_("Memory document %d"), ++doc_count);
471     doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
473     return doc;
476 SPDocument *
477 sp_document_ref(SPDocument *doc)
479     g_return_val_if_fail(doc != NULL, NULL);
480     Inkscape::GC::anchor(doc);
481     return doc;
484 SPDocument *
485 sp_document_unref(SPDocument *doc)
487     g_return_val_if_fail(doc != NULL, NULL);
488     Inkscape::GC::release(doc);
489     return NULL;
492 gdouble sp_document_width(SPDocument *document)
494     g_return_val_if_fail(document != NULL, 0.0);
495     g_return_val_if_fail(document->priv != NULL, 0.0);
496     g_return_val_if_fail(document->root != NULL, 0.0);
498     SPRoot *root = SP_ROOT(document->root);
500     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set)
501         return root->viewBox.x1 - root->viewBox.x0;
502     return root->width.computed;
505 void
506 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
508     SPRoot *root = SP_ROOT(document->root);
510     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
511         root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
512     } else { // set to width=
513         root->width.computed = sp_units_get_pixels (width, *unit);
514         /* SVG does not support meters as a unit, so we must translate meters to
515          * cm when writing */
516         if (!strcmp(unit->abbr, "m")) {
517             root->width.value = 100*width;
518             root->width.unit = SVGLength::CM;
519         } else {
520             root->width.value = width;
521             root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
522         }
523     }
525     SP_OBJECT (root)->updateRepr();
528 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
530     SPRoot *root = SP_ROOT(document->root);
532     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
533         root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
534     } else { // set to height=
535         root->height.computed = sp_units_get_pixels (height, *unit);
536         /* SVG does not support meters as a unit, so we must translate meters to
537          * cm when writing */
538         if (!strcmp(unit->abbr, "m")) {
539             root->height.value = 100*height;
540             root->height.unit = SVGLength::CM;
541         } else {
542             root->height.value = height;
543             root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
544         }
545     }
547     SP_OBJECT (root)->updateRepr();
550 gdouble sp_document_height(SPDocument *document)
552     g_return_val_if_fail(document != NULL, 0.0);
553     g_return_val_if_fail(document->priv != NULL, 0.0);
554     g_return_val_if_fail(document->root != NULL, 0.0);
556     SPRoot *root = SP_ROOT(document->root);
558     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set)
559         return root->viewBox.y1 - root->viewBox.y0;
560     return root->height.computed;
563 Geom::Point sp_document_dimensions(SPDocument *doc)
565     return Geom::Point(sp_document_width(doc), sp_document_height(doc));
568 /**
569  * Given a Geom::Rect that may, for example, correspond to the bbox of an object,
570  * this function fits the canvas to that rect by resizing the canvas
571  * and translating the document root into position.
572  */
573 void SPDocument::fitToRect(Geom::Rect const &rect)
575     double const w = rect.width();
576     double const h = rect.height();
578     double const old_height = sp_document_height(this);
579     SPUnit const &px(sp_unit_get_by_id(SP_UNIT_PX));
580     sp_document_set_width(this, w, &px);
581     sp_document_set_height(this, h, &px);
583     Geom::Translate const tr(Geom::Point(0, (old_height - h))
584                              - to_2geom(rect.min()));
585     SP_GROUP(root)->translateChildItems(tr);
586     SPNamedView *nv = sp_document_namedview(this, 0);
587     if(nv) {
588         Geom::Translate tr2(-rect.min());
589         nv->translateGuides(tr2);
591         // update the viewport so the drawing appears to stay where it was
592         nv->scrollAllDesktops(-tr2[0], tr2[1], false);
593     }
596 void sp_document_set_uri(SPDocument *document, gchar const *uri)
598     g_return_if_fail(document != NULL);
600     if (document->name) {
601         g_free(document->name);
602         document->name = NULL;
603     }
604     if (document->base) {
605         g_free(document->base);
606         document->base = NULL;
607     }
608     if (document->uri) {
609         g_free(document->uri);
610         document->uri = NULL;
611     }
613     if (uri) {
615 #ifndef WIN32
616         prepend_current_dir_if_relative(&(document->uri), uri);
617 #else
618         // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
619         document->uri = g_strdup(uri);
620 #endif
622         /* fixme: Think, what this means for images (Lauris) */
623         document->base = g_path_get_dirname(document->uri);
624         document->name = g_path_get_basename(document->uri);
626     } else {
627         document->uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
628         document->base = NULL;
629         document->name = g_strdup(document->uri);
630     }
632     // Update saveable repr attributes.
633     Inkscape::XML::Node *repr = sp_document_repr_root(document);
634     // changing uri in the document repr must not be not undoable
635     bool saved = sp_document_get_undo_sensitive(document);
636     sp_document_set_undo_sensitive(document, false);
638     repr->setAttribute("sodipodi:docname", document->name);
639     sp_document_set_undo_sensitive(document, saved);
641     document->priv->uri_set_signal.emit(document->uri);
644 void
645 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
647     g_return_if_fail(doc != NULL);
649     doc->priv->resized_signal.emit(width, height);
652 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
654     return priv->modified_signal.connect(slot);
657 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
659     return priv->uri_set_signal.connect(slot);
662 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
664     return priv->resized_signal.connect(slot);
667 sigc::connection
668 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
670     return priv->_reconstruction_start_signal.connect(slot);
673 void
674 SPDocument::emitReconstructionStart(void)
676     // printf("Starting Reconstruction\n");
677     priv->_reconstruction_start_signal.emit();
678     return;
681 sigc::connection
682 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type  slot)
684     return priv->_reconstruction_finish_signal.connect(slot);
687 void
688 SPDocument::emitReconstructionFinish(void)
690     // printf("Finishing Reconstruction\n");
691     priv->_reconstruction_finish_signal.emit();
692     return;
695 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
697     return priv->commit_signal.connect(slot);
702 void SPDocument::_emitModified() {
703     static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
704     root->emitModified(0);
705     priv->modified_signal.emit(flags);
708 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
709     GQuark idq = g_quark_from_string(id);
711     if (object) {
712         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
713         g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
714     } else {
715         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
716         g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
717     }
719     SPDocumentPrivate::IDChangedSignalMap::iterator pos;
721     pos = priv->id_changed_signals.find(idq);
722     if ( pos != priv->id_changed_signals.end() ) {
723         if (!(*pos).second.empty()) {
724             (*pos).second.emit(object);
725         } else { // discard unused signal
726             priv->id_changed_signals.erase(pos);
727         }
728     }
731 void
732 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
734     this->priv->undoStackObservers.add(observer);
737 void
738 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
740     this->priv->undoStackObservers.remove(observer);
743 SPObject *SPDocument::getObjectById(gchar const *id) {
744     g_return_val_if_fail(id != NULL, NULL);
746     GQuark idq = g_quark_from_string(id);
747     return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
750 sigc::connection SPDocument::connectIdChanged(gchar const *id,
751                                               SPDocument::IDChangedSignal::slot_type slot)
753     return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
756 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
757     if (object) {
758         g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
759         g_hash_table_insert(priv->reprdef, repr, object);
760     } else {
761         g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
762         g_hash_table_remove(priv->reprdef, repr);
763     }
766 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
767     g_return_val_if_fail(repr != NULL, NULL);
768     return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
771 Glib::ustring SPDocument::getLanguage() {
772     gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
773     if (document_language) {
774         while (isspace(*document_language))
775             document_language++;
776     }
777     if ( !document_language || 0 == *document_language) {
778         // retrieve system language
779         document_language = getenv("LC_ALL");
780         if ( NULL == document_language || *document_language == 0 ) {
781             document_language = getenv ("LC_MESSAGES");
782         }
783         if ( NULL == document_language || *document_language == 0 ) {
784             document_language = getenv ("LANG");
785         }
787         if ( NULL != document_language ) {
788             gchar *pos = strchr(document_language, '_');
789             if ( NULL != pos ) {
790                 return Glib::ustring(document_language, pos - document_language);
791             }
792         }
793     }
795     if ( NULL == document_language )
796         return Glib::ustring();
797     return document_language;
800 /* Object modification root handler */
802 void
803 sp_document_request_modified(SPDocument *doc)
805     if (!doc->modified_id) {
806         doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
807     }
810 void
811 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
813     ctx->ctx.flags = 0;
814     ctx->i2doc = Geom::identity();
815     /* Set up viewport in case svg has it defined as percentages */
816     if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
817         ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
818         ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
819         ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
820         ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
821     } else { // as a last resort, set size to A4
822         ctx->vp.x0 = 0.0;
823         ctx->vp.y0 = 0.0;
824         ctx->vp.x1 = 210 * PX_PER_MM;
825         ctx->vp.y1 = 297 * PX_PER_MM;
826     }
827     ctx->i2vp = Geom::identity();
830 /**
831  * Tries to update the document state based on the modified and
832  * "update required" flags, and return true if the document has
833  * been brought fully up to date.
834  */
835 bool
836 SPDocument::_updateDocument()
838     /* Process updates */
839     if (this->root->uflags || this->root->mflags) {
840         if (this->root->uflags) {
841             SPItemCtx ctx;
842             sp_document_setup_viewport (this, &ctx);
844             bool saved = sp_document_get_undo_sensitive(this);
845             sp_document_set_undo_sensitive(this, false);
847             this->root->updateDisplay((SPCtx *)&ctx, 0);
849             sp_document_set_undo_sensitive(this, saved);
850         }
851         this->_emitModified();
852     }
854     return !(this->root->uflags || this->root->mflags);
858 /**
859  * Repeatedly works on getting the document updated, since sometimes
860  * it takes more than one pass to get the document updated.  But it
861  * usually should not take more than a few loops, and certainly never
862  * more than 32 iterations.  So we bail out if we hit 32 iterations,
863  * since this typically indicates we're stuck in an update loop.
864  */
865 gint
866 sp_document_ensure_up_to_date(SPDocument *doc)
868     int counter = 32;
869     while (!doc->_updateDocument()) {
870         if (counter == 0) {
871             g_warning("More than 32 iteration while updating document '%s'", doc->uri);
872             break;
873         }
874         counter--;
875     }
877     if (doc->modified_id) {
878         /* Remove handler */
879         gtk_idle_remove(doc->modified_id);
880         doc->modified_id = 0;
881     }
882     return counter>0;
885 /**
886  * An idle handler to update the document.  Returns true if
887  * the document needs further updates.
888  */
889 static gint
890 sp_document_idle_handler(gpointer data)
892     SPDocument *doc = static_cast<SPDocument *>(data);
893     if (doc->_updateDocument()) {
894         doc->modified_id = 0;
895         return false;
896     } else {
897         return true;
898     }
901 static bool is_within(Geom::Rect const &area, Geom::Rect const &box)
903     return area.contains(box);
906 static bool overlaps(Geom::Rect const &area, Geom::Rect const &box)
908     return area.intersects(box);
911 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, Geom::Rect const &area,
912                                   bool (*test)(Geom::Rect const &, Geom::Rect const &), bool take_insensitive = false)
914     g_return_val_if_fail(SP_IS_GROUP(group), s);
916     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
917         if (!SP_IS_ITEM(o)) {
918             continue;
919         }
920         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
921             s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
922         } else {
923             SPItem *child = SP_ITEM(o);
924             Geom::OptRect box = sp_item_bbox_desktop(child);
925             if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
926                 s = g_slist_append(s, child);
927             }
928         }
929     }
931     return s;
934 /**
935 Returns true if an item is among the descendants of group (recursively).
936  */
937 bool item_is_in_group(SPItem *item, SPGroup *group)
939     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
940         if (!SP_IS_ITEM(o)) continue;
941         if (SP_ITEM(o) == item)
942             return true;
943         if (SP_IS_GROUP(o))
944             if (item_is_in_group(item, SP_GROUP(o)))
945                 return true;
946     }
947     return false;
950 /**
951 Returns the bottommost item from the list which is at the point, or NULL if none.
952 */
953 SPItem*
954 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
955                                            Geom::Point const p, bool take_insensitive)
957     g_return_val_if_fail(group, NULL);
958     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
959     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
961     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
963         if (!SP_IS_ITEM(o)) continue;
965         SPItem *item = SP_ITEM(o);
966         NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
967         if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
968             && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
969             if (g_slist_find((GSList *) list, item) != NULL)
970                 return item;
971         }
973         if (SP_IS_GROUP(o)) {
974             SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
975             if (found)
976                 return found;
977         }
979     }
980     return NULL;
983 /**
984 Returns the topmost (in z-order) item from the descendants of group (recursively) which
985 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
986 non-layer groups or not. Honors take_insensitive on whether to return insensitive
987 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
988 upwards in z-order and returns what it has found so far (i.e. the found item is
989 guaranteed to be lower than upto).
990  */
991 SPItem*
992 find_item_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
994     SPItem *seen = NULL, *newseen = NULL;
995     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
996     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
998     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
999         if (!SP_IS_ITEM(o)) continue;
1001         if (upto && SP_ITEM(o) == upto)
1002             break;
1004         if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
1005             // if nothing found yet, recurse into the group
1006             newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
1007             if (newseen) {
1008                 seen = newseen;
1009                 newseen = NULL;
1010             }
1012             if (item_is_in_group(upto, SP_GROUP(o)))
1013                 break;
1015         } else {
1016             SPItem *child = SP_ITEM(o);
1017             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1019             // seen remembers the last (topmost) of items pickable at this point
1020             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1021                 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1022                 seen = child;
1023             }
1024         }
1025     }
1026     return seen;
1029 /**
1030 Returns the topmost non-layer group from the descendants of group which is at point
1031 p, or NULL if none. Recurses into layers but not into groups.
1032  */
1033 SPItem*
1034 find_group_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p)
1036     SPItem *seen = NULL;
1037     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1038     gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1040     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1041         if (!SP_IS_ITEM(o)) continue;
1042         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1043             SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1044             if (newseen) {
1045                 seen = newseen;
1046             }
1047         }
1048         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1049             SPItem *child = SP_ITEM(o);
1050             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1052             // seen remembers the last (topmost) of groups pickable at this point
1053             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1054                 seen = child;
1055             }
1056         }
1057     }
1058     return seen;
1061 /*
1062  * Return list of items, contained in box
1063  *
1064  * Assumes box is normalized (and g_asserts it!)
1065  *
1066  */
1068 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1070     g_return_val_if_fail(document != NULL, NULL);
1071     g_return_val_if_fail(document->priv != NULL, NULL);
1073     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
1076 /*
1077  * Return list of items, that the parts of the item contained in box
1078  *
1079  * Assumes box is normalized (and g_asserts it!)
1080  *
1081  */
1083 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1085     g_return_val_if_fail(document != NULL, NULL);
1086     g_return_val_if_fail(document->priv != NULL, NULL);
1088     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1091 GSList *
1092 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<Geom::Point> points)
1094     GSList *items = NULL;
1095     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1097     // When picking along the path, we don't want small objects close together
1098     // (such as hatching strokes) to obscure each other by their deltas,
1099     // so we temporarily set delta to a small value
1100     gdouble saved_delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1101     prefs->setDouble("/options/cursortolerance/value", 0.25);
1103     for(unsigned int i = 0; i < points.size(); i++) {
1104         SPItem *item = sp_document_item_at_point(document, key, points[i],
1105                                                  false, NULL);
1106         if (item && !g_slist_find(items, item))
1107             items = g_slist_prepend (items, item);
1108     }
1110     // and now we restore it back
1111     prefs->setDouble("/options/cursortolerance/value", saved_delta);
1113     return items;
1116 SPItem *
1117 sp_document_item_at_point(SPDocument *document, unsigned const key, Geom::Point const p,
1118                           gboolean const into_groups, SPItem *upto)
1120     g_return_val_if_fail(document != NULL, NULL);
1121     g_return_val_if_fail(document->priv != NULL, NULL);
1123     return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1126 SPItem*
1127 sp_document_group_at_point(SPDocument *document, unsigned int key, Geom::Point const p)
1129     g_return_val_if_fail(document != NULL, NULL);
1130     g_return_val_if_fail(document->priv != NULL, NULL);
1132     return find_group_at_point(key, SP_GROUP(document->root), p);
1136 /* Resource management */
1138 gboolean
1139 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1141     GSList *rlist;
1142     GQuark q = g_quark_from_string(key);
1144     g_return_val_if_fail(document != NULL, FALSE);
1145     g_return_val_if_fail(key != NULL, FALSE);
1146     g_return_val_if_fail(*key != '\0', FALSE);
1147     g_return_val_if_fail(object != NULL, FALSE);
1148     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1150     if (SP_OBJECT_IS_CLONED(object))
1151         return FALSE;
1153     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1154     g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1155     rlist = g_slist_prepend(rlist, object);
1156     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1158     document->priv->resources_changed_signals[q].emit();
1160     return TRUE;
1163 gboolean
1164 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1166     GSList *rlist;
1167     GQuark q = g_quark_from_string(key);
1169     g_return_val_if_fail(document != NULL, FALSE);
1170     g_return_val_if_fail(key != NULL, FALSE);
1171     g_return_val_if_fail(*key != '\0', FALSE);
1172     g_return_val_if_fail(object != NULL, FALSE);
1173     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1175     if (SP_OBJECT_IS_CLONED(object))
1176         return FALSE;
1178     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1179     g_return_val_if_fail(rlist != NULL, FALSE);
1180     g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1181     rlist = g_slist_remove(rlist, object);
1182     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1184     document->priv->resources_changed_signals[q].emit();
1186     return TRUE;
1189 GSList const *
1190 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1192     g_return_val_if_fail(document != NULL, NULL);
1193     g_return_val_if_fail(key != NULL, NULL);
1194     g_return_val_if_fail(*key != '\0', NULL);
1196     return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1199 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1200                                                        gchar const *key,
1201                                                        SPDocument::ResourcesChangedSignal::slot_type slot)
1203     GQuark q = g_quark_from_string(key);
1204     return document->priv->resources_changed_signals[q].connect(slot);
1207 /* Helpers */
1209 gboolean
1210 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1212     g_slist_free((GSList *) value);
1213     return TRUE;
1216 unsigned int
1217 count_objects_recursive(SPObject *obj, unsigned int count)
1219     count++; // obj itself
1221     for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1222         count = count_objects_recursive(i, count);
1223     }
1225     return count;
1228 unsigned int
1229 objects_in_document(SPDocument *document)
1231     return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1234 void
1235 vacuum_document_recursive(SPObject *obj)
1237     if (SP_IS_DEFS(obj)) {
1238         for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1239             /* fixme: some inkscape-internal nodes in the future might not be collectable */
1240             def->requestOrphanCollection();
1241         }
1242     } else {
1243         for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1244             vacuum_document_recursive(i);
1245         }
1246     }
1249 unsigned int
1250 vacuum_document(SPDocument *document)
1252     unsigned int start = objects_in_document(document);
1253     unsigned int end;
1254     unsigned int newend = start;
1256     unsigned int iterations = 0;
1258     do {
1259         end = newend;
1261         vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1262         document->collectOrphans();
1263         iterations++;
1265         newend = objects_in_document(document);
1267     } while (iterations < 100 && newend < end);
1269     return start - newend;
1272 bool SPDocument::isSeeking() const {
1273     return priv->seeking;
1277 /*
1278   Local Variables:
1279   mode:c++
1280   c-file-style:"stroustrup"
1281   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1282   indent-tabs-mode:nil
1283   fill-column:99
1284   End:
1285 */
1286 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :