Code

add breton win32 installer translation
[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 "libnr/nr-matrix-fns.h"
46 #include "xml/repr.h"
47 #include "helper/units.h"
48 #include "inkscape-private.h"
49 #include "inkscape_version.h"
50 #include "sp-object-repr.h"
51 #include "document-private.h"
52 #include "dir-util.h"
53 #include "unit-constants.h"
54 #include "prefs-utils.h"
55 #include "libavoid/router.h"
56 #include "libnr/nr-rect.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 A4_WIDTH_STR "210mm"
68 #define A4_HEIGHT_STR "297mm"
70 #define SP_DOCUMENT_UPDATE_PRIORITY (G_PRIORITY_HIGH_IDLE - 1)
73 static gint sp_document_idle_handler(gpointer data);
75 gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data);
77 static gint doc_count = 0;
79 static unsigned long next_serial = 0;
81 SPDocument::SPDocument() {
82     SPDocumentPrivate *p;
84     keepalive = FALSE;
85     virgin    = TRUE;
87     modified_id = 0;
89     rdoc = NULL;
90     rroot = NULL;
91     root = NULL;
92     style_cascade = cr_cascade_new(NULL, NULL, NULL);
94     uri = NULL;
95     base = NULL;
96     name = NULL;
98     _collection_queue = NULL;
100     // Initialise instance of connector router.
101     router = new Avoid::Router();
102     // Don't use the Consolidate moves optimisation.
103     router->ConsolidateMoves = false;
105     perspectives = NULL;
107     p = new SPDocumentPrivate();
109     p->serial = next_serial++;
111     p->iddef = g_hash_table_new(g_direct_hash, g_direct_equal);
112     p->reprdef = g_hash_table_new(g_direct_hash, g_direct_equal);
114     p->resources = g_hash_table_new(g_str_hash, g_str_equal);
116     p->sensitive = FALSE;
117     p->partial = NULL;
118     p->history_size = 0;
119     p->undo = NULL;
120     p->redo = NULL;
121     p->seeking = false;
123     priv = p;
125     // Once things are set, hook in the manager
126     profileManager = new Inkscape::ProfileManager(this);
128     // XXX only for testing!
129     priv->undoStackObservers.add(p->console_output_undo_observer);
132 SPDocument::~SPDocument() {
133     collectOrphans();
135     // kill/unhook this first
136     if ( profileManager ) {
137         delete profileManager;
138         profileManager = 0;
139     }
141     if (priv) {
142         if (priv->partial) {
143             sp_repr_free_log(priv->partial);
144             priv->partial = NULL;
145         }
147         sp_document_clear_redo(this);
148         sp_document_clear_undo(this);
150         if (root) {
151             root->releaseReferences();
152             sp_object_unref(root);
153             root = NULL;
154         }
156         if (priv->iddef) g_hash_table_destroy(priv->iddef);
157         if (priv->reprdef) g_hash_table_destroy(priv->reprdef);
159         if (rdoc) Inkscape::GC::release(rdoc);
161         /* Free resources */
162         g_hash_table_foreach_remove(priv->resources, sp_document_resource_list_free, this);
163         g_hash_table_destroy(priv->resources);
165         delete priv;
166         priv = NULL;
167     }
169     cr_cascade_unref(style_cascade);
170     style_cascade = NULL;
172     if (name) {
173         g_free(name);
174         name = NULL;
175     }
176     if (base) {
177         g_free(base);
178         base = NULL;
179     }
180     if (uri) {
181         g_free(uri);
182         uri = NULL;
183     }
185     if (modified_id) {
186         gtk_idle_remove(modified_id);
187         modified_id = 0;
188     }
190     _selection_changed_connection.disconnect();
191     _desktop_activated_connection.disconnect();
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;
268     rroot = rdoc->root();
270     document = new SPDocument();
272     document->keepalive = keepalive;
274     document->rdoc = rdoc;
275     document->rroot = rroot;
277 #ifndef WIN32
278     prepend_current_dir_if_relative(&(document->uri), uri);
279 #else
280     // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
281     document->uri = uri? g_strdup(uri) : NULL;
282 #endif
284     // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
285     // which is why we use g_get_current_dir() in calculating the abs path above
286     //This is NULL for a new document
287     if (base)
288         document->base = g_strdup(base);
289     else
290         document->base = NULL;
291     document->name = g_strdup(name);
293     document->root = sp_object_repr_build_tree(document, rroot);
295     sodipodi_version = SP_ROOT(document->root)->version.sodipodi;
297     /* fixme: Not sure about this, but lets assume ::build updates */
298     rroot->setAttribute("sodipodi:version", SODIPODI_VERSION);
299     rroot->setAttribute("inkscape:version", INKSCAPE_VERSION);
300     /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
302     /* Quick hack 2 - get default image size into document */
303     if (!rroot->attribute("width")) rroot->setAttribute("width", A4_WIDTH_STR);
304     if (!rroot->attribute("height")) rroot->setAttribute("height", A4_HEIGHT_STR);
305     /* End of quick hack 2 */
307     /* Quick hack 3 - Set uri attributes */
308     if (uri) {
309         rroot->setAttribute("sodipodi:docname", uri);
310     }
311     /* End of quick hack 3 */
313     // creating namedview
314     if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
315         // if there's none in the document already,
316         Inkscape::XML::Node *r = NULL;
317         Inkscape::XML::Node *rnew = NULL;
318         r = inkscape_get_repr(INKSCAPE, "template.base");
319         // see if there's a template with id="base" in the preferences
320         if (!r) {
321             // if there's none, create an empty element
322             rnew = rdoc->createElement("sodipodi:namedview");
323             rnew->setAttribute("id", "base");
324         } else {
325             // otherwise, take from preferences
326             rnew = r->duplicate(rroot->document());
327         }
328         // insert into the document
329         rroot->addChild(rnew, NULL);
330         // clean up
331         Inkscape::GC::release(rnew);
332     }
334     /* Defs */
335     if (!SP_ROOT(document->root)->defs) {
336         Inkscape::XML::Node *r;
337         r = rdoc->createElement("svg:defs");
338         rroot->addChild(r, NULL);
339         Inkscape::GC::release(r);
340         g_assert(SP_ROOT(document->root)->defs);
341     }
343     /* Default RDF */
344     rdf_set_defaults( document );
346     if (keepalive) {
347         inkscape_ref();
348     }
350     // Remark: Here, we used to create a "currentpersp3d" element in the document defs.
351     // But this is probably a bad idea since we need to adapt it for every change of selection, which will
352     // completely clutter the undo history. Maybe rather save it to prefs on exit and re-read it on startup?
354     document->current_persp3d = persp3d_create_xml_element (document);
356     sp_document_set_undo_sensitive(document, true);
358     // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
359     if (!Inkscape::NSApplication::Application::getNewGui()) {
360         g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
361                          G_CALLBACK(sp_document_reset_key), document);
362         g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
363                          G_CALLBACK(sp_document_reset_key), document);
364     } else {
365         document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
366         document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
367     }
369     return document;
372 /**
373  * Fetches document from URI, or creates new, if NULL; public document
374  * appears in document list.
375  */
376 SPDocument *
377 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
379     SPDocument *doc;
380     Inkscape::XML::Document *rdoc;
381     gchar *base = NULL;
382     gchar *name = NULL;
384     if (uri) {
385         Inkscape::XML::Node *rroot;
386         gchar *s, *p;
387         /* Try to fetch repr from file */
388         rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
389         /* If file cannot be loaded, return NULL without warning */
390         if (rdoc == NULL) return NULL;
391         rroot = rdoc->root();
392         /* If xml file is not svg, return NULL without warning */
393         /* fixme: destroy document */
394         if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
395         s = g_strdup(uri);
396         p = strrchr(s, '/');
397         if (p) {
398             name = g_strdup(p + 1);
399             p[1] = '\0';
400             base = g_strdup(s);
401         } else {
402             base = NULL;
403             name = g_strdup(uri);
404         }
405         g_free(s);
406     } else {
407         rdoc = sp_repr_document_new("svg:svg");
408     }
410     if (make_new) {
411         base = NULL;
412         uri = NULL;
413         name = g_strdup_printf(_("New document %d"), ++doc_count);
414     }
416     //# These should be set by now
417     g_assert(name);
419     doc = sp_document_create(rdoc, uri, base, name, keepalive);
421     g_free(base);
422     g_free(name);
424     return doc;
427 SPDocument *
428 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
430     SPDocument *doc;
431     Inkscape::XML::Document *rdoc;
432     Inkscape::XML::Node *rroot;
433     gchar *name;
435     rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
437     /* If it cannot be loaded, return NULL without warning */
438     if (rdoc == NULL) return NULL;
440     rroot = rdoc->root();
441     /* If xml file is not svg, return NULL without warning */
442     /* fixme: destroy document */
443     if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
445     name = g_strdup_printf(_("Memory document %d"), ++doc_count);
447     doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
449     return doc;
452 SPDocument *
453 sp_document_ref(SPDocument *doc)
455     g_return_val_if_fail(doc != NULL, NULL);
456     Inkscape::GC::anchor(doc);
457     return doc;
460 SPDocument *
461 sp_document_unref(SPDocument *doc)
463     g_return_val_if_fail(doc != NULL, NULL);
464     Inkscape::GC::release(doc);
465     return NULL;
468 gdouble sp_document_width(SPDocument *document)
470     g_return_val_if_fail(document != NULL, 0.0);
471     g_return_val_if_fail(document->priv != NULL, 0.0);
472     g_return_val_if_fail(document->root != NULL, 0.0);
474     return SP_ROOT(document->root)->width.computed;
477 void
478 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
480     SPRoot *root = SP_ROOT(document->root);
482     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
483         root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
484     } else { // set to width=
485         root->width.computed = sp_units_get_pixels (width, *unit);
486         /* SVG does not support meters as a unit, so we must translate meters to
487          * cm when writing */
488         if (!strcmp(unit->abbr, "m")) {
489             root->width.value = 100*width;
490             root->width.unit = SVGLength::CM;
491         } else {
492             root->width.value = width;
493             root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
494         }
495     }
497     SP_OBJECT (root)->updateRepr();
500 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
502     SPRoot *root = SP_ROOT(document->root);
504     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
505         root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
506     } else { // set to height=
507         root->height.computed = sp_units_get_pixels (height, *unit);
508         /* SVG does not support meters as a unit, so we must translate meters to
509          * cm when writing */
510         if (!strcmp(unit->abbr, "m")) {
511             root->height.value = 100*height;
512             root->height.unit = SVGLength::CM;
513         } else {
514             root->height.value = height;
515             root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
516         }
517     }
519     SP_OBJECT (root)->updateRepr();
522 gdouble sp_document_height(SPDocument *document)
524     g_return_val_if_fail(document != NULL, 0.0);
525     g_return_val_if_fail(document->priv != NULL, 0.0);
526     g_return_val_if_fail(document->root != NULL, 0.0);
528     return SP_ROOT(document->root)->height.computed;
531 /**
532  * Given an NR::Rect that may, for example, correspond to the bbox of an object,
533  * this function fits the canvas to that rect by resizing the canvas
534  * and translating the document root into position.
535  */
536 void SPDocument::fitToRect(NR::Rect const &rect)
538     g_return_if_fail(!rect.isEmpty());
540     using NR::X; using NR::Y;
541     double const w = rect.extent(X);
542     double const h = rect.extent(Y);
544     double const old_height = sp_document_height(this);
545     SPUnit const &px(sp_unit_get_by_id(SP_UNIT_PX));
546     sp_document_set_width(this, w, &px);
547     sp_document_set_height(this, h, &px);
549     NR::translate const tr(NR::Point(0, (old_height - h))
550                            - rect.min());
551     SP_GROUP(root)->translateChildItems(tr);
554 void sp_document_set_uri(SPDocument *document, gchar const *uri)
556     g_return_if_fail(document != NULL);
558     if (document->name) {
559         g_free(document->name);
560         document->name = NULL;
561     }
562     if (document->base) {
563         g_free(document->base);
564         document->base = NULL;
565     }
566     if (document->uri) {
567         g_free(document->uri);
568         document->uri = NULL;
569     }
571     if (uri) {
573 #ifndef WIN32
574         prepend_current_dir_if_relative(&(document->uri), uri);
575 #else
576         // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
577         document->uri = g_strdup(uri);
578 #endif
580         /* fixme: Think, what this means for images (Lauris) */
581         document->base = g_path_get_dirname(document->uri);
582         document->name = g_path_get_basename(document->uri);
584     } else {
585         document->uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
586         document->base = NULL;
587         document->name = g_strdup(document->uri);
588     }
590     // Update saveable repr attributes.
591     Inkscape::XML::Node *repr = sp_document_repr_root(document);
592     // changing uri in the document repr must not be not undoable
593     bool saved = sp_document_get_undo_sensitive(document);
594     sp_document_set_undo_sensitive(document, false);
596     repr->setAttribute("sodipodi:docname", document->name);
597     sp_document_set_undo_sensitive(document, saved);
599     document->priv->uri_set_signal.emit(document->uri);
602 void
603 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
605     g_return_if_fail(doc != NULL);
607     doc->priv->resized_signal.emit(width, height);
610 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
612     return priv->modified_signal.connect(slot);
615 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
617     return priv->uri_set_signal.connect(slot);
620 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
622     return priv->resized_signal.connect(slot);
625 sigc::connection
626 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
628     return priv->_reconstruction_start_signal.connect(slot);
631 void
632 SPDocument::emitReconstructionStart(void)
634     // printf("Starting Reconstruction\n");
635     priv->_reconstruction_start_signal.emit();
636     return;
639 sigc::connection
640 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type  slot)
642     return priv->_reconstruction_finish_signal.connect(slot);
645 void
646 SPDocument::emitReconstructionFinish(void)
648     // printf("Finishing Reconstruction\n");
649     priv->_reconstruction_finish_signal.emit();
650     return;
653 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
655     return priv->commit_signal.connect(slot);
660 void SPDocument::_emitModified() {
661     static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
662     root->emitModified(0);
663     priv->modified_signal.emit(flags);
666 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
667     GQuark idq = g_quark_from_string(id);
669     if (object) {
670         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
671         g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
672     } else {
673         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
674         g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
675     }
677     SPDocumentPrivate::IDChangedSignalMap::iterator pos;
679     pos = priv->id_changed_signals.find(idq);
680     if ( pos != priv->id_changed_signals.end() ) {
681         if (!(*pos).second.empty()) {
682             (*pos).second.emit(object);
683         } else { // discard unused signal
684             priv->id_changed_signals.erase(pos);
685         }
686     }
689 void
690 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
692     this->priv->undoStackObservers.add(observer);
695 void
696 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
698     this->priv->undoStackObservers.remove(observer);
701 SPObject *SPDocument::getObjectById(gchar const *id) {
702     g_return_val_if_fail(id != NULL, NULL);
704     GQuark idq = g_quark_from_string(id);
705     return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
708 sigc::connection SPDocument::connectIdChanged(gchar const *id,
709                                               SPDocument::IDChangedSignal::slot_type slot)
711     return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
714 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
715     if (object) {
716         g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
717         g_hash_table_insert(priv->reprdef, repr, object);
718     } else {
719         g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
720         g_hash_table_remove(priv->reprdef, repr);
721     }
724 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
725     g_return_val_if_fail(repr != NULL, NULL);
726     return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
729 Glib::ustring SPDocument::getLanguage() {
730     gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
731     if (document_language) {
732         while (isspace(*document_language))
733             document_language++;
734     }
735     if ( !document_language || 0 == *document_language) {
736         // retrieve system language
737         document_language = getenv("LC_ALL");
738         if ( NULL == document_language || *document_language == 0 ) {
739             document_language = getenv ("LC_MESSAGES");
740         }
741         if ( NULL == document_language || *document_language == 0 ) {
742             document_language = getenv ("LANG");
743         }
745         if ( NULL != document_language ) {
746             gchar *pos = strchr(document_language, '_');
747             if ( NULL != pos ) {
748                 return Glib::ustring(document_language, pos - document_language);
749             }
750         }
751     }
753     if ( NULL == document_language )
754         return Glib::ustring();
755     return document_language;
758 /* Object modification root handler */
760 void
761 sp_document_request_modified(SPDocument *doc)
763     if (!doc->modified_id) {
764         doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
765     }
768 void
769 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
771     ctx->ctx.flags = 0;
772     ctx->i2doc = NR::identity();
773     /* Set up viewport in case svg has it defined as percentages */
774     if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
775         ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
776         ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
777         ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
778         ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
779     } else { // as a last resort, set size to A4
780         ctx->vp.x0 = 0.0;
781         ctx->vp.y0 = 0.0;
782         ctx->vp.x1 = 210 * PX_PER_MM;
783         ctx->vp.y1 = 297 * PX_PER_MM;
784     }
785     ctx->i2vp = NR::identity();
788 /**
789  * Tries to update the document state based on the modified and
790  * "update required" flags, and return true if the document has
791  * been brought fully up to date.
792  */
793 bool
794 SPDocument::_updateDocument()
796     /* Process updates */
797     if (this->root->uflags || this->root->mflags) {
798         if (this->root->uflags) {
799             SPItemCtx ctx;
800             sp_document_setup_viewport (this, &ctx);
802             bool saved = sp_document_get_undo_sensitive(this);
803             sp_document_set_undo_sensitive(this, false);
805             this->root->updateDisplay((SPCtx *)&ctx, 0);
807             sp_document_set_undo_sensitive(this, saved);
808         }
809         this->_emitModified();
810     }
812     return !(this->root->uflags || this->root->mflags);
816 /**
817  * Repeatedly works on getting the document updated, since sometimes
818  * it takes more than one pass to get the document updated.  But it
819  * usually should not take more than a few loops, and certainly never
820  * more than 32 iterations.  So we bail out if we hit 32 iterations,
821  * since this typically indicates we're stuck in an update loop.
822  */
823 gint
824 sp_document_ensure_up_to_date(SPDocument *doc)
826     int counter = 32;
827     while (!doc->_updateDocument()) {
828         if (counter == 0) {
829             g_warning("More than 32 iteration while updating document '%s'", doc->uri);
830             break;
831         }
832         counter--;
833     }
835     if (doc->modified_id) {
836         /* Remove handler */
837         gtk_idle_remove(doc->modified_id);
838         doc->modified_id = 0;
839     }
840     return counter>0;
843 /**
844  * An idle handler to update the document.  Returns true if
845  * the document needs further updates.
846  */
847 static gint
848 sp_document_idle_handler(gpointer data)
850     SPDocument *doc = static_cast<SPDocument *>(data);
851     if (doc->_updateDocument()) {
852         doc->modified_id = 0;
853         return false;
854     } else {
855         return true;
856     }
859 static bool is_within(NR::Rect const &area, NR::Rect const &box)
861     return area.contains(box);
864 static bool overlaps(NR::Rect const &area, NR::Rect const &box)
866     return area.intersects(box);
869 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, NR::Rect const &area,
870                                   bool (*test)(NR::Rect const &, NR::Rect const &), bool take_insensitive = false)
872     g_return_val_if_fail(SP_IS_GROUP(group), s);
874     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
875         if (!SP_IS_ITEM(o)) {
876             continue;
877         }
878         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
879             s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
880         } else {
881             SPItem *child = SP_ITEM(o);
882             NR::Maybe<NR::Rect> box = sp_item_bbox_desktop(child);
883             if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
884                 s = g_slist_append(s, child);
885             }
886         }
887     }
889     return s;
892 /**
893 Returns true if an item is among the descendants of group (recursively).
894  */
895 bool item_is_in_group(SPItem *item, SPGroup *group)
897     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
898         if (!SP_IS_ITEM(o)) continue;
899         if (SP_ITEM(o) == item)
900             return true;
901         if (SP_IS_GROUP(o))
902             if (item_is_in_group(item, SP_GROUP(o)))
903                 return true;
904     }
905     return false;
908 /**
909 Returns the bottommost item from the list which is at the point, or NULL if none.
910 */
911 SPItem*
912 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
913                                            NR::Point const p, bool take_insensitive)
915     g_return_val_if_fail(group, NULL);
917     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
919     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
921         if (!SP_IS_ITEM(o)) continue;
923         SPItem *item = SP_ITEM(o);
924         NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
925         if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
926             && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
927             if (g_slist_find((GSList *) list, item) != NULL)
928                 return item;
929         }
931         if (SP_IS_GROUP(o)) {
932             SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
933             if (found)
934                 return found;
935         }
937     }
938     return NULL;
941 /**
942 Returns the topmost (in z-order) item from the descendants of group (recursively) which
943 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
944 non-layer groups or not. Honors take_insensitive on whether to return insensitive
945 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
946 upwards in z-order and returns what it has found so far (i.e. the found item is
947 guaranteed to be lower than upto).
948  */
949 SPItem*
950 find_item_at_point(unsigned int dkey, SPGroup *group, NR::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
952     SPItem *seen = NULL, *newseen = NULL;
954     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
956     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
957         if (!SP_IS_ITEM(o)) continue;
959         if (upto && SP_ITEM(o) == upto)
960             break;
962         if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
963             // if nothing found yet, recurse into the group
964             newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
965             if (newseen) {
966                 seen = newseen;
967                 newseen = NULL;
968             }
970             if (item_is_in_group(upto, SP_GROUP(o)))
971                 break;
973         } else {
974             SPItem *child = SP_ITEM(o);
975             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
977             // seen remembers the last (topmost) of items pickable at this point
978             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
979                 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
980                 seen = child;
981             }
982         }
983     }
984     return seen;
987 /**
988 Returns the topmost non-layer group from the descendants of group which is at point
989 p, or NULL if none. Recurses into layers but not into groups.
990  */
991 SPItem*
992 find_group_at_point(unsigned int dkey, SPGroup *group, NR::Point const p)
994     SPItem *seen = NULL;
996     gdouble delta = prefs_get_double_attribute ("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;
1000         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1001             SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1002             if (newseen) {
1003                 seen = newseen;
1004             }
1005         }
1006         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1007             SPItem *child = SP_ITEM(o);
1008             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1010             // seen remembers the last (topmost) of groups pickable at this point
1011             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1012                 seen = child;
1013             }
1014         }
1015     }
1016     return seen;
1019 /*
1020  * Return list of items, contained in box
1021  *
1022  * Assumes box is normalized (and g_asserts it!)
1023  *
1024  */
1026 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
1028     g_return_val_if_fail(document != NULL, NULL);
1029     g_return_val_if_fail(document->priv != NULL, NULL);
1031     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
1034 /*
1035  * Return list of items, that the parts of the item contained in box
1036  *
1037  * Assumes box is normalized (and g_asserts it!)
1038  *
1039  */
1041 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
1043     g_return_val_if_fail(document != NULL, NULL);
1044     g_return_val_if_fail(document->priv != NULL, NULL);
1046     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1049 GSList *
1050 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<NR::Point> points)
1052     GSList *items = NULL;
1054     // When picking along the path, we don't want small objects close together
1055     // (such as hatching strokes) to obscure each other by their deltas,
1056     // so we temporarily set delta to a small value
1057     gdouble saved_delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
1058     prefs_set_double_attribute ("options.cursortolerance", "value", 0.25);
1060     for(unsigned int i = 0; i < points.size(); i++) {
1061         SPItem *item = sp_document_item_at_point(document, key, points[i],
1062                                          false, NULL);
1063         if (item && !g_slist_find(items, item))
1064             items = g_slist_prepend (items, item);
1065     }
1067     // and now we restore it back
1068     prefs_set_double_attribute ("options.cursortolerance", "value", saved_delta);
1070     return items;
1073 SPItem *
1074 sp_document_item_at_point(SPDocument *document, unsigned const key, NR::Point const p,
1075                           gboolean const into_groups, SPItem *upto)
1077     g_return_val_if_fail(document != NULL, NULL);
1078     g_return_val_if_fail(document->priv != NULL, NULL);
1080     return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1083 SPItem*
1084 sp_document_group_at_point(SPDocument *document, unsigned int key, NR::Point const p)
1086     g_return_val_if_fail(document != NULL, NULL);
1087     g_return_val_if_fail(document->priv != NULL, NULL);
1089     return find_group_at_point(key, SP_GROUP(document->root), p);
1093 /* Resource management */
1095 gboolean
1096 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1098     GSList *rlist;
1099     GQuark q = g_quark_from_string(key);
1101     g_return_val_if_fail(document != NULL, FALSE);
1102     g_return_val_if_fail(key != NULL, FALSE);
1103     g_return_val_if_fail(*key != '\0', FALSE);
1104     g_return_val_if_fail(object != NULL, FALSE);
1105     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1107     if (SP_OBJECT_IS_CLONED(object))
1108         return FALSE;
1110     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1111     g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1112     rlist = g_slist_prepend(rlist, object);
1113     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1115     document->priv->resources_changed_signals[q].emit();
1117     return TRUE;
1120 gboolean
1121 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1123     GSList *rlist;
1124     GQuark q = g_quark_from_string(key);
1126     g_return_val_if_fail(document != NULL, FALSE);
1127     g_return_val_if_fail(key != NULL, FALSE);
1128     g_return_val_if_fail(*key != '\0', FALSE);
1129     g_return_val_if_fail(object != NULL, FALSE);
1130     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1132     if (SP_OBJECT_IS_CLONED(object))
1133         return FALSE;
1135     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1136     g_return_val_if_fail(rlist != NULL, FALSE);
1137     g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1138     rlist = g_slist_remove(rlist, object);
1139     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1141     document->priv->resources_changed_signals[q].emit();
1143     return TRUE;
1146 GSList const *
1147 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1149     g_return_val_if_fail(document != NULL, NULL);
1150     g_return_val_if_fail(key != NULL, NULL);
1151     g_return_val_if_fail(*key != '\0', NULL);
1153     return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1156 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1157                                                        gchar const *key,
1158                                                        SPDocument::ResourcesChangedSignal::slot_type slot)
1160     GQuark q = g_quark_from_string(key);
1161     return document->priv->resources_changed_signals[q].connect(slot);
1164 /* Helpers */
1166 gboolean
1167 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1169     g_slist_free((GSList *) value);
1170     return TRUE;
1173 unsigned int
1174 count_objects_recursive(SPObject *obj, unsigned int count)
1176     count++; // obj itself
1178     for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1179         count = count_objects_recursive(i, count);
1180     }
1182     return count;
1185 unsigned int
1186 objects_in_document(SPDocument *document)
1188     return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1191 void
1192 vacuum_document_recursive(SPObject *obj)
1194     if (SP_IS_DEFS(obj)) {
1195         for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1196             /* fixme: some inkscape-internal nodes in the future might not be collectable */
1197             def->requestOrphanCollection();
1198         }
1199     } else {
1200         for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1201             vacuum_document_recursive(i);
1202         }
1203     }
1206 unsigned int
1207 vacuum_document(SPDocument *document)
1209     unsigned int start = objects_in_document(document);
1210     unsigned int end;
1211     unsigned int newend = start;
1213     unsigned int iterations = 0;
1215     do {
1216         end = newend;
1218         vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1219         document->collectOrphans();
1220         iterations++;
1222         newend = objects_in_document(document);
1224     } while (iterations < 100 && newend < end);
1226     return start - newend;
1229 bool SPDocument::isSeeking() const {
1230     return priv->seeking;
1234 /*
1235   Local Variables:
1236   mode:c++
1237   c-file-style:"stroustrup"
1238   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1239   indent-tabs-mode:nil
1240   fill-column:99
1241   End:
1242 */
1243 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :