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"
57 #include "display/nr-arena-item.h"
59 #include "dialogs/rdf.h"
61 #define A4_WIDTH_STR "210mm"
62 #define A4_HEIGHT_STR "297mm"
64 #define SP_DOCUMENT_UPDATE_PRIORITY (G_PRIORITY_HIGH_IDLE - 1)
67 static gint sp_document_idle_handler(gpointer data);
69 gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data);
71 static gint doc_count = 0;
73 static unsigned long next_serial = 0;
75 SPDocument::SPDocument() {
76 SPDocumentPrivate *p;
78 keepalive = FALSE;
79 virgin = TRUE;
81 modified_id = 0;
83 rdoc = NULL;
84 rroot = NULL;
85 root = NULL;
86 style_cascade = cr_cascade_new(NULL, NULL, NULL);
88 uri = NULL;
89 base = NULL;
90 name = NULL;
92 _collection_queue = NULL;
94 // Initialise instance of connector router.
95 router = new Avoid::Router();
96 // Don't use the Consolidate moves optimisation.
97 router->ConsolidateMoves = false;
99 p = new SPDocumentPrivate();
101 p->serial = next_serial++;
103 p->iddef = g_hash_table_new(g_direct_hash, g_direct_equal);
104 p->reprdef = g_hash_table_new(g_direct_hash, g_direct_equal);
106 p->resources = g_hash_table_new(g_str_hash, g_str_equal);
108 p->sensitive = FALSE;
109 p->partial = NULL;
110 p->history_size = 0;
111 p->undo = NULL;
112 p->redo = NULL;
113 p->seeking = false;
115 priv = p;
117 // XXX only for testing!
118 priv->undoStackObservers.add(p->console_output_undo_observer);
119 }
121 SPDocument::~SPDocument() {
122 collectOrphans();
124 if (priv) {
125 if (priv->partial) {
126 sp_repr_free_log(priv->partial);
127 priv->partial = NULL;
128 }
130 sp_document_clear_redo(this);
131 sp_document_clear_undo(this);
133 if (root) {
134 root->releaseReferences();
135 sp_object_unref(root);
136 root = NULL;
137 }
139 if (priv->iddef) g_hash_table_destroy(priv->iddef);
140 if (priv->reprdef) g_hash_table_destroy(priv->reprdef);
142 if (rdoc) Inkscape::GC::release(rdoc);
144 /* Free resources */
145 g_hash_table_foreach_remove(priv->resources, sp_document_resource_list_free, this);
146 g_hash_table_destroy(priv->resources);
148 delete priv;
149 priv = NULL;
150 }
152 cr_cascade_unref(style_cascade);
153 style_cascade = NULL;
155 if (name) {
156 g_free(name);
157 name = NULL;
158 }
159 if (base) {
160 g_free(base);
161 base = NULL;
162 }
163 if (uri) {
164 g_free(uri);
165 uri = NULL;
166 }
168 if (modified_id) {
169 gtk_idle_remove(modified_id);
170 modified_id = 0;
171 }
173 _selection_changed_connection.disconnect();
174 _desktop_activated_connection.disconnect();
176 if (keepalive) {
177 inkscape_unref();
178 keepalive = FALSE;
179 }
181 if (router) {
182 delete router;
183 router = NULL;
184 }
186 //delete this->_whiteboard_session_manager;
187 }
189 unsigned long SPDocument::serial() const {
190 return priv->serial;
191 }
193 void SPDocument::queueForOrphanCollection(SPObject *object) {
194 g_return_if_fail(object != NULL);
195 g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
197 sp_object_ref(object, NULL);
198 _collection_queue = g_slist_prepend(_collection_queue, object);
199 }
201 void SPDocument::collectOrphans() {
202 while (_collection_queue) {
203 GSList *objects=_collection_queue;
204 _collection_queue = NULL;
205 for ( GSList *iter=objects ; iter ; iter = iter->next ) {
206 SPObject *object=reinterpret_cast<SPObject *>(iter->data);
207 object->collectOrphan();
208 sp_object_unref(object, NULL);
209 }
210 g_slist_free(objects);
211 }
212 }
214 void SPDocument::reset_key (void *dummy)
215 {
216 actionkey = NULL;
217 }
219 SPDocument *
220 sp_document_create(Inkscape::XML::Document *rdoc,
221 gchar const *uri,
222 gchar const *base,
223 gchar const *name,
224 unsigned int keepalive)
225 {
226 SPDocument *document;
227 Inkscape::XML::Node *rroot;
228 Inkscape::Version sodipodi_version;
230 rroot = rdoc->root();
232 document = new SPDocument();
234 document->keepalive = keepalive;
236 document->rdoc = rdoc;
237 document->rroot = rroot;
239 #ifndef WIN32
240 prepend_current_dir_if_relative(&(document->uri), uri);
241 #else
242 // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
243 document->uri = uri? g_strdup(uri) : NULL;
244 #endif
246 // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
247 // which is why we use g_get_current_dir() in calculating the abs path above
248 //This is NULL for a new document
249 if (base)
250 document->base = g_strdup(base);
251 else
252 document->base = NULL;
253 document->name = g_strdup(name);
255 document->root = sp_object_repr_build_tree(document, rroot);
257 sodipodi_version = SP_ROOT(document->root)->version.sodipodi;
259 /* fixme: Not sure about this, but lets assume ::build updates */
260 rroot->setAttribute("sodipodi:version", SODIPODI_VERSION);
261 rroot->setAttribute("inkscape:version", INKSCAPE_VERSION);
262 /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
264 /* Quick hack 2 - get default image size into document */
265 if (!rroot->attribute("width")) rroot->setAttribute("width", A4_WIDTH_STR);
266 if (!rroot->attribute("height")) rroot->setAttribute("height", A4_HEIGHT_STR);
267 /* End of quick hack 2 */
269 /* Quick hack 3 - Set uri attributes */
270 if (uri) {
271 rroot->setAttribute("sodipodi:docname", uri);
272 }
273 /* End of quick hack 3 */
275 // creating namedview
276 if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
277 // if there's none in the document already,
278 Inkscape::XML::Node *r = NULL;
279 Inkscape::XML::Node *rnew = NULL;
280 r = inkscape_get_repr(INKSCAPE, "template.base");
281 // see if there's a template with id="base" in the preferences
282 if (!r) {
283 // if there's none, create an empty element
284 rnew = rdoc->createElement("sodipodi:namedview");
285 rnew->setAttribute("id", "base");
286 } else {
287 // otherwise, take from preferences
288 rnew = r->duplicate(rroot->document());
289 }
290 // insert into the document
291 rroot->addChild(rnew, NULL);
292 // clean up
293 Inkscape::GC::release(rnew);
294 }
296 /* Defs */
297 if (!SP_ROOT(document->root)->defs) {
298 Inkscape::XML::Node *r;
299 r = rdoc->createElement("svg:defs");
300 rroot->addChild(r, NULL);
301 Inkscape::GC::release(r);
302 g_assert(SP_ROOT(document->root)->defs);
303 }
305 /* Default RDF */
306 rdf_set_defaults( document );
308 if (keepalive) {
309 inkscape_ref();
310 }
312 sp_document_set_undo_sensitive(document, true);
314 // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
315 if (!Inkscape::NSApplication::Application::getNewGui()) {
316 g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
317 G_CALLBACK(sp_document_reset_key), document);
318 g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
319 G_CALLBACK(sp_document_reset_key), document);
320 } else {
321 document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
322 document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
323 }
325 return document;
326 }
328 /**
329 * Fetches document from URI, or creates new, if NULL; public document
330 * appears in document list.
331 */
332 SPDocument *
333 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
334 {
335 SPDocument *doc;
336 Inkscape::XML::Document *rdoc;
337 gchar *base = NULL;
338 gchar *name = NULL;
340 if (uri) {
341 Inkscape::XML::Node *rroot;
342 gchar *s, *p;
343 /* Try to fetch repr from file */
344 rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
345 /* If file cannot be loaded, return NULL without warning */
346 if (rdoc == NULL) return NULL;
347 rroot = rdoc->root();
348 /* If xml file is not svg, return NULL without warning */
349 /* fixme: destroy document */
350 if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
351 s = g_strdup(uri);
352 p = strrchr(s, '/');
353 if (p) {
354 name = g_strdup(p + 1);
355 p[1] = '\0';
356 base = g_strdup(s);
357 } else {
358 base = NULL;
359 name = g_strdup(uri);
360 }
361 g_free(s);
362 } else {
363 rdoc = sp_repr_document_new("svg:svg");
364 }
366 if (make_new) {
367 base = NULL;
368 uri = NULL;
369 name = g_strdup_printf(_("New document %d"), ++doc_count);
370 }
372 //# These should be set by now
373 g_assert(name);
375 doc = sp_document_create(rdoc, uri, base, name, keepalive);
377 g_free(base);
378 g_free(name);
380 return doc;
381 }
383 SPDocument *
384 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
385 {
386 SPDocument *doc;
387 Inkscape::XML::Document *rdoc;
388 Inkscape::XML::Node *rroot;
389 gchar *name;
391 rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
393 /* If it cannot be loaded, return NULL without warning */
394 if (rdoc == NULL) return NULL;
396 rroot = rdoc->root();
397 /* If xml file is not svg, return NULL without warning */
398 /* fixme: destroy document */
399 if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
401 name = g_strdup_printf(_("Memory document %d"), ++doc_count);
403 doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
405 return doc;
406 }
408 SPDocument *
409 sp_document_ref(SPDocument *doc)
410 {
411 g_return_val_if_fail(doc != NULL, NULL);
412 Inkscape::GC::anchor(doc);
413 return doc;
414 }
416 SPDocument *
417 sp_document_unref(SPDocument *doc)
418 {
419 g_return_val_if_fail(doc != NULL, NULL);
420 Inkscape::GC::release(doc);
421 return NULL;
422 }
424 gdouble sp_document_width(SPDocument *document)
425 {
426 g_return_val_if_fail(document != NULL, 0.0);
427 g_return_val_if_fail(document->priv != NULL, 0.0);
428 g_return_val_if_fail(document->root != NULL, 0.0);
430 return SP_ROOT(document->root)->width.computed;
431 }
433 void
434 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
435 {
436 SPRoot *root = SP_ROOT(document->root);
438 if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
439 root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
440 } else { // set to width=
441 root->width.computed = sp_units_get_pixels (width, *unit);
442 /* SVG does not support meters as a unit, so we must translate meters to
443 * cm when writing */
444 if (!strcmp(unit->abbr, "m")) {
445 root->width.value = 100*width;
446 root->width.unit = SVGLength::CM;
447 } else {
448 root->width.value = width;
449 root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
450 }
451 }
453 SP_OBJECT (root)->updateRepr();
454 }
456 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
457 {
458 SPRoot *root = SP_ROOT(document->root);
460 if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
461 root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
462 } else { // set to height=
463 root->height.computed = sp_units_get_pixels (height, *unit);
464 /* SVG does not support meters as a unit, so we must translate meters to
465 * cm when writing */
466 if (!strcmp(unit->abbr, "m")) {
467 root->height.value = 100*height;
468 root->height.unit = SVGLength::CM;
469 } else {
470 root->height.value = height;
471 root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
472 }
473 }
475 SP_OBJECT (root)->updateRepr();
476 }
478 gdouble sp_document_height(SPDocument *document)
479 {
480 g_return_val_if_fail(document != NULL, 0.0);
481 g_return_val_if_fail(document->priv != NULL, 0.0);
482 g_return_val_if_fail(document->root != NULL, 0.0);
484 return SP_ROOT(document->root)->height.computed;
485 }
487 /**
488 * Given an NRRect that may, for example, correspond to the bbox of an object
489 * this function fits the canvas to that rect by resizing the canvas
490 * and translating the document root into position.
491 */
492 void SPDocument::fitToRect(NRRect const & rect)
493 {
494 g_return_if_fail(!nr_rect_d_test_empty(&rect));
496 gdouble w = rect.x1 - rect.x0;
497 gdouble h = rect.y1 - rect.y0;
498 gdouble old_height = sp_document_height(this);
499 SPUnit unit = sp_unit_get_by_id(SP_UNIT_PX);
500 sp_document_set_width(this, w, &unit);
501 sp_document_set_height(this, h, &unit);
503 NR::translate tr = NR::translate::translate(-rect.x0,-(rect.y0 + (h - old_height)));
504 static_cast<SPGroup *>(root)->translateChildItems(tr);
505 }
507 void sp_document_set_uri(SPDocument *document, gchar const *uri)
508 {
509 g_return_if_fail(document != NULL);
511 if (document->name) {
512 g_free(document->name);
513 document->name = NULL;
514 }
515 if (document->base) {
516 g_free(document->base);
517 document->base = NULL;
518 }
519 if (document->uri) {
520 g_free(document->uri);
521 document->uri = NULL;
522 }
524 if (uri) {
526 #ifndef WIN32
527 prepend_current_dir_if_relative(&(document->uri), uri);
528 #else
529 // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
530 document->uri = g_strdup(uri);
531 #endif
533 /* fixme: Think, what this means for images (Lauris) */
534 document->base = g_path_get_dirname(document->uri);
535 document->name = g_path_get_basename(document->uri);
537 } else {
538 document->uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
539 document->base = NULL;
540 document->name = g_strdup(document->uri);
541 }
543 // Update saveable repr attributes.
544 Inkscape::XML::Node *repr = sp_document_repr_root(document);
545 // changing uri in the document repr must not be not undoable
546 bool saved = sp_document_get_undo_sensitive(document);
547 sp_document_set_undo_sensitive(document, false);
549 repr->setAttribute("sodipodi:docname", document->name);
550 sp_document_set_undo_sensitive(document, saved);
552 document->priv->uri_set_signal.emit(document->uri);
553 }
555 void
556 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
557 {
558 g_return_if_fail(doc != NULL);
560 doc->priv->resized_signal.emit(width, height);
561 }
563 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
564 {
565 return priv->modified_signal.connect(slot);
566 }
568 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
569 {
570 return priv->uri_set_signal.connect(slot);
571 }
573 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
574 {
575 return priv->resized_signal.connect(slot);
576 }
578 sigc::connection
579 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
580 {
581 return priv->_reconstruction_start_signal.connect(slot);
582 }
584 void
585 SPDocument::emitReconstructionStart(void)
586 {
587 // printf("Starting Reconstruction\n");
588 priv->_reconstruction_start_signal.emit();
589 return;
590 }
592 sigc::connection
593 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type slot)
594 {
595 return priv->_reconstruction_finish_signal.connect(slot);
596 }
598 void
599 SPDocument::emitReconstructionFinish(void)
600 {
601 // printf("Finishing Reconstruction\n");
602 priv->_reconstruction_finish_signal.emit();
603 return;
604 }
606 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
607 {
608 return priv->commit_signal.connect(slot);
609 }
613 void SPDocument::_emitModified() {
614 static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
615 root->emitModified(0);
616 priv->modified_signal.emit(flags);
617 }
619 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
620 GQuark idq = g_quark_from_string(id);
622 if (object) {
623 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
624 g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
625 } else {
626 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
627 g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
628 }
630 SPDocumentPrivate::IDChangedSignalMap::iterator pos;
632 pos = priv->id_changed_signals.find(idq);
633 if ( pos != priv->id_changed_signals.end() ) {
634 if (!(*pos).second.empty()) {
635 (*pos).second.emit(object);
636 } else { // discard unused signal
637 priv->id_changed_signals.erase(pos);
638 }
639 }
640 }
642 void
643 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
644 {
645 this->priv->undoStackObservers.add(observer);
646 }
648 void
649 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
650 {
651 this->priv->undoStackObservers.remove(observer);
652 }
654 SPObject *SPDocument::getObjectById(gchar const *id) {
655 g_return_val_if_fail(id != NULL, NULL);
657 GQuark idq = g_quark_from_string(id);
658 return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
659 }
661 sigc::connection SPDocument::connectIdChanged(gchar const *id,
662 SPDocument::IDChangedSignal::slot_type slot)
663 {
664 return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
665 }
667 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
668 if (object) {
669 g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
670 g_hash_table_insert(priv->reprdef, repr, object);
671 } else {
672 g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
673 g_hash_table_remove(priv->reprdef, repr);
674 }
675 }
677 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
678 g_return_val_if_fail(repr != NULL, NULL);
679 return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
680 }
682 Glib::ustring SPDocument::getLanguage() {
683 gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
684 if (document_language) {
685 while (isspace(*document_language))
686 document_language++;
687 }
688 if ( !document_language || 0 == *document_language) {
689 // retrieve system language
690 document_language = getenv("LC_ALL");
691 if ( NULL == document_language || *document_language == 0 ) {
692 document_language = getenv ("LC_MESSAGES");
693 }
694 if ( NULL == document_language || *document_language == 0 ) {
695 document_language = getenv ("LANG");
696 }
698 if ( NULL != document_language ) {
699 gchar *pos = strchr(document_language, '_');
700 if ( NULL != pos ) {
701 return Glib::ustring(document_language, pos - document_language);
702 }
703 }
704 }
706 if ( NULL == document_language )
707 return Glib::ustring();
708 return document_language;
709 }
711 /* Object modification root handler */
713 void
714 sp_document_request_modified(SPDocument *doc)
715 {
716 if (!doc->modified_id) {
717 doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
718 }
719 }
721 void
722 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
723 {
724 ctx->ctx.flags = 0;
725 ctx->i2doc = NR::identity();
726 /* Set up viewport in case svg has it defined as percentages */
727 if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
728 ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
729 ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
730 ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
731 ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
732 } else { // as a last resort, set size to A4
733 ctx->vp.x0 = 0.0;
734 ctx->vp.y0 = 0.0;
735 ctx->vp.x1 = 210 * PX_PER_MM;
736 ctx->vp.y1 = 297 * PX_PER_MM;
737 }
738 ctx->i2vp = NR::identity();
739 }
741 /**
742 * Tries to update the document state based on the modified and
743 * "update required" flags, and return true if the document has
744 * been brought fully up to date.
745 */
746 bool
747 SPDocument::_updateDocument()
748 {
749 /* Process updates */
750 if (this->root->uflags || this->root->mflags) {
751 if (this->root->uflags) {
752 SPItemCtx ctx;
753 sp_document_setup_viewport (this, &ctx);
755 bool saved = sp_document_get_undo_sensitive(this);
756 sp_document_set_undo_sensitive(this, false);
758 this->root->updateDisplay((SPCtx *)&ctx, 0);
760 sp_document_set_undo_sensitive(this, saved);
761 }
762 this->_emitModified();
763 }
765 return !(this->root->uflags || this->root->mflags);
766 }
769 /**
770 * Repeatedly works on getting the document updated, since sometimes
771 * it takes more than one pass to get the document updated. But it
772 * usually should not take more than a few loops, and certainly never
773 * more than 32 iterations. So we bail out if we hit 32 iterations,
774 * since this typically indicates we're stuck in an update loop.
775 */
776 gint
777 sp_document_ensure_up_to_date(SPDocument *doc)
778 {
779 int counter = 32;
780 while (!doc->_updateDocument()) {
781 if (counter == 0) {
782 g_warning("More than 32 iteration while updating document '%s'", doc->uri);
783 break;
784 }
785 counter--;
786 }
788 if (doc->modified_id) {
789 /* Remove handler */
790 gtk_idle_remove(doc->modified_id);
791 doc->modified_id = 0;
792 }
793 return counter>0;
794 }
796 /**
797 * An idle handler to update the document. Returns true if
798 * the document needs further updates.
799 */
800 static gint
801 sp_document_idle_handler(gpointer data)
802 {
803 SPDocument *doc = static_cast<SPDocument *>(data);
804 if (doc->_updateDocument()) {
805 doc->modified_id = 0;
806 return false;
807 } else {
808 return true;
809 }
810 }
812 static bool is_within(NR::Rect const &area, NR::Rect const &box)
813 {
814 return area.contains(box);
815 }
817 static bool overlaps(NR::Rect const &area, NR::Rect const &box)
818 {
819 return area.intersects(box);
820 }
822 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, NR::Rect const &area,
823 bool (*test)(NR::Rect const &, NR::Rect const &), bool take_insensitive = false)
824 {
825 g_return_val_if_fail(SP_IS_GROUP(group), s);
827 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
828 if (!SP_IS_ITEM(o)) {
829 continue;
830 }
831 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
832 s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
833 } else {
834 SPItem *child = SP_ITEM(o);
835 NR::Maybe<NR::Rect> box = sp_item_bbox_desktop(child);
836 if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
837 s = g_slist_append(s, child);
838 }
839 }
840 }
842 return s;
843 }
845 /**
846 Returns true if an item is among the descendants of group (recursively).
847 */
848 bool item_is_in_group(SPItem *item, SPGroup *group)
849 {
850 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
851 if (!SP_IS_ITEM(o)) continue;
852 if (SP_ITEM(o) == item)
853 return true;
854 if (SP_IS_GROUP(o))
855 if (item_is_in_group(item, SP_GROUP(o)))
856 return true;
857 }
858 return false;
859 }
861 /**
862 Returns the bottommost item from the list which is at the point, or NULL if none.
863 */
864 SPItem*
865 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
866 NR::Point const p, bool take_insensitive)
867 {
868 g_return_val_if_fail(group, NULL);
870 gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
872 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
874 if (!SP_IS_ITEM(o)) continue;
876 SPItem *item = SP_ITEM(o);
877 NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
878 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
879 && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
880 if (g_slist_find((GSList *) list, item) != NULL)
881 return item;
882 }
884 if (SP_IS_GROUP(o)) {
885 SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
886 if (found)
887 return found;
888 }
890 }
891 return NULL;
892 }
894 /**
895 Returns the topmost (in z-order) item from the descendants of group (recursively) which
896 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
897 non-layer groups or not. Honors take_insensitive on whether to return insensitive
898 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
899 upwards in z-order and returns what it has found so far (i.e. the found item is
900 guaranteed to be lower than upto).
901 */
902 SPItem*
903 find_item_at_point(unsigned int dkey, SPGroup *group, NR::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
904 {
905 SPItem *seen = NULL, *newseen = NULL;
907 gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
909 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
910 if (!SP_IS_ITEM(o)) continue;
912 if (upto && SP_ITEM(o) == upto)
913 break;
915 if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
916 // if nothing found yet, recurse into the group
917 newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
918 if (newseen) {
919 seen = newseen;
920 newseen = NULL;
921 }
923 if (item_is_in_group(upto, SP_GROUP(o)))
924 break;
926 } else {
927 SPItem *child = SP_ITEM(o);
928 NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
930 // seen remembers the last (topmost) of items pickable at this point
931 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
932 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
933 seen = child;
934 }
935 }
936 }
937 return seen;
938 }
940 /**
941 Returns the topmost non-layer group from the descendants of group which is at point
942 p, or NULL if none. Recurses into layers but not into groups.
943 */
944 SPItem*
945 find_group_at_point(unsigned int dkey, SPGroup *group, NR::Point const p)
946 {
947 SPItem *seen = NULL;
949 gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
951 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
952 if (!SP_IS_ITEM(o)) continue;
953 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
954 SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
955 if (newseen) {
956 seen = newseen;
957 }
958 }
959 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
960 SPItem *child = SP_ITEM(o);
961 NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
963 // seen remembers the last (topmost) of groups pickable at this point
964 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
965 seen = child;
966 }
967 }
968 }
969 return seen;
970 }
972 /*
973 * Return list of items, contained in box
974 *
975 * Assumes box is normalized (and g_asserts it!)
976 *
977 */
979 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
980 {
981 g_return_val_if_fail(document != NULL, NULL);
982 g_return_val_if_fail(document->priv != NULL, NULL);
984 return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
985 }
987 /*
988 * Return list of items, that the parts of the item contained in box
989 *
990 * Assumes box is normalized (and g_asserts it!)
991 *
992 */
994 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
995 {
996 g_return_val_if_fail(document != NULL, NULL);
997 g_return_val_if_fail(document->priv != NULL, NULL);
999 return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1000 }
1002 GSList *
1003 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<NR::Point> points)
1004 {
1005 GSList *items = NULL;
1007 // When picking along the path, we don't want small objects close together
1008 // (such as hatching strokes) to obscure each other by their deltas,
1009 // so we temporarily set delta to a small value
1010 gdouble saved_delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
1011 prefs_set_double_attribute ("options.cursortolerance", "value", 0.25);
1013 for(unsigned int i = 0; i < points.size(); i++) {
1014 SPItem *item = sp_document_item_at_point(document, key, points[i],
1015 false, NULL);
1016 if (item && !g_slist_find(items, item))
1017 items = g_slist_prepend (items, item);
1018 }
1020 // and now we restore it back
1021 prefs_set_double_attribute ("options.cursortolerance", "value", saved_delta);
1023 return items;
1024 }
1026 SPItem *
1027 sp_document_item_at_point(SPDocument *document, unsigned const key, NR::Point const p,
1028 gboolean const into_groups, SPItem *upto)
1029 {
1030 g_return_val_if_fail(document != NULL, NULL);
1031 g_return_val_if_fail(document->priv != NULL, NULL);
1033 return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1034 }
1036 SPItem*
1037 sp_document_group_at_point(SPDocument *document, unsigned int key, NR::Point const p)
1038 {
1039 g_return_val_if_fail(document != NULL, NULL);
1040 g_return_val_if_fail(document->priv != NULL, NULL);
1042 return find_group_at_point(key, SP_GROUP(document->root), p);
1043 }
1046 /* Resource management */
1048 gboolean
1049 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1050 {
1051 GSList *rlist;
1052 GQuark q = g_quark_from_string(key);
1054 g_return_val_if_fail(document != NULL, FALSE);
1055 g_return_val_if_fail(key != NULL, FALSE);
1056 g_return_val_if_fail(*key != '\0', FALSE);
1057 g_return_val_if_fail(object != NULL, FALSE);
1058 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1060 if (SP_OBJECT_IS_CLONED(object))
1061 return FALSE;
1063 rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1064 g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1065 rlist = g_slist_prepend(rlist, object);
1066 g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1068 document->priv->resources_changed_signals[q].emit();
1070 return TRUE;
1071 }
1073 gboolean
1074 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1075 {
1076 GSList *rlist;
1077 GQuark q = g_quark_from_string(key);
1079 g_return_val_if_fail(document != NULL, FALSE);
1080 g_return_val_if_fail(key != NULL, FALSE);
1081 g_return_val_if_fail(*key != '\0', FALSE);
1082 g_return_val_if_fail(object != NULL, FALSE);
1083 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1085 if (SP_OBJECT_IS_CLONED(object))
1086 return FALSE;
1088 rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1089 g_return_val_if_fail(rlist != NULL, FALSE);
1090 g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1091 rlist = g_slist_remove(rlist, object);
1092 g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1094 document->priv->resources_changed_signals[q].emit();
1096 return TRUE;
1097 }
1099 GSList const *
1100 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1101 {
1102 g_return_val_if_fail(document != NULL, NULL);
1103 g_return_val_if_fail(key != NULL, NULL);
1104 g_return_val_if_fail(*key != '\0', NULL);
1106 return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1107 }
1109 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1110 gchar const *key,
1111 SPDocument::ResourcesChangedSignal::slot_type slot)
1112 {
1113 GQuark q = g_quark_from_string(key);
1114 return document->priv->resources_changed_signals[q].connect(slot);
1115 }
1117 /* Helpers */
1119 gboolean
1120 sp_document_resource_list_free(gpointer key, gpointer value, gpointer data)
1121 {
1122 g_slist_free((GSList *) value);
1123 return TRUE;
1124 }
1126 unsigned int
1127 count_objects_recursive(SPObject *obj, unsigned int count)
1128 {
1129 count++; // obj itself
1131 for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1132 count = count_objects_recursive(i, count);
1133 }
1135 return count;
1136 }
1138 unsigned int
1139 objects_in_document(SPDocument *document)
1140 {
1141 return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1142 }
1144 void
1145 vacuum_document_recursive(SPObject *obj)
1146 {
1147 if (SP_IS_DEFS(obj)) {
1148 for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1149 /* fixme: some inkscape-internal nodes in the future might not be collectable */
1150 def->requestOrphanCollection();
1151 }
1152 } else {
1153 for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1154 vacuum_document_recursive(i);
1155 }
1156 }
1157 }
1159 unsigned int
1160 vacuum_document(SPDocument *document)
1161 {
1162 unsigned int start = objects_in_document(document);
1163 unsigned int end;
1164 unsigned int newend = start;
1166 unsigned int iterations = 0;
1168 do {
1169 end = newend;
1171 vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1172 document->collectOrphans();
1173 iterations++;
1175 newend = objects_in_document(document);
1177 } while (iterations < 100 && newend < end);
1179 return start - newend;
1180 }
1182 bool SPDocument::isSeeking() const {
1183 return priv->seeking;
1184 }
1187 /*
1188 Local Variables:
1189 mode:c++
1190 c-file-style:"stroustrup"
1191 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1192 indent-tabs-mode:nil
1193 fill-column:99
1194 End:
1195 */
1196 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :