28a2be9a168d20014fd46d1c1b1300f57524ad82
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/pagecolor");
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 root->width.computed = sp_units_get_pixels (width, *unit);
514 /* SVG does not support meters as a unit, so we must translate meters to
515 * cm when writing */
516 if (!strcmp(unit->abbr, "m")) {
517 root->width.value = 100*width;
518 root->width.unit = SVGLength::CM;
519 } else {
520 root->width.value = width;
521 root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
522 }
523 }
525 SP_OBJECT (root)->updateRepr();
526 }
528 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
529 {
530 SPRoot *root = SP_ROOT(document->root);
532 if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
533 root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
534 } else { // set to height=
535 root->height.computed = sp_units_get_pixels (height, *unit);
536 /* SVG does not support meters as a unit, so we must translate meters to
537 * cm when writing */
538 if (!strcmp(unit->abbr, "m")) {
539 root->height.value = 100*height;
540 root->height.unit = SVGLength::CM;
541 } else {
542 root->height.value = height;
543 root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
544 }
545 }
547 SP_OBJECT (root)->updateRepr();
548 }
550 gdouble sp_document_height(SPDocument *document)
551 {
552 g_return_val_if_fail(document != NULL, 0.0);
553 g_return_val_if_fail(document->priv != NULL, 0.0);
554 g_return_val_if_fail(document->root != NULL, 0.0);
556 SPRoot *root = SP_ROOT(document->root);
558 if (root->height.unit == SVGLength::PERCENT && root->viewBox_set)
559 return root->viewBox.y1 - root->viewBox.y0;
560 return root->height.computed;
561 }
563 /**
564 * Given a Geom::Rect that may, for example, correspond to the bbox of an object,
565 * this function fits the canvas to that rect by resizing the canvas
566 * and translating the document root into position.
567 */
568 void SPDocument::fitToRect(Geom::Rect const &rect)
569 {
570 g_return_if_fail(!rect.isEmpty());
572 double const w = rect.width();
573 double const h = rect.height();
575 double const old_height = sp_document_height(this);
576 SPUnit const &px(sp_unit_get_by_id(SP_UNIT_PX));
577 sp_document_set_width(this, w, &px);
578 sp_document_set_height(this, h, &px);
580 Geom::Translate const tr(Geom::Point(0, (old_height - h))
581 - to_2geom(rect.min()));
582 SP_GROUP(root)->translateChildItems(tr);
583 SPNamedView *nv = sp_document_namedview(this, 0);
584 if(nv) {
585 Geom::Translate tr2(-rect.min());
586 nv->translateGuides(tr2);
588 // update the viewport so the drawing appears to stay where it was
589 nv->scrollAllDesktops(-tr2[0], tr2[1], false);
590 }
591 }
593 void sp_document_set_uri(SPDocument *document, gchar const *uri)
594 {
595 g_return_if_fail(document != NULL);
597 if (document->name) {
598 g_free(document->name);
599 document->name = NULL;
600 }
601 if (document->base) {
602 g_free(document->base);
603 document->base = NULL;
604 }
605 if (document->uri) {
606 g_free(document->uri);
607 document->uri = NULL;
608 }
610 if (uri) {
612 #ifndef WIN32
613 prepend_current_dir_if_relative(&(document->uri), uri);
614 #else
615 // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
616 document->uri = g_strdup(uri);
617 #endif
619 /* fixme: Think, what this means for images (Lauris) */
620 document->base = g_path_get_dirname(document->uri);
621 document->name = g_path_get_basename(document->uri);
623 } else {
624 document->uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
625 document->base = NULL;
626 document->name = g_strdup(document->uri);
627 }
629 // Update saveable repr attributes.
630 Inkscape::XML::Node *repr = sp_document_repr_root(document);
631 // changing uri in the document repr must not be not undoable
632 bool saved = sp_document_get_undo_sensitive(document);
633 sp_document_set_undo_sensitive(document, false);
635 repr->setAttribute("sodipodi:docname", document->name);
636 sp_document_set_undo_sensitive(document, saved);
638 document->priv->uri_set_signal.emit(document->uri);
639 }
641 void
642 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
643 {
644 g_return_if_fail(doc != NULL);
646 doc->priv->resized_signal.emit(width, height);
647 }
649 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
650 {
651 return priv->modified_signal.connect(slot);
652 }
654 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
655 {
656 return priv->uri_set_signal.connect(slot);
657 }
659 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
660 {
661 return priv->resized_signal.connect(slot);
662 }
664 sigc::connection
665 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
666 {
667 return priv->_reconstruction_start_signal.connect(slot);
668 }
670 void
671 SPDocument::emitReconstructionStart(void)
672 {
673 // printf("Starting Reconstruction\n");
674 priv->_reconstruction_start_signal.emit();
675 return;
676 }
678 sigc::connection
679 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type slot)
680 {
681 return priv->_reconstruction_finish_signal.connect(slot);
682 }
684 void
685 SPDocument::emitReconstructionFinish(void)
686 {
687 // printf("Finishing Reconstruction\n");
688 priv->_reconstruction_finish_signal.emit();
689 return;
690 }
692 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
693 {
694 return priv->commit_signal.connect(slot);
695 }
699 void SPDocument::_emitModified() {
700 static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
701 root->emitModified(0);
702 priv->modified_signal.emit(flags);
703 }
705 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
706 GQuark idq = g_quark_from_string(id);
708 if (object) {
709 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
710 g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
711 } else {
712 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
713 g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
714 }
716 SPDocumentPrivate::IDChangedSignalMap::iterator pos;
718 pos = priv->id_changed_signals.find(idq);
719 if ( pos != priv->id_changed_signals.end() ) {
720 if (!(*pos).second.empty()) {
721 (*pos).second.emit(object);
722 } else { // discard unused signal
723 priv->id_changed_signals.erase(pos);
724 }
725 }
726 }
728 void
729 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
730 {
731 this->priv->undoStackObservers.add(observer);
732 }
734 void
735 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
736 {
737 this->priv->undoStackObservers.remove(observer);
738 }
740 SPObject *SPDocument::getObjectById(gchar const *id) {
741 g_return_val_if_fail(id != NULL, NULL);
743 GQuark idq = g_quark_from_string(id);
744 return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
745 }
747 sigc::connection SPDocument::connectIdChanged(gchar const *id,
748 SPDocument::IDChangedSignal::slot_type slot)
749 {
750 return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
751 }
753 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
754 if (object) {
755 g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
756 g_hash_table_insert(priv->reprdef, repr, object);
757 } else {
758 g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
759 g_hash_table_remove(priv->reprdef, repr);
760 }
761 }
763 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
764 g_return_val_if_fail(repr != NULL, NULL);
765 return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
766 }
768 Glib::ustring SPDocument::getLanguage() {
769 gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
770 if (document_language) {
771 while (isspace(*document_language))
772 document_language++;
773 }
774 if ( !document_language || 0 == *document_language) {
775 // retrieve system language
776 document_language = getenv("LC_ALL");
777 if ( NULL == document_language || *document_language == 0 ) {
778 document_language = getenv ("LC_MESSAGES");
779 }
780 if ( NULL == document_language || *document_language == 0 ) {
781 document_language = getenv ("LANG");
782 }
784 if ( NULL != document_language ) {
785 gchar *pos = strchr(document_language, '_');
786 if ( NULL != pos ) {
787 return Glib::ustring(document_language, pos - document_language);
788 }
789 }
790 }
792 if ( NULL == document_language )
793 return Glib::ustring();
794 return document_language;
795 }
797 /* Object modification root handler */
799 void
800 sp_document_request_modified(SPDocument *doc)
801 {
802 if (!doc->modified_id) {
803 doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
804 }
805 }
807 void
808 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
809 {
810 ctx->ctx.flags = 0;
811 ctx->i2doc = Geom::identity();
812 /* Set up viewport in case svg has it defined as percentages */
813 if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
814 ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
815 ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
816 ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
817 ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
818 } else { // as a last resort, set size to A4
819 ctx->vp.x0 = 0.0;
820 ctx->vp.y0 = 0.0;
821 ctx->vp.x1 = 210 * PX_PER_MM;
822 ctx->vp.y1 = 297 * PX_PER_MM;
823 }
824 ctx->i2vp = Geom::identity();
825 }
827 /**
828 * Tries to update the document state based on the modified and
829 * "update required" flags, and return true if the document has
830 * been brought fully up to date.
831 */
832 bool
833 SPDocument::_updateDocument()
834 {
835 /* Process updates */
836 if (this->root->uflags || this->root->mflags) {
837 if (this->root->uflags) {
838 SPItemCtx ctx;
839 sp_document_setup_viewport (this, &ctx);
841 bool saved = sp_document_get_undo_sensitive(this);
842 sp_document_set_undo_sensitive(this, false);
844 this->root->updateDisplay((SPCtx *)&ctx, 0);
846 sp_document_set_undo_sensitive(this, saved);
847 }
848 this->_emitModified();
849 }
851 return !(this->root->uflags || this->root->mflags);
852 }
855 /**
856 * Repeatedly works on getting the document updated, since sometimes
857 * it takes more than one pass to get the document updated. But it
858 * usually should not take more than a few loops, and certainly never
859 * more than 32 iterations. So we bail out if we hit 32 iterations,
860 * since this typically indicates we're stuck in an update loop.
861 */
862 gint
863 sp_document_ensure_up_to_date(SPDocument *doc)
864 {
865 int counter = 32;
866 while (!doc->_updateDocument()) {
867 if (counter == 0) {
868 g_warning("More than 32 iteration while updating document '%s'", doc->uri);
869 break;
870 }
871 counter--;
872 }
874 if (doc->modified_id) {
875 /* Remove handler */
876 gtk_idle_remove(doc->modified_id);
877 doc->modified_id = 0;
878 }
879 return counter>0;
880 }
882 /**
883 * An idle handler to update the document. Returns true if
884 * the document needs further updates.
885 */
886 static gint
887 sp_document_idle_handler(gpointer data)
888 {
889 SPDocument *doc = static_cast<SPDocument *>(data);
890 if (doc->_updateDocument()) {
891 doc->modified_id = 0;
892 return false;
893 } else {
894 return true;
895 }
896 }
898 static bool is_within(Geom::Rect const &area, Geom::Rect const &box)
899 {
900 return area.contains(box);
901 }
903 static bool overlaps(Geom::Rect const &area, Geom::Rect const &box)
904 {
905 return area.intersects(box);
906 }
908 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, Geom::Rect const &area,
909 bool (*test)(Geom::Rect const &, Geom::Rect const &), bool take_insensitive = false)
910 {
911 g_return_val_if_fail(SP_IS_GROUP(group), s);
913 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
914 if (!SP_IS_ITEM(o)) {
915 continue;
916 }
917 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
918 s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
919 } else {
920 SPItem *child = SP_ITEM(o);
921 boost::optional<Geom::Rect> box = sp_item_bbox_desktop(child);
922 if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
923 s = g_slist_append(s, child);
924 }
925 }
926 }
928 return s;
929 }
931 /**
932 Returns true if an item is among the descendants of group (recursively).
933 */
934 bool item_is_in_group(SPItem *item, SPGroup *group)
935 {
936 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
937 if (!SP_IS_ITEM(o)) continue;
938 if (SP_ITEM(o) == item)
939 return true;
940 if (SP_IS_GROUP(o))
941 if (item_is_in_group(item, SP_GROUP(o)))
942 return true;
943 }
944 return false;
945 }
947 /**
948 Returns the bottommost item from the list which is at the point, or NULL if none.
949 */
950 SPItem*
951 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
952 Geom::Point const p, bool take_insensitive)
953 {
954 g_return_val_if_fail(group, NULL);
955 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
956 gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
958 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
960 if (!SP_IS_ITEM(o)) continue;
962 SPItem *item = SP_ITEM(o);
963 NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
964 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
965 && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
966 if (g_slist_find((GSList *) list, item) != NULL)
967 return item;
968 }
970 if (SP_IS_GROUP(o)) {
971 SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
972 if (found)
973 return found;
974 }
976 }
977 return NULL;
978 }
980 /**
981 Returns the topmost (in z-order) item from the descendants of group (recursively) which
982 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
983 non-layer groups or not. Honors take_insensitive on whether to return insensitive
984 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
985 upwards in z-order and returns what it has found so far (i.e. the found item is
986 guaranteed to be lower than upto).
987 */
988 SPItem*
989 find_item_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
990 {
991 SPItem *seen = NULL, *newseen = NULL;
992 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
993 gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
995 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
996 if (!SP_IS_ITEM(o)) continue;
998 if (upto && SP_ITEM(o) == upto)
999 break;
1001 if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
1002 // if nothing found yet, recurse into the group
1003 newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
1004 if (newseen) {
1005 seen = newseen;
1006 newseen = NULL;
1007 }
1009 if (item_is_in_group(upto, SP_GROUP(o)))
1010 break;
1012 } else {
1013 SPItem *child = SP_ITEM(o);
1014 NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1016 // seen remembers the last (topmost) of items pickable at this point
1017 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1018 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1019 seen = child;
1020 }
1021 }
1022 }
1023 return seen;
1024 }
1026 /**
1027 Returns the topmost non-layer group from the descendants of group which is at point
1028 p, or NULL if none. Recurses into layers but not into groups.
1029 */
1030 SPItem*
1031 find_group_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p)
1032 {
1033 SPItem *seen = NULL;
1034 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1035 gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1037 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1038 if (!SP_IS_ITEM(o)) continue;
1039 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1040 SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1041 if (newseen) {
1042 seen = newseen;
1043 }
1044 }
1045 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1046 SPItem *child = SP_ITEM(o);
1047 NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1049 // seen remembers the last (topmost) of groups pickable at this point
1050 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1051 seen = child;
1052 }
1053 }
1054 }
1055 return seen;
1056 }
1058 /*
1059 * Return list of items, contained in box
1060 *
1061 * Assumes box is normalized (and g_asserts it!)
1062 *
1063 */
1065 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1066 {
1067 g_return_val_if_fail(document != NULL, NULL);
1068 g_return_val_if_fail(document->priv != NULL, NULL);
1070 return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
1071 }
1073 /*
1074 * Return list of items, that the parts of the item contained in box
1075 *
1076 * Assumes box is normalized (and g_asserts it!)
1077 *
1078 */
1080 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1081 {
1082 g_return_val_if_fail(document != NULL, NULL);
1083 g_return_val_if_fail(document->priv != NULL, NULL);
1085 return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1086 }
1088 GSList *
1089 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<Geom::Point> points)
1090 {
1091 GSList *items = NULL;
1092 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1094 // When picking along the path, we don't want small objects close together
1095 // (such as hatching strokes) to obscure each other by their deltas,
1096 // so we temporarily set delta to a small value
1097 gdouble saved_delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1098 prefs->setDouble("/options/cursortolerance/value", 0.25);
1100 for(unsigned int i = 0; i < points.size(); i++) {
1101 SPItem *item = sp_document_item_at_point(document, key, points[i],
1102 false, NULL);
1103 if (item && !g_slist_find(items, item))
1104 items = g_slist_prepend (items, item);
1105 }
1107 // and now we restore it back
1108 prefs->setDouble("/options/cursortolerance/value", saved_delta);
1110 return items;
1111 }
1113 SPItem *
1114 sp_document_item_at_point(SPDocument *document, unsigned const key, Geom::Point const p,
1115 gboolean const into_groups, SPItem *upto)
1116 {
1117 g_return_val_if_fail(document != NULL, NULL);
1118 g_return_val_if_fail(document->priv != NULL, NULL);
1120 return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1121 }
1123 SPItem*
1124 sp_document_group_at_point(SPDocument *document, unsigned int key, Geom::Point const p)
1125 {
1126 g_return_val_if_fail(document != NULL, NULL);
1127 g_return_val_if_fail(document->priv != NULL, NULL);
1129 return find_group_at_point(key, SP_GROUP(document->root), p);
1130 }
1133 /* Resource management */
1135 gboolean
1136 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1137 {
1138 GSList *rlist;
1139 GQuark q = g_quark_from_string(key);
1141 g_return_val_if_fail(document != NULL, FALSE);
1142 g_return_val_if_fail(key != NULL, FALSE);
1143 g_return_val_if_fail(*key != '\0', FALSE);
1144 g_return_val_if_fail(object != NULL, FALSE);
1145 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1147 if (SP_OBJECT_IS_CLONED(object))
1148 return FALSE;
1150 rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1151 g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1152 rlist = g_slist_prepend(rlist, object);
1153 g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1155 document->priv->resources_changed_signals[q].emit();
1157 return TRUE;
1158 }
1160 gboolean
1161 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1162 {
1163 GSList *rlist;
1164 GQuark q = g_quark_from_string(key);
1166 g_return_val_if_fail(document != NULL, FALSE);
1167 g_return_val_if_fail(key != NULL, FALSE);
1168 g_return_val_if_fail(*key != '\0', FALSE);
1169 g_return_val_if_fail(object != NULL, FALSE);
1170 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1172 if (SP_OBJECT_IS_CLONED(object))
1173 return FALSE;
1175 rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1176 g_return_val_if_fail(rlist != NULL, FALSE);
1177 g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1178 rlist = g_slist_remove(rlist, object);
1179 g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1181 document->priv->resources_changed_signals[q].emit();
1183 return TRUE;
1184 }
1186 GSList const *
1187 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1188 {
1189 g_return_val_if_fail(document != NULL, NULL);
1190 g_return_val_if_fail(key != NULL, NULL);
1191 g_return_val_if_fail(*key != '\0', NULL);
1193 return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1194 }
1196 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1197 gchar const *key,
1198 SPDocument::ResourcesChangedSignal::slot_type slot)
1199 {
1200 GQuark q = g_quark_from_string(key);
1201 return document->priv->resources_changed_signals[q].connect(slot);
1202 }
1204 /* Helpers */
1206 gboolean
1207 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1208 {
1209 g_slist_free((GSList *) value);
1210 return TRUE;
1211 }
1213 unsigned int
1214 count_objects_recursive(SPObject *obj, unsigned int count)
1215 {
1216 count++; // obj itself
1218 for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1219 count = count_objects_recursive(i, count);
1220 }
1222 return count;
1223 }
1225 unsigned int
1226 objects_in_document(SPDocument *document)
1227 {
1228 return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1229 }
1231 void
1232 vacuum_document_recursive(SPObject *obj)
1233 {
1234 if (SP_IS_DEFS(obj)) {
1235 for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1236 /* fixme: some inkscape-internal nodes in the future might not be collectable */
1237 def->requestOrphanCollection();
1238 }
1239 } else {
1240 for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1241 vacuum_document_recursive(i);
1242 }
1243 }
1244 }
1246 unsigned int
1247 vacuum_document(SPDocument *document)
1248 {
1249 unsigned int start = objects_in_document(document);
1250 unsigned int end;
1251 unsigned int newend = start;
1253 unsigned int iterations = 0;
1255 do {
1256 end = newend;
1258 vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1259 document->collectOrphans();
1260 iterations++;
1262 newend = objects_in_document(document);
1264 } while (iterations < 100 && newend < end);
1266 return start - newend;
1267 }
1269 bool SPDocument::isSeeking() const {
1270 return priv->seeking;
1271 }
1274 /*
1275 Local Variables:
1276 mode:c++
1277 c-file-style:"stroustrup"
1278 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1279 indent-tabs-mode:nil
1280 fill-column:99
1281 End:
1282 */
1283 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :