Code

make win32 compile using libxslt
[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 "application/application.h"
42 #include "application/editor.h"
43 #include "libnr/nr-matrix-fns.h"
44 #include "xml/repr.h"
45 #include "helper/units.h"
46 #include "inkscape-private.h"
47 #include "inkscape_version.h"
48 #include "sp-object-repr.h"
49 #include "document-private.h"
50 #include "dir-util.h"
51 #include "unit-constants.h"
52 #include "prefs-utils.h"
53 #include "libavoid/router.h"
54 #include "libnr/nr-rect.h"
55 #include "sp-item-group.h"
56 #include "perspective3d.h"
58 #include "display/nr-arena-item.h"
60 #include "dialogs/rdf.h"
62 #define A4_WIDTH_STR "210mm"
63 #define A4_HEIGHT_STR "297mm"
65 #define SP_DOCUMENT_UPDATE_PRIORITY (G_PRIORITY_HIGH_IDLE - 1)
68 static gint sp_document_idle_handler(gpointer data);
70 gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data);
72 static gint doc_count = 0;
74 static unsigned long next_serial = 0;
76 SPDocument::SPDocument() {
77     SPDocumentPrivate *p;
79     keepalive = FALSE;
80     virgin    = TRUE;
82     modified_id = 0;
84     rdoc = NULL;
85     rroot = NULL;
86     root = NULL;
87     style_cascade = cr_cascade_new(NULL, NULL, NULL);
89     uri = NULL;
90     base = NULL;
91     name = NULL;
93     _collection_queue = NULL;
95     // Initialise instance of connector router.
96     router = new Avoid::Router();
97     // Don't use the Consolidate moves optimisation.
98     router->ConsolidateMoves = false;
100     perspectives = NULL;
102     /* Create an initial perspective, make it current and append it to the list of existing perspectives */
103     current_perspective = new Box3D::Perspective3D (
104                               // VP in x-direction
105                               Box3D::VanishingPoint( NR::Point(-50.0, 600.0),
106                                                      NR::Point( -1.0,   0.0), Box3D::VP_FINITE),
107                               // VP in y-direction
108                               Box3D::VanishingPoint( NR::Point(500.0,1000.0),
109                                                      NR::Point(  0.0,   1.0), Box3D::VP_INFINITE),
110                               // VP in z-direction
111                               Box3D::VanishingPoint( NR::Point(700.0, 600.0),
112                                                      NR::Point(sqrt(3.0),1.0), Box3D::VP_FINITE),
113                               this);
115     add_perspective (current_perspective);    
117     p = new SPDocumentPrivate();
119     p->serial = next_serial++;
121     p->iddef = g_hash_table_new(g_direct_hash, g_direct_equal);
122     p->reprdef = g_hash_table_new(g_direct_hash, g_direct_equal);
124     p->resources = g_hash_table_new(g_str_hash, g_str_equal);
126     p->sensitive = FALSE;
127     p->partial = NULL;
128     p->history_size = 0;
129     p->undo = NULL;
130     p->redo = NULL;
131     p->seeking = false;
133     priv = p;
135     // XXX only for testing!
136     priv->undoStackObservers.add(p->console_output_undo_observer);
139 SPDocument::~SPDocument() {
140     collectOrphans();
142     if (priv) {
143         if (priv->partial) {
144             sp_repr_free_log(priv->partial);
145             priv->partial = NULL;
146         }
148         sp_document_clear_redo(this);
149         sp_document_clear_undo(this);
151         if (root) {
152             root->releaseReferences();
153             sp_object_unref(root);
154             root = NULL;
155         }
157         if (priv->iddef) g_hash_table_destroy(priv->iddef);
158         if (priv->reprdef) g_hash_table_destroy(priv->reprdef);
160         if (rdoc) Inkscape::GC::release(rdoc);
162         /* Free resources */
163         g_hash_table_foreach_remove(priv->resources, sp_document_resource_list_free, this);
164         g_hash_table_destroy(priv->resources);
166         delete priv;
167         priv = NULL;
168     }
170     cr_cascade_unref(style_cascade);
171     style_cascade = NULL;
173     if (name) {
174         g_free(name);
175         name = NULL;
176     }
177     if (base) {
178         g_free(base);
179         base = NULL;
180     }
181     if (uri) {
182         g_free(uri);
183         uri = NULL;
184     }
186     if (modified_id) {
187         gtk_idle_remove(modified_id);
188         modified_id = 0;
189     }
191     _selection_changed_connection.disconnect();
192     _desktop_activated_connection.disconnect();
194     if (keepalive) {
195         inkscape_unref();
196         keepalive = FALSE;
197     }
199     if (router) {
200         delete router;
201         router = NULL;
202     }
204     //delete this->_whiteboard_session_manager;
206     current_perspective = NULL;
207     // TODO: Do we have to delete the perspectives?
208     /***
209     for (GSList *i = perspectives; i != NULL; ++i) {
210         delete ((Box3D::Perspective3D *) i->data);
211     }
212     g_slist_free (perspectives);
213     ***/
216 void SPDocument::add_perspective (Box3D::Perspective3D * const persp)
218     // FIXME: Should we handle the case that the perspectives have equal VPs but are not identical?
219     //        If so, we need to take care of relinking the boxes, etc.
220     if (persp == NULL || g_slist_find (perspectives, persp)) return;
221     perspectives = g_slist_prepend (perspectives, persp);
224 void SPDocument::remove_perspective (Box3D::Perspective3D * const persp)
226     if (persp == NULL || !g_slist_find (perspectives, persp)) return;
227     perspectives = g_slist_remove (perspectives, persp);
230 // find an existing perspective whose VPs are equal to those of persp
231 Box3D::Perspective3D * SPDocument::find_perspective (const Box3D::Perspective3D * persp)
233     for (GSList *p = perspectives; p != NULL; p = p->next) {
234         if (*((Box3D::Perspective3D *) p->data) == *persp) {
235             return ((Box3D::Perspective3D *) p->data);
236         }
237     }
238     return NULL; // perspective was not found
241 Box3D::Perspective3D * SPDocument::get_persp_of_box (const SP3DBox *box)
243     for (GSList *p = perspectives; p != NULL; p = p->next) {
244         if (((Box3D::Perspective3D *) p->data)->has_box (box))
245             return (Box3D::Perspective3D *) p->data;
246     }
247     g_warning ("Stray 3D box!\n");
248     g_assert_not_reached();
251 Box3D::Perspective3D * SPDocument::get_persp_of_VP (const Box3D::VanishingPoint *vp)
253     Box3D::Perspective3D *persp;
254     for (GSList *p = perspectives; p != NULL; p = p->next) {
255         persp = (Box3D::Perspective3D *) p->data;
256         // we compare the pointers, not the position/state of the VPs; is this correct?
257         if (persp->get_vanishing_point (Box3D::X) == vp ||
258             persp->get_vanishing_point (Box3D::Y) == vp ||
259             persp->get_vanishing_point (Box3D::Z) == vp)
260             return persp;
261     }
263     g_warning ("Stray vanishing point!\n");
264     g_assert_not_reached();
267 unsigned long SPDocument::serial() const {
268     return priv->serial;
271 void SPDocument::queueForOrphanCollection(SPObject *object) {
272     g_return_if_fail(object != NULL);
273     g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
275     sp_object_ref(object, NULL);
276     _collection_queue = g_slist_prepend(_collection_queue, object);
279 void SPDocument::collectOrphans() {
280     while (_collection_queue) {
281         GSList *objects=_collection_queue;
282         _collection_queue = NULL;
283         for ( GSList *iter=objects ; iter ; iter = iter->next ) {
284             SPObject *object=reinterpret_cast<SPObject *>(iter->data);
285             object->collectOrphan();
286             sp_object_unref(object, NULL);
287         }
288         g_slist_free(objects);
289     }
292 void SPDocument::reset_key (void *dummy)
294     actionkey = NULL;
297 SPDocument *
298 sp_document_create(Inkscape::XML::Document *rdoc,
299                    gchar const *uri,
300                    gchar const *base,
301                    gchar const *name,
302                    unsigned int keepalive)
304     SPDocument *document;
305     Inkscape::XML::Node *rroot;
306     Inkscape::Version sodipodi_version;
308     rroot = rdoc->root();
310     document = new SPDocument();
312     document->keepalive = keepalive;
314     document->rdoc = rdoc;
315     document->rroot = rroot;
317 #ifndef WIN32
318     prepend_current_dir_if_relative(&(document->uri), uri);
319 #else
320     // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
321     document->uri = uri? g_strdup(uri) : NULL;
322 #endif
324     // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
325     // which is why we use g_get_current_dir() in calculating the abs path above
326     //This is NULL for a new document
327     if (base)
328         document->base = g_strdup(base);
329     else
330         document->base = NULL;
331     document->name = g_strdup(name);
333     document->root = sp_object_repr_build_tree(document, rroot);
335     sodipodi_version = SP_ROOT(document->root)->version.sodipodi;
337     /* fixme: Not sure about this, but lets assume ::build updates */
338     rroot->setAttribute("sodipodi:version", SODIPODI_VERSION);
339     rroot->setAttribute("inkscape:version", INKSCAPE_VERSION);
340     /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
342     /* Quick hack 2 - get default image size into document */
343     if (!rroot->attribute("width")) rroot->setAttribute("width", A4_WIDTH_STR);
344     if (!rroot->attribute("height")) rroot->setAttribute("height", A4_HEIGHT_STR);
345     /* End of quick hack 2 */
347     /* Quick hack 3 - Set uri attributes */
348     if (uri) {
349         rroot->setAttribute("sodipodi:docname", uri);
350     }
351     /* End of quick hack 3 */
353     // creating namedview
354     if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
355         // if there's none in the document already,
356         Inkscape::XML::Node *r = NULL;
357         Inkscape::XML::Node *rnew = NULL;
358         r = inkscape_get_repr(INKSCAPE, "template.base");
359         // see if there's a template with id="base" in the preferences
360         if (!r) {
361             // if there's none, create an empty element
362             rnew = rdoc->createElement("sodipodi:namedview");
363             rnew->setAttribute("id", "base");
364         } else {
365             // otherwise, take from preferences
366             rnew = r->duplicate(rroot->document());
367         }
368         // insert into the document
369         rroot->addChild(rnew, NULL);
370         // clean up
371         Inkscape::GC::release(rnew);
372     }
374     /* Defs */
375     if (!SP_ROOT(document->root)->defs) {
376         Inkscape::XML::Node *r;
377         r = rdoc->createElement("svg:defs");
378         rroot->addChild(r, NULL);
379         Inkscape::GC::release(r);
380         g_assert(SP_ROOT(document->root)->defs);
381     }
383     /* Default RDF */
384     rdf_set_defaults( document );
386     if (keepalive) {
387         inkscape_ref();
388     }
390     sp_document_set_undo_sensitive(document, true);
392     // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
393     if (!Inkscape::NSApplication::Application::getNewGui()) {
394         g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
395                          G_CALLBACK(sp_document_reset_key), document);
396         g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
397                          G_CALLBACK(sp_document_reset_key), document);
398     } else {
399         document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
400         document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
401     }
403     return document;
406 /**
407  * Fetches document from URI, or creates new, if NULL; public document
408  * appears in document list.
409  */
410 SPDocument *
411 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
413     SPDocument *doc;
414     Inkscape::XML::Document *rdoc;
415     gchar *base = NULL;
416     gchar *name = NULL;
418     if (uri) {
419         Inkscape::XML::Node *rroot;
420         gchar *s, *p;
421         /* Try to fetch repr from file */
422         rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
423         /* If file cannot be loaded, return NULL without warning */
424         if (rdoc == NULL) return NULL;
425         rroot = rdoc->root();
426         /* If xml file is not svg, return NULL without warning */
427         /* fixme: destroy document */
428         if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
429         s = g_strdup(uri);
430         p = strrchr(s, '/');
431         if (p) {
432             name = g_strdup(p + 1);
433             p[1] = '\0';
434             base = g_strdup(s);
435         } else {
436             base = NULL;
437             name = g_strdup(uri);
438         }
439         g_free(s);
440     } else {
441         rdoc = sp_repr_document_new("svg:svg");
442     }
444     if (make_new) {
445         base = NULL;
446         uri = NULL;
447         name = g_strdup_printf(_("New document %d"), ++doc_count);
448     }
450     //# These should be set by now
451     g_assert(name);
453     doc = sp_document_create(rdoc, uri, base, name, keepalive);
455     g_free(base);
456     g_free(name);
458     return doc;
461 SPDocument *
462 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
464     SPDocument *doc;
465     Inkscape::XML::Document *rdoc;
466     Inkscape::XML::Node *rroot;
467     gchar *name;
469     rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
471     /* If it cannot be loaded, return NULL without warning */
472     if (rdoc == NULL) return NULL;
474     rroot = rdoc->root();
475     /* If xml file is not svg, return NULL without warning */
476     /* fixme: destroy document */
477     if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
479     name = g_strdup_printf(_("Memory document %d"), ++doc_count);
481     doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
483     return doc;
486 SPDocument *
487 sp_document_ref(SPDocument *doc)
489     g_return_val_if_fail(doc != NULL, NULL);
490     Inkscape::GC::anchor(doc);
491     return doc;
494 SPDocument *
495 sp_document_unref(SPDocument *doc)
497     g_return_val_if_fail(doc != NULL, NULL);
498     Inkscape::GC::release(doc);
499     return NULL;
502 gdouble sp_document_width(SPDocument *document)
504     g_return_val_if_fail(document != NULL, 0.0);
505     g_return_val_if_fail(document->priv != NULL, 0.0);
506     g_return_val_if_fail(document->root != NULL, 0.0);
508     return SP_ROOT(document->root)->width.computed;
511 void
512 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
514     SPRoot *root = SP_ROOT(document->root);
516     if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
517         root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
518     } else { // set to width=
519         root->width.computed = sp_units_get_pixels (width, *unit);
520         /* SVG does not support meters as a unit, so we must translate meters to
521          * cm when writing */
522         if (!strcmp(unit->abbr, "m")) {
523             root->width.value = 100*width;
524             root->width.unit = SVGLength::CM;
525         } else {
526             root->width.value = width;
527             root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
528         }
529     }
531     SP_OBJECT (root)->updateRepr();
534 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
536     SPRoot *root = SP_ROOT(document->root);
538     if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
539         root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
540     } else { // set to height=
541         root->height.computed = sp_units_get_pixels (height, *unit);
542         /* SVG does not support meters as a unit, so we must translate meters to
543          * cm when writing */
544         if (!strcmp(unit->abbr, "m")) {
545             root->height.value = 100*height;
546             root->height.unit = SVGLength::CM;
547         } else {
548             root->height.value = height;
549             root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
550         }
551     }
553     SP_OBJECT (root)->updateRepr();
556 gdouble sp_document_height(SPDocument *document)
558     g_return_val_if_fail(document != NULL, 0.0);
559     g_return_val_if_fail(document->priv != NULL, 0.0);
560     g_return_val_if_fail(document->root != NULL, 0.0);
562     return SP_ROOT(document->root)->height.computed;
565 /**
566  * Given an NR::Rect that may, for example, correspond to the bbox of an object,
567  * this function fits the canvas to that rect by resizing the canvas
568  * and translating the document root into position.
569  */
570 void SPDocument::fitToRect(NR::Rect const &rect)
572     g_return_if_fail(!rect.isEmpty());
574     using NR::X; using NR::Y;
575     double const w = rect.extent(X);
576     double const h = rect.extent(Y);
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     NR::translate const tr(NR::Point(0, (old_height - h))
584                            - rect.min());
585     SP_GROUP(root)->translateChildItems(tr);
588 void sp_document_set_uri(SPDocument *document, gchar const *uri)
590     g_return_if_fail(document != NULL);
592     if (document->name) {
593         g_free(document->name);
594         document->name = NULL;
595     }
596     if (document->base) {
597         g_free(document->base);
598         document->base = NULL;
599     }
600     if (document->uri) {
601         g_free(document->uri);
602         document->uri = NULL;
603     }
605     if (uri) {
607 #ifndef WIN32
608         prepend_current_dir_if_relative(&(document->uri), uri);
609 #else
610         // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
611         document->uri = g_strdup(uri);
612 #endif
614         /* fixme: Think, what this means for images (Lauris) */
615         document->base = g_path_get_dirname(document->uri);
616         document->name = g_path_get_basename(document->uri);
618     } else {
619         document->uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
620         document->base = NULL;
621         document->name = g_strdup(document->uri);
622     }
624     // Update saveable repr attributes.
625     Inkscape::XML::Node *repr = sp_document_repr_root(document);
626     // changing uri in the document repr must not be not undoable
627     bool saved = sp_document_get_undo_sensitive(document);
628     sp_document_set_undo_sensitive(document, false);
630     repr->setAttribute("sodipodi:docname", document->name);
631     sp_document_set_undo_sensitive(document, saved);
633     document->priv->uri_set_signal.emit(document->uri);
636 void
637 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
639     g_return_if_fail(doc != NULL);
641     doc->priv->resized_signal.emit(width, height);
644 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
646     return priv->modified_signal.connect(slot);
649 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
651     return priv->uri_set_signal.connect(slot);
654 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
656     return priv->resized_signal.connect(slot);
659 sigc::connection
660 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
662     return priv->_reconstruction_start_signal.connect(slot);
665 void
666 SPDocument::emitReconstructionStart(void)
668     // printf("Starting Reconstruction\n");
669     priv->_reconstruction_start_signal.emit();
670     return;
673 sigc::connection
674 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type  slot)
676     return priv->_reconstruction_finish_signal.connect(slot);
679 void
680 SPDocument::emitReconstructionFinish(void)
682     // printf("Finishing Reconstruction\n");
683     priv->_reconstruction_finish_signal.emit();
684     return;
687 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
689     return priv->commit_signal.connect(slot);
694 void SPDocument::_emitModified() {
695     static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
696     root->emitModified(0);
697     priv->modified_signal.emit(flags);
700 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
701     GQuark idq = g_quark_from_string(id);
703     if (object) {
704         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
705         g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
706     } else {
707         g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
708         g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
709     }
711     SPDocumentPrivate::IDChangedSignalMap::iterator pos;
713     pos = priv->id_changed_signals.find(idq);
714     if ( pos != priv->id_changed_signals.end() ) {
715         if (!(*pos).second.empty()) {
716             (*pos).second.emit(object);
717         } else { // discard unused signal
718             priv->id_changed_signals.erase(pos);
719         }
720     }
723 void
724 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
726         this->priv->undoStackObservers.add(observer);
729 void
730 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
732         this->priv->undoStackObservers.remove(observer);
735 SPObject *SPDocument::getObjectById(gchar const *id) {
736     g_return_val_if_fail(id != NULL, NULL);
738     GQuark idq = g_quark_from_string(id);
739     return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
742 sigc::connection SPDocument::connectIdChanged(gchar const *id,
743                                               SPDocument::IDChangedSignal::slot_type slot)
745     return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
748 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
749     if (object) {
750         g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
751         g_hash_table_insert(priv->reprdef, repr, object);
752     } else {
753         g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
754         g_hash_table_remove(priv->reprdef, repr);
755     }
758 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
759     g_return_val_if_fail(repr != NULL, NULL);
760     return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
763 Glib::ustring SPDocument::getLanguage() {
764     gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
765     if (document_language) {
766         while (isspace(*document_language))
767             document_language++;
768     }
769     if ( !document_language || 0 == *document_language) {
770         // retrieve system language
771         document_language = getenv("LC_ALL");
772         if ( NULL == document_language || *document_language == 0 ) {
773             document_language = getenv ("LC_MESSAGES");
774         }
775         if ( NULL == document_language || *document_language == 0 ) {
776             document_language = getenv ("LANG");
777         }
778         
779         if ( NULL != document_language ) {
780             gchar *pos = strchr(document_language, '_');
781             if ( NULL != pos ) {
782                 return Glib::ustring(document_language, pos - document_language);
783             }
784         }
785     }
787     if ( NULL == document_language )
788         return Glib::ustring();
789     return document_language;
792 /* Object modification root handler */
794 void
795 sp_document_request_modified(SPDocument *doc)
797     if (!doc->modified_id) {
798         doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
799     }
802 void
803 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
805     ctx->ctx.flags = 0;
806     ctx->i2doc = NR::identity();
807     /* Set up viewport in case svg has it defined as percentages */
808     if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
809         ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
810         ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
811         ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
812         ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
813     } else { // as a last resort, set size to A4
814         ctx->vp.x0 = 0.0;
815         ctx->vp.y0 = 0.0;
816         ctx->vp.x1 = 210 * PX_PER_MM;
817         ctx->vp.y1 = 297 * PX_PER_MM;
818     }
819     ctx->i2vp = NR::identity();
822 /**
823  * Tries to update the document state based on the modified and 
824  * "update required" flags, and return true if the document has
825  * been brought fully up to date.
826  */
827 bool
828 SPDocument::_updateDocument()
830     /* Process updates */
831     if (this->root->uflags || this->root->mflags) {
832         if (this->root->uflags) {
833             SPItemCtx ctx;
834             sp_document_setup_viewport (this, &ctx);
836             bool saved = sp_document_get_undo_sensitive(this);
837             sp_document_set_undo_sensitive(this, false);
839             this->root->updateDisplay((SPCtx *)&ctx, 0);
841             sp_document_set_undo_sensitive(this, saved);
842         }
843         this->_emitModified();
844     }
846     return !(this->root->uflags || this->root->mflags);
850 /**
851  * Repeatedly works on getting the document updated, since sometimes
852  * it takes more than one pass to get the document updated.  But it
853  * usually should not take more than a few loops, and certainly never
854  * more than 32 iterations.  So we bail out if we hit 32 iterations,
855  * since this typically indicates we're stuck in an update loop.
856  */
857 gint
858 sp_document_ensure_up_to_date(SPDocument *doc)
860     int counter = 32;
861     while (!doc->_updateDocument()) {
862         if (counter == 0) {
863             g_warning("More than 32 iteration while updating document '%s'", doc->uri);
864             break;
865         }
866         counter--;
867     }
869     if (doc->modified_id) {
870         /* Remove handler */
871         gtk_idle_remove(doc->modified_id);
872         doc->modified_id = 0;
873     }
874     return counter>0;
877 /**
878  * An idle handler to update the document.  Returns true if
879  * the document needs further updates.
880  */
881 static gint
882 sp_document_idle_handler(gpointer data)
884     SPDocument *doc = static_cast<SPDocument *>(data);
885     if (doc->_updateDocument()) {
886         doc->modified_id = 0;
887         return false;
888     } else {
889         return true;
890     }
893 static bool is_within(NR::Rect const &area, NR::Rect const &box)
895     return area.contains(box);
898 static bool overlaps(NR::Rect const &area, NR::Rect const &box)
900     return area.intersects(box);
903 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, NR::Rect const &area,
904                                   bool (*test)(NR::Rect const &, NR::Rect const &), bool take_insensitive = false)
906     g_return_val_if_fail(SP_IS_GROUP(group), s);
908     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
909         if (!SP_IS_ITEM(o)) {
910             continue;
911         }
912         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
913             s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
914         } else {
915             SPItem *child = SP_ITEM(o);
916             NR::Maybe<NR::Rect> box = sp_item_bbox_desktop(child);
917             if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
918                 s = g_slist_append(s, child);
919             }
920         }
921     }
923     return s;
926 /**
927 Returns true if an item is among the descendants of group (recursively).
928  */
929 bool item_is_in_group(SPItem *item, SPGroup *group)
931     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
932         if (!SP_IS_ITEM(o)) continue;
933         if (SP_ITEM(o) == item)
934             return true;
935         if (SP_IS_GROUP(o))
936             if (item_is_in_group(item, SP_GROUP(o)))
937                 return true;
938     }
939     return false;
942 /**
943 Returns the bottommost item from the list which is at the point, or NULL if none.
944 */
945 SPItem*
946 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
947                                            NR::Point const p, bool take_insensitive)
949     g_return_val_if_fail(group, NULL);
951     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
953     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
955         if (!SP_IS_ITEM(o)) continue;
957         SPItem *item = SP_ITEM(o);
958         NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
959         if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
960             && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
961             if (g_slist_find((GSList *) list, item) != NULL)
962                 return item;
963         }
965         if (SP_IS_GROUP(o)) {
966             SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
967             if (found)
968                 return found;
969         }
971     }
972     return NULL;
975 /**
976 Returns the topmost (in z-order) item from the descendants of group (recursively) which
977 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
978 non-layer groups or not. Honors take_insensitive on whether to return insensitive
979 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
980 upwards in z-order and returns what it has found so far (i.e. the found item is
981 guaranteed to be lower than upto).
982  */
983 SPItem*
984 find_item_at_point(unsigned int dkey, SPGroup *group, NR::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
986     SPItem *seen = NULL, *newseen = NULL;
988     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
990     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
991         if (!SP_IS_ITEM(o)) continue;
993         if (upto && SP_ITEM(o) == upto)
994             break;
996         if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
997             // if nothing found yet, recurse into the group
998             newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
999             if (newseen) {
1000                 seen = newseen;
1001                 newseen = NULL;
1002             }
1004             if (item_is_in_group(upto, SP_GROUP(o)))
1005                 break;
1007         } else {
1008             SPItem *child = SP_ITEM(o);
1009             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1011             // seen remembers the last (topmost) of items pickable at this point
1012             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1013                 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1014                 seen = child;
1015             }
1016         }
1017     }
1018     return seen;
1021 /**
1022 Returns the topmost non-layer group from the descendants of group which is at point
1023 p, or NULL if none. Recurses into layers but not into groups.
1024  */
1025 SPItem*
1026 find_group_at_point(unsigned int dkey, SPGroup *group, NR::Point const p)
1028     SPItem *seen = NULL;
1030     gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
1032     for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1033         if (!SP_IS_ITEM(o)) continue;
1034         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1035             SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1036             if (newseen) {
1037                 seen = newseen;
1038             }
1039         }
1040         if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1041             SPItem *child = SP_ITEM(o);
1042             NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1044             // seen remembers the last (topmost) of groups pickable at this point
1045             if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1046                 seen = child;
1047             }
1048         }
1049     }
1050     return seen;
1053 /*
1054  * Return list of items, contained in box
1055  *
1056  * Assumes box is normalized (and g_asserts it!)
1057  *
1058  */
1060 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
1062     g_return_val_if_fail(document != NULL, NULL);
1063     g_return_val_if_fail(document->priv != NULL, NULL);
1065     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
1068 /*
1069  * Return list of items, that the parts of the item contained in box
1070  *
1071  * Assumes box is normalized (and g_asserts it!)
1072  *
1073  */
1075 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
1077     g_return_val_if_fail(document != NULL, NULL);
1078     g_return_val_if_fail(document->priv != NULL, NULL);
1080     return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1083 GSList *
1084 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<NR::Point> points)
1086     GSList *items = NULL;
1088     // When picking along the path, we don't want small objects close together 
1089     // (such as hatching strokes) to obscure each other by their deltas, 
1090     // so we temporarily set delta to a small value
1091     gdouble saved_delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
1092     prefs_set_double_attribute ("options.cursortolerance", "value", 0.25);
1094     for(unsigned int i = 0; i < points.size(); i++) {
1095         SPItem *item = sp_document_item_at_point(document, key, points[i],
1096                                          false, NULL);
1097         if (item && !g_slist_find(items, item))
1098             items = g_slist_prepend (items, item);
1099     }
1101     // and now we restore it back
1102     prefs_set_double_attribute ("options.cursortolerance", "value", saved_delta);
1104     return items;
1107 SPItem *
1108 sp_document_item_at_point(SPDocument *document, unsigned const key, NR::Point const p,
1109                           gboolean const into_groups, SPItem *upto)
1111     g_return_val_if_fail(document != NULL, NULL);
1112     g_return_val_if_fail(document->priv != NULL, NULL);
1114     return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1117 SPItem*
1118 sp_document_group_at_point(SPDocument *document, unsigned int key, NR::Point const p)
1120     g_return_val_if_fail(document != NULL, NULL);
1121     g_return_val_if_fail(document->priv != NULL, NULL);
1123     return find_group_at_point(key, SP_GROUP(document->root), p);
1127 /* Resource management */
1129 gboolean
1130 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1132     GSList *rlist;
1133     GQuark q = g_quark_from_string(key);
1135     g_return_val_if_fail(document != NULL, FALSE);
1136     g_return_val_if_fail(key != NULL, FALSE);
1137     g_return_val_if_fail(*key != '\0', FALSE);
1138     g_return_val_if_fail(object != NULL, FALSE);
1139     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1141     if (SP_OBJECT_IS_CLONED(object))
1142         return FALSE;
1144     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1145     g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1146     rlist = g_slist_prepend(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 gboolean
1155 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1157     GSList *rlist;
1158     GQuark q = g_quark_from_string(key);
1160     g_return_val_if_fail(document != NULL, FALSE);
1161     g_return_val_if_fail(key != NULL, FALSE);
1162     g_return_val_if_fail(*key != '\0', FALSE);
1163     g_return_val_if_fail(object != NULL, FALSE);
1164     g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1166     if (SP_OBJECT_IS_CLONED(object))
1167         return FALSE;
1169     rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1170     g_return_val_if_fail(rlist != NULL, FALSE);
1171     g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1172     rlist = g_slist_remove(rlist, object);
1173     g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1175     document->priv->resources_changed_signals[q].emit();
1177     return TRUE;
1180 GSList const *
1181 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1183     g_return_val_if_fail(document != NULL, NULL);
1184     g_return_val_if_fail(key != NULL, NULL);
1185     g_return_val_if_fail(*key != '\0', NULL);
1187     return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1190 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1191                                                        gchar const *key,
1192                                                        SPDocument::ResourcesChangedSignal::slot_type slot)
1194     GQuark q = g_quark_from_string(key);
1195     return document->priv->resources_changed_signals[q].connect(slot);
1198 /* Helpers */
1200 gboolean
1201 sp_document_resource_list_free(gpointer key, gpointer value, gpointer data)
1203     g_slist_free((GSList *) value);
1204     return TRUE;
1207 unsigned int
1208 count_objects_recursive(SPObject *obj, unsigned int count)
1210     count++; // obj itself
1212     for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1213         count = count_objects_recursive(i, count);
1214     }
1216     return count;
1219 unsigned int
1220 objects_in_document(SPDocument *document)
1222     return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1225 void
1226 vacuum_document_recursive(SPObject *obj)
1228     if (SP_IS_DEFS(obj)) {
1229         for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1230             /* fixme: some inkscape-internal nodes in the future might not be collectable */
1231             def->requestOrphanCollection();
1232         }
1233     } else {
1234         for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1235             vacuum_document_recursive(i);
1236         }
1237     }
1240 unsigned int
1241 vacuum_document(SPDocument *document)
1243     unsigned int start = objects_in_document(document);
1244     unsigned int end;
1245     unsigned int newend = start;
1247     unsigned int iterations = 0;
1249     do {
1250         end = newend;
1252         vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1253         document->collectOrphans();
1254         iterations++;
1256         newend = objects_in_document(document);
1258     } while (iterations < 100 && newend < end);
1260     return start - newend;
1263 bool SPDocument::isSeeking() const {
1264     return priv->seeking;
1268 /*
1269   Local Variables:
1270   mode:c++
1271   c-file-style:"stroustrup"
1272   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1273   indent-tabs-mode:nil
1274   fill-column:99
1275   End:
1276 */
1277 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :