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 "profile-manager.h"
57 #include "persp3d.h"
59 #include "display/nr-arena-item.h"
61 #include "dialogs/rdf.h"
63 #include "transf_mat_3x4.h"
65 #define A4_WIDTH_STR "210mm"
66 #define A4_HEIGHT_STR "297mm"
68 #define SP_DOCUMENT_UPDATE_PRIORITY (G_PRIORITY_HIGH_IDLE - 1)
71 static gint sp_document_idle_handler(gpointer data);
73 gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data);
75 static gint doc_count = 0;
77 static unsigned long next_serial = 0;
79 SPDocument::SPDocument() {
80 SPDocumentPrivate *p;
82 keepalive = FALSE;
83 virgin = TRUE;
85 modified_id = 0;
87 rdoc = NULL;
88 rroot = NULL;
89 root = NULL;
90 style_cascade = cr_cascade_new(NULL, NULL, NULL);
92 uri = NULL;
93 base = NULL;
94 name = NULL;
96 _collection_queue = NULL;
98 // Initialise instance of connector router.
99 router = new Avoid::Router();
100 // Don't use the Consolidate moves optimisation.
101 router->ConsolidateMoves = false;
103 perspectives = NULL;
105 p = new SPDocumentPrivate();
107 p->serial = next_serial++;
109 p->iddef = g_hash_table_new(g_direct_hash, g_direct_equal);
110 p->reprdef = g_hash_table_new(g_direct_hash, g_direct_equal);
112 p->resources = g_hash_table_new(g_str_hash, g_str_equal);
114 p->sensitive = FALSE;
115 p->partial = NULL;
116 p->history_size = 0;
117 p->undo = NULL;
118 p->redo = NULL;
119 p->seeking = false;
121 priv = p;
123 // Once things are set, hook in the manager
124 profileManager = new Inkscape::ProfileManager(this);
126 // XXX only for testing!
127 priv->undoStackObservers.add(p->console_output_undo_observer);
128 }
130 SPDocument::~SPDocument() {
131 collectOrphans();
133 // kill/unhook this first
134 if ( profileManager ) {
135 delete profileManager;
136 profileManager = 0;
137 }
139 if (priv) {
140 if (priv->partial) {
141 sp_repr_free_log(priv->partial);
142 priv->partial = NULL;
143 }
145 sp_document_clear_redo(this);
146 sp_document_clear_undo(this);
148 if (root) {
149 root->releaseReferences();
150 sp_object_unref(root);
151 root = NULL;
152 }
154 if (priv->iddef) g_hash_table_destroy(priv->iddef);
155 if (priv->reprdef) g_hash_table_destroy(priv->reprdef);
157 if (rdoc) Inkscape::GC::release(rdoc);
159 /* Free resources */
160 g_hash_table_foreach_remove(priv->resources, sp_document_resource_list_free, this);
161 g_hash_table_destroy(priv->resources);
163 delete priv;
164 priv = NULL;
165 }
167 cr_cascade_unref(style_cascade);
168 style_cascade = NULL;
170 if (name) {
171 g_free(name);
172 name = NULL;
173 }
174 if (base) {
175 g_free(base);
176 base = NULL;
177 }
178 if (uri) {
179 g_free(uri);
180 uri = NULL;
181 }
183 if (modified_id) {
184 gtk_idle_remove(modified_id);
185 modified_id = 0;
186 }
188 _selection_changed_connection.disconnect();
189 _desktop_activated_connection.disconnect();
191 if (keepalive) {
192 inkscape_unref();
193 keepalive = FALSE;
194 }
196 if (router) {
197 delete router;
198 router = NULL;
199 }
201 //delete this->_whiteboard_session_manager;
203 }
205 void SPDocument::add_persp3d (Persp3D * const persp)
206 {
207 SPDefs *defs = SP_ROOT(this->root)->defs;
208 for (SPObject *i = sp_object_first_child(SP_OBJECT(defs)); i != NULL; i = SP_OBJECT_NEXT(i) ) {
209 if (SP_IS_PERSP3D(i)) {
210 g_print ("Encountered a Persp3D in defs\n");
211 }
212 }
214 g_print ("Adding Persp3D to defs\n");
215 persp3d_create_xml_element (this);
216 }
218 void SPDocument::remove_persp3d (Persp3D * const persp)
219 {
220 // TODO: Delete the repr, maybe perform a check if any boxes are still linked to the perspective.
221 // Anything else?
222 g_print ("Please implement deletion of perspectives here.\n");
223 }
225 unsigned long SPDocument::serial() const {
226 return priv->serial;
227 }
229 void SPDocument::queueForOrphanCollection(SPObject *object) {
230 g_return_if_fail(object != NULL);
231 g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
233 sp_object_ref(object, NULL);
234 _collection_queue = g_slist_prepend(_collection_queue, object);
235 }
237 void SPDocument::collectOrphans() {
238 while (_collection_queue) {
239 GSList *objects=_collection_queue;
240 _collection_queue = NULL;
241 for ( GSList *iter=objects ; iter ; iter = iter->next ) {
242 SPObject *object=reinterpret_cast<SPObject *>(iter->data);
243 object->collectOrphan();
244 sp_object_unref(object, NULL);
245 }
246 g_slist_free(objects);
247 }
248 }
250 void SPDocument::reset_key (void */*dummy*/)
251 {
252 actionkey = NULL;
253 }
255 SPDocument *
256 sp_document_create(Inkscape::XML::Document *rdoc,
257 gchar const *uri,
258 gchar const *base,
259 gchar const *name,
260 unsigned int keepalive)
261 {
262 SPDocument *document;
263 Inkscape::XML::Node *rroot;
264 Inkscape::Version sodipodi_version;
266 rroot = rdoc->root();
268 document = new SPDocument();
270 document->keepalive = keepalive;
272 document->rdoc = rdoc;
273 document->rroot = rroot;
275 #ifndef WIN32
276 prepend_current_dir_if_relative(&(document->uri), uri);
277 #else
278 // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
279 document->uri = uri? g_strdup(uri) : NULL;
280 #endif
282 // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
283 // which is why we use g_get_current_dir() in calculating the abs path above
284 //This is NULL for a new document
285 if (base)
286 document->base = g_strdup(base);
287 else
288 document->base = NULL;
289 document->name = g_strdup(name);
291 document->root = sp_object_repr_build_tree(document, rroot);
293 sodipodi_version = SP_ROOT(document->root)->version.sodipodi;
295 /* fixme: Not sure about this, but lets assume ::build updates */
296 rroot->setAttribute("sodipodi:version", SODIPODI_VERSION);
297 rroot->setAttribute("inkscape:version", INKSCAPE_VERSION);
298 /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
300 /* Quick hack 2 - get default image size into document */
301 if (!rroot->attribute("width")) rroot->setAttribute("width", A4_WIDTH_STR);
302 if (!rroot->attribute("height")) rroot->setAttribute("height", A4_HEIGHT_STR);
303 /* End of quick hack 2 */
305 /* Quick hack 3 - Set uri attributes */
306 if (uri) {
307 rroot->setAttribute("sodipodi:docname", uri);
308 }
309 /* End of quick hack 3 */
311 // creating namedview
312 if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
313 // if there's none in the document already,
314 Inkscape::XML::Node *r = NULL;
315 Inkscape::XML::Node *rnew = NULL;
316 r = inkscape_get_repr(INKSCAPE, "template.base");
317 // see if there's a template with id="base" in the preferences
318 if (!r) {
319 // if there's none, create an empty element
320 rnew = rdoc->createElement("sodipodi:namedview");
321 rnew->setAttribute("id", "base");
322 } else {
323 // otherwise, take from preferences
324 rnew = r->duplicate(rroot->document());
325 }
326 // insert into the document
327 rroot->addChild(rnew, NULL);
328 // clean up
329 Inkscape::GC::release(rnew);
330 }
332 /* Defs */
333 if (!SP_ROOT(document->root)->defs) {
334 Inkscape::XML::Node *r;
335 r = rdoc->createElement("svg:defs");
336 rroot->addChild(r, NULL);
337 Inkscape::GC::release(r);
338 g_assert(SP_ROOT(document->root)->defs);
339 }
341 /* Default RDF */
342 rdf_set_defaults( document );
344 if (keepalive) {
345 inkscape_ref();
346 }
348 // Remark: Here, we used to create a "currentpersp3d" element in the document defs.
349 // But this is probably a bad idea since we need to adapt it for every change of selection, which will
350 // completely clutter the undo history. Maybe rather save it to prefs on exit and re-read it on startup?
352 document->current_persp3d = persp3d_create_xml_element (document);
354 sp_document_set_undo_sensitive(document, true);
356 // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
357 if (!Inkscape::NSApplication::Application::getNewGui()) {
358 g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
359 G_CALLBACK(sp_document_reset_key), document);
360 g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
361 G_CALLBACK(sp_document_reset_key), document);
362 } else {
363 document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
364 document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
365 }
367 return document;
368 }
370 /**
371 * Fetches document from URI, or creates new, if NULL; public document
372 * appears in document list.
373 */
374 SPDocument *
375 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
376 {
377 SPDocument *doc;
378 Inkscape::XML::Document *rdoc;
379 gchar *base = NULL;
380 gchar *name = NULL;
382 if (uri) {
383 Inkscape::XML::Node *rroot;
384 gchar *s, *p;
385 /* Try to fetch repr from file */
386 rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
387 /* If file cannot be loaded, return NULL without warning */
388 if (rdoc == NULL) return NULL;
389 rroot = rdoc->root();
390 /* If xml file is not svg, return NULL without warning */
391 /* fixme: destroy document */
392 if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
393 s = g_strdup(uri);
394 p = strrchr(s, '/');
395 if (p) {
396 name = g_strdup(p + 1);
397 p[1] = '\0';
398 base = g_strdup(s);
399 } else {
400 base = NULL;
401 name = g_strdup(uri);
402 }
403 g_free(s);
404 } else {
405 rdoc = sp_repr_document_new("svg:svg");
406 }
408 if (make_new) {
409 base = NULL;
410 uri = NULL;
411 name = g_strdup_printf(_("New document %d"), ++doc_count);
412 }
414 //# These should be set by now
415 g_assert(name);
417 doc = sp_document_create(rdoc, uri, base, name, keepalive);
419 g_free(base);
420 g_free(name);
422 return doc;
423 }
425 SPDocument *
426 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
427 {
428 SPDocument *doc;
429 Inkscape::XML::Document *rdoc;
430 Inkscape::XML::Node *rroot;
431 gchar *name;
433 rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
435 /* If it cannot be loaded, return NULL without warning */
436 if (rdoc == NULL) return NULL;
438 rroot = rdoc->root();
439 /* If xml file is not svg, return NULL without warning */
440 /* fixme: destroy document */
441 if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
443 name = g_strdup_printf(_("Memory document %d"), ++doc_count);
445 doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
447 return doc;
448 }
450 SPDocument *
451 sp_document_ref(SPDocument *doc)
452 {
453 g_return_val_if_fail(doc != NULL, NULL);
454 Inkscape::GC::anchor(doc);
455 return doc;
456 }
458 SPDocument *
459 sp_document_unref(SPDocument *doc)
460 {
461 g_return_val_if_fail(doc != NULL, NULL);
462 Inkscape::GC::release(doc);
463 return NULL;
464 }
466 gdouble sp_document_width(SPDocument *document)
467 {
468 g_return_val_if_fail(document != NULL, 0.0);
469 g_return_val_if_fail(document->priv != NULL, 0.0);
470 g_return_val_if_fail(document->root != NULL, 0.0);
472 return SP_ROOT(document->root)->width.computed;
473 }
475 void
476 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
477 {
478 SPRoot *root = SP_ROOT(document->root);
480 if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
481 root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
482 } else { // set to width=
483 root->width.computed = sp_units_get_pixels (width, *unit);
484 /* SVG does not support meters as a unit, so we must translate meters to
485 * cm when writing */
486 if (!strcmp(unit->abbr, "m")) {
487 root->width.value = 100*width;
488 root->width.unit = SVGLength::CM;
489 } else {
490 root->width.value = width;
491 root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
492 }
493 }
495 SP_OBJECT (root)->updateRepr();
496 }
498 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
499 {
500 SPRoot *root = SP_ROOT(document->root);
502 if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
503 root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
504 } else { // set to height=
505 root->height.computed = sp_units_get_pixels (height, *unit);
506 /* SVG does not support meters as a unit, so we must translate meters to
507 * cm when writing */
508 if (!strcmp(unit->abbr, "m")) {
509 root->height.value = 100*height;
510 root->height.unit = SVGLength::CM;
511 } else {
512 root->height.value = height;
513 root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
514 }
515 }
517 SP_OBJECT (root)->updateRepr();
518 }
520 gdouble sp_document_height(SPDocument *document)
521 {
522 g_return_val_if_fail(document != NULL, 0.0);
523 g_return_val_if_fail(document->priv != NULL, 0.0);
524 g_return_val_if_fail(document->root != NULL, 0.0);
526 return SP_ROOT(document->root)->height.computed;
527 }
529 /**
530 * Given an NR::Rect that may, for example, correspond to the bbox of an object,
531 * this function fits the canvas to that rect by resizing the canvas
532 * and translating the document root into position.
533 */
534 void SPDocument::fitToRect(NR::Rect const &rect)
535 {
536 g_return_if_fail(!rect.isEmpty());
538 using NR::X; using NR::Y;
539 double const w = rect.extent(X);
540 double const h = rect.extent(Y);
542 double const old_height = sp_document_height(this);
543 SPUnit const &px(sp_unit_get_by_id(SP_UNIT_PX));
544 sp_document_set_width(this, w, &px);
545 sp_document_set_height(this, h, &px);
547 NR::translate const tr(NR::Point(0, (old_height - h))
548 - rect.min());
549 SP_GROUP(root)->translateChildItems(tr);
550 }
552 void sp_document_set_uri(SPDocument *document, gchar const *uri)
553 {
554 g_return_if_fail(document != NULL);
556 if (document->name) {
557 g_free(document->name);
558 document->name = NULL;
559 }
560 if (document->base) {
561 g_free(document->base);
562 document->base = NULL;
563 }
564 if (document->uri) {
565 g_free(document->uri);
566 document->uri = NULL;
567 }
569 if (uri) {
571 #ifndef WIN32
572 prepend_current_dir_if_relative(&(document->uri), uri);
573 #else
574 // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
575 document->uri = g_strdup(uri);
576 #endif
578 /* fixme: Think, what this means for images (Lauris) */
579 document->base = g_path_get_dirname(document->uri);
580 document->name = g_path_get_basename(document->uri);
582 } else {
583 document->uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
584 document->base = NULL;
585 document->name = g_strdup(document->uri);
586 }
588 // Update saveable repr attributes.
589 Inkscape::XML::Node *repr = sp_document_repr_root(document);
590 // changing uri in the document repr must not be not undoable
591 bool saved = sp_document_get_undo_sensitive(document);
592 sp_document_set_undo_sensitive(document, false);
594 repr->setAttribute("sodipodi:docname", document->name);
595 sp_document_set_undo_sensitive(document, saved);
597 document->priv->uri_set_signal.emit(document->uri);
598 }
600 void
601 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
602 {
603 g_return_if_fail(doc != NULL);
605 doc->priv->resized_signal.emit(width, height);
606 }
608 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
609 {
610 return priv->modified_signal.connect(slot);
611 }
613 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
614 {
615 return priv->uri_set_signal.connect(slot);
616 }
618 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
619 {
620 return priv->resized_signal.connect(slot);
621 }
623 sigc::connection
624 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
625 {
626 return priv->_reconstruction_start_signal.connect(slot);
627 }
629 void
630 SPDocument::emitReconstructionStart(void)
631 {
632 // printf("Starting Reconstruction\n");
633 priv->_reconstruction_start_signal.emit();
634 return;
635 }
637 sigc::connection
638 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type slot)
639 {
640 return priv->_reconstruction_finish_signal.connect(slot);
641 }
643 void
644 SPDocument::emitReconstructionFinish(void)
645 {
646 // printf("Finishing Reconstruction\n");
647 priv->_reconstruction_finish_signal.emit();
648 return;
649 }
651 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
652 {
653 return priv->commit_signal.connect(slot);
654 }
658 void SPDocument::_emitModified() {
659 static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
660 root->emitModified(0);
661 priv->modified_signal.emit(flags);
662 }
664 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
665 GQuark idq = g_quark_from_string(id);
667 if (object) {
668 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
669 g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
670 } else {
671 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
672 g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
673 }
675 SPDocumentPrivate::IDChangedSignalMap::iterator pos;
677 pos = priv->id_changed_signals.find(idq);
678 if ( pos != priv->id_changed_signals.end() ) {
679 if (!(*pos).second.empty()) {
680 (*pos).second.emit(object);
681 } else { // discard unused signal
682 priv->id_changed_signals.erase(pos);
683 }
684 }
685 }
687 void
688 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
689 {
690 this->priv->undoStackObservers.add(observer);
691 }
693 void
694 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
695 {
696 this->priv->undoStackObservers.remove(observer);
697 }
699 SPObject *SPDocument::getObjectById(gchar const *id) {
700 g_return_val_if_fail(id != NULL, NULL);
702 GQuark idq = g_quark_from_string(id);
703 return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
704 }
706 sigc::connection SPDocument::connectIdChanged(gchar const *id,
707 SPDocument::IDChangedSignal::slot_type slot)
708 {
709 return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
710 }
712 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
713 if (object) {
714 g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
715 g_hash_table_insert(priv->reprdef, repr, object);
716 } else {
717 g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
718 g_hash_table_remove(priv->reprdef, repr);
719 }
720 }
722 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
723 g_return_val_if_fail(repr != NULL, NULL);
724 return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
725 }
727 Glib::ustring SPDocument::getLanguage() {
728 gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
729 if (document_language) {
730 while (isspace(*document_language))
731 document_language++;
732 }
733 if ( !document_language || 0 == *document_language) {
734 // retrieve system language
735 document_language = getenv("LC_ALL");
736 if ( NULL == document_language || *document_language == 0 ) {
737 document_language = getenv ("LC_MESSAGES");
738 }
739 if ( NULL == document_language || *document_language == 0 ) {
740 document_language = getenv ("LANG");
741 }
743 if ( NULL != document_language ) {
744 gchar *pos = strchr(document_language, '_');
745 if ( NULL != pos ) {
746 return Glib::ustring(document_language, pos - document_language);
747 }
748 }
749 }
751 if ( NULL == document_language )
752 return Glib::ustring();
753 return document_language;
754 }
756 /* Object modification root handler */
758 void
759 sp_document_request_modified(SPDocument *doc)
760 {
761 if (!doc->modified_id) {
762 doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
763 }
764 }
766 void
767 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
768 {
769 ctx->ctx.flags = 0;
770 ctx->i2doc = NR::identity();
771 /* Set up viewport in case svg has it defined as percentages */
772 if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
773 ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
774 ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
775 ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
776 ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
777 } else { // as a last resort, set size to A4
778 ctx->vp.x0 = 0.0;
779 ctx->vp.y0 = 0.0;
780 ctx->vp.x1 = 210 * PX_PER_MM;
781 ctx->vp.y1 = 297 * PX_PER_MM;
782 }
783 ctx->i2vp = NR::identity();
784 }
786 /**
787 * Tries to update the document state based on the modified and
788 * "update required" flags, and return true if the document has
789 * been brought fully up to date.
790 */
791 bool
792 SPDocument::_updateDocument()
793 {
794 /* Process updates */
795 if (this->root->uflags || this->root->mflags) {
796 if (this->root->uflags) {
797 SPItemCtx ctx;
798 sp_document_setup_viewport (this, &ctx);
800 bool saved = sp_document_get_undo_sensitive(this);
801 sp_document_set_undo_sensitive(this, false);
803 this->root->updateDisplay((SPCtx *)&ctx, 0);
805 sp_document_set_undo_sensitive(this, saved);
806 }
807 this->_emitModified();
808 }
810 return !(this->root->uflags || this->root->mflags);
811 }
814 /**
815 * Repeatedly works on getting the document updated, since sometimes
816 * it takes more than one pass to get the document updated. But it
817 * usually should not take more than a few loops, and certainly never
818 * more than 32 iterations. So we bail out if we hit 32 iterations,
819 * since this typically indicates we're stuck in an update loop.
820 */
821 gint
822 sp_document_ensure_up_to_date(SPDocument *doc)
823 {
824 int counter = 32;
825 while (!doc->_updateDocument()) {
826 if (counter == 0) {
827 g_warning("More than 32 iteration while updating document '%s'", doc->uri);
828 break;
829 }
830 counter--;
831 }
833 if (doc->modified_id) {
834 /* Remove handler */
835 gtk_idle_remove(doc->modified_id);
836 doc->modified_id = 0;
837 }
838 return counter>0;
839 }
841 /**
842 * An idle handler to update the document. Returns true if
843 * the document needs further updates.
844 */
845 static gint
846 sp_document_idle_handler(gpointer data)
847 {
848 SPDocument *doc = static_cast<SPDocument *>(data);
849 if (doc->_updateDocument()) {
850 doc->modified_id = 0;
851 return false;
852 } else {
853 return true;
854 }
855 }
857 static bool is_within(NR::Rect const &area, NR::Rect const &box)
858 {
859 return area.contains(box);
860 }
862 static bool overlaps(NR::Rect const &area, NR::Rect const &box)
863 {
864 return area.intersects(box);
865 }
867 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, NR::Rect const &area,
868 bool (*test)(NR::Rect const &, NR::Rect const &), bool take_insensitive = false)
869 {
870 g_return_val_if_fail(SP_IS_GROUP(group), s);
872 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
873 if (!SP_IS_ITEM(o)) {
874 continue;
875 }
876 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
877 s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
878 } else {
879 SPItem *child = SP_ITEM(o);
880 NR::Maybe<NR::Rect> box = sp_item_bbox_desktop(child);
881 if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
882 s = g_slist_append(s, child);
883 }
884 }
885 }
887 return s;
888 }
890 /**
891 Returns true if an item is among the descendants of group (recursively).
892 */
893 bool item_is_in_group(SPItem *item, SPGroup *group)
894 {
895 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
896 if (!SP_IS_ITEM(o)) continue;
897 if (SP_ITEM(o) == item)
898 return true;
899 if (SP_IS_GROUP(o))
900 if (item_is_in_group(item, SP_GROUP(o)))
901 return true;
902 }
903 return false;
904 }
906 /**
907 Returns the bottommost item from the list which is at the point, or NULL if none.
908 */
909 SPItem*
910 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
911 NR::Point const p, bool take_insensitive)
912 {
913 g_return_val_if_fail(group, NULL);
915 gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
917 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
919 if (!SP_IS_ITEM(o)) continue;
921 SPItem *item = SP_ITEM(o);
922 NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
923 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
924 && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
925 if (g_slist_find((GSList *) list, item) != NULL)
926 return item;
927 }
929 if (SP_IS_GROUP(o)) {
930 SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
931 if (found)
932 return found;
933 }
935 }
936 return NULL;
937 }
939 /**
940 Returns the topmost (in z-order) item from the descendants of group (recursively) which
941 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
942 non-layer groups or not. Honors take_insensitive on whether to return insensitive
943 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
944 upwards in z-order and returns what it has found so far (i.e. the found item is
945 guaranteed to be lower than upto).
946 */
947 SPItem*
948 find_item_at_point(unsigned int dkey, SPGroup *group, NR::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
949 {
950 SPItem *seen = NULL, *newseen = NULL;
952 gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
954 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 if (upto && SP_ITEM(o) == upto)
958 break;
960 if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
961 // if nothing found yet, recurse into the group
962 newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
963 if (newseen) {
964 seen = newseen;
965 newseen = NULL;
966 }
968 if (item_is_in_group(upto, SP_GROUP(o)))
969 break;
971 } else {
972 SPItem *child = SP_ITEM(o);
973 NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
975 // seen remembers the last (topmost) of items pickable at this point
976 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
977 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
978 seen = child;
979 }
980 }
981 }
982 return seen;
983 }
985 /**
986 Returns the topmost non-layer group from the descendants of group which is at point
987 p, or NULL if none. Recurses into layers but not into groups.
988 */
989 SPItem*
990 find_group_at_point(unsigned int dkey, SPGroup *group, NR::Point const p)
991 {
992 SPItem *seen = NULL;
994 gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
996 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
997 if (!SP_IS_ITEM(o)) continue;
998 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
999 SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1000 if (newseen) {
1001 seen = newseen;
1002 }
1003 }
1004 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1005 SPItem *child = SP_ITEM(o);
1006 NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1008 // seen remembers the last (topmost) of groups pickable at this point
1009 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1010 seen = child;
1011 }
1012 }
1013 }
1014 return seen;
1015 }
1017 /*
1018 * Return list of items, contained in box
1019 *
1020 * Assumes box is normalized (and g_asserts it!)
1021 *
1022 */
1024 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
1025 {
1026 g_return_val_if_fail(document != NULL, NULL);
1027 g_return_val_if_fail(document->priv != NULL, NULL);
1029 return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
1030 }
1032 /*
1033 * Return list of items, that the parts of the item contained in box
1034 *
1035 * Assumes box is normalized (and g_asserts it!)
1036 *
1037 */
1039 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
1040 {
1041 g_return_val_if_fail(document != NULL, NULL);
1042 g_return_val_if_fail(document->priv != NULL, NULL);
1044 return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1045 }
1047 GSList *
1048 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<NR::Point> points)
1049 {
1050 GSList *items = NULL;
1052 // When picking along the path, we don't want small objects close together
1053 // (such as hatching strokes) to obscure each other by their deltas,
1054 // so we temporarily set delta to a small value
1055 gdouble saved_delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
1056 prefs_set_double_attribute ("options.cursortolerance", "value", 0.25);
1058 for(unsigned int i = 0; i < points.size(); i++) {
1059 SPItem *item = sp_document_item_at_point(document, key, points[i],
1060 false, NULL);
1061 if (item && !g_slist_find(items, item))
1062 items = g_slist_prepend (items, item);
1063 }
1065 // and now we restore it back
1066 prefs_set_double_attribute ("options.cursortolerance", "value", saved_delta);
1068 return items;
1069 }
1071 SPItem *
1072 sp_document_item_at_point(SPDocument *document, unsigned const key, NR::Point const p,
1073 gboolean const into_groups, SPItem *upto)
1074 {
1075 g_return_val_if_fail(document != NULL, NULL);
1076 g_return_val_if_fail(document->priv != NULL, NULL);
1078 return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1079 }
1081 SPItem*
1082 sp_document_group_at_point(SPDocument *document, unsigned int key, NR::Point const p)
1083 {
1084 g_return_val_if_fail(document != NULL, NULL);
1085 g_return_val_if_fail(document->priv != NULL, NULL);
1087 return find_group_at_point(key, SP_GROUP(document->root), p);
1088 }
1091 /* Resource management */
1093 gboolean
1094 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1095 {
1096 GSList *rlist;
1097 GQuark q = g_quark_from_string(key);
1099 g_return_val_if_fail(document != NULL, FALSE);
1100 g_return_val_if_fail(key != NULL, FALSE);
1101 g_return_val_if_fail(*key != '\0', FALSE);
1102 g_return_val_if_fail(object != NULL, FALSE);
1103 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1105 if (SP_OBJECT_IS_CLONED(object))
1106 return FALSE;
1108 rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1109 g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1110 rlist = g_slist_prepend(rlist, object);
1111 g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1113 document->priv->resources_changed_signals[q].emit();
1115 return TRUE;
1116 }
1118 gboolean
1119 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1120 {
1121 GSList *rlist;
1122 GQuark q = g_quark_from_string(key);
1124 g_return_val_if_fail(document != NULL, FALSE);
1125 g_return_val_if_fail(key != NULL, FALSE);
1126 g_return_val_if_fail(*key != '\0', FALSE);
1127 g_return_val_if_fail(object != NULL, FALSE);
1128 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1130 if (SP_OBJECT_IS_CLONED(object))
1131 return FALSE;
1133 rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1134 g_return_val_if_fail(rlist != NULL, FALSE);
1135 g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1136 rlist = g_slist_remove(rlist, object);
1137 g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1139 document->priv->resources_changed_signals[q].emit();
1141 return TRUE;
1142 }
1144 GSList const *
1145 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1146 {
1147 g_return_val_if_fail(document != NULL, NULL);
1148 g_return_val_if_fail(key != NULL, NULL);
1149 g_return_val_if_fail(*key != '\0', NULL);
1151 return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1152 }
1154 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1155 gchar const *key,
1156 SPDocument::ResourcesChangedSignal::slot_type slot)
1157 {
1158 GQuark q = g_quark_from_string(key);
1159 return document->priv->resources_changed_signals[q].connect(slot);
1160 }
1162 /* Helpers */
1164 gboolean
1165 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1166 {
1167 g_slist_free((GSList *) value);
1168 return TRUE;
1169 }
1171 unsigned int
1172 count_objects_recursive(SPObject *obj, unsigned int count)
1173 {
1174 count++; // obj itself
1176 for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1177 count = count_objects_recursive(i, count);
1178 }
1180 return count;
1181 }
1183 unsigned int
1184 objects_in_document(SPDocument *document)
1185 {
1186 return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1187 }
1189 void
1190 vacuum_document_recursive(SPObject *obj)
1191 {
1192 if (SP_IS_DEFS(obj)) {
1193 for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1194 /* fixme: some inkscape-internal nodes in the future might not be collectable */
1195 def->requestOrphanCollection();
1196 }
1197 } else {
1198 for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1199 vacuum_document_recursive(i);
1200 }
1201 }
1202 }
1204 unsigned int
1205 vacuum_document(SPDocument *document)
1206 {
1207 unsigned int start = objects_in_document(document);
1208 unsigned int end;
1209 unsigned int newend = start;
1211 unsigned int iterations = 0;
1213 do {
1214 end = newend;
1216 vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1217 document->collectOrphans();
1218 iterations++;
1220 newend = objects_in_document(document);
1222 } while (iterations < 100 && newend < end);
1224 return start - newend;
1225 }
1227 bool SPDocument::isSeeking() const {
1228 return priv->seeking;
1229 }
1232 /*
1233 Local Variables:
1234 mode:c++
1235 c-file-style:"stroustrup"
1236 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1237 indent-tabs-mode:nil
1238 fill-column:99
1239 End:
1240 */
1241 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :