1 #define __SP_DOCUMENT_C__
3 /** \file
4 * SPDocument manipulation
5 *
6 * Authors:
7 * Lauris Kaplinski <lauris@kaplinski.com>
8 * MenTaLguY <mental@rydia.net>
9 * bulia byak <buliabyak@users.sf.net>
10 *
11 * Copyright (C) 2004-2005 MenTaLguY
12 * Copyright (C) 1999-2002 Lauris Kaplinski
13 * Copyright (C) 2000-2001 Ximian, Inc.
14 *
15 * Released under GNU GPL, read the file 'COPYING' for more information
16 */
18 /** \class SPDocument
19 * SPDocument serves as the container of both model trees (agnostic XML
20 * and typed object tree), and implements all of the document-level
21 * functionality used by the program. Many document level operations, like
22 * load, save, print, export and so on, use SPDocument as their basic datatype.
23 *
24 * SPDocument implements undo and redo stacks and an id-based object
25 * dictionary. Thanks to unique id attributes, the latter can be used to
26 * map from the XML tree back to the object tree.
27 *
28 * SPDocument performs the basic operations needed for asynchronous
29 * update notification (SPObject ::modified virtual method), and implements
30 * the 'modified' signal, as well.
31 */
34 #define noSP_DOCUMENT_DEBUG_IDLE
35 #define noSP_DOCUMENT_DEBUG_UNDO
37 #ifdef HAVE_CONFIG_H
38 # include "config.h"
39 #endif
40 #include <gtk/gtkmain.h>
41 #include <string>
42 #include <cstring>
43 #include "application/application.h"
44 #include "application/editor.h"
45 #include "xml/repr.h"
46 #include "helper/units.h"
47 #include "inkscape-private.h"
48 #include "inkscape-version.h"
49 #include "sp-object-repr.h"
50 #include "sp-namedview.h"
51 #include "desktop.h"
52 #include "document-private.h"
53 #include "dir-util.h"
54 #include "unit-constants.h"
55 #include "preferences.h"
56 #include "libavoid/router.h"
57 #include "sp-item-group.h"
58 #include "profile-manager.h"
59 #include "persp3d.h"
61 #include "display/nr-arena-item.h"
63 #include "dialogs/rdf.h"
65 #include "transf_mat_3x4.h"
67 #define SP_DOCUMENT_UPDATE_PRIORITY (G_PRIORITY_HIGH_IDLE - 1)
70 static gint sp_document_idle_handler(gpointer data);
72 gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data);
74 static gint doc_count = 0;
76 static unsigned long next_serial = 0;
78 SPDocument::SPDocument() :
79 keepalive(FALSE),
80 virgin(TRUE),
81 modified_since_save(FALSE),
82 rdoc(0),
83 rroot(0),
84 root(0),
85 style_cascade(cr_cascade_new(NULL, NULL, NULL)),
86 uri(0),
87 base(0),
88 name(0),
89 priv(0), // reset in ctor
90 actionkey(0),
91 modified_id(0),
92 profileManager(0), // deferred until after other initialization
93 router(new Avoid::Router()),
94 perspectives(0),
95 current_persp3d(0),
96 _collection_queue(0),
97 oldSignalsConnected(false)
98 {
99 // Don't use the Consolidate moves optimisation.
100 router->ConsolidateMoves = false;
102 SPDocumentPrivate *p = new SPDocumentPrivate();
104 p->serial = next_serial++;
106 p->iddef = g_hash_table_new(g_direct_hash, g_direct_equal);
107 p->reprdef = g_hash_table_new(g_direct_hash, g_direct_equal);
109 p->resources = g_hash_table_new(g_str_hash, g_str_equal);
111 p->sensitive = FALSE;
112 p->partial = NULL;
113 p->history_size = 0;
114 p->undo = NULL;
115 p->redo = NULL;
116 p->seeking = false;
118 priv = p;
120 // Once things are set, hook in the manager
121 profileManager = new Inkscape::ProfileManager(this);
123 // XXX only for testing!
124 priv->undoStackObservers.add(p->console_output_undo_observer);
125 }
127 SPDocument::~SPDocument() {
128 collectOrphans();
130 // kill/unhook this first
131 if ( profileManager ) {
132 delete profileManager;
133 profileManager = 0;
134 }
136 if (priv) {
137 if (priv->partial) {
138 sp_repr_free_log(priv->partial);
139 priv->partial = NULL;
140 }
142 sp_document_clear_redo(this);
143 sp_document_clear_undo(this);
145 if (root) {
146 root->releaseReferences();
147 sp_object_unref(root);
148 root = NULL;
149 }
151 if (priv->iddef) g_hash_table_destroy(priv->iddef);
152 if (priv->reprdef) g_hash_table_destroy(priv->reprdef);
154 if (rdoc) Inkscape::GC::release(rdoc);
156 /* Free resources */
157 g_hash_table_foreach_remove(priv->resources, sp_document_resource_list_free, this);
158 g_hash_table_destroy(priv->resources);
160 delete priv;
161 priv = NULL;
162 }
164 cr_cascade_unref(style_cascade);
165 style_cascade = NULL;
167 if (name) {
168 g_free(name);
169 name = NULL;
170 }
171 if (base) {
172 g_free(base);
173 base = NULL;
174 }
175 if (uri) {
176 g_free(uri);
177 uri = NULL;
178 }
180 if (modified_id) {
181 gtk_idle_remove(modified_id);
182 modified_id = 0;
183 }
185 if (oldSignalsConnected) {
186 g_signal_handlers_disconnect_by_func(G_OBJECT(INKSCAPE),
187 reinterpret_cast<gpointer>(sp_document_reset_key),
188 static_cast<gpointer>(this));
189 } else {
190 _selection_changed_connection.disconnect();
191 _desktop_activated_connection.disconnect();
192 }
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 }
208 void SPDocument::add_persp3d (Persp3D * const /*persp*/)
209 {
210 SPDefs *defs = SP_ROOT(this->root)->defs;
211 for (SPObject *i = sp_object_first_child(SP_OBJECT(defs)); i != NULL; i = SP_OBJECT_NEXT(i) ) {
212 if (SP_IS_PERSP3D(i)) {
213 g_print ("Encountered a Persp3D in defs\n");
214 }
215 }
217 g_print ("Adding Persp3D to defs\n");
218 persp3d_create_xml_element (this);
219 }
221 void SPDocument::remove_persp3d (Persp3D * const /*persp*/)
222 {
223 // TODO: Delete the repr, maybe perform a check if any boxes are still linked to the perspective.
224 // Anything else?
225 g_print ("Please implement deletion of perspectives here.\n");
226 }
228 unsigned long SPDocument::serial() const {
229 return priv->serial;
230 }
232 void SPDocument::queueForOrphanCollection(SPObject *object) {
233 g_return_if_fail(object != NULL);
234 g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
236 sp_object_ref(object, NULL);
237 _collection_queue = g_slist_prepend(_collection_queue, object);
238 }
240 void SPDocument::collectOrphans() {
241 while (_collection_queue) {
242 GSList *objects=_collection_queue;
243 _collection_queue = NULL;
244 for ( GSList *iter=objects ; iter ; iter = iter->next ) {
245 SPObject *object=reinterpret_cast<SPObject *>(iter->data);
246 object->collectOrphan();
247 sp_object_unref(object, NULL);
248 }
249 g_slist_free(objects);
250 }
251 }
253 void SPDocument::reset_key (void */*dummy*/)
254 {
255 actionkey = NULL;
256 }
258 SPDocument *
259 sp_document_create(Inkscape::XML::Document *rdoc,
260 gchar const *uri,
261 gchar const *base,
262 gchar const *name,
263 unsigned int keepalive)
264 {
265 SPDocument *document;
266 Inkscape::XML::Node *rroot;
267 Inkscape::Version sodipodi_version;
268 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
270 rroot = rdoc->root();
272 document = new SPDocument();
274 document->keepalive = keepalive;
276 document->rdoc = rdoc;
277 document->rroot = rroot;
279 #ifndef WIN32
280 prepend_current_dir_if_relative(&(document->uri), uri);
281 #else
282 // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
283 document->uri = uri? g_strdup(uri) : NULL;
284 #endif
286 // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
287 // which is why we use g_get_current_dir() in calculating the abs path above
288 //This is NULL for a new document
289 if (base)
290 document->base = g_strdup(base);
291 else
292 document->base = NULL;
293 document->name = g_strdup(name);
295 document->root = sp_object_repr_build_tree(document, rroot);
297 sodipodi_version = SP_ROOT(document->root)->version.sodipodi;
299 /* fixme: Not sure about this, but lets assume ::build updates */
300 rroot->setAttribute("sodipodi:version", SODIPODI_VERSION);
301 rroot->setAttribute("inkscape:version", Inkscape::version_string);
302 /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
304 /* Quick hack 2 - get default image size into document */
305 if (!rroot->attribute("width")) rroot->setAttribute("width", "100%");
306 if (!rroot->attribute("height")) rroot->setAttribute("height", "100%");
307 /* End of quick hack 2 */
309 /* Quick hack 3 - Set uri attributes */
310 if (uri) {
311 rroot->setAttribute("sodipodi:docname", uri);
312 }
313 /* End of quick hack 3 */
315 /* Eliminate obsolete sodipodi:docbase, for privacy reasons */
316 rroot->setAttribute("sodipodi:docbase", NULL);
318 /* Eliminate any claim to adhere to a profile, as we don't try to */
319 rroot->setAttribute("baseProfile", NULL);
321 // creating namedview
322 if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
323 // if there's none in the document already,
324 Inkscape::XML::Node *rnew = NULL;
326 rnew = rdoc->createElement("sodipodi:namedview");
327 //rnew->setAttribute("id", "base");
329 // Add namedview data from the preferences
330 // we can't use getAllEntries because this could produce non-SVG doubles
331 Glib::ustring pagecolor = prefs->getString("/template/base/pagecolor");
332 if (!pagecolor.empty()) {
333 rnew->setAttribute("pagecolor", pagecolor.data());
334 }
335 Glib::ustring bordercolor = prefs->getString("/template/base/bordercolor");
336 if (!bordercolor.empty()) {
337 rnew->setAttribute("bordercolor", bordercolor.data());
338 }
339 sp_repr_set_svg_double(rnew, "borderopacity",
340 prefs->getDouble("/template/base/borderopacity", 1.0));
341 sp_repr_set_svg_double(rnew, "objecttolerance",
342 prefs->getDouble("/template/base/objecttolerance", 10.0));
343 sp_repr_set_svg_double(rnew, "gridtolerance",
344 prefs->getDouble("/template/base/gridtolerance", 10.0));
345 sp_repr_set_svg_double(rnew, "guidetolerance",
346 prefs->getDouble("/template/base/guidetolerance", 10.0));
347 sp_repr_set_svg_double(rnew, "inkscape:pageopacity",
348 prefs->getDouble("/template/base/inkscape:pageopacity", 0.0));
349 sp_repr_set_int(rnew, "inkscape:pageshadow",
350 prefs->getInt("/template/base/inkscape:pageshadow", 2));
351 sp_repr_set_int(rnew, "inkscape:window-width",
352 prefs->getInt("/template/base/inkscape:window-width", 640));
353 sp_repr_set_int(rnew, "inkscape:window-height",
354 prefs->getInt("/template/base/inkscape:window-height", 480));
356 // insert into the document
357 rroot->addChild(rnew, NULL);
358 // clean up
359 Inkscape::GC::release(rnew);
360 }
362 /* Defs */
363 if (!SP_ROOT(document->root)->defs) {
364 Inkscape::XML::Node *r;
365 r = rdoc->createElement("svg:defs");
366 rroot->addChild(r, NULL);
367 Inkscape::GC::release(r);
368 g_assert(SP_ROOT(document->root)->defs);
369 }
371 /* Default RDF */
372 rdf_set_defaults( document );
374 if (keepalive) {
375 inkscape_ref();
376 }
378 // Remark: Here, we used to create a "currentpersp3d" element in the document defs.
379 // But this is probably a bad idea since we need to adapt it for every change of selection, which will
380 // completely clutter the undo history. Maybe rather save it to prefs on exit and re-read it on startup?
382 document->current_persp3d = persp3d_document_first_persp(document);
383 if (!document->current_persp3d) {
384 document->current_persp3d = persp3d_create_xml_element (document);
385 }
387 sp_document_set_undo_sensitive(document, true);
389 // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
390 if (!Inkscape::NSApplication::Application::getNewGui()) {
391 g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
392 G_CALLBACK(sp_document_reset_key), document);
393 g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
394 G_CALLBACK(sp_document_reset_key), document);
395 document->oldSignalsConnected = true;
396 } else {
397 document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
398 document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
399 document->oldSignalsConnected = false;
400 }
402 return document;
403 }
405 /**
406 * Fetches document from URI, or creates new, if NULL; public document
407 * appears in document list.
408 */
409 SPDocument *
410 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
411 {
412 SPDocument *doc;
413 Inkscape::XML::Document *rdoc;
414 gchar *base = NULL;
415 gchar *name = NULL;
417 if (uri) {
418 Inkscape::XML::Node *rroot;
419 gchar *s, *p;
420 /* Try to fetch repr from file */
421 rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
422 /* If file cannot be loaded, return NULL without warning */
423 if (rdoc == NULL) return NULL;
424 rroot = rdoc->root();
425 /* If xml file is not svg, return NULL without warning */
426 /* fixme: destroy document */
427 if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
428 s = g_strdup(uri);
429 p = strrchr(s, '/');
430 if (p) {
431 name = g_strdup(p + 1);
432 p[1] = '\0';
433 base = g_strdup(s);
434 } else {
435 base = NULL;
436 name = g_strdup(uri);
437 }
438 g_free(s);
439 } else {
440 rdoc = sp_repr_document_new("svg:svg");
441 }
443 if (make_new) {
444 base = NULL;
445 uri = NULL;
446 name = g_strdup_printf(_("New document %d"), ++doc_count);
447 }
449 //# These should be set by now
450 g_assert(name);
452 doc = sp_document_create(rdoc, uri, base, name, keepalive);
454 g_free(base);
455 g_free(name);
457 return doc;
458 }
460 SPDocument *
461 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
462 {
463 SPDocument *doc;
464 Inkscape::XML::Document *rdoc;
465 Inkscape::XML::Node *rroot;
466 gchar *name;
468 rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
470 /* If it cannot be loaded, return NULL without warning */
471 if (rdoc == NULL) return NULL;
473 rroot = rdoc->root();
474 /* If xml file is not svg, return NULL without warning */
475 /* fixme: destroy document */
476 if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
478 name = g_strdup_printf(_("Memory document %d"), ++doc_count);
480 doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
482 return doc;
483 }
485 SPDocument *
486 sp_document_ref(SPDocument *doc)
487 {
488 g_return_val_if_fail(doc != NULL, NULL);
489 Inkscape::GC::anchor(doc);
490 return doc;
491 }
493 SPDocument *
494 sp_document_unref(SPDocument *doc)
495 {
496 g_return_val_if_fail(doc != NULL, NULL);
497 Inkscape::GC::release(doc);
498 return NULL;
499 }
501 gdouble sp_document_width(SPDocument *document)
502 {
503 g_return_val_if_fail(document != NULL, 0.0);
504 g_return_val_if_fail(document->priv != NULL, 0.0);
505 g_return_val_if_fail(document->root != NULL, 0.0);
507 SPRoot *root = SP_ROOT(document->root);
509 if (root->width.unit == SVGLength::PERCENT && root->viewBox_set)
510 return root->viewBox.x1 - root->viewBox.x0;
511 return root->width.computed;
512 }
514 void
515 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
516 {
517 SPRoot *root = SP_ROOT(document->root);
519 if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
520 root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
521 } else { // set to width=
522 gdouble old_computed = root->width.computed;
523 root->width.computed = sp_units_get_pixels (width, *unit);
524 /* SVG does not support meters as a unit, so we must translate meters to
525 * cm when writing */
526 if (!strcmp(unit->abbr, "m")) {
527 root->width.value = 100*width;
528 root->width.unit = SVGLength::CM;
529 } else {
530 root->width.value = width;
531 root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
532 }
534 if (root->viewBox_set)
535 root->viewBox.x1 = root->viewBox.x0 + (root->width.computed / old_computed) * (root->viewBox.x1 - root->viewBox.x0);
536 }
538 SP_OBJECT (root)->updateRepr();
539 }
541 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
542 {
543 SPRoot *root = SP_ROOT(document->root);
545 if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
546 root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
547 } else { // set to height=
548 gdouble old_computed = root->height.computed;
549 root->height.computed = sp_units_get_pixels (height, *unit);
550 /* SVG does not support meters as a unit, so we must translate meters to
551 * cm when writing */
552 if (!strcmp(unit->abbr, "m")) {
553 root->height.value = 100*height;
554 root->height.unit = SVGLength::CM;
555 } else {
556 root->height.value = height;
557 root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
558 }
560 if (root->viewBox_set)
561 root->viewBox.y1 = root->viewBox.y0 + (root->height.computed / old_computed) * (root->viewBox.y1 - root->viewBox.y0);
562 }
564 SP_OBJECT (root)->updateRepr();
565 }
567 gdouble sp_document_height(SPDocument *document)
568 {
569 g_return_val_if_fail(document != NULL, 0.0);
570 g_return_val_if_fail(document->priv != NULL, 0.0);
571 g_return_val_if_fail(document->root != NULL, 0.0);
573 SPRoot *root = SP_ROOT(document->root);
575 if (root->height.unit == SVGLength::PERCENT && root->viewBox_set)
576 return root->viewBox.y1 - root->viewBox.y0;
577 return root->height.computed;
578 }
580 Geom::Point sp_document_dimensions(SPDocument *doc)
581 {
582 return Geom::Point(sp_document_width(doc), sp_document_height(doc));
583 }
585 /**
586 * Given a Geom::Rect that may, for example, correspond to the bbox of an object,
587 * this function fits the canvas to that rect by resizing the canvas
588 * and translating the document root into position.
589 */
590 void SPDocument::fitToRect(Geom::Rect const &rect)
591 {
592 double const w = rect.width();
593 double const h = rect.height();
595 double const old_height = sp_document_height(this);
596 SPUnit const &px(sp_unit_get_by_id(SP_UNIT_PX));
597 sp_document_set_width(this, w, &px);
598 sp_document_set_height(this, h, &px);
600 Geom::Translate const tr(Geom::Point(0, (old_height - h))
601 - to_2geom(rect.min()));
602 SP_GROUP(root)->translateChildItems(tr);
603 SPNamedView *nv = sp_document_namedview(this, 0);
604 if(nv) {
605 Geom::Translate tr2(-rect.min());
606 nv->translateGuides(tr2);
608 // update the viewport so the drawing appears to stay where it was
609 nv->scrollAllDesktops(-tr2[0], tr2[1], false);
610 }
611 }
613 void sp_document_set_uri(SPDocument *document, gchar const *uri)
614 {
615 g_return_if_fail(document != NULL);
617 if (document->name) {
618 g_free(document->name);
619 document->name = NULL;
620 }
621 if (document->base) {
622 g_free(document->base);
623 document->base = NULL;
624 }
625 if (document->uri) {
626 g_free(document->uri);
627 document->uri = NULL;
628 }
630 if (uri) {
632 #ifndef WIN32
633 prepend_current_dir_if_relative(&(document->uri), uri);
634 #else
635 // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
636 document->uri = g_strdup(uri);
637 #endif
639 /* fixme: Think, what this means for images (Lauris) */
640 document->base = g_path_get_dirname(document->uri);
641 document->name = g_path_get_basename(document->uri);
643 } else {
644 document->uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
645 document->base = NULL;
646 document->name = g_strdup(document->uri);
647 }
649 // Update saveable repr attributes.
650 Inkscape::XML::Node *repr = sp_document_repr_root(document);
651 // changing uri in the document repr must not be not undoable
652 bool saved = sp_document_get_undo_sensitive(document);
653 sp_document_set_undo_sensitive(document, false);
655 repr->setAttribute("sodipodi:docname", document->name);
656 sp_document_set_undo_sensitive(document, saved);
658 document->priv->uri_set_signal.emit(document->uri);
659 }
661 void
662 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
663 {
664 g_return_if_fail(doc != NULL);
666 doc->priv->resized_signal.emit(width, height);
667 }
669 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
670 {
671 return priv->modified_signal.connect(slot);
672 }
674 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
675 {
676 return priv->uri_set_signal.connect(slot);
677 }
679 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
680 {
681 return priv->resized_signal.connect(slot);
682 }
684 sigc::connection
685 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
686 {
687 return priv->_reconstruction_start_signal.connect(slot);
688 }
690 void
691 SPDocument::emitReconstructionStart(void)
692 {
693 // printf("Starting Reconstruction\n");
694 priv->_reconstruction_start_signal.emit();
695 return;
696 }
698 sigc::connection
699 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type slot)
700 {
701 return priv->_reconstruction_finish_signal.connect(slot);
702 }
704 void
705 SPDocument::emitReconstructionFinish(void)
706 {
707 // printf("Finishing Reconstruction\n");
708 priv->_reconstruction_finish_signal.emit();
709 return;
710 }
712 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
713 {
714 return priv->commit_signal.connect(slot);
715 }
719 void SPDocument::_emitModified() {
720 static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
721 root->emitModified(0);
722 priv->modified_signal.emit(flags);
723 }
725 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
726 GQuark idq = g_quark_from_string(id);
728 if (object) {
729 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
730 g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
731 } else {
732 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
733 g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
734 }
736 SPDocumentPrivate::IDChangedSignalMap::iterator pos;
738 pos = priv->id_changed_signals.find(idq);
739 if ( pos != priv->id_changed_signals.end() ) {
740 if (!(*pos).second.empty()) {
741 (*pos).second.emit(object);
742 } else { // discard unused signal
743 priv->id_changed_signals.erase(pos);
744 }
745 }
746 }
748 void
749 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
750 {
751 this->priv->undoStackObservers.add(observer);
752 }
754 void
755 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
756 {
757 this->priv->undoStackObservers.remove(observer);
758 }
760 SPObject *SPDocument::getObjectById(gchar const *id) {
761 g_return_val_if_fail(id != NULL, NULL);
763 GQuark idq = g_quark_from_string(id);
764 return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
765 }
767 sigc::connection SPDocument::connectIdChanged(gchar const *id,
768 SPDocument::IDChangedSignal::slot_type slot)
769 {
770 return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
771 }
773 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
774 if (object) {
775 g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
776 g_hash_table_insert(priv->reprdef, repr, object);
777 } else {
778 g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
779 g_hash_table_remove(priv->reprdef, repr);
780 }
781 }
783 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
784 g_return_val_if_fail(repr != NULL, NULL);
785 return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
786 }
788 Glib::ustring SPDocument::getLanguage() {
789 gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
790 if (document_language) {
791 while (isspace(*document_language))
792 document_language++;
793 }
794 if ( !document_language || 0 == *document_language) {
795 // retrieve system language
796 document_language = getenv("LC_ALL");
797 if ( NULL == document_language || *document_language == 0 ) {
798 document_language = getenv ("LC_MESSAGES");
799 }
800 if ( NULL == document_language || *document_language == 0 ) {
801 document_language = getenv ("LANG");
802 }
804 if ( NULL != document_language ) {
805 gchar *pos = strchr(document_language, '_');
806 if ( NULL != pos ) {
807 return Glib::ustring(document_language, pos - document_language);
808 }
809 }
810 }
812 if ( NULL == document_language )
813 return Glib::ustring();
814 return document_language;
815 }
817 /* Object modification root handler */
819 void
820 sp_document_request_modified(SPDocument *doc)
821 {
822 if (!doc->modified_id) {
823 doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
824 }
825 }
827 void
828 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
829 {
830 ctx->ctx.flags = 0;
831 ctx->i2doc = Geom::identity();
832 /* Set up viewport in case svg has it defined as percentages */
833 if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
834 ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
835 ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
836 ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
837 ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
838 } else { // as a last resort, set size to A4
839 ctx->vp.x0 = 0.0;
840 ctx->vp.y0 = 0.0;
841 ctx->vp.x1 = 210 * PX_PER_MM;
842 ctx->vp.y1 = 297 * PX_PER_MM;
843 }
844 ctx->i2vp = Geom::identity();
845 }
847 /**
848 * Tries to update the document state based on the modified and
849 * "update required" flags, and return true if the document has
850 * been brought fully up to date.
851 */
852 bool
853 SPDocument::_updateDocument()
854 {
855 /* Process updates */
856 if (this->root->uflags || this->root->mflags) {
857 if (this->root->uflags) {
858 SPItemCtx ctx;
859 sp_document_setup_viewport (this, &ctx);
861 bool saved = sp_document_get_undo_sensitive(this);
862 sp_document_set_undo_sensitive(this, false);
864 this->root->updateDisplay((SPCtx *)&ctx, 0);
866 sp_document_set_undo_sensitive(this, saved);
867 }
868 this->_emitModified();
869 }
871 return !(this->root->uflags || this->root->mflags);
872 }
875 /**
876 * Repeatedly works on getting the document updated, since sometimes
877 * it takes more than one pass to get the document updated. But it
878 * usually should not take more than a few loops, and certainly never
879 * more than 32 iterations. So we bail out if we hit 32 iterations,
880 * since this typically indicates we're stuck in an update loop.
881 */
882 gint
883 sp_document_ensure_up_to_date(SPDocument *doc)
884 {
885 int counter = 32;
886 while (!doc->_updateDocument()) {
887 if (counter == 0) {
888 g_warning("More than 32 iteration while updating document '%s'", doc->uri);
889 break;
890 }
891 counter--;
892 }
894 if (doc->modified_id) {
895 /* Remove handler */
896 gtk_idle_remove(doc->modified_id);
897 doc->modified_id = 0;
898 }
899 return counter>0;
900 }
902 /**
903 * An idle handler to update the document. Returns true if
904 * the document needs further updates.
905 */
906 static gint
907 sp_document_idle_handler(gpointer data)
908 {
909 SPDocument *doc = static_cast<SPDocument *>(data);
910 if (doc->_updateDocument()) {
911 doc->modified_id = 0;
912 return false;
913 } else {
914 return true;
915 }
916 }
918 static bool is_within(Geom::Rect const &area, Geom::Rect const &box)
919 {
920 return area.contains(box);
921 }
923 static bool overlaps(Geom::Rect const &area, Geom::Rect const &box)
924 {
925 return area.intersects(box);
926 }
928 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, Geom::Rect const &area,
929 bool (*test)(Geom::Rect const &, Geom::Rect const &), bool take_insensitive = false)
930 {
931 g_return_val_if_fail(SP_IS_GROUP(group), s);
933 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
934 if (!SP_IS_ITEM(o)) {
935 continue;
936 }
937 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
938 s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
939 } else {
940 SPItem *child = SP_ITEM(o);
941 Geom::OptRect box = sp_item_bbox_desktop(child);
942 if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
943 s = g_slist_append(s, child);
944 }
945 }
946 }
948 return s;
949 }
951 /**
952 Returns true if an item is among the descendants of group (recursively).
953 */
954 bool item_is_in_group(SPItem *item, SPGroup *group)
955 {
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;
958 if (SP_ITEM(o) == item)
959 return true;
960 if (SP_IS_GROUP(o))
961 if (item_is_in_group(item, SP_GROUP(o)))
962 return true;
963 }
964 return false;
965 }
967 /**
968 Returns the bottommost item from the list which is at the point, or NULL if none.
969 */
970 SPItem*
971 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
972 Geom::Point const p, bool take_insensitive)
973 {
974 g_return_val_if_fail(group, NULL);
975 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
976 gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
978 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
980 if (!SP_IS_ITEM(o)) continue;
982 SPItem *item = SP_ITEM(o);
983 NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
984 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
985 && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
986 if (g_slist_find((GSList *) list, item) != NULL)
987 return item;
988 }
990 if (SP_IS_GROUP(o)) {
991 SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
992 if (found)
993 return found;
994 }
996 }
997 return NULL;
998 }
1000 /**
1001 Returns the topmost (in z-order) item from the descendants of group (recursively) which
1002 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
1003 non-layer groups or not. Honors take_insensitive on whether to return insensitive
1004 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
1005 upwards in z-order and returns what it has found so far (i.e. the found item is
1006 guaranteed to be lower than upto).
1007 */
1008 SPItem*
1009 find_item_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
1010 {
1011 SPItem *seen = NULL, *newseen = NULL;
1012 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1013 gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1015 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1016 if (!SP_IS_ITEM(o)) continue;
1018 if (upto && SP_ITEM(o) == upto)
1019 break;
1021 if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
1022 // if nothing found yet, recurse into the group
1023 newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
1024 if (newseen) {
1025 seen = newseen;
1026 newseen = NULL;
1027 }
1029 if (item_is_in_group(upto, SP_GROUP(o)))
1030 break;
1032 } else {
1033 SPItem *child = SP_ITEM(o);
1034 NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1036 // seen remembers the last (topmost) of items pickable at this point
1037 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1038 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1039 seen = child;
1040 }
1041 }
1042 }
1043 return seen;
1044 }
1046 /**
1047 Returns the topmost non-layer group from the descendants of group which is at point
1048 p, or NULL if none. Recurses into layers but not into groups.
1049 */
1050 SPItem*
1051 find_group_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p)
1052 {
1053 SPItem *seen = NULL;
1054 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1055 gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1057 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1058 if (!SP_IS_ITEM(o)) continue;
1059 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1060 SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1061 if (newseen) {
1062 seen = newseen;
1063 }
1064 }
1065 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1066 SPItem *child = SP_ITEM(o);
1067 NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1069 // seen remembers the last (topmost) of groups pickable at this point
1070 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1071 seen = child;
1072 }
1073 }
1074 }
1075 return seen;
1076 }
1078 /*
1079 * Return list of items, contained in box
1080 *
1081 * Assumes box is normalized (and g_asserts it!)
1082 *
1083 */
1085 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1086 {
1087 g_return_val_if_fail(document != NULL, NULL);
1088 g_return_val_if_fail(document->priv != NULL, NULL);
1090 return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
1091 }
1093 /*
1094 * Return list of items, that the parts of the item contained in box
1095 *
1096 * Assumes box is normalized (and g_asserts it!)
1097 *
1098 */
1100 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1101 {
1102 g_return_val_if_fail(document != NULL, NULL);
1103 g_return_val_if_fail(document->priv != NULL, NULL);
1105 return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1106 }
1108 GSList *
1109 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<Geom::Point> points)
1110 {
1111 GSList *items = NULL;
1112 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1114 // When picking along the path, we don't want small objects close together
1115 // (such as hatching strokes) to obscure each other by their deltas,
1116 // so we temporarily set delta to a small value
1117 gdouble saved_delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1118 prefs->setDouble("/options/cursortolerance/value", 0.25);
1120 for(unsigned int i = 0; i < points.size(); i++) {
1121 SPItem *item = sp_document_item_at_point(document, key, points[i],
1122 false, NULL);
1123 if (item && !g_slist_find(items, item))
1124 items = g_slist_prepend (items, item);
1125 }
1127 // and now we restore it back
1128 prefs->setDouble("/options/cursortolerance/value", saved_delta);
1130 return items;
1131 }
1133 SPItem *
1134 sp_document_item_at_point(SPDocument *document, unsigned const key, Geom::Point const p,
1135 gboolean const into_groups, SPItem *upto)
1136 {
1137 g_return_val_if_fail(document != NULL, NULL);
1138 g_return_val_if_fail(document->priv != NULL, NULL);
1140 return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1141 }
1143 SPItem*
1144 sp_document_group_at_point(SPDocument *document, unsigned int key, Geom::Point const p)
1145 {
1146 g_return_val_if_fail(document != NULL, NULL);
1147 g_return_val_if_fail(document->priv != NULL, NULL);
1149 return find_group_at_point(key, SP_GROUP(document->root), p);
1150 }
1153 /* Resource management */
1155 gboolean
1156 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1157 {
1158 GSList *rlist;
1159 GQuark q = g_quark_from_string(key);
1161 g_return_val_if_fail(document != NULL, FALSE);
1162 g_return_val_if_fail(key != NULL, FALSE);
1163 g_return_val_if_fail(*key != '\0', FALSE);
1164 g_return_val_if_fail(object != NULL, FALSE);
1165 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1167 if (SP_OBJECT_IS_CLONED(object))
1168 return FALSE;
1170 rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1171 g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1172 rlist = g_slist_prepend(rlist, object);
1173 g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1175 document->priv->resources_changed_signals[q].emit();
1177 return TRUE;
1178 }
1180 gboolean
1181 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1182 {
1183 GSList *rlist;
1184 GQuark q = g_quark_from_string(key);
1186 g_return_val_if_fail(document != NULL, FALSE);
1187 g_return_val_if_fail(key != NULL, FALSE);
1188 g_return_val_if_fail(*key != '\0', FALSE);
1189 g_return_val_if_fail(object != NULL, FALSE);
1190 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1192 if (SP_OBJECT_IS_CLONED(object))
1193 return FALSE;
1195 rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1196 g_return_val_if_fail(rlist != NULL, FALSE);
1197 g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1198 rlist = g_slist_remove(rlist, object);
1199 g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1201 document->priv->resources_changed_signals[q].emit();
1203 return TRUE;
1204 }
1206 GSList const *
1207 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1208 {
1209 g_return_val_if_fail(document != NULL, NULL);
1210 g_return_val_if_fail(key != NULL, NULL);
1211 g_return_val_if_fail(*key != '\0', NULL);
1213 return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1214 }
1216 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1217 gchar const *key,
1218 SPDocument::ResourcesChangedSignal::slot_type slot)
1219 {
1220 GQuark q = g_quark_from_string(key);
1221 return document->priv->resources_changed_signals[q].connect(slot);
1222 }
1224 /* Helpers */
1226 gboolean
1227 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1228 {
1229 g_slist_free((GSList *) value);
1230 return TRUE;
1231 }
1233 unsigned int
1234 count_objects_recursive(SPObject *obj, unsigned int count)
1235 {
1236 count++; // obj itself
1238 for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1239 count = count_objects_recursive(i, count);
1240 }
1242 return count;
1243 }
1245 unsigned int
1246 objects_in_document(SPDocument *document)
1247 {
1248 return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1249 }
1251 void
1252 vacuum_document_recursive(SPObject *obj)
1253 {
1254 if (SP_IS_DEFS(obj)) {
1255 for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1256 /* fixme: some inkscape-internal nodes in the future might not be collectable */
1257 def->requestOrphanCollection();
1258 }
1259 } else {
1260 for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1261 vacuum_document_recursive(i);
1262 }
1263 }
1264 }
1266 unsigned int
1267 vacuum_document(SPDocument *document)
1268 {
1269 unsigned int start = objects_in_document(document);
1270 unsigned int end;
1271 unsigned int newend = start;
1273 unsigned int iterations = 0;
1275 do {
1276 end = newend;
1278 vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1279 document->collectOrphans();
1280 iterations++;
1282 newend = objects_in_document(document);
1284 } while (iterations < 100 && newend < end);
1286 return start - newend;
1287 }
1289 bool SPDocument::isSeeking() const {
1290 return priv->seeking;
1291 }
1294 /*
1295 Local Variables:
1296 mode:c++
1297 c-file-style:"stroustrup"
1298 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1299 indent-tabs-mode:nil
1300 fill-column:99
1301 End:
1302 */
1303 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :