1 #define __SP_DOCUMENT_C__
3 /** \file
4 * SPDocument manipulation
5 *
6 * Authors:
7 * Lauris Kaplinski <lauris@kaplinski.com>
8 * MenTaLguY <mental@rydia.net>
9 * bulia byak <buliabyak@users.sf.net>
10 *
11 * Copyright (C) 2004-2005 MenTaLguY
12 * Copyright (C) 1999-2002 Lauris Kaplinski
13 * Copyright (C) 2000-2001 Ximian, Inc.
14 *
15 * Released under GNU GPL, read the file 'COPYING' for more information
16 */
18 /** \class SPDocument
19 * SPDocument serves as the container of both model trees (agnostic XML
20 * and typed object tree), and implements all of the document-level
21 * functionality used by the program. Many document level operations, like
22 * load, save, print, export and so on, use SPDocument as their basic datatype.
23 *
24 * SPDocument implements undo and redo stacks and an id-based object
25 * dictionary. Thanks to unique id attributes, the latter can be used to
26 * map from the XML tree back to the object tree.
27 *
28 * SPDocument performs the basic operations needed for asynchronous
29 * update notification (SPObject ::modified virtual method), and implements
30 * the 'modified' signal, as well.
31 */
34 #define noSP_DOCUMENT_DEBUG_IDLE
35 #define noSP_DOCUMENT_DEBUG_UNDO
37 #ifdef HAVE_CONFIG_H
38 # include "config.h"
39 #endif
40 #include <gtk/gtkmain.h>
41 #include <string>
42 #include <cstring>
43 #include "application/application.h"
44 #include "application/editor.h"
45 #include "libnr/nr-matrix-fns.h"
46 #include "xml/repr.h"
47 #include "helper/units.h"
48 #include "inkscape-private.h"
49 #include "inkscape_version.h"
50 #include "sp-object-repr.h"
51 #include "document-private.h"
52 #include "dir-util.h"
53 #include "unit-constants.h"
54 #include "prefs-utils.h"
55 #include "libavoid/router.h"
56 #include "libnr/nr-rect.h"
57 #include "sp-item-group.h"
58 #include "profile-manager.h"
59 #include "persp3d.h"
61 #include "display/nr-arena-item.h"
63 #include "dialogs/rdf.h"
65 #include "transf_mat_3x4.h"
67 #define A4_WIDTH_STR "210mm"
68 #define A4_HEIGHT_STR "297mm"
70 #define SP_DOCUMENT_UPDATE_PRIORITY (G_PRIORITY_HIGH_IDLE - 1)
73 static gint sp_document_idle_handler(gpointer data);
75 gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data);
77 static gint doc_count = 0;
79 static unsigned long next_serial = 0;
81 SPDocument::SPDocument() {
82 SPDocumentPrivate *p;
84 keepalive = FALSE;
85 virgin = TRUE;
87 modified_id = 0;
89 rdoc = NULL;
90 rroot = NULL;
91 root = NULL;
92 style_cascade = cr_cascade_new(NULL, NULL, NULL);
94 uri = NULL;
95 base = NULL;
96 name = NULL;
98 _collection_queue = NULL;
100 // Initialise instance of connector router.
101 router = new Avoid::Router();
102 // Don't use the Consolidate moves optimisation.
103 router->ConsolidateMoves = false;
105 perspectives = NULL;
107 p = new SPDocumentPrivate();
109 p->serial = next_serial++;
111 p->iddef = g_hash_table_new(g_direct_hash, g_direct_equal);
112 p->reprdef = g_hash_table_new(g_direct_hash, g_direct_equal);
114 p->resources = g_hash_table_new(g_str_hash, g_str_equal);
116 p->sensitive = FALSE;
117 p->partial = NULL;
118 p->history_size = 0;
119 p->undo = NULL;
120 p->redo = NULL;
121 p->seeking = false;
123 priv = p;
125 // Once things are set, hook in the manager
126 profileManager = new Inkscape::ProfileManager(this);
128 // XXX only for testing!
129 priv->undoStackObservers.add(p->console_output_undo_observer);
130 }
132 SPDocument::~SPDocument() {
133 collectOrphans();
135 // kill/unhook this first
136 if ( profileManager ) {
137 delete profileManager;
138 profileManager = 0;
139 }
141 if (priv) {
142 if (priv->partial) {
143 sp_repr_free_log(priv->partial);
144 priv->partial = NULL;
145 }
147 sp_document_clear_redo(this);
148 sp_document_clear_undo(this);
150 if (root) {
151 root->releaseReferences();
152 sp_object_unref(root);
153 root = NULL;
154 }
156 if (priv->iddef) g_hash_table_destroy(priv->iddef);
157 if (priv->reprdef) g_hash_table_destroy(priv->reprdef);
159 if (rdoc) Inkscape::GC::release(rdoc);
161 /* Free resources */
162 g_hash_table_foreach_remove(priv->resources, sp_document_resource_list_free, this);
163 g_hash_table_destroy(priv->resources);
165 delete priv;
166 priv = NULL;
167 }
169 cr_cascade_unref(style_cascade);
170 style_cascade = NULL;
172 if (name) {
173 g_free(name);
174 name = NULL;
175 }
176 if (base) {
177 g_free(base);
178 base = NULL;
179 }
180 if (uri) {
181 g_free(uri);
182 uri = NULL;
183 }
185 if (modified_id) {
186 gtk_idle_remove(modified_id);
187 modified_id = 0;
188 }
190 _selection_changed_connection.disconnect();
191 _desktop_activated_connection.disconnect();
193 if (keepalive) {
194 inkscape_unref();
195 keepalive = FALSE;
196 }
198 if (router) {
199 delete router;
200 router = NULL;
201 }
203 //delete this->_whiteboard_session_manager;
205 }
207 void SPDocument::add_persp3d (Persp3D * const /*persp*/)
208 {
209 SPDefs *defs = SP_ROOT(this->root)->defs;
210 for (SPObject *i = sp_object_first_child(SP_OBJECT(defs)); i != NULL; i = SP_OBJECT_NEXT(i) ) {
211 if (SP_IS_PERSP3D(i)) {
212 g_print ("Encountered a Persp3D in defs\n");
213 }
214 }
216 g_print ("Adding Persp3D to defs\n");
217 persp3d_create_xml_element (this);
218 }
220 void SPDocument::remove_persp3d (Persp3D * const /*persp*/)
221 {
222 // TODO: Delete the repr, maybe perform a check if any boxes are still linked to the perspective.
223 // Anything else?
224 g_print ("Please implement deletion of perspectives here.\n");
225 }
227 unsigned long SPDocument::serial() const {
228 return priv->serial;
229 }
231 void SPDocument::queueForOrphanCollection(SPObject *object) {
232 g_return_if_fail(object != NULL);
233 g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
235 sp_object_ref(object, NULL);
236 _collection_queue = g_slist_prepend(_collection_queue, object);
237 }
239 void SPDocument::collectOrphans() {
240 while (_collection_queue) {
241 GSList *objects=_collection_queue;
242 _collection_queue = NULL;
243 for ( GSList *iter=objects ; iter ; iter = iter->next ) {
244 SPObject *object=reinterpret_cast<SPObject *>(iter->data);
245 object->collectOrphan();
246 sp_object_unref(object, NULL);
247 }
248 g_slist_free(objects);
249 }
250 }
252 void SPDocument::reset_key (void */*dummy*/)
253 {
254 actionkey = NULL;
255 }
257 SPDocument *
258 sp_document_create(Inkscape::XML::Document *rdoc,
259 gchar const *uri,
260 gchar const *base,
261 gchar const *name,
262 unsigned int keepalive)
263 {
264 SPDocument *document;
265 Inkscape::XML::Node *rroot;
266 Inkscape::Version sodipodi_version;
268 rroot = rdoc->root();
270 document = new SPDocument();
272 document->keepalive = keepalive;
274 document->rdoc = rdoc;
275 document->rroot = rroot;
277 #ifndef WIN32
278 prepend_current_dir_if_relative(&(document->uri), uri);
279 #else
280 // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
281 document->uri = uri? g_strdup(uri) : NULL;
282 #endif
284 // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
285 // which is why we use g_get_current_dir() in calculating the abs path above
286 //This is NULL for a new document
287 if (base)
288 document->base = g_strdup(base);
289 else
290 document->base = NULL;
291 document->name = g_strdup(name);
293 document->root = sp_object_repr_build_tree(document, rroot);
295 sodipodi_version = SP_ROOT(document->root)->version.sodipodi;
297 /* fixme: Not sure about this, but lets assume ::build updates */
298 rroot->setAttribute("sodipodi:version", SODIPODI_VERSION);
299 rroot->setAttribute("inkscape:version", INKSCAPE_VERSION);
300 /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
302 /* Quick hack 2 - get default image size into document */
303 if (!rroot->attribute("width")) rroot->setAttribute("width", A4_WIDTH_STR);
304 if (!rroot->attribute("height")) rroot->setAttribute("height", A4_HEIGHT_STR);
305 /* End of quick hack 2 */
307 /* Quick hack 3 - Set uri attributes */
308 if (uri) {
309 rroot->setAttribute("sodipodi:docname", uri);
310 }
311 /* End of quick hack 3 */
313 // creating namedview
314 if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
315 // if there's none in the document already,
316 Inkscape::XML::Node *r = NULL;
317 Inkscape::XML::Node *rnew = NULL;
318 r = inkscape_get_repr(INKSCAPE, "template.base");
319 // see if there's a template with id="base" in the preferences
320 if (!r) {
321 // if there's none, create an empty element
322 rnew = rdoc->createElement("sodipodi:namedview");
323 rnew->setAttribute("id", "base");
324 } else {
325 // otherwise, take from preferences
326 rnew = r->duplicate(rroot->document());
327 }
328 // insert into the document
329 rroot->addChild(rnew, NULL);
330 // clean up
331 Inkscape::GC::release(rnew);
332 }
334 /* Defs */
335 if (!SP_ROOT(document->root)->defs) {
336 Inkscape::XML::Node *r;
337 r = rdoc->createElement("svg:defs");
338 rroot->addChild(r, NULL);
339 Inkscape::GC::release(r);
340 g_assert(SP_ROOT(document->root)->defs);
341 }
343 /* Default RDF */
344 rdf_set_defaults( document );
346 if (keepalive) {
347 inkscape_ref();
348 }
350 // Remark: Here, we used to create a "currentpersp3d" element in the document defs.
351 // But this is probably a bad idea since we need to adapt it for every change of selection, which will
352 // completely clutter the undo history. Maybe rather save it to prefs on exit and re-read it on startup?
354 document->current_persp3d = persp3d_document_first_persp(document);
355 if (!document->current_persp3d) {
356 document->current_persp3d = persp3d_create_xml_element (document);
357 }
359 sp_document_set_undo_sensitive(document, true);
361 // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
362 if (!Inkscape::NSApplication::Application::getNewGui()) {
363 g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
364 G_CALLBACK(sp_document_reset_key), document);
365 g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
366 G_CALLBACK(sp_document_reset_key), document);
367 } else {
368 document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
369 document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
370 }
372 return document;
373 }
375 /**
376 * Fetches document from URI, or creates new, if NULL; public document
377 * appears in document list.
378 */
379 SPDocument *
380 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
381 {
382 SPDocument *doc;
383 Inkscape::XML::Document *rdoc;
384 gchar *base = NULL;
385 gchar *name = NULL;
387 if (uri) {
388 Inkscape::XML::Node *rroot;
389 gchar *s, *p;
390 /* Try to fetch repr from file */
391 rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
392 /* If file cannot be loaded, return NULL without warning */
393 if (rdoc == NULL) return NULL;
394 rroot = rdoc->root();
395 /* If xml file is not svg, return NULL without warning */
396 /* fixme: destroy document */
397 if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
398 s = g_strdup(uri);
399 p = strrchr(s, '/');
400 if (p) {
401 name = g_strdup(p + 1);
402 p[1] = '\0';
403 base = g_strdup(s);
404 } else {
405 base = NULL;
406 name = g_strdup(uri);
407 }
408 g_free(s);
409 } else {
410 rdoc = sp_repr_document_new("svg:svg");
411 }
413 if (make_new) {
414 base = NULL;
415 uri = NULL;
416 name = g_strdup_printf(_("New document %d"), ++doc_count);
417 }
419 //# These should be set by now
420 g_assert(name);
422 doc = sp_document_create(rdoc, uri, base, name, keepalive);
424 g_free(base);
425 g_free(name);
427 return doc;
428 }
430 SPDocument *
431 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
432 {
433 SPDocument *doc;
434 Inkscape::XML::Document *rdoc;
435 Inkscape::XML::Node *rroot;
436 gchar *name;
438 rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
440 /* If it cannot be loaded, return NULL without warning */
441 if (rdoc == NULL) return NULL;
443 rroot = rdoc->root();
444 /* If xml file is not svg, return NULL without warning */
445 /* fixme: destroy document */
446 if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
448 name = g_strdup_printf(_("Memory document %d"), ++doc_count);
450 doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
452 return doc;
453 }
455 SPDocument *
456 sp_document_ref(SPDocument *doc)
457 {
458 g_return_val_if_fail(doc != NULL, NULL);
459 Inkscape::GC::anchor(doc);
460 return doc;
461 }
463 SPDocument *
464 sp_document_unref(SPDocument *doc)
465 {
466 g_return_val_if_fail(doc != NULL, NULL);
467 Inkscape::GC::release(doc);
468 return NULL;
469 }
471 gdouble sp_document_width(SPDocument *document)
472 {
473 g_return_val_if_fail(document != NULL, 0.0);
474 g_return_val_if_fail(document->priv != NULL, 0.0);
475 g_return_val_if_fail(document->root != NULL, 0.0);
477 return SP_ROOT(document->root)->width.computed;
478 }
480 void
481 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
482 {
483 SPRoot *root = SP_ROOT(document->root);
485 if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
486 root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
487 } else { // set to width=
488 root->width.computed = sp_units_get_pixels (width, *unit);
489 /* SVG does not support meters as a unit, so we must translate meters to
490 * cm when writing */
491 if (!strcmp(unit->abbr, "m")) {
492 root->width.value = 100*width;
493 root->width.unit = SVGLength::CM;
494 } else {
495 root->width.value = width;
496 root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
497 }
498 }
500 SP_OBJECT (root)->updateRepr();
501 }
503 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
504 {
505 SPRoot *root = SP_ROOT(document->root);
507 if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
508 root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
509 } else { // set to height=
510 root->height.computed = sp_units_get_pixels (height, *unit);
511 /* SVG does not support meters as a unit, so we must translate meters to
512 * cm when writing */
513 if (!strcmp(unit->abbr, "m")) {
514 root->height.value = 100*height;
515 root->height.unit = SVGLength::CM;
516 } else {
517 root->height.value = height;
518 root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
519 }
520 }
522 SP_OBJECT (root)->updateRepr();
523 }
525 gdouble sp_document_height(SPDocument *document)
526 {
527 g_return_val_if_fail(document != NULL, 0.0);
528 g_return_val_if_fail(document->priv != NULL, 0.0);
529 g_return_val_if_fail(document->root != NULL, 0.0);
531 return SP_ROOT(document->root)->height.computed;
532 }
534 /**
535 * Given an NR::Rect that may, for example, correspond to the bbox of an object,
536 * this function fits the canvas to that rect by resizing the canvas
537 * and translating the document root into position.
538 */
539 void SPDocument::fitToRect(NR::Rect const &rect)
540 {
541 g_return_if_fail(!rect.isEmpty());
543 using NR::X; using NR::Y;
544 double const w = rect.extent(X);
545 double const h = rect.extent(Y);
547 double const old_height = sp_document_height(this);
548 SPUnit const &px(sp_unit_get_by_id(SP_UNIT_PX));
549 sp_document_set_width(this, w, &px);
550 sp_document_set_height(this, h, &px);
552 NR::translate const tr(NR::Point(0, (old_height - h))
553 - rect.min());
554 SP_GROUP(root)->translateChildItems(tr);
555 }
557 void sp_document_set_uri(SPDocument *document, gchar const *uri)
558 {
559 g_return_if_fail(document != NULL);
561 if (document->name) {
562 g_free(document->name);
563 document->name = NULL;
564 }
565 if (document->base) {
566 g_free(document->base);
567 document->base = NULL;
568 }
569 if (document->uri) {
570 g_free(document->uri);
571 document->uri = NULL;
572 }
574 if (uri) {
576 #ifndef WIN32
577 prepend_current_dir_if_relative(&(document->uri), uri);
578 #else
579 // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
580 document->uri = g_strdup(uri);
581 #endif
583 /* fixme: Think, what this means for images (Lauris) */
584 document->base = g_path_get_dirname(document->uri);
585 document->name = g_path_get_basename(document->uri);
587 } else {
588 document->uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
589 document->base = NULL;
590 document->name = g_strdup(document->uri);
591 }
593 // Update saveable repr attributes.
594 Inkscape::XML::Node *repr = sp_document_repr_root(document);
595 // changing uri in the document repr must not be not undoable
596 bool saved = sp_document_get_undo_sensitive(document);
597 sp_document_set_undo_sensitive(document, false);
599 repr->setAttribute("sodipodi:docname", document->name);
600 sp_document_set_undo_sensitive(document, saved);
602 document->priv->uri_set_signal.emit(document->uri);
603 }
605 void
606 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
607 {
608 g_return_if_fail(doc != NULL);
610 doc->priv->resized_signal.emit(width, height);
611 }
613 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
614 {
615 return priv->modified_signal.connect(slot);
616 }
618 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
619 {
620 return priv->uri_set_signal.connect(slot);
621 }
623 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
624 {
625 return priv->resized_signal.connect(slot);
626 }
628 sigc::connection
629 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
630 {
631 return priv->_reconstruction_start_signal.connect(slot);
632 }
634 void
635 SPDocument::emitReconstructionStart(void)
636 {
637 // printf("Starting Reconstruction\n");
638 priv->_reconstruction_start_signal.emit();
639 return;
640 }
642 sigc::connection
643 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type slot)
644 {
645 return priv->_reconstruction_finish_signal.connect(slot);
646 }
648 void
649 SPDocument::emitReconstructionFinish(void)
650 {
651 // printf("Finishing Reconstruction\n");
652 priv->_reconstruction_finish_signal.emit();
653 return;
654 }
656 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
657 {
658 return priv->commit_signal.connect(slot);
659 }
663 void SPDocument::_emitModified() {
664 static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
665 root->emitModified(0);
666 priv->modified_signal.emit(flags);
667 }
669 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
670 GQuark idq = g_quark_from_string(id);
672 if (object) {
673 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
674 g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
675 } else {
676 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
677 g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
678 }
680 SPDocumentPrivate::IDChangedSignalMap::iterator pos;
682 pos = priv->id_changed_signals.find(idq);
683 if ( pos != priv->id_changed_signals.end() ) {
684 if (!(*pos).second.empty()) {
685 (*pos).second.emit(object);
686 } else { // discard unused signal
687 priv->id_changed_signals.erase(pos);
688 }
689 }
690 }
692 void
693 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
694 {
695 this->priv->undoStackObservers.add(observer);
696 }
698 void
699 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
700 {
701 this->priv->undoStackObservers.remove(observer);
702 }
704 SPObject *SPDocument::getObjectById(gchar const *id) {
705 g_return_val_if_fail(id != NULL, NULL);
707 GQuark idq = g_quark_from_string(id);
708 return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
709 }
711 sigc::connection SPDocument::connectIdChanged(gchar const *id,
712 SPDocument::IDChangedSignal::slot_type slot)
713 {
714 return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
715 }
717 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
718 if (object) {
719 g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
720 g_hash_table_insert(priv->reprdef, repr, object);
721 } else {
722 g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
723 g_hash_table_remove(priv->reprdef, repr);
724 }
725 }
727 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
728 g_return_val_if_fail(repr != NULL, NULL);
729 return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
730 }
732 Glib::ustring SPDocument::getLanguage() {
733 gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
734 if (document_language) {
735 while (isspace(*document_language))
736 document_language++;
737 }
738 if ( !document_language || 0 == *document_language) {
739 // retrieve system language
740 document_language = getenv("LC_ALL");
741 if ( NULL == document_language || *document_language == 0 ) {
742 document_language = getenv ("LC_MESSAGES");
743 }
744 if ( NULL == document_language || *document_language == 0 ) {
745 document_language = getenv ("LANG");
746 }
748 if ( NULL != document_language ) {
749 gchar *pos = strchr(document_language, '_');
750 if ( NULL != pos ) {
751 return Glib::ustring(document_language, pos - document_language);
752 }
753 }
754 }
756 if ( NULL == document_language )
757 return Glib::ustring();
758 return document_language;
759 }
761 /* Object modification root handler */
763 void
764 sp_document_request_modified(SPDocument *doc)
765 {
766 if (!doc->modified_id) {
767 doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
768 }
769 }
771 void
772 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
773 {
774 ctx->ctx.flags = 0;
775 ctx->i2doc = NR::identity();
776 /* Set up viewport in case svg has it defined as percentages */
777 if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
778 ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
779 ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
780 ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
781 ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
782 } else { // as a last resort, set size to A4
783 ctx->vp.x0 = 0.0;
784 ctx->vp.y0 = 0.0;
785 ctx->vp.x1 = 210 * PX_PER_MM;
786 ctx->vp.y1 = 297 * PX_PER_MM;
787 }
788 ctx->i2vp = NR::identity();
789 }
791 /**
792 * Tries to update the document state based on the modified and
793 * "update required" flags, and return true if the document has
794 * been brought fully up to date.
795 */
796 bool
797 SPDocument::_updateDocument()
798 {
799 /* Process updates */
800 if (this->root->uflags || this->root->mflags) {
801 if (this->root->uflags) {
802 SPItemCtx ctx;
803 sp_document_setup_viewport (this, &ctx);
805 bool saved = sp_document_get_undo_sensitive(this);
806 sp_document_set_undo_sensitive(this, false);
808 this->root->updateDisplay((SPCtx *)&ctx, 0);
810 sp_document_set_undo_sensitive(this, saved);
811 }
812 this->_emitModified();
813 }
815 return !(this->root->uflags || this->root->mflags);
816 }
819 /**
820 * Repeatedly works on getting the document updated, since sometimes
821 * it takes more than one pass to get the document updated. But it
822 * usually should not take more than a few loops, and certainly never
823 * more than 32 iterations. So we bail out if we hit 32 iterations,
824 * since this typically indicates we're stuck in an update loop.
825 */
826 gint
827 sp_document_ensure_up_to_date(SPDocument *doc)
828 {
829 int counter = 32;
830 while (!doc->_updateDocument()) {
831 if (counter == 0) {
832 g_warning("More than 32 iteration while updating document '%s'", doc->uri);
833 break;
834 }
835 counter--;
836 }
838 if (doc->modified_id) {
839 /* Remove handler */
840 gtk_idle_remove(doc->modified_id);
841 doc->modified_id = 0;
842 }
843 return counter>0;
844 }
846 /**
847 * An idle handler to update the document. Returns true if
848 * the document needs further updates.
849 */
850 static gint
851 sp_document_idle_handler(gpointer data)
852 {
853 SPDocument *doc = static_cast<SPDocument *>(data);
854 if (doc->_updateDocument()) {
855 doc->modified_id = 0;
856 return false;
857 } else {
858 return true;
859 }
860 }
862 static bool is_within(NR::Rect const &area, NR::Rect const &box)
863 {
864 return area.contains(box);
865 }
867 static bool overlaps(NR::Rect const &area, NR::Rect const &box)
868 {
869 return area.intersects(box);
870 }
872 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, NR::Rect const &area,
873 bool (*test)(NR::Rect const &, NR::Rect const &), bool take_insensitive = false)
874 {
875 g_return_val_if_fail(SP_IS_GROUP(group), s);
877 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
878 if (!SP_IS_ITEM(o)) {
879 continue;
880 }
881 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
882 s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
883 } else {
884 SPItem *child = SP_ITEM(o);
885 NR::Maybe<NR::Rect> box = sp_item_bbox_desktop(child);
886 if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
887 s = g_slist_append(s, child);
888 }
889 }
890 }
892 return s;
893 }
895 /**
896 Returns true if an item is among the descendants of group (recursively).
897 */
898 bool item_is_in_group(SPItem *item, SPGroup *group)
899 {
900 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
901 if (!SP_IS_ITEM(o)) continue;
902 if (SP_ITEM(o) == item)
903 return true;
904 if (SP_IS_GROUP(o))
905 if (item_is_in_group(item, SP_GROUP(o)))
906 return true;
907 }
908 return false;
909 }
911 /**
912 Returns the bottommost item from the list which is at the point, or NULL if none.
913 */
914 SPItem*
915 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
916 NR::Point const p, bool take_insensitive)
917 {
918 g_return_val_if_fail(group, NULL);
920 gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
922 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
924 if (!SP_IS_ITEM(o)) continue;
926 SPItem *item = SP_ITEM(o);
927 NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
928 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
929 && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
930 if (g_slist_find((GSList *) list, item) != NULL)
931 return item;
932 }
934 if (SP_IS_GROUP(o)) {
935 SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
936 if (found)
937 return found;
938 }
940 }
941 return NULL;
942 }
944 /**
945 Returns the topmost (in z-order) item from the descendants of group (recursively) which
946 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
947 non-layer groups or not. Honors take_insensitive on whether to return insensitive
948 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
949 upwards in z-order and returns what it has found so far (i.e. the found item is
950 guaranteed to be lower than upto).
951 */
952 SPItem*
953 find_item_at_point(unsigned int dkey, SPGroup *group, NR::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
954 {
955 SPItem *seen = NULL, *newseen = NULL;
957 gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
959 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
960 if (!SP_IS_ITEM(o)) continue;
962 if (upto && SP_ITEM(o) == upto)
963 break;
965 if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
966 // if nothing found yet, recurse into the group
967 newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
968 if (newseen) {
969 seen = newseen;
970 newseen = NULL;
971 }
973 if (item_is_in_group(upto, SP_GROUP(o)))
974 break;
976 } else {
977 SPItem *child = SP_ITEM(o);
978 NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
980 // seen remembers the last (topmost) of items pickable at this point
981 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
982 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
983 seen = child;
984 }
985 }
986 }
987 return seen;
988 }
990 /**
991 Returns the topmost non-layer group from the descendants of group which is at point
992 p, or NULL if none. Recurses into layers but not into groups.
993 */
994 SPItem*
995 find_group_at_point(unsigned int dkey, SPGroup *group, NR::Point const p)
996 {
997 SPItem *seen = NULL;
999 gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
1001 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1002 if (!SP_IS_ITEM(o)) continue;
1003 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1004 SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1005 if (newseen) {
1006 seen = newseen;
1007 }
1008 }
1009 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1010 SPItem *child = SP_ITEM(o);
1011 NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1013 // seen remembers the last (topmost) of groups pickable at this point
1014 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1015 seen = child;
1016 }
1017 }
1018 }
1019 return seen;
1020 }
1022 /*
1023 * Return list of items, contained in box
1024 *
1025 * Assumes box is normalized (and g_asserts it!)
1026 *
1027 */
1029 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
1030 {
1031 g_return_val_if_fail(document != NULL, NULL);
1032 g_return_val_if_fail(document->priv != NULL, NULL);
1034 return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
1035 }
1037 /*
1038 * Return list of items, that the parts of the item contained in box
1039 *
1040 * Assumes box is normalized (and g_asserts it!)
1041 *
1042 */
1044 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
1045 {
1046 g_return_val_if_fail(document != NULL, NULL);
1047 g_return_val_if_fail(document->priv != NULL, NULL);
1049 return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1050 }
1052 GSList *
1053 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<NR::Point> points)
1054 {
1055 GSList *items = NULL;
1057 // When picking along the path, we don't want small objects close together
1058 // (such as hatching strokes) to obscure each other by their deltas,
1059 // so we temporarily set delta to a small value
1060 gdouble saved_delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
1061 prefs_set_double_attribute ("options.cursortolerance", "value", 0.25);
1063 for(unsigned int i = 0; i < points.size(); i++) {
1064 SPItem *item = sp_document_item_at_point(document, key, points[i],
1065 false, NULL);
1066 if (item && !g_slist_find(items, item))
1067 items = g_slist_prepend (items, item);
1068 }
1070 // and now we restore it back
1071 prefs_set_double_attribute ("options.cursortolerance", "value", saved_delta);
1073 return items;
1074 }
1076 SPItem *
1077 sp_document_item_at_point(SPDocument *document, unsigned const key, NR::Point const p,
1078 gboolean const into_groups, SPItem *upto)
1079 {
1080 g_return_val_if_fail(document != NULL, NULL);
1081 g_return_val_if_fail(document->priv != NULL, NULL);
1083 return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1084 }
1086 SPItem*
1087 sp_document_group_at_point(SPDocument *document, unsigned int key, NR::Point const p)
1088 {
1089 g_return_val_if_fail(document != NULL, NULL);
1090 g_return_val_if_fail(document->priv != NULL, NULL);
1092 return find_group_at_point(key, SP_GROUP(document->root), p);
1093 }
1096 /* Resource management */
1098 gboolean
1099 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1100 {
1101 GSList *rlist;
1102 GQuark q = g_quark_from_string(key);
1104 g_return_val_if_fail(document != NULL, FALSE);
1105 g_return_val_if_fail(key != NULL, FALSE);
1106 g_return_val_if_fail(*key != '\0', FALSE);
1107 g_return_val_if_fail(object != NULL, FALSE);
1108 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1110 if (SP_OBJECT_IS_CLONED(object))
1111 return FALSE;
1113 rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1114 g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1115 rlist = g_slist_prepend(rlist, object);
1116 g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1118 document->priv->resources_changed_signals[q].emit();
1120 return TRUE;
1121 }
1123 gboolean
1124 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1125 {
1126 GSList *rlist;
1127 GQuark q = g_quark_from_string(key);
1129 g_return_val_if_fail(document != NULL, FALSE);
1130 g_return_val_if_fail(key != NULL, FALSE);
1131 g_return_val_if_fail(*key != '\0', FALSE);
1132 g_return_val_if_fail(object != NULL, FALSE);
1133 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1135 if (SP_OBJECT_IS_CLONED(object))
1136 return FALSE;
1138 rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1139 g_return_val_if_fail(rlist != NULL, FALSE);
1140 g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1141 rlist = g_slist_remove(rlist, object);
1142 g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1144 document->priv->resources_changed_signals[q].emit();
1146 return TRUE;
1147 }
1149 GSList const *
1150 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1151 {
1152 g_return_val_if_fail(document != NULL, NULL);
1153 g_return_val_if_fail(key != NULL, NULL);
1154 g_return_val_if_fail(*key != '\0', NULL);
1156 return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1157 }
1159 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1160 gchar const *key,
1161 SPDocument::ResourcesChangedSignal::slot_type slot)
1162 {
1163 GQuark q = g_quark_from_string(key);
1164 return document->priv->resources_changed_signals[q].connect(slot);
1165 }
1167 /* Helpers */
1169 gboolean
1170 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1171 {
1172 g_slist_free((GSList *) value);
1173 return TRUE;
1174 }
1176 unsigned int
1177 count_objects_recursive(SPObject *obj, unsigned int count)
1178 {
1179 count++; // obj itself
1181 for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1182 count = count_objects_recursive(i, count);
1183 }
1185 return count;
1186 }
1188 unsigned int
1189 objects_in_document(SPDocument *document)
1190 {
1191 return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1192 }
1194 void
1195 vacuum_document_recursive(SPObject *obj)
1196 {
1197 if (SP_IS_DEFS(obj)) {
1198 for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1199 /* fixme: some inkscape-internal nodes in the future might not be collectable */
1200 def->requestOrphanCollection();
1201 }
1202 } else {
1203 for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1204 vacuum_document_recursive(i);
1205 }
1206 }
1207 }
1209 unsigned int
1210 vacuum_document(SPDocument *document)
1211 {
1212 unsigned int start = objects_in_document(document);
1213 unsigned int end;
1214 unsigned int newend = start;
1216 unsigned int iterations = 0;
1218 do {
1219 end = newend;
1221 vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1222 document->collectOrphans();
1223 iterations++;
1225 newend = objects_in_document(document);
1227 } while (iterations < 100 && newend < end);
1229 return start - newend;
1230 }
1232 bool SPDocument::isSeeking() const {
1233 return priv->seeking;
1234 }
1237 /*
1238 Local Variables:
1239 mode:c++
1240 c-file-style:"stroustrup"
1241 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1242 indent-tabs-mode:nil
1243 fill-column:99
1244 End:
1245 */
1246 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :