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