Code

Fix incorrect preview problems on Win32 with native dialogues - see LP #229045
[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 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     SPDocumentPrivate *p;
81     keepalive = FALSE;
82     virgin    = TRUE;
84     modified_id = 0;
86     rdoc = NULL;
87     rroot = NULL;
88     root = NULL;
89     style_cascade = cr_cascade_new(NULL, NULL, NULL);
91     uri = NULL;
92     base = NULL;
93     name = NULL;
95     _collection_queue = NULL;
97     // Initialise instance of connector router.
98     router = new Avoid::Router();
99     // Don't use the Consolidate moves optimisation.
100     router->ConsolidateMoves = false;
102     perspectives = NULL;
104     p = new SPDocumentPrivate();
106     p->serial = next_serial++;
108     p->iddef = g_hash_table_new(g_direct_hash, g_direct_equal);
109     p->reprdef = g_hash_table_new(g_direct_hash, g_direct_equal);
111     p->resources = g_hash_table_new(g_str_hash, g_str_equal);
113     p->sensitive = FALSE;
114     p->partial = NULL;
115     p->history_size = 0;
116     p->undo = NULL;
117     p->redo = NULL;
118     p->seeking = false;
120     priv = p;
122     // Once things are set, hook in the manager
123     profileManager = new Inkscape::ProfileManager(this);
125     // XXX only for testing!
126     priv->undoStackObservers.add(p->console_output_undo_observer);
129 SPDocument::~SPDocument() {
130     collectOrphans();
132     // kill/unhook this first
133     if ( profileManager ) {
134         delete profileManager;
135         profileManager = 0;
136     }
138     if (priv) {
139         if (priv->partial) {
140             sp_repr_free_log(priv->partial);
141             priv->partial = NULL;
142         }
144         sp_document_clear_redo(this);
145         sp_document_clear_undo(this);
147         if (root) {
148             root->releaseReferences();
149             sp_object_unref(root);
150             root = NULL;
151         }
153         if (priv->iddef) g_hash_table_destroy(priv->iddef);
154         if (priv->reprdef) g_hash_table_destroy(priv->reprdef);
156         if (rdoc) Inkscape::GC::release(rdoc);
158         /* Free resources */
159         g_hash_table_foreach_remove(priv->resources, sp_document_resource_list_free, this);
160         g_hash_table_destroy(priv->resources);
162         delete priv;
163         priv = NULL;
164     }
166     cr_cascade_unref(style_cascade);
167     style_cascade = NULL;
169     if (name) {
170         g_free(name);
171         name = NULL;
172     }
173     if (base) {
174         g_free(base);
175         base = NULL;
176     }
177     if (uri) {
178         g_free(uri);
179         uri = NULL;
180     }
182     if (modified_id) {
183         gtk_idle_remove(modified_id);
184         modified_id = 0;
185     }
187     _selection_changed_connection.disconnect();
188     _desktop_activated_connection.disconnect();
190     if (keepalive) {
191         inkscape_unref();
192         keepalive = FALSE;
193     }
195     if (router) {
196         delete router;
197         router = NULL;
198     }
200     //delete this->_whiteboard_session_manager;
204 void SPDocument::add_persp3d (Persp3D * const /*persp*/)
206     SPDefs *defs = SP_ROOT(this->root)->defs;
207     for (SPObject *i = sp_object_first_child(SP_OBJECT(defs)); i != NULL; i = SP_OBJECT_NEXT(i) ) {
208         if (SP_IS_PERSP3D(i)) {
209             g_print ("Encountered a Persp3D in defs\n");
210         }
211     }
213     g_print ("Adding Persp3D to defs\n");
214     persp3d_create_xml_element (this);
217 void SPDocument::remove_persp3d (Persp3D * const /*persp*/)
219     // TODO: Delete the repr, maybe perform a check if any boxes are still linked to the perspective.
220     //       Anything else?
221     g_print ("Please implement deletion of perspectives here.\n");
224 unsigned long SPDocument::serial() const {
225     return priv->serial;
228 void SPDocument::queueForOrphanCollection(SPObject *object) {
229     g_return_if_fail(object != NULL);
230     g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
232     sp_object_ref(object, NULL);
233     _collection_queue = g_slist_prepend(_collection_queue, object);
236 void SPDocument::collectOrphans() {
237     while (_collection_queue) {
238         GSList *objects=_collection_queue;
239         _collection_queue = NULL;
240         for ( GSList *iter=objects ; iter ; iter = iter->next ) {
241             SPObject *object=reinterpret_cast<SPObject *>(iter->data);
242             object->collectOrphan();
243             sp_object_unref(object, NULL);
244         }
245         g_slist_free(objects);
246     }
249 void SPDocument::reset_key (void */*dummy*/)
251     actionkey = NULL;
254 SPDocument *
255 sp_document_create(Inkscape::XML::Document *rdoc,
256                    gchar const *uri,
257                    gchar const *base,
258                    gchar const *name,
259                    unsigned int keepalive)
261     SPDocument *document;
262     Inkscape::XML::Node *rroot;
263     Inkscape::Version sodipodi_version;
265     rroot = rdoc->root();
267     document = new SPDocument();
269     document->keepalive = keepalive;
271     document->rdoc = rdoc;
272     document->rroot = rroot;
274 #ifndef WIN32
275     prepend_current_dir_if_relative(&(document->uri), uri);
276 #else
277     // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
278     document->uri = uri? g_strdup(uri) : NULL;
279 #endif
281     // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
282     // which is why we use g_get_current_dir() in calculating the abs path above
283     //This is NULL for a new document
284     if (base)
285         document->base = g_strdup(base);
286     else
287         document->base = NULL;
288     document->name = g_strdup(name);
290     document->root = sp_object_repr_build_tree(document, rroot);
292     sodipodi_version = SP_ROOT(document->root)->version.sodipodi;
294     /* fixme: Not sure about this, but lets assume ::build updates */
295     rroot->setAttribute("sodipodi:version", SODIPODI_VERSION);
296     rroot->setAttribute("inkscape:version", INKSCAPE_VERSION);
297     /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
299     /* Quick hack 2 - get default image size into document */
300     if (!rroot->attribute("width")) rroot->setAttribute("width", "100%");
301     if (!rroot->attribute("height")) rroot->setAttribute("height", "100%");
302     /* End of quick hack 2 */
304     /* Quick hack 3 - Set uri attributes */
305     if (uri) {
306         rroot->setAttribute("sodipodi:docname", uri);
307     }
308     /* End of quick hack 3 */
310     // creating namedview
311     if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
312         // if there's none in the document already,
313         Inkscape::XML::Node *r = NULL;
314         Inkscape::XML::Node *rnew = NULL;
315         r = inkscape_get_repr(INKSCAPE, "template.base");
316         // see if there's a template with id="base" in the preferences
317         if (!r) {
318             // if there's none, create an empty element
319             rnew = rdoc->createElement("sodipodi:namedview");
320             rnew->setAttribute("id", "base");
321         } else {
322             // otherwise, take from preferences
323             rnew = r->duplicate(rroot->document());
324         }
325         // insert into the document
326         rroot->addChild(rnew, NULL);
327         // clean up
328         Inkscape::GC::release(rnew);
329     }
331     /* Defs */
332     if (!SP_ROOT(document->root)->defs) {
333         Inkscape::XML::Node *r;
334         r = rdoc->createElement("svg:defs");
335         rroot->addChild(r, NULL);
336         Inkscape::GC::release(r);
337         g_assert(SP_ROOT(document->root)->defs);
338     }
340     /* Default RDF */
341     rdf_set_defaults( document );
343     if (keepalive) {
344         inkscape_ref();
345     }
347     // Remark: Here, we used to create a "currentpersp3d" element in the document defs.
348     // But this is probably a bad idea since we need to adapt it for every change of selection, which will
349     // completely clutter the undo history. Maybe rather save it to prefs on exit and re-read it on startup?
351     document->current_persp3d = persp3d_document_first_persp(document);
352     if (!document->current_persp3d) {
353         document->current_persp3d = persp3d_create_xml_element (document);
354     }
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     SPRoot *root = SP_ROOT(document->root);
476     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set)
477         return root->viewBox.x1 - root->viewBox.x0;
478     return root->width.computed;
481 void
482 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
484     SPRoot *root = SP_ROOT(document->root);
486     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
487         root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
488     } else { // set to width=
489         root->width.computed = sp_units_get_pixels (width, *unit);
490         /* SVG does not support meters as a unit, so we must translate meters to
491          * cm when writing */
492         if (!strcmp(unit->abbr, "m")) {
493             root->width.value = 100*width;
494             root->width.unit = SVGLength::CM;
495         } else {
496             root->width.value = width;
497             root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
498         }
499     }
501     SP_OBJECT (root)->updateRepr();
504 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
506     SPRoot *root = SP_ROOT(document->root);
508     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
509         root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
510     } else { // set to height=
511         root->height.computed = sp_units_get_pixels (height, *unit);
512         /* SVG does not support meters as a unit, so we must translate meters to
513          * cm when writing */
514         if (!strcmp(unit->abbr, "m")) {
515             root->height.value = 100*height;
516             root->height.unit = SVGLength::CM;
517         } else {
518             root->height.value = height;
519             root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
520         }
521     }
523     SP_OBJECT (root)->updateRepr();
526 gdouble sp_document_height(SPDocument *document)
528     g_return_val_if_fail(document != NULL, 0.0);
529     g_return_val_if_fail(document->priv != NULL, 0.0);
530     g_return_val_if_fail(document->root != NULL, 0.0);
532     SPRoot *root = SP_ROOT(document->root);
534     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set)
535         return root->viewBox.y1 - root->viewBox.y0;
536     return root->height.computed;
539 /**
540  * Given an NR::Rect that may, for example, correspond to the bbox of an object,
541  * this function fits the canvas to that rect by resizing the canvas
542  * and translating the document root into position.
543  */
544 void SPDocument::fitToRect(NR::Rect const &rect)
546     g_return_if_fail(!rect.isEmpty());
548     using NR::X; using NR::Y;
549     double const w = rect.extent(X);
550     double const h = rect.extent(Y);
552     double const old_height = sp_document_height(this);
553     SPUnit const &px(sp_unit_get_by_id(SP_UNIT_PX));
554     sp_document_set_width(this, w, &px);
555     sp_document_set_height(this, h, &px);
557     NR::translate const tr(NR::Point(0, (old_height - h))
558                            - rect.min());
559     SP_GROUP(root)->translateChildItems(tr);
562 void sp_document_set_uri(SPDocument *document, gchar const *uri)
564     g_return_if_fail(document != NULL);
566     if (document->name) {
567         g_free(document->name);
568         document->name = NULL;
569     }
570     if (document->base) {
571         g_free(document->base);
572         document->base = NULL;
573     }
574     if (document->uri) {
575         g_free(document->uri);
576         document->uri = NULL;
577     }
579     if (uri) {
581 #ifndef WIN32
582         prepend_current_dir_if_relative(&(document->uri), uri);
583 #else
584         // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
585         document->uri = g_strdup(uri);
586 #endif
588         /* fixme: Think, what this means for images (Lauris) */
589         document->base = g_path_get_dirname(document->uri);
590         document->name = g_path_get_basename(document->uri);
592     } else {
593         document->uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
594         document->base = NULL;
595         document->name = g_strdup(document->uri);
596     }
598     // Update saveable repr attributes.
599     Inkscape::XML::Node *repr = sp_document_repr_root(document);
600     // changing uri in the document repr must not be not undoable
601     bool saved = sp_document_get_undo_sensitive(document);
602     sp_document_set_undo_sensitive(document, false);
604     repr->setAttribute("sodipodi:docname", document->name);
605     sp_document_set_undo_sensitive(document, saved);
607     document->priv->uri_set_signal.emit(document->uri);
610 void
611 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
613     g_return_if_fail(doc != NULL);
615     doc->priv->resized_signal.emit(width, height);
618 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
620     return priv->modified_signal.connect(slot);
623 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
625     return priv->uri_set_signal.connect(slot);
628 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
630     return priv->resized_signal.connect(slot);
633 sigc::connection
634 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
636     return priv->_reconstruction_start_signal.connect(slot);
639 void
640 SPDocument::emitReconstructionStart(void)
642     // printf("Starting Reconstruction\n");
643     priv->_reconstruction_start_signal.emit();
644     return;
647 sigc::connection
648 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type  slot)
650     return priv->_reconstruction_finish_signal.connect(slot);
653 void
654 SPDocument::emitReconstructionFinish(void)
656     // printf("Finishing Reconstruction\n");
657     priv->_reconstruction_finish_signal.emit();
658     return;
661 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
663     return priv->commit_signal.connect(slot);
668 void SPDocument::_emitModified() {
669     static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
670     root->emitModified(0);
671     priv->modified_signal.emit(flags);
674 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
675     GQuark idq = g_quark_from_string(id);
677     if (object) {
678         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
679         g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
680     } else {
681         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
682         g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
683     }
685     SPDocumentPrivate::IDChangedSignalMap::iterator pos;
687     pos = priv->id_changed_signals.find(idq);
688     if ( pos != priv->id_changed_signals.end() ) {
689         if (!(*pos).second.empty()) {
690             (*pos).second.emit(object);
691         } else { // discard unused signal
692             priv->id_changed_signals.erase(pos);
693         }
694     }
697 void
698 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
700     this->priv->undoStackObservers.add(observer);
703 void
704 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
706     this->priv->undoStackObservers.remove(observer);
709 SPObject *SPDocument::getObjectById(gchar const *id) {
710     g_return_val_if_fail(id != NULL, NULL);
712     GQuark idq = g_quark_from_string(id);
713     return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
716 sigc::connection SPDocument::connectIdChanged(gchar const *id,
717                                               SPDocument::IDChangedSignal::slot_type slot)
719     return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
722 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
723     if (object) {
724         g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
725         g_hash_table_insert(priv->reprdef, repr, object);
726     } else {
727         g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
728         g_hash_table_remove(priv->reprdef, repr);
729     }
732 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
733     g_return_val_if_fail(repr != NULL, NULL);
734     return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
737 Glib::ustring SPDocument::getLanguage() {
738     gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
739     if (document_language) {
740         while (isspace(*document_language))
741             document_language++;
742     }
743     if ( !document_language || 0 == *document_language) {
744         // retrieve system language
745         document_language = getenv("LC_ALL");
746         if ( NULL == document_language || *document_language == 0 ) {
747             document_language = getenv ("LC_MESSAGES");
748         }
749         if ( NULL == document_language || *document_language == 0 ) {
750             document_language = getenv ("LANG");
751         }
753         if ( NULL != document_language ) {
754             gchar *pos = strchr(document_language, '_');
755             if ( NULL != pos ) {
756                 return Glib::ustring(document_language, pos - document_language);
757             }
758         }
759     }
761     if ( NULL == document_language )
762         return Glib::ustring();
763     return document_language;
766 /* Object modification root handler */
768 void
769 sp_document_request_modified(SPDocument *doc)
771     if (!doc->modified_id) {
772         doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
773     }
776 void
777 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
779     ctx->ctx.flags = 0;
780     ctx->i2doc = NR::identity();
781     /* Set up viewport in case svg has it defined as percentages */
782     if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
783         ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
784         ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
785         ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
786         ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
787     } else { // as a last resort, set size to A4
788         ctx->vp.x0 = 0.0;
789         ctx->vp.y0 = 0.0;
790         ctx->vp.x1 = 210 * PX_PER_MM;
791         ctx->vp.y1 = 297 * PX_PER_MM;
792     }
793     ctx->i2vp = NR::identity();
796 /**
797  * Tries to update the document state based on the modified and
798  * "update required" flags, and return true if the document has
799  * been brought fully up to date.
800  */
801 bool
802 SPDocument::_updateDocument()
804     /* Process updates */
805     if (this->root->uflags || this->root->mflags) {
806         if (this->root->uflags) {
807             SPItemCtx ctx;
808             sp_document_setup_viewport (this, &ctx);
810             bool saved = sp_document_get_undo_sensitive(this);
811             sp_document_set_undo_sensitive(this, false);
813             this->root->updateDisplay((SPCtx *)&ctx, 0);
815             sp_document_set_undo_sensitive(this, saved);
816         }
817         this->_emitModified();
818     }
820     return !(this->root->uflags || this->root->mflags);
824 /**
825  * Repeatedly works on getting the document updated, since sometimes
826  * it takes more than one pass to get the document updated.  But it
827  * usually should not take more than a few loops, and certainly never
828  * more than 32 iterations.  So we bail out if we hit 32 iterations,
829  * since this typically indicates we're stuck in an update loop.
830  */
831 gint
832 sp_document_ensure_up_to_date(SPDocument *doc)
834     int counter = 32;
835     while (!doc->_updateDocument()) {
836         if (counter == 0) {
837             g_warning("More than 32 iteration while updating document '%s'", doc->uri);
838             break;
839         }
840         counter--;
841     }
843     if (doc->modified_id) {
844         /* Remove handler */
845         gtk_idle_remove(doc->modified_id);
846         doc->modified_id = 0;
847     }
848     return counter>0;
851 /**
852  * An idle handler to update the document.  Returns true if
853  * the document needs further updates.
854  */
855 static gint
856 sp_document_idle_handler(gpointer data)
858     SPDocument *doc = static_cast<SPDocument *>(data);
859     if (doc->_updateDocument()) {
860         doc->modified_id = 0;
861         return false;
862     } else {
863         return true;
864     }
867 static bool is_within(NR::Rect const &area, NR::Rect const &box)
869     return area.contains(box);
872 static bool overlaps(NR::Rect const &area, NR::Rect const &box)
874     return area.intersects(box);
877 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, NR::Rect const &area,
878                                   bool (*test)(NR::Rect const &, NR::Rect const &), bool take_insensitive = false)
880     g_return_val_if_fail(SP_IS_GROUP(group), s);
882     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
883         if (!SP_IS_ITEM(o)) {
884             continue;
885         }
886         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
887             s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
888         } else {
889             SPItem *child = SP_ITEM(o);
890             NR::Maybe<NR::Rect> box = sp_item_bbox_desktop(child);
891             if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
892                 s = g_slist_append(s, child);
893             }
894         }
895     }
897     return s;
900 /**
901 Returns true if an item is among the descendants of group (recursively).
902  */
903 bool item_is_in_group(SPItem *item, SPGroup *group)
905     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
906         if (!SP_IS_ITEM(o)) continue;
907         if (SP_ITEM(o) == item)
908             return true;
909         if (SP_IS_GROUP(o))
910             if (item_is_in_group(item, SP_GROUP(o)))
911                 return true;
912     }
913     return false;
916 /**
917 Returns the bottommost item from the list which is at the point, or NULL if none.
918 */
919 SPItem*
920 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
921                                            NR::Point const p, bool take_insensitive)
923     g_return_val_if_fail(group, NULL);
925     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
927     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
929         if (!SP_IS_ITEM(o)) continue;
931         SPItem *item = SP_ITEM(o);
932         NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
933         if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
934             && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
935             if (g_slist_find((GSList *) list, item) != NULL)
936                 return item;
937         }
939         if (SP_IS_GROUP(o)) {
940             SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
941             if (found)
942                 return found;
943         }
945     }
946     return NULL;
949 /**
950 Returns the topmost (in z-order) item from the descendants of group (recursively) which
951 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
952 non-layer groups or not. Honors take_insensitive on whether to return insensitive
953 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
954 upwards in z-order and returns what it has found so far (i.e. the found item is
955 guaranteed to be lower than upto).
956  */
957 SPItem*
958 find_item_at_point(unsigned int dkey, SPGroup *group, NR::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
960     SPItem *seen = NULL, *newseen = NULL;
962     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
964     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
965         if (!SP_IS_ITEM(o)) continue;
967         if (upto && SP_ITEM(o) == upto)
968             break;
970         if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
971             // if nothing found yet, recurse into the group
972             newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
973             if (newseen) {
974                 seen = newseen;
975                 newseen = NULL;
976             }
978             if (item_is_in_group(upto, SP_GROUP(o)))
979                 break;
981         } else {
982             SPItem *child = SP_ITEM(o);
983             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
985             // seen remembers the last (topmost) of items pickable at this point
986             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
987                 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
988                 seen = child;
989             }
990         }
991     }
992     return seen;
995 /**
996 Returns the topmost non-layer group from the descendants of group which is at point
997 p, or NULL if none. Recurses into layers but not into groups.
998  */
999 SPItem*
1000 find_group_at_point(unsigned int dkey, SPGroup *group, NR::Point const p)
1002     SPItem *seen = NULL;
1004     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
1006     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1007         if (!SP_IS_ITEM(o)) continue;
1008         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1009             SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1010             if (newseen) {
1011                 seen = newseen;
1012             }
1013         }
1014         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1015             SPItem *child = SP_ITEM(o);
1016             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1018             // seen remembers the last (topmost) of groups pickable at this point
1019             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1020                 seen = child;
1021             }
1022         }
1023     }
1024     return seen;
1027 /*
1028  * Return list of items, contained in box
1029  *
1030  * Assumes box is normalized (and g_asserts it!)
1031  *
1032  */
1034 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
1036     g_return_val_if_fail(document != NULL, NULL);
1037     g_return_val_if_fail(document->priv != NULL, NULL);
1039     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
1042 /*
1043  * Return list of items, that the parts of the item contained in box
1044  *
1045  * Assumes box is normalized (and g_asserts it!)
1046  *
1047  */
1049 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
1051     g_return_val_if_fail(document != NULL, NULL);
1052     g_return_val_if_fail(document->priv != NULL, NULL);
1054     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1057 GSList *
1058 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<NR::Point> points)
1060     GSList *items = NULL;
1062     // When picking along the path, we don't want small objects close together
1063     // (such as hatching strokes) to obscure each other by their deltas,
1064     // so we temporarily set delta to a small value
1065     gdouble saved_delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
1066     prefs_set_double_attribute ("options.cursortolerance", "value", 0.25);
1068     for(unsigned int i = 0; i < points.size(); i++) {
1069         SPItem *item = sp_document_item_at_point(document, key, points[i],
1070                                          false, NULL);
1071         if (item && !g_slist_find(items, item))
1072             items = g_slist_prepend (items, item);
1073     }
1075     // and now we restore it back
1076     prefs_set_double_attribute ("options.cursortolerance", "value", saved_delta);
1078     return items;
1081 SPItem *
1082 sp_document_item_at_point(SPDocument *document, unsigned const key, NR::Point const p,
1083                           gboolean const into_groups, SPItem *upto)
1085     g_return_val_if_fail(document != NULL, NULL);
1086     g_return_val_if_fail(document->priv != NULL, NULL);
1088     return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1091 SPItem*
1092 sp_document_group_at_point(SPDocument *document, unsigned int key, NR::Point const p)
1094     g_return_val_if_fail(document != NULL, NULL);
1095     g_return_val_if_fail(document->priv != NULL, NULL);
1097     return find_group_at_point(key, SP_GROUP(document->root), p);
1101 /* Resource management */
1103 gboolean
1104 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1106     GSList *rlist;
1107     GQuark q = g_quark_from_string(key);
1109     g_return_val_if_fail(document != NULL, FALSE);
1110     g_return_val_if_fail(key != NULL, FALSE);
1111     g_return_val_if_fail(*key != '\0', FALSE);
1112     g_return_val_if_fail(object != NULL, FALSE);
1113     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1115     if (SP_OBJECT_IS_CLONED(object))
1116         return FALSE;
1118     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1119     g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1120     rlist = g_slist_prepend(rlist, object);
1121     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1123     document->priv->resources_changed_signals[q].emit();
1125     return TRUE;
1128 gboolean
1129 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1131     GSList *rlist;
1132     GQuark q = g_quark_from_string(key);
1134     g_return_val_if_fail(document != NULL, FALSE);
1135     g_return_val_if_fail(key != NULL, FALSE);
1136     g_return_val_if_fail(*key != '\0', FALSE);
1137     g_return_val_if_fail(object != NULL, FALSE);
1138     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1140     if (SP_OBJECT_IS_CLONED(object))
1141         return FALSE;
1143     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1144     g_return_val_if_fail(rlist != NULL, FALSE);
1145     g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1146     rlist = g_slist_remove(rlist, object);
1147     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1149     document->priv->resources_changed_signals[q].emit();
1151     return TRUE;
1154 GSList const *
1155 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1157     g_return_val_if_fail(document != NULL, NULL);
1158     g_return_val_if_fail(key != NULL, NULL);
1159     g_return_val_if_fail(*key != '\0', NULL);
1161     return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1164 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1165                                                        gchar const *key,
1166                                                        SPDocument::ResourcesChangedSignal::slot_type slot)
1168     GQuark q = g_quark_from_string(key);
1169     return document->priv->resources_changed_signals[q].connect(slot);
1172 /* Helpers */
1174 gboolean
1175 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1177     g_slist_free((GSList *) value);
1178     return TRUE;
1181 unsigned int
1182 count_objects_recursive(SPObject *obj, unsigned int count)
1184     count++; // obj itself
1186     for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1187         count = count_objects_recursive(i, count);
1188     }
1190     return count;
1193 unsigned int
1194 objects_in_document(SPDocument *document)
1196     return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1199 void
1200 vacuum_document_recursive(SPObject *obj)
1202     if (SP_IS_DEFS(obj)) {
1203         for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1204             /* fixme: some inkscape-internal nodes in the future might not be collectable */
1205             def->requestOrphanCollection();
1206         }
1207     } else {
1208         for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1209             vacuum_document_recursive(i);
1210         }
1211     }
1214 unsigned int
1215 vacuum_document(SPDocument *document)
1217     unsigned int start = objects_in_document(document);
1218     unsigned int end;
1219     unsigned int newend = start;
1221     unsigned int iterations = 0;
1223     do {
1224         end = newend;
1226         vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1227         document->collectOrphans();
1228         iterations++;
1230         newend = objects_in_document(document);
1232     } while (iterations < 100 && newend < end);
1234     return start - newend;
1237 bool SPDocument::isSeeking() const {
1238     return priv->seeking;
1242 /*
1243   Local Variables:
1244   mode:c++
1245   c-file-style:"stroustrup"
1246   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1247   indent-tabs-mode:nil
1248   fill-column:99
1249   End:
1250 */
1251 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :