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 #define SP_DOCUMENT_UPDATE_PRIORITY (G_PRIORITY_HIGH_IDLE - 1)
69 static gint sp_document_idle_handler(gpointer data);
71 gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data);
73 static gint doc_count = 0;
75 static unsigned long next_serial = 0;
77 SPDocument::SPDocument() :
78 keepalive(FALSE),
79 virgin(TRUE),
80 modified_since_save(FALSE),
81 rdoc(0),
82 rroot(0),
83 root(0),
84 style_cascade(cr_cascade_new(NULL, NULL, NULL)),
85 uri(0),
86 base(0),
87 name(0),
88 priv(0), // reset in ctor
89 actionkey(0),
90 modified_id(0),
91 profileManager(0), // deferred until after other initialization
92 router(new Avoid::Router()),
93 perspectives(0),
94 current_persp3d(0),
95 _collection_queue(0),
96 oldSignalsConnected(false)
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 if (oldSignalsConnected) {
185 g_signal_handlers_disconnect_by_func(G_OBJECT(INKSCAPE),
186 reinterpret_cast<gpointer>(sp_document_reset_key),
187 static_cast<gpointer>(this));
188 } else {
189 _selection_changed_connection.disconnect();
190 _desktop_activated_connection.disconnect();
191 }
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::Preferences *prefs = Inkscape::Preferences::get();
268 rroot = rdoc->root();
270 document = new SPDocument();
272 document->keepalive = keepalive;
274 document->rdoc = rdoc;
275 document->rroot = rroot;
277 #ifndef WIN32
278 document->uri = prepend_current_dir_if_relative(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 /* fixme: Not sure about this, but lets assume ::build updates */
296 rroot->setAttribute("inkscape:version", Inkscape::version_string);
297 /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
299 /* Quick hack 2 - get default image size into document */
300 if (!rroot->attribute("width")) rroot->setAttribute("width", "100%");
301 if (!rroot->attribute("height")) rroot->setAttribute("height", "100%");
302 /* End of quick hack 2 */
304 /* Quick hack 3 - Set uri attributes */
305 if (uri) {
306 rroot->setAttribute("sodipodi:docname", uri);
307 }
308 /* End of quick hack 3 */
310 /* Eliminate obsolete sodipodi:docbase, for privacy reasons */
311 rroot->setAttribute("sodipodi:docbase", NULL);
313 /* Eliminate any claim to adhere to a profile, as we don't try to */
314 rroot->setAttribute("baseProfile", NULL);
316 // creating namedview
317 if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
318 // if there's none in the document already,
319 Inkscape::XML::Node *rnew = NULL;
321 rnew = rdoc->createElement("sodipodi:namedview");
322 //rnew->setAttribute("id", "base");
324 // Add namedview data from the preferences
325 // we can't use getAllEntries because this could produce non-SVG doubles
326 Glib::ustring pagecolor = prefs->getString("/template/base/pagecolor");
327 if (!pagecolor.empty()) {
328 rnew->setAttribute("pagecolor", pagecolor.data());
329 }
330 Glib::ustring bordercolor = prefs->getString("/template/base/bordercolor");
331 if (!bordercolor.empty()) {
332 rnew->setAttribute("bordercolor", bordercolor.data());
333 }
334 sp_repr_set_svg_double(rnew, "borderopacity",
335 prefs->getDouble("/template/base/borderopacity", 1.0));
336 sp_repr_set_svg_double(rnew, "objecttolerance",
337 prefs->getDouble("/template/base/objecttolerance", 10.0));
338 sp_repr_set_svg_double(rnew, "gridtolerance",
339 prefs->getDouble("/template/base/gridtolerance", 10.0));
340 sp_repr_set_svg_double(rnew, "guidetolerance",
341 prefs->getDouble("/template/base/guidetolerance", 10.0));
342 sp_repr_set_svg_double(rnew, "inkscape:pageopacity",
343 prefs->getDouble("/template/base/inkscape:pageopacity", 0.0));
344 sp_repr_set_int(rnew, "inkscape:pageshadow",
345 prefs->getInt("/template/base/inkscape:pageshadow", 2));
346 sp_repr_set_int(rnew, "inkscape:window-width",
347 prefs->getInt("/template/base/inkscape:window-width", 640));
348 sp_repr_set_int(rnew, "inkscape:window-height",
349 prefs->getInt("/template/base/inkscape:window-height", 480));
351 // insert into the document
352 rroot->addChild(rnew, NULL);
353 // clean up
354 Inkscape::GC::release(rnew);
355 }
357 /* Defs */
358 if (!SP_ROOT(document->root)->defs) {
359 Inkscape::XML::Node *r;
360 r = rdoc->createElement("svg:defs");
361 rroot->addChild(r, NULL);
362 Inkscape::GC::release(r);
363 g_assert(SP_ROOT(document->root)->defs);
364 }
366 /* Default RDF */
367 rdf_set_defaults( document );
369 if (keepalive) {
370 inkscape_ref();
371 }
373 // Remark: Here, we used to create a "currentpersp3d" element in the document defs.
374 // But this is probably a bad idea since we need to adapt it for every change of selection, which will
375 // completely clutter the undo history. Maybe rather save it to prefs on exit and re-read it on startup?
377 document->current_persp3d = persp3d_document_first_persp(document);
378 if (!document->current_persp3d) {
379 document->current_persp3d = persp3d_create_xml_element (document);
380 }
382 sp_document_set_undo_sensitive(document, true);
384 // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
385 if (!Inkscape::NSApplication::Application::getNewGui()) {
386 g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
387 G_CALLBACK(sp_document_reset_key), document);
388 g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
389 G_CALLBACK(sp_document_reset_key), document);
390 document->oldSignalsConnected = true;
391 } else {
392 document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
393 document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
394 document->oldSignalsConnected = false;
395 }
397 return document;
398 }
400 /**
401 * Fetches document from URI, or creates new, if NULL; public document
402 * appears in document list.
403 */
404 SPDocument *
405 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
406 {
407 SPDocument *doc;
408 Inkscape::XML::Document *rdoc;
409 gchar *base = NULL;
410 gchar *name = NULL;
412 if (uri) {
413 Inkscape::XML::Node *rroot;
414 gchar *s, *p;
415 /* Try to fetch repr from file */
416 rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
417 /* If file cannot be loaded, return NULL without warning */
418 if (rdoc == NULL) return NULL;
419 rroot = rdoc->root();
420 /* If xml file is not svg, return NULL without warning */
421 /* fixme: destroy document */
422 if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
423 s = g_strdup(uri);
424 p = strrchr(s, '/');
425 if (p) {
426 name = g_strdup(p + 1);
427 p[1] = '\0';
428 base = g_strdup(s);
429 } else {
430 base = NULL;
431 name = g_strdup(uri);
432 }
433 g_free(s);
434 } else {
435 rdoc = sp_repr_document_new("svg:svg");
436 }
438 if (make_new) {
439 base = NULL;
440 uri = NULL;
441 name = g_strdup_printf(_("New document %d"), ++doc_count);
442 }
444 //# These should be set by now
445 g_assert(name);
447 doc = sp_document_create(rdoc, uri, base, name, keepalive);
449 g_free(base);
450 g_free(name);
452 return doc;
453 }
455 SPDocument *
456 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
457 {
458 SPDocument *doc;
459 Inkscape::XML::Document *rdoc;
460 Inkscape::XML::Node *rroot;
461 gchar *name;
463 rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
465 /* If it cannot be loaded, return NULL without warning */
466 if (rdoc == NULL) return NULL;
468 rroot = rdoc->root();
469 /* If xml file is not svg, return NULL without warning */
470 /* fixme: destroy document */
471 if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
473 name = g_strdup_printf(_("Memory document %d"), ++doc_count);
475 doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
477 return doc;
478 }
480 SPDocument *
481 sp_document_ref(SPDocument *doc)
482 {
483 g_return_val_if_fail(doc != NULL, NULL);
484 Inkscape::GC::anchor(doc);
485 return doc;
486 }
488 SPDocument *
489 sp_document_unref(SPDocument *doc)
490 {
491 g_return_val_if_fail(doc != NULL, NULL);
492 Inkscape::GC::release(doc);
493 return NULL;
494 }
496 gdouble sp_document_width(SPDocument *document)
497 {
498 g_return_val_if_fail(document != NULL, 0.0);
499 g_return_val_if_fail(document->priv != NULL, 0.0);
500 g_return_val_if_fail(document->root != NULL, 0.0);
502 SPRoot *root = SP_ROOT(document->root);
504 if (root->width.unit == SVGLength::PERCENT && root->viewBox_set)
505 return root->viewBox.x1 - root->viewBox.x0;
506 return root->width.computed;
507 }
509 void
510 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
511 {
512 SPRoot *root = SP_ROOT(document->root);
514 if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
515 root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
516 } else { // set to width=
517 gdouble old_computed = root->width.computed;
518 root->width.computed = sp_units_get_pixels (width, *unit);
519 /* SVG does not support meters as a unit, so we must translate meters to
520 * cm when writing */
521 if (!strcmp(unit->abbr, "m")) {
522 root->width.value = 100*width;
523 root->width.unit = SVGLength::CM;
524 } else {
525 root->width.value = width;
526 root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
527 }
529 if (root->viewBox_set)
530 root->viewBox.x1 = root->viewBox.x0 + (root->width.computed / old_computed) * (root->viewBox.x1 - root->viewBox.x0);
531 }
533 SP_OBJECT (root)->updateRepr();
534 }
536 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
537 {
538 SPRoot *root = SP_ROOT(document->root);
540 if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
541 root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
542 } else { // set to height=
543 gdouble old_computed = root->height.computed;
544 root->height.computed = sp_units_get_pixels (height, *unit);
545 /* SVG does not support meters as a unit, so we must translate meters to
546 * cm when writing */
547 if (!strcmp(unit->abbr, "m")) {
548 root->height.value = 100*height;
549 root->height.unit = SVGLength::CM;
550 } else {
551 root->height.value = height;
552 root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
553 }
555 if (root->viewBox_set)
556 root->viewBox.y1 = root->viewBox.y0 + (root->height.computed / old_computed) * (root->viewBox.y1 - root->viewBox.y0);
557 }
559 SP_OBJECT (root)->updateRepr();
560 }
562 gdouble sp_document_height(SPDocument *document)
563 {
564 g_return_val_if_fail(document != NULL, 0.0);
565 g_return_val_if_fail(document->priv != NULL, 0.0);
566 g_return_val_if_fail(document->root != NULL, 0.0);
568 SPRoot *root = SP_ROOT(document->root);
570 if (root->height.unit == SVGLength::PERCENT && root->viewBox_set)
571 return root->viewBox.y1 - root->viewBox.y0;
572 return root->height.computed;
573 }
575 void sp_document_set_landscape (SPDocument *document, gboolean landscape)
576 {
577 SPRoot *root = SP_ROOT(document->root);
579 root->landscape = landscape;
580 SP_OBJECT (root)->updateRepr();
581 }
583 gboolean sp_document_landscape(SPDocument *document)
584 {
585 g_return_val_if_fail(document != NULL, 0.0);
586 g_return_val_if_fail(document->priv != NULL, 0.0);
587 g_return_val_if_fail(document->root != NULL, 0.0);
589 SPRoot *root = SP_ROOT(document->root);
591 return root->landscape;
592 }
594 Geom::Point sp_document_dimensions(SPDocument *doc)
595 {
596 return Geom::Point(sp_document_width(doc), sp_document_height(doc));
597 }
599 /**
600 * Given a Geom::Rect that may, for example, correspond to the bbox of an object,
601 * this function fits the canvas to that rect by resizing the canvas
602 * and translating the document root into position.
603 */
604 void SPDocument::fitToRect(Geom::Rect const &rect)
605 {
606 double const w = rect.width();
607 double const h = rect.height();
609 double const old_height = sp_document_height(this);
610 SPUnit const &px(sp_unit_get_by_id(SP_UNIT_PX));
611 sp_document_set_width(this, w, &px);
612 sp_document_set_height(this, h, &px);
614 Geom::Translate const tr(Geom::Point(0, (old_height - h))
615 - to_2geom(rect.min()));
616 SP_GROUP(root)->translateChildItems(tr);
617 SPNamedView *nv = sp_document_namedview(this, 0);
618 if(nv) {
619 Geom::Translate tr2(-rect.min());
620 nv->translateGuides(tr2);
622 // update the viewport so the drawing appears to stay where it was
623 nv->scrollAllDesktops(-tr2[0], tr2[1], false);
624 }
625 }
627 static void
628 do_change_uri(SPDocument *const document, gchar const *const filename, bool const rebase)
629 {
630 g_return_if_fail(document != NULL);
632 gchar *new_base;
633 gchar *new_name;
634 gchar *new_uri;
635 if (filename) {
637 #ifndef WIN32
638 new_uri = prepend_current_dir_if_relative(filename);
639 #else
640 // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
641 new_uri = g_strdup(filename);
642 #endif
644 new_base = g_path_get_dirname(new_uri);
645 new_name = g_path_get_basename(new_uri);
646 } else {
647 new_uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
648 new_base = NULL;
649 new_name = g_strdup(document->uri);
650 }
652 // Update saveable repr attributes.
653 Inkscape::XML::Node *repr = sp_document_repr_root(document);
655 // Changing uri in the document repr must not be not undoable.
656 bool const saved = sp_document_get_undo_sensitive(document);
657 sp_document_set_undo_sensitive(document, false);
659 if (rebase) {
660 Inkscape::XML::rebase_hrefs(document, new_base, true);
661 }
663 repr->setAttribute("sodipodi:docname", document->name);
664 sp_document_set_undo_sensitive(document, saved);
667 g_free(document->name);
668 g_free(document->base);
669 g_free(document->uri);
670 document->name = new_name;
671 document->base = new_base;
672 document->uri = new_uri;
674 document->priv->uri_set_signal.emit(document->uri);
675 }
677 /**
678 * Sets base, name and uri members of \a document. Doesn't update
679 * any relative hrefs in the document: thus, this is primarily for
680 * newly-created documents.
681 *
682 * \see sp_document_change_uri_and_hrefs
683 */
684 void sp_document_set_uri(SPDocument *document, gchar const *filename)
685 {
686 g_return_if_fail(document != NULL);
688 do_change_uri(document, filename, false);
689 }
691 /**
692 * Changes the base, name and uri members of \a document, and updates any
693 * relative hrefs in the document to be relative to the new base.
694 *
695 * \see sp_document_set_uri
696 */
697 void sp_document_change_uri_and_hrefs(SPDocument *document, gchar const *filename)
698 {
699 g_return_if_fail(document != NULL);
701 do_change_uri(document, filename, true);
702 }
704 void
705 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
706 {
707 g_return_if_fail(doc != NULL);
709 doc->priv->resized_signal.emit(width, height);
710 }
712 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
713 {
714 return priv->modified_signal.connect(slot);
715 }
717 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
718 {
719 return priv->uri_set_signal.connect(slot);
720 }
722 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
723 {
724 return priv->resized_signal.connect(slot);
725 }
727 sigc::connection
728 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
729 {
730 return priv->_reconstruction_start_signal.connect(slot);
731 }
733 void
734 SPDocument::emitReconstructionStart(void)
735 {
736 // printf("Starting Reconstruction\n");
737 priv->_reconstruction_start_signal.emit();
738 return;
739 }
741 sigc::connection
742 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type slot)
743 {
744 return priv->_reconstruction_finish_signal.connect(slot);
745 }
747 void
748 SPDocument::emitReconstructionFinish(void)
749 {
750 // printf("Finishing Reconstruction\n");
751 priv->_reconstruction_finish_signal.emit();
752 return;
753 }
755 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
756 {
757 return priv->commit_signal.connect(slot);
758 }
762 void SPDocument::_emitModified() {
763 static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
764 root->emitModified(0);
765 priv->modified_signal.emit(flags);
766 }
768 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
769 GQuark idq = g_quark_from_string(id);
771 if (object) {
772 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
773 g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
774 } else {
775 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
776 g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
777 }
779 SPDocumentPrivate::IDChangedSignalMap::iterator pos;
781 pos = priv->id_changed_signals.find(idq);
782 if ( pos != priv->id_changed_signals.end() ) {
783 if (!(*pos).second.empty()) {
784 (*pos).second.emit(object);
785 } else { // discard unused signal
786 priv->id_changed_signals.erase(pos);
787 }
788 }
789 }
791 void
792 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
793 {
794 this->priv->undoStackObservers.add(observer);
795 }
797 void
798 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
799 {
800 this->priv->undoStackObservers.remove(observer);
801 }
803 SPObject *SPDocument::getObjectById(gchar const *id) {
804 g_return_val_if_fail(id != NULL, NULL);
806 GQuark idq = g_quark_from_string(id);
807 return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
808 }
810 sigc::connection SPDocument::connectIdChanged(gchar const *id,
811 SPDocument::IDChangedSignal::slot_type slot)
812 {
813 return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
814 }
816 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
817 if (object) {
818 g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
819 g_hash_table_insert(priv->reprdef, repr, object);
820 } else {
821 g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
822 g_hash_table_remove(priv->reprdef, repr);
823 }
824 }
826 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
827 g_return_val_if_fail(repr != NULL, NULL);
828 return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
829 }
831 Glib::ustring SPDocument::getLanguage() {
832 gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
833 if (document_language) {
834 while (isspace(*document_language))
835 document_language++;
836 }
837 if ( !document_language || 0 == *document_language) {
838 // retrieve system language
839 document_language = getenv("LC_ALL");
840 if ( NULL == document_language || *document_language == 0 ) {
841 document_language = getenv ("LC_MESSAGES");
842 }
843 if ( NULL == document_language || *document_language == 0 ) {
844 document_language = getenv ("LANG");
845 }
847 if ( NULL != document_language ) {
848 const char *pos = strchr(document_language, '_');
849 if ( NULL != pos ) {
850 return Glib::ustring(document_language, pos - document_language);
851 }
852 }
853 }
855 if ( NULL == document_language )
856 return Glib::ustring();
857 return document_language;
858 }
860 /* Object modification root handler */
862 void
863 sp_document_request_modified(SPDocument *doc)
864 {
865 if (!doc->modified_id) {
866 doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
867 }
868 }
870 void
871 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
872 {
873 ctx->ctx.flags = 0;
874 ctx->i2doc = Geom::identity();
875 /* Set up viewport in case svg has it defined as percentages */
876 if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
877 ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
878 ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
879 ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
880 ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
881 } else { // as a last resort, set size to A4
882 ctx->vp.x0 = 0.0;
883 ctx->vp.y0 = 0.0;
884 ctx->vp.x1 = 210 * PX_PER_MM;
885 ctx->vp.y1 = 297 * PX_PER_MM;
886 }
887 ctx->i2vp = Geom::identity();
888 }
890 /**
891 * Tries to update the document state based on the modified and
892 * "update required" flags, and return true if the document has
893 * been brought fully up to date.
894 */
895 bool
896 SPDocument::_updateDocument()
897 {
898 /* Process updates */
899 if (this->root->uflags || this->root->mflags) {
900 if (this->root->uflags) {
901 SPItemCtx ctx;
902 sp_document_setup_viewport (this, &ctx);
904 bool saved = sp_document_get_undo_sensitive(this);
905 sp_document_set_undo_sensitive(this, false);
907 this->root->updateDisplay((SPCtx *)&ctx, 0);
909 sp_document_set_undo_sensitive(this, saved);
910 }
911 this->_emitModified();
912 }
914 return !(this->root->uflags || this->root->mflags);
915 }
918 /**
919 * Repeatedly works on getting the document updated, since sometimes
920 * it takes more than one pass to get the document updated. But it
921 * usually should not take more than a few loops, and certainly never
922 * more than 32 iterations. So we bail out if we hit 32 iterations,
923 * since this typically indicates we're stuck in an update loop.
924 */
925 gint
926 sp_document_ensure_up_to_date(SPDocument *doc)
927 {
928 int counter = 32;
929 while (!doc->_updateDocument()) {
930 if (counter == 0) {
931 g_warning("More than 32 iteration while updating document '%s'", doc->uri);
932 break;
933 }
934 counter--;
935 }
937 if (doc->modified_id) {
938 /* Remove handler */
939 gtk_idle_remove(doc->modified_id);
940 doc->modified_id = 0;
941 }
942 return counter>0;
943 }
945 /**
946 * An idle handler to update the document. Returns true if
947 * the document needs further updates.
948 */
949 static gint
950 sp_document_idle_handler(gpointer data)
951 {
952 SPDocument *doc = static_cast<SPDocument *>(data);
953 if (doc->_updateDocument()) {
954 doc->modified_id = 0;
955 return false;
956 } else {
957 return true;
958 }
959 }
961 static bool is_within(Geom::Rect const &area, Geom::Rect const &box)
962 {
963 return area.contains(box);
964 }
966 static bool overlaps(Geom::Rect const &area, Geom::Rect const &box)
967 {
968 return area.intersects(box);
969 }
971 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, Geom::Rect const &area,
972 bool (*test)(Geom::Rect const &, Geom::Rect const &), bool take_insensitive = false)
973 {
974 g_return_val_if_fail(SP_IS_GROUP(group), s);
976 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
977 if (!SP_IS_ITEM(o)) {
978 continue;
979 }
980 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
981 s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
982 } else {
983 SPItem *child = SP_ITEM(o);
984 Geom::OptRect box = sp_item_bbox_desktop(child);
985 if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
986 s = g_slist_append(s, child);
987 }
988 }
989 }
991 return s;
992 }
994 /**
995 Returns true if an item is among the descendants of group (recursively).
996 */
997 bool item_is_in_group(SPItem *item, SPGroup *group)
998 {
999 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1000 if (!SP_IS_ITEM(o)) continue;
1001 if (SP_ITEM(o) == item)
1002 return true;
1003 if (SP_IS_GROUP(o))
1004 if (item_is_in_group(item, SP_GROUP(o)))
1005 return true;
1006 }
1007 return false;
1008 }
1010 /**
1011 Returns the bottommost item from the list which is at the point, or NULL if none.
1012 */
1013 SPItem*
1014 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
1015 Geom::Point const p, bool take_insensitive)
1016 {
1017 g_return_val_if_fail(group, NULL);
1018 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1019 gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1021 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1023 if (!SP_IS_ITEM(o)) continue;
1025 SPItem *item = SP_ITEM(o);
1026 NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
1027 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1028 && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
1029 if (g_slist_find((GSList *) list, item) != NULL)
1030 return item;
1031 }
1033 if (SP_IS_GROUP(o)) {
1034 SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
1035 if (found)
1036 return found;
1037 }
1039 }
1040 return NULL;
1041 }
1043 /**
1044 Returns the topmost (in z-order) item from the descendants of group (recursively) which
1045 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
1046 non-layer groups or not. Honors take_insensitive on whether to return insensitive
1047 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
1048 upwards in z-order and returns what it has found so far (i.e. the found item is
1049 guaranteed to be lower than upto).
1050 */
1051 SPItem*
1052 find_item_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
1053 {
1054 SPItem *seen = NULL, *newseen = NULL;
1055 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1056 gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1058 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1059 if (!SP_IS_ITEM(o)) continue;
1061 if (upto && SP_ITEM(o) == upto)
1062 break;
1064 if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
1065 // if nothing found yet, recurse into the group
1066 newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
1067 if (newseen) {
1068 seen = newseen;
1069 newseen = NULL;
1070 }
1072 if (item_is_in_group(upto, SP_GROUP(o)))
1073 break;
1075 } else {
1076 SPItem *child = SP_ITEM(o);
1077 NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1079 // seen remembers the last (topmost) of items pickable at this point
1080 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1081 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1082 seen = child;
1083 }
1084 }
1085 }
1086 return seen;
1087 }
1089 /**
1090 Returns the topmost non-layer group from the descendants of group which is at point
1091 p, or NULL if none. Recurses into layers but not into groups.
1092 */
1093 SPItem*
1094 find_group_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p)
1095 {
1096 SPItem *seen = NULL;
1097 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1098 gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1100 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1101 if (!SP_IS_ITEM(o)) continue;
1102 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1103 SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1104 if (newseen) {
1105 seen = newseen;
1106 }
1107 }
1108 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1109 SPItem *child = SP_ITEM(o);
1110 NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1112 // seen remembers the last (topmost) of groups pickable at this point
1113 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1114 seen = child;
1115 }
1116 }
1117 }
1118 return seen;
1119 }
1121 /*
1122 * Return list of items, contained in box
1123 *
1124 * Assumes box is normalized (and g_asserts it!)
1125 *
1126 */
1128 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1129 {
1130 g_return_val_if_fail(document != NULL, NULL);
1131 g_return_val_if_fail(document->priv != NULL, NULL);
1133 return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
1134 }
1136 /*
1137 * Return list of items, that the parts of the item contained in box
1138 *
1139 * Assumes box is normalized (and g_asserts it!)
1140 *
1141 */
1143 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1144 {
1145 g_return_val_if_fail(document != NULL, NULL);
1146 g_return_val_if_fail(document->priv != NULL, NULL);
1148 return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1149 }
1151 GSList *
1152 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<Geom::Point> points)
1153 {
1154 GSList *items = NULL;
1155 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1157 // When picking along the path, we don't want small objects close together
1158 // (such as hatching strokes) to obscure each other by their deltas,
1159 // so we temporarily set delta to a small value
1160 gdouble saved_delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1161 prefs->setDouble("/options/cursortolerance/value", 0.25);
1163 for(unsigned int i = 0; i < points.size(); i++) {
1164 SPItem *item = sp_document_item_at_point(document, key, points[i],
1165 false, NULL);
1166 if (item && !g_slist_find(items, item))
1167 items = g_slist_prepend (items, item);
1168 }
1170 // and now we restore it back
1171 prefs->setDouble("/options/cursortolerance/value", saved_delta);
1173 return items;
1174 }
1176 SPItem *
1177 sp_document_item_at_point(SPDocument *document, unsigned const key, Geom::Point const p,
1178 gboolean const into_groups, SPItem *upto)
1179 {
1180 g_return_val_if_fail(document != NULL, NULL);
1181 g_return_val_if_fail(document->priv != NULL, NULL);
1183 return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1184 }
1186 SPItem*
1187 sp_document_group_at_point(SPDocument *document, unsigned int key, Geom::Point const p)
1188 {
1189 g_return_val_if_fail(document != NULL, NULL);
1190 g_return_val_if_fail(document->priv != NULL, NULL);
1192 return find_group_at_point(key, SP_GROUP(document->root), p);
1193 }
1196 /* Resource management */
1198 gboolean
1199 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1200 {
1201 GSList *rlist;
1202 GQuark q = g_quark_from_string(key);
1204 g_return_val_if_fail(document != NULL, FALSE);
1205 g_return_val_if_fail(key != NULL, FALSE);
1206 g_return_val_if_fail(*key != '\0', FALSE);
1207 g_return_val_if_fail(object != NULL, FALSE);
1208 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1210 if (SP_OBJECT_IS_CLONED(object))
1211 return FALSE;
1213 rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1214 g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1215 rlist = g_slist_prepend(rlist, object);
1216 g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1218 document->priv->resources_changed_signals[q].emit();
1220 return TRUE;
1221 }
1223 gboolean
1224 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1225 {
1226 GSList *rlist;
1227 GQuark q = g_quark_from_string(key);
1229 g_return_val_if_fail(document != NULL, FALSE);
1230 g_return_val_if_fail(key != NULL, FALSE);
1231 g_return_val_if_fail(*key != '\0', FALSE);
1232 g_return_val_if_fail(object != NULL, FALSE);
1233 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1235 if (SP_OBJECT_IS_CLONED(object))
1236 return FALSE;
1238 rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1239 g_return_val_if_fail(rlist != NULL, FALSE);
1240 g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1241 rlist = g_slist_remove(rlist, object);
1242 g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1244 document->priv->resources_changed_signals[q].emit();
1246 return TRUE;
1247 }
1249 GSList const *
1250 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1251 {
1252 g_return_val_if_fail(document != NULL, NULL);
1253 g_return_val_if_fail(key != NULL, NULL);
1254 g_return_val_if_fail(*key != '\0', NULL);
1256 return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1257 }
1259 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1260 gchar const *key,
1261 SPDocument::ResourcesChangedSignal::slot_type slot)
1262 {
1263 GQuark q = g_quark_from_string(key);
1264 return document->priv->resources_changed_signals[q].connect(slot);
1265 }
1267 /* Helpers */
1269 gboolean
1270 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1271 {
1272 g_slist_free((GSList *) value);
1273 return TRUE;
1274 }
1276 unsigned int
1277 count_objects_recursive(SPObject *obj, unsigned int count)
1278 {
1279 count++; // obj itself
1281 for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1282 count = count_objects_recursive(i, count);
1283 }
1285 return count;
1286 }
1288 unsigned int
1289 objects_in_document(SPDocument *document)
1290 {
1291 return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1292 }
1294 void
1295 vacuum_document_recursive(SPObject *obj)
1296 {
1297 if (SP_IS_DEFS(obj)) {
1298 for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1299 /* fixme: some inkscape-internal nodes in the future might not be collectable */
1300 def->requestOrphanCollection();
1301 }
1302 } else {
1303 for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1304 vacuum_document_recursive(i);
1305 }
1306 }
1307 }
1309 unsigned int
1310 vacuum_document(SPDocument *document)
1311 {
1312 unsigned int start = objects_in_document(document);
1313 unsigned int end;
1314 unsigned int newend = start;
1316 unsigned int iterations = 0;
1318 do {
1319 end = newend;
1321 vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1322 document->collectOrphans();
1323 iterations++;
1325 newend = objects_in_document(document);
1327 } while (iterations < 100 && newend < end);
1329 return start - newend;
1330 }
1332 bool SPDocument::isSeeking() const {
1333 return priv->seeking;
1334 }
1337 /*
1338 Local Variables:
1339 mode:c++
1340 c-file-style:"stroustrup"
1341 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1342 indent-tabs-mode:nil
1343 fill-column:99
1344 End:
1345 */
1346 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :