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