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>
44 #include "application/application.h"
45 #include "application/editor.h"
46 #include "desktop.h"
47 #include "dir-util.h"
48 #include "display/nr-arena-item.h"
49 #include "document-private.h"
50 #include "helper/units.h"
51 #include "inkscape-private.h"
52 #include "inkscape-version.h"
53 #include "libavoid/router.h"
54 #include "persp3d.h"
55 #include "preferences.h"
56 #include "profile-manager.h"
57 #include "rdf.h"
58 #include "sp-item-group.h"
59 #include "sp-namedview.h"
60 #include "sp-object-repr.h"
61 #include "transf_mat_3x4.h"
62 #include "unit-constants.h"
63 #include "xml/repr.h"
64 #include "xml/rebase-hrefs.h"
66 // Higher number means lower priority.
67 #define SP_DOCUMENT_UPDATE_PRIORITY (G_PRIORITY_HIGH_IDLE - 2)
69 // Should have a lower priority than SP_DOCUMENT_UPDATE_PRIORITY,
70 // since we want it to happen when there are no more updates.
71 #define SP_DOCUMENT_REROUTING_PRIORITY (G_PRIORITY_HIGH_IDLE - 1)
74 static gint sp_document_idle_handler(gpointer data);
75 static gint sp_document_rerouting_handler(gpointer data);
77 gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data);
79 static gint doc_count = 0;
81 static unsigned long next_serial = 0;
83 SPDocument::SPDocument() :
84 keepalive(FALSE),
85 virgin(TRUE),
86 modified_since_save(FALSE),
87 rdoc(0),
88 rroot(0),
89 root(0),
90 style_cascade(cr_cascade_new(NULL, NULL, NULL)),
91 uri(0),
92 base(0),
93 name(0),
94 priv(0), // reset in ctor
95 actionkey(0),
96 modified_id(0),
97 rerouting_handler_id(0),
98 profileManager(0), // deferred until after other initialization
99 router(new Avoid::Router(Avoid::PolyLineRouting|Avoid::OrthogonalRouting)),
100 perspectives(0),
101 current_persp3d(0),
102 _collection_queue(0),
103 oldSignalsConnected(false)
104 {
105 // Penalise libavoid for choosing paths with needless extra segments.
106 // This results in much better looking orthogonal connector paths.
107 router->setRoutingPenalty(Avoid::segmentPenalty);
109 SPDocumentPrivate *p = new SPDocumentPrivate();
111 p->serial = next_serial++;
113 p->iddef = g_hash_table_new(g_direct_hash, g_direct_equal);
114 p->reprdef = g_hash_table_new(g_direct_hash, g_direct_equal);
116 p->resources = g_hash_table_new(g_str_hash, g_str_equal);
118 p->sensitive = FALSE;
119 p->partial = NULL;
120 p->history_size = 0;
121 p->undo = NULL;
122 p->redo = NULL;
123 p->seeking = false;
125 priv = p;
127 // Once things are set, hook in the manager
128 profileManager = new Inkscape::ProfileManager(this);
130 // XXX only for testing!
131 priv->undoStackObservers.add(p->console_output_undo_observer);
132 }
134 SPDocument::~SPDocument() {
135 collectOrphans();
137 // kill/unhook this first
138 if ( profileManager ) {
139 delete profileManager;
140 profileManager = 0;
141 }
143 if (router) {
144 delete router;
145 router = NULL;
146 }
148 if (priv) {
149 if (priv->partial) {
150 sp_repr_free_log(priv->partial);
151 priv->partial = NULL;
152 }
154 sp_document_clear_redo(this);
155 sp_document_clear_undo(this);
157 if (root) {
158 root->releaseReferences();
159 sp_object_unref(root);
160 root = NULL;
161 }
163 if (priv->iddef) g_hash_table_destroy(priv->iddef);
164 if (priv->reprdef) g_hash_table_destroy(priv->reprdef);
166 if (rdoc) Inkscape::GC::release(rdoc);
168 /* Free resources */
169 g_hash_table_foreach_remove(priv->resources, sp_document_resource_list_free, this);
170 g_hash_table_destroy(priv->resources);
172 delete priv;
173 priv = NULL;
174 }
176 cr_cascade_unref(style_cascade);
177 style_cascade = NULL;
179 if (name) {
180 g_free(name);
181 name = NULL;
182 }
183 if (base) {
184 g_free(base);
185 base = NULL;
186 }
187 if (uri) {
188 g_free(uri);
189 uri = NULL;
190 }
192 if (modified_id) {
193 g_source_remove(modified_id);
194 modified_id = 0;
195 }
197 if (rerouting_handler_id) {
198 g_source_remove(rerouting_handler_id);
199 rerouting_handler_id = 0;
200 }
202 if (oldSignalsConnected) {
203 g_signal_handlers_disconnect_by_func(G_OBJECT(INKSCAPE),
204 reinterpret_cast<gpointer>(sp_document_reset_key),
205 static_cast<gpointer>(this));
206 } else {
207 _selection_changed_connection.disconnect();
208 _desktop_activated_connection.disconnect();
209 }
211 if (keepalive) {
212 inkscape_unref();
213 keepalive = FALSE;
214 }
216 //delete this->_whiteboard_session_manager;
217 }
219 void SPDocument::add_persp3d (Persp3D * const /*persp*/)
220 {
221 SPDefs *defs = SP_ROOT(this->root)->defs;
222 for (SPObject *i = sp_object_first_child(SP_OBJECT(defs)); i != NULL; i = SP_OBJECT_NEXT(i) ) {
223 if (SP_IS_PERSP3D(i)) {
224 g_print ("Encountered a Persp3D in defs\n");
225 }
226 }
228 g_print ("Adding Persp3D to defs\n");
229 persp3d_create_xml_element (this);
230 }
232 void SPDocument::remove_persp3d (Persp3D * const /*persp*/)
233 {
234 // TODO: Delete the repr, maybe perform a check if any boxes are still linked to the perspective.
235 // Anything else?
236 g_print ("Please implement deletion of perspectives here.\n");
237 }
239 void SPDocument::initialize_current_persp3d()
240 {
241 this->current_persp3d = persp3d_document_first_persp(this);
242 if (!this->current_persp3d) {
243 this->current_persp3d = persp3d_create_xml_element(this);
244 }
245 }
247 unsigned long SPDocument::serial() const {
248 return priv->serial;
249 }
251 void SPDocument::queueForOrphanCollection(SPObject *object) {
252 g_return_if_fail(object != NULL);
253 g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
255 sp_object_ref(object, NULL);
256 _collection_queue = g_slist_prepend(_collection_queue, object);
257 }
259 void SPDocument::collectOrphans() {
260 while (_collection_queue) {
261 GSList *objects=_collection_queue;
262 _collection_queue = NULL;
263 for ( GSList *iter=objects ; iter ; iter = iter->next ) {
264 SPObject *object=reinterpret_cast<SPObject *>(iter->data);
265 object->collectOrphan();
266 sp_object_unref(object, NULL);
267 }
268 g_slist_free(objects);
269 }
270 }
272 void SPDocument::reset_key (void */*dummy*/)
273 {
274 actionkey = NULL;
275 }
277 SPDocument *
278 sp_document_create(Inkscape::XML::Document *rdoc,
279 gchar const *uri,
280 gchar const *base,
281 gchar const *name,
282 unsigned int keepalive)
283 {
284 SPDocument *document;
285 Inkscape::XML::Node *rroot;
286 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
288 rroot = rdoc->root();
290 document = new SPDocument();
292 document->keepalive = keepalive;
294 document->rdoc = rdoc;
295 document->rroot = rroot;
297 #ifndef WIN32
298 document->uri = prepend_current_dir_if_relative(uri);
299 #else
300 // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
301 document->uri = uri? g_strdup(uri) : NULL;
302 #endif
304 // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
305 // which is why we use g_get_current_dir() in calculating the abs path above
306 //This is NULL for a new document
307 if (base)
308 document->base = g_strdup(base);
309 else
310 document->base = NULL;
311 document->name = g_strdup(name);
313 document->root = sp_object_repr_build_tree(document, rroot);
315 /* fixme: Not sure about this, but lets assume ::build updates */
316 rroot->setAttribute("inkscape:version", Inkscape::version_string);
317 /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
319 /* Quick hack 2 - get default image size into document */
320 if (!rroot->attribute("width")) rroot->setAttribute("width", "100%");
321 if (!rroot->attribute("height")) rroot->setAttribute("height", "100%");
322 /* End of quick hack 2 */
324 /* Quick hack 3 - Set uri attributes */
325 if (uri) {
326 rroot->setAttribute("sodipodi:docname", uri);
327 }
328 /* End of quick hack 3 */
330 /* Eliminate obsolete sodipodi:docbase, for privacy reasons */
331 rroot->setAttribute("sodipodi:docbase", NULL);
333 /* Eliminate any claim to adhere to a profile, as we don't try to */
334 rroot->setAttribute("baseProfile", NULL);
336 // creating namedview
337 if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
338 // if there's none in the document already,
339 Inkscape::XML::Node *rnew = NULL;
341 rnew = rdoc->createElement("sodipodi:namedview");
342 //rnew->setAttribute("id", "base");
344 // Add namedview data from the preferences
345 // we can't use getAllEntries because this could produce non-SVG doubles
346 Glib::ustring pagecolor = prefs->getString("/template/base/pagecolor");
347 if (!pagecolor.empty()) {
348 rnew->setAttribute("pagecolor", pagecolor.data());
349 }
350 Glib::ustring bordercolor = prefs->getString("/template/base/bordercolor");
351 if (!bordercolor.empty()) {
352 rnew->setAttribute("bordercolor", bordercolor.data());
353 }
354 sp_repr_set_svg_double(rnew, "borderopacity",
355 prefs->getDouble("/template/base/borderopacity", 1.0));
356 sp_repr_set_svg_double(rnew, "objecttolerance",
357 prefs->getDouble("/template/base/objecttolerance", 10.0));
358 sp_repr_set_svg_double(rnew, "gridtolerance",
359 prefs->getDouble("/template/base/gridtolerance", 10.0));
360 sp_repr_set_svg_double(rnew, "guidetolerance",
361 prefs->getDouble("/template/base/guidetolerance", 10.0));
362 sp_repr_set_svg_double(rnew, "inkscape:pageopacity",
363 prefs->getDouble("/template/base/inkscape:pageopacity", 0.0));
364 sp_repr_set_int(rnew, "inkscape:pageshadow",
365 prefs->getInt("/template/base/inkscape:pageshadow", 2));
366 sp_repr_set_int(rnew, "inkscape:window-width",
367 prefs->getInt("/template/base/inkscape:window-width", 640));
368 sp_repr_set_int(rnew, "inkscape:window-height",
369 prefs->getInt("/template/base/inkscape:window-height", 480));
371 // insert into the document
372 rroot->addChild(rnew, NULL);
373 // clean up
374 Inkscape::GC::release(rnew);
375 }
377 /* Defs */
378 if (!SP_ROOT(document->root)->defs) {
379 Inkscape::XML::Node *r;
380 r = rdoc->createElement("svg:defs");
381 rroot->addChild(r, NULL);
382 Inkscape::GC::release(r);
383 g_assert(SP_ROOT(document->root)->defs);
384 }
386 /* Default RDF */
387 rdf_set_defaults( document );
389 if (keepalive) {
390 inkscape_ref();
391 }
393 // Remark: Here, we used to create a "currentpersp3d" element in the document defs.
394 // But this is probably a bad idea since we need to adapt it for every change of selection, which will
395 // completely clutter the undo history. Maybe rather save it to prefs on exit and re-read it on startup?
396 document->initialize_current_persp3d();
398 sp_document_set_undo_sensitive(document, true);
400 // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
401 if (!Inkscape::NSApplication::Application::getNewGui()) {
402 g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
403 G_CALLBACK(sp_document_reset_key), document);
404 g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
405 G_CALLBACK(sp_document_reset_key), document);
406 document->oldSignalsConnected = true;
407 } else {
408 document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
409 document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
410 document->oldSignalsConnected = false;
411 }
413 return document;
414 }
416 /**
417 * Fetches document from URI, or creates new, if NULL; public document
418 * appears in document list.
419 */
420 SPDocument *
421 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
422 {
423 SPDocument *doc;
424 Inkscape::XML::Document *rdoc;
425 gchar *base = NULL;
426 gchar *name = NULL;
428 if (uri) {
429 Inkscape::XML::Node *rroot;
430 gchar *s, *p;
431 /* Try to fetch repr from file */
432 rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
433 /* If file cannot be loaded, return NULL without warning */
434 if (rdoc == NULL) return NULL;
435 rroot = rdoc->root();
436 /* If xml file is not svg, return NULL without warning */
437 /* fixme: destroy document */
438 if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
439 s = g_strdup(uri);
440 p = strrchr(s, '/');
441 if (p) {
442 name = g_strdup(p + 1);
443 p[1] = '\0';
444 base = g_strdup(s);
445 } else {
446 base = NULL;
447 name = g_strdup(uri);
448 }
449 g_free(s);
450 } else {
451 rdoc = sp_repr_document_new("svg:svg");
452 }
454 if (make_new) {
455 base = NULL;
456 uri = NULL;
457 name = g_strdup_printf(_("New document %d"), ++doc_count);
458 }
460 //# These should be set by now
461 g_assert(name);
463 doc = sp_document_create(rdoc, uri, base, name, keepalive);
465 g_free(base);
466 g_free(name);
468 return doc;
469 }
471 SPDocument *
472 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
473 {
474 SPDocument *doc;
475 Inkscape::XML::Document *rdoc;
476 Inkscape::XML::Node *rroot;
477 gchar *name;
479 rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
481 /* If it cannot be loaded, return NULL without warning */
482 if (rdoc == NULL) return NULL;
484 rroot = rdoc->root();
485 /* If xml file is not svg, return NULL without warning */
486 /* fixme: destroy document */
487 if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
489 name = g_strdup_printf(_("Memory document %d"), ++doc_count);
491 doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
493 return doc;
494 }
496 SPDocument *
497 sp_document_ref(SPDocument *doc)
498 {
499 g_return_val_if_fail(doc != NULL, NULL);
500 Inkscape::GC::anchor(doc);
501 return doc;
502 }
504 SPDocument *
505 sp_document_unref(SPDocument *doc)
506 {
507 g_return_val_if_fail(doc != NULL, NULL);
508 Inkscape::GC::release(doc);
509 return NULL;
510 }
512 gdouble sp_document_width(SPDocument *document)
513 {
514 g_return_val_if_fail(document != NULL, 0.0);
515 g_return_val_if_fail(document->priv != NULL, 0.0);
516 g_return_val_if_fail(document->root != NULL, 0.0);
518 SPRoot *root = SP_ROOT(document->root);
520 if (root->width.unit == SVGLength::PERCENT && root->viewBox_set)
521 return root->viewBox.x1 - root->viewBox.x0;
522 return root->width.computed;
523 }
525 void
526 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
527 {
528 SPRoot *root = SP_ROOT(document->root);
530 if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
531 root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
532 } else { // set to width=
533 gdouble old_computed = root->width.computed;
534 root->width.computed = sp_units_get_pixels (width, *unit);
535 /* SVG does not support meters as a unit, so we must translate meters to
536 * cm when writing */
537 if (!strcmp(unit->abbr, "m")) {
538 root->width.value = 100*width;
539 root->width.unit = SVGLength::CM;
540 } else {
541 root->width.value = width;
542 root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
543 }
545 if (root->viewBox_set)
546 root->viewBox.x1 = root->viewBox.x0 + (root->width.computed / old_computed) * (root->viewBox.x1 - root->viewBox.x0);
547 }
549 SP_OBJECT (root)->updateRepr();
550 }
552 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
553 {
554 SPRoot *root = SP_ROOT(document->root);
556 if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
557 root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
558 } else { // set to height=
559 gdouble old_computed = root->height.computed;
560 root->height.computed = sp_units_get_pixels (height, *unit);
561 /* SVG does not support meters as a unit, so we must translate meters to
562 * cm when writing */
563 if (!strcmp(unit->abbr, "m")) {
564 root->height.value = 100*height;
565 root->height.unit = SVGLength::CM;
566 } else {
567 root->height.value = height;
568 root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
569 }
571 if (root->viewBox_set)
572 root->viewBox.y1 = root->viewBox.y0 + (root->height.computed / old_computed) * (root->viewBox.y1 - root->viewBox.y0);
573 }
575 SP_OBJECT (root)->updateRepr();
576 }
578 gdouble sp_document_height(SPDocument *document)
579 {
580 g_return_val_if_fail(document != NULL, 0.0);
581 g_return_val_if_fail(document->priv != NULL, 0.0);
582 g_return_val_if_fail(document->root != NULL, 0.0);
584 SPRoot *root = SP_ROOT(document->root);
586 if (root->height.unit == SVGLength::PERCENT && root->viewBox_set)
587 return root->viewBox.y1 - root->viewBox.y0;
588 return root->height.computed;
589 }
591 Geom::Point sp_document_dimensions(SPDocument *doc)
592 {
593 return Geom::Point(sp_document_width(doc), sp_document_height(doc));
594 }
596 /**
597 * Given a Geom::Rect that may, for example, correspond to the bbox of an object,
598 * this function fits the canvas to that rect by resizing the canvas
599 * and translating the document root into position.
600 */
601 void SPDocument::fitToRect(Geom::Rect const &rect)
602 {
603 double const w = rect.width();
604 double const h = rect.height();
606 double const old_height = sp_document_height(this);
607 SPUnit const &px(sp_unit_get_by_id(SP_UNIT_PX));
608 sp_document_set_width(this, w, &px);
609 sp_document_set_height(this, h, &px);
611 Geom::Translate const tr(Geom::Point(0, (old_height - h))
612 - to_2geom(rect.min()));
613 SP_GROUP(root)->translateChildItems(tr);
614 SPNamedView *nv = sp_document_namedview(this, 0);
615 if(nv) {
616 Geom::Translate tr2(-rect.min());
617 nv->translateGuides(tr2);
619 // update the viewport so the drawing appears to stay where it was
620 nv->scrollAllDesktops(-tr2[0], tr2[1], false);
621 }
622 }
624 static void
625 do_change_uri(SPDocument *const document, gchar const *const filename, bool const rebase)
626 {
627 g_return_if_fail(document != NULL);
629 gchar *new_base;
630 gchar *new_name;
631 gchar *new_uri;
632 if (filename) {
634 #ifndef WIN32
635 new_uri = prepend_current_dir_if_relative(filename);
636 #else
637 // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
638 new_uri = g_strdup(filename);
639 #endif
641 new_base = g_path_get_dirname(new_uri);
642 new_name = g_path_get_basename(new_uri);
643 } else {
644 new_uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
645 new_base = NULL;
646 new_name = g_strdup(document->uri);
647 }
649 // Update saveable repr attributes.
650 Inkscape::XML::Node *repr = sp_document_repr_root(document);
652 // Changing uri in the document repr must not be not undoable.
653 bool const saved = sp_document_get_undo_sensitive(document);
654 sp_document_set_undo_sensitive(document, false);
656 if (rebase) {
657 Inkscape::XML::rebase_hrefs(document, new_base, true);
658 }
660 repr->setAttribute("sodipodi:docname", document->name);
661 sp_document_set_undo_sensitive(document, saved);
664 g_free(document->name);
665 g_free(document->base);
666 g_free(document->uri);
667 document->name = new_name;
668 document->base = new_base;
669 document->uri = new_uri;
671 document->priv->uri_set_signal.emit(document->uri);
672 }
674 /**
675 * Sets base, name and uri members of \a document. Doesn't update
676 * any relative hrefs in the document: thus, this is primarily for
677 * newly-created documents.
678 *
679 * \see sp_document_change_uri_and_hrefs
680 */
681 void sp_document_set_uri(SPDocument *document, gchar const *filename)
682 {
683 g_return_if_fail(document != NULL);
685 do_change_uri(document, filename, false);
686 }
688 /**
689 * Changes the base, name and uri members of \a document, and updates any
690 * relative hrefs in the document to be relative to the new base.
691 *
692 * \see sp_document_set_uri
693 */
694 void sp_document_change_uri_and_hrefs(SPDocument *document, gchar const *filename)
695 {
696 g_return_if_fail(document != NULL);
698 do_change_uri(document, filename, true);
699 }
701 void
702 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
703 {
704 g_return_if_fail(doc != NULL);
706 doc->priv->resized_signal.emit(width, height);
707 }
709 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
710 {
711 return priv->modified_signal.connect(slot);
712 }
714 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
715 {
716 return priv->uri_set_signal.connect(slot);
717 }
719 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
720 {
721 return priv->resized_signal.connect(slot);
722 }
724 sigc::connection
725 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
726 {
727 return priv->_reconstruction_start_signal.connect(slot);
728 }
730 void
731 SPDocument::emitReconstructionStart(void)
732 {
733 // printf("Starting Reconstruction\n");
734 priv->_reconstruction_start_signal.emit();
735 return;
736 }
738 sigc::connection
739 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type slot)
740 {
741 return priv->_reconstruction_finish_signal.connect(slot);
742 }
744 void
745 SPDocument::emitReconstructionFinish(void)
746 {
747 // printf("Finishing Reconstruction\n");
748 priv->_reconstruction_finish_signal.emit();
750 // Reference to the old persp3d object is invalid after reconstruction.
751 initialize_current_persp3d();
753 return;
754 }
756 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
757 {
758 return priv->commit_signal.connect(slot);
759 }
763 void SPDocument::_emitModified() {
764 static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
765 root->emitModified(0);
766 priv->modified_signal.emit(flags);
767 }
769 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
770 GQuark idq = g_quark_from_string(id);
772 if (object) {
773 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
774 g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
775 } else {
776 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
777 g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
778 }
780 SPDocumentPrivate::IDChangedSignalMap::iterator pos;
782 pos = priv->id_changed_signals.find(idq);
783 if ( pos != priv->id_changed_signals.end() ) {
784 if (!(*pos).second.empty()) {
785 (*pos).second.emit(object);
786 } else { // discard unused signal
787 priv->id_changed_signals.erase(pos);
788 }
789 }
790 }
792 void
793 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
794 {
795 this->priv->undoStackObservers.add(observer);
796 }
798 void
799 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
800 {
801 this->priv->undoStackObservers.remove(observer);
802 }
804 SPObject *SPDocument::getObjectById(gchar const *id) {
805 g_return_val_if_fail(id != NULL, NULL);
807 GQuark idq = g_quark_from_string(id);
808 return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
809 }
811 sigc::connection SPDocument::connectIdChanged(gchar const *id,
812 SPDocument::IDChangedSignal::slot_type slot)
813 {
814 return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
815 }
817 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
818 if (object) {
819 g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
820 g_hash_table_insert(priv->reprdef, repr, object);
821 } else {
822 g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
823 g_hash_table_remove(priv->reprdef, repr);
824 }
825 }
827 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
828 g_return_val_if_fail(repr != NULL, NULL);
829 return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
830 }
832 Glib::ustring SPDocument::getLanguage() {
833 gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
834 if (document_language) {
835 while (isspace(*document_language))
836 document_language++;
837 }
838 if ( !document_language || 0 == *document_language) {
839 // retrieve system language
840 document_language = getenv("LC_ALL");
841 if ( NULL == document_language || *document_language == 0 ) {
842 document_language = getenv ("LC_MESSAGES");
843 }
844 if ( NULL == document_language || *document_language == 0 ) {
845 document_language = getenv ("LANG");
846 }
848 if ( NULL != document_language ) {
849 const char *pos = strchr(document_language, '_');
850 if ( NULL != pos ) {
851 return Glib::ustring(document_language, pos - document_language);
852 }
853 }
854 }
856 if ( NULL == document_language )
857 return Glib::ustring();
858 return document_language;
859 }
861 /* Object modification root handler */
863 void
864 sp_document_request_modified(SPDocument *doc)
865 {
866 if (!doc->modified_id) {
867 doc->modified_id = g_idle_add_full(SP_DOCUMENT_UPDATE_PRIORITY,
868 sp_document_idle_handler, doc, NULL);
869 }
870 if (!doc->rerouting_handler_id) {
871 doc->rerouting_handler_id = g_idle_add_full(SP_DOCUMENT_REROUTING_PRIORITY,
872 sp_document_rerouting_handler, doc, NULL);
873 }
874 }
876 void
877 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
878 {
879 ctx->ctx.flags = 0;
880 ctx->i2doc = Geom::identity();
881 /* Set up viewport in case svg has it defined as percentages */
882 if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
883 ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
884 ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
885 ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
886 ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
887 } else { // as a last resort, set size to A4
888 ctx->vp.x0 = 0.0;
889 ctx->vp.y0 = 0.0;
890 ctx->vp.x1 = 210 * PX_PER_MM;
891 ctx->vp.y1 = 297 * PX_PER_MM;
892 }
893 ctx->i2vp = Geom::identity();
894 }
896 /**
897 * Tries to update the document state based on the modified and
898 * "update required" flags, and return true if the document has
899 * been brought fully up to date.
900 */
901 bool
902 SPDocument::_updateDocument()
903 {
904 /* Process updates */
905 if (this->root->uflags || this->root->mflags) {
906 if (this->root->uflags) {
907 SPItemCtx ctx;
908 sp_document_setup_viewport (this, &ctx);
910 bool saved = sp_document_get_undo_sensitive(this);
911 sp_document_set_undo_sensitive(this, false);
913 this->root->updateDisplay((SPCtx *)&ctx, 0);
915 sp_document_set_undo_sensitive(this, saved);
916 }
917 this->_emitModified();
918 }
920 return !(this->root->uflags || this->root->mflags);
921 }
924 /**
925 * Repeatedly works on getting the document updated, since sometimes
926 * it takes more than one pass to get the document updated. But it
927 * usually should not take more than a few loops, and certainly never
928 * more than 32 iterations. So we bail out if we hit 32 iterations,
929 * since this typically indicates we're stuck in an update loop.
930 */
931 gint
932 sp_document_ensure_up_to_date(SPDocument *doc)
933 {
934 // Bring the document up-to-date, specifically via the following:
935 // 1a) Process all document updates.
936 // 1b) When completed, process connector routing changes.
937 // 2a) Process any updates resulting from connector reroutings.
938 int counter = 32;
939 for (unsigned int pass = 1; pass <= 2; ++pass) {
940 // Process document updates.
941 while (!doc->_updateDocument()) {
942 if (counter == 0) {
943 g_warning("More than 32 iteration while updating document '%s'", doc->uri);
944 break;
945 }
946 counter--;
947 }
948 if (counter == 0)
949 {
950 break;
951 }
953 // After updates on the first pass we get libavoid to process all the
954 // changed objects and provide new routings. This may cause some objects
955 // to be modified, hence the second update pass.
956 if (pass == 1) {
957 doc->router->processTransaction();
958 }
959 }
961 if (doc->modified_id) {
962 /* Remove handler */
963 g_source_remove(doc->modified_id);
964 doc->modified_id = 0;
965 }
966 if (doc->rerouting_handler_id) {
967 /* Remove handler */
968 g_source_remove(doc->rerouting_handler_id);
969 doc->rerouting_handler_id = 0;
970 }
971 return counter>0;
972 }
974 /**
975 * An idle handler to update the document. Returns true if
976 * the document needs further updates.
977 */
978 static gint
979 sp_document_idle_handler(gpointer data)
980 {
981 SPDocument *doc = static_cast<SPDocument *>(data);
982 if (doc->_updateDocument()) {
983 doc->modified_id = 0;
984 return false;
985 } else {
986 return true;
987 }
988 }
990 /**
991 * An idle handler to reroute connectors in the document.
992 */
993 static gint
994 sp_document_rerouting_handler(gpointer data)
995 {
996 // Process any queued movement actions and determine new routings for
997 // object-avoiding connectors. Callbacks will be used to update and
998 // redraw affected connectors.
999 SPDocument *doc = static_cast<SPDocument *>(data);
1000 doc->router->processTransaction();
1002 // We don't need to handle rerouting again until there are further
1003 // diagram updates.
1004 doc->rerouting_handler_id = 0;
1005 return false;
1006 }
1008 static bool is_within(Geom::Rect const &area, Geom::Rect const &box)
1009 {
1010 return area.contains(box);
1011 }
1013 static bool overlaps(Geom::Rect const &area, Geom::Rect const &box)
1014 {
1015 return area.intersects(box);
1016 }
1018 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, Geom::Rect const &area,
1019 bool (*test)(Geom::Rect const &, Geom::Rect const &), bool take_insensitive = false)
1020 {
1021 g_return_val_if_fail(SP_IS_GROUP(group), s);
1023 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1024 if (!SP_IS_ITEM(o)) {
1025 continue;
1026 }
1027 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
1028 s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
1029 } else {
1030 SPItem *child = SP_ITEM(o);
1031 Geom::OptRect box = sp_item_bbox_desktop(child);
1032 if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1033 s = g_slist_append(s, child);
1034 }
1035 }
1036 }
1038 return s;
1039 }
1041 /**
1042 Returns true if an item is among the descendants of group (recursively).
1043 */
1044 bool item_is_in_group(SPItem *item, SPGroup *group)
1045 {
1046 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1047 if (!SP_IS_ITEM(o)) continue;
1048 if (SP_ITEM(o) == item)
1049 return true;
1050 if (SP_IS_GROUP(o))
1051 if (item_is_in_group(item, SP_GROUP(o)))
1052 return true;
1053 }
1054 return false;
1055 }
1057 /**
1058 Returns the bottommost item from the list which is at the point, or NULL if none.
1059 */
1060 SPItem*
1061 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
1062 Geom::Point const p, bool take_insensitive)
1063 {
1064 g_return_val_if_fail(group, NULL);
1065 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1066 gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1068 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1070 if (!SP_IS_ITEM(o)) continue;
1072 SPItem *item = SP_ITEM(o);
1073 NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
1074 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1075 && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
1076 if (g_slist_find((GSList *) list, item) != NULL)
1077 return item;
1078 }
1080 if (SP_IS_GROUP(o)) {
1081 SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
1082 if (found)
1083 return found;
1084 }
1086 }
1087 return NULL;
1088 }
1090 /**
1091 Returns the topmost (in z-order) item from the descendants of group (recursively) which
1092 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
1093 non-layer groups or not. Honors take_insensitive on whether to return insensitive
1094 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
1095 upwards in z-order and returns what it has found so far (i.e. the found item is
1096 guaranteed to be lower than upto).
1097 */
1098 SPItem*
1099 find_item_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
1100 {
1101 SPItem *seen = NULL, *newseen = NULL;
1102 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1103 gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1105 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1106 if (!SP_IS_ITEM(o)) continue;
1108 if (upto && SP_ITEM(o) == upto)
1109 break;
1111 if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
1112 // if nothing found yet, recurse into the group
1113 newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
1114 if (newseen) {
1115 seen = newseen;
1116 newseen = NULL;
1117 }
1119 if (item_is_in_group(upto, SP_GROUP(o)))
1120 break;
1122 } else {
1123 SPItem *child = SP_ITEM(o);
1124 NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1126 // seen remembers the last (topmost) of items pickable at this point
1127 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1128 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1129 seen = child;
1130 }
1131 }
1132 }
1133 return seen;
1134 }
1136 /**
1137 Returns the topmost non-layer group from the descendants of group which is at point
1138 p, or NULL if none. Recurses into layers but not into groups.
1139 */
1140 SPItem*
1141 find_group_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p)
1142 {
1143 SPItem *seen = NULL;
1144 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1145 gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1147 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1148 if (!SP_IS_ITEM(o)) continue;
1149 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1150 SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1151 if (newseen) {
1152 seen = newseen;
1153 }
1154 }
1155 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1156 SPItem *child = SP_ITEM(o);
1157 NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1159 // seen remembers the last (topmost) of groups pickable at this point
1160 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1161 seen = child;
1162 }
1163 }
1164 }
1165 return seen;
1166 }
1168 /*
1169 * Return list of items, contained in box
1170 *
1171 * Assumes box is normalized (and g_asserts it!)
1172 *
1173 */
1175 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1176 {
1177 g_return_val_if_fail(document != NULL, NULL);
1178 g_return_val_if_fail(document->priv != NULL, NULL);
1180 return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
1181 }
1183 /*
1184 * Return list of items, that the parts of the item contained in box
1185 *
1186 * Assumes box is normalized (and g_asserts it!)
1187 *
1188 */
1190 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1191 {
1192 g_return_val_if_fail(document != NULL, NULL);
1193 g_return_val_if_fail(document->priv != NULL, NULL);
1195 return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1196 }
1198 GSList *
1199 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<Geom::Point> points)
1200 {
1201 GSList *items = NULL;
1202 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1204 // When picking along the path, we don't want small objects close together
1205 // (such as hatching strokes) to obscure each other by their deltas,
1206 // so we temporarily set delta to a small value
1207 gdouble saved_delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1208 prefs->setDouble("/options/cursortolerance/value", 0.25);
1210 for(unsigned int i = 0; i < points.size(); i++) {
1211 SPItem *item = sp_document_item_at_point(document, key, points[i],
1212 false, NULL);
1213 if (item && !g_slist_find(items, item))
1214 items = g_slist_prepend (items, item);
1215 }
1217 // and now we restore it back
1218 prefs->setDouble("/options/cursortolerance/value", saved_delta);
1220 return items;
1221 }
1223 SPItem *
1224 sp_document_item_at_point(SPDocument *document, unsigned const key, Geom::Point const p,
1225 gboolean const into_groups, SPItem *upto)
1226 {
1227 g_return_val_if_fail(document != NULL, NULL);
1228 g_return_val_if_fail(document->priv != NULL, NULL);
1230 return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1231 }
1233 SPItem*
1234 sp_document_group_at_point(SPDocument *document, unsigned int key, Geom::Point const p)
1235 {
1236 g_return_val_if_fail(document != NULL, NULL);
1237 g_return_val_if_fail(document->priv != NULL, NULL);
1239 return find_group_at_point(key, SP_GROUP(document->root), p);
1240 }
1243 /* Resource management */
1245 gboolean
1246 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1247 {
1248 GSList *rlist;
1249 GQuark q = g_quark_from_string(key);
1251 g_return_val_if_fail(document != NULL, FALSE);
1252 g_return_val_if_fail(key != NULL, FALSE);
1253 g_return_val_if_fail(*key != '\0', FALSE);
1254 g_return_val_if_fail(object != NULL, FALSE);
1255 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1257 if (SP_OBJECT_IS_CLONED(object))
1258 return FALSE;
1260 rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1261 g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1262 rlist = g_slist_prepend(rlist, object);
1263 g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1265 document->priv->resources_changed_signals[q].emit();
1267 return TRUE;
1268 }
1270 gboolean
1271 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1272 {
1273 GSList *rlist;
1274 GQuark q = g_quark_from_string(key);
1276 g_return_val_if_fail(document != NULL, FALSE);
1277 g_return_val_if_fail(key != NULL, FALSE);
1278 g_return_val_if_fail(*key != '\0', FALSE);
1279 g_return_val_if_fail(object != NULL, FALSE);
1280 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1282 if (SP_OBJECT_IS_CLONED(object))
1283 return FALSE;
1285 rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1286 g_return_val_if_fail(rlist != NULL, FALSE);
1287 g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1288 rlist = g_slist_remove(rlist, object);
1289 g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1291 document->priv->resources_changed_signals[q].emit();
1293 return TRUE;
1294 }
1296 GSList const *
1297 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1298 {
1299 g_return_val_if_fail(document != NULL, NULL);
1300 g_return_val_if_fail(key != NULL, NULL);
1301 g_return_val_if_fail(*key != '\0', NULL);
1303 return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1304 }
1306 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1307 gchar const *key,
1308 SPDocument::ResourcesChangedSignal::slot_type slot)
1309 {
1310 GQuark q = g_quark_from_string(key);
1311 return document->priv->resources_changed_signals[q].connect(slot);
1312 }
1314 /* Helpers */
1316 gboolean
1317 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1318 {
1319 g_slist_free((GSList *) value);
1320 return TRUE;
1321 }
1323 unsigned int
1324 count_objects_recursive(SPObject *obj, unsigned int count)
1325 {
1326 count++; // obj itself
1328 for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1329 count = count_objects_recursive(i, count);
1330 }
1332 return count;
1333 }
1335 unsigned int
1336 objects_in_document(SPDocument *document)
1337 {
1338 return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1339 }
1341 void
1342 vacuum_document_recursive(SPObject *obj)
1343 {
1344 if (SP_IS_DEFS(obj)) {
1345 for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1346 /* fixme: some inkscape-internal nodes in the future might not be collectable */
1347 def->requestOrphanCollection();
1348 }
1349 } else {
1350 for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1351 vacuum_document_recursive(i);
1352 }
1353 }
1354 }
1356 unsigned int
1357 vacuum_document(SPDocument *document)
1358 {
1359 unsigned int start = objects_in_document(document);
1360 unsigned int end;
1361 unsigned int newend = start;
1363 unsigned int iterations = 0;
1365 do {
1366 end = newend;
1368 vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1369 document->collectOrphans();
1370 iterations++;
1372 newend = objects_in_document(document);
1374 } while (iterations < 100 && newend < end);
1376 return start - newend;
1377 }
1379 bool SPDocument::isSeeking() const {
1380 return priv->seeking;
1381 }
1384 /*
1385 Local Variables:
1386 mode:c++
1387 c-file-style:"stroustrup"
1388 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1389 indent-tabs-mode:nil
1390 fill-column:99
1391 End:
1392 */
1393 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :