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 "prefs-utils.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;
262 rroot = rdoc->root();
264 document = new SPDocument();
266 document->keepalive = keepalive;
268 document->rdoc = rdoc;
269 document->rroot = rroot;
271 #ifndef WIN32
272 prepend_current_dir_if_relative(&(document->uri), uri);
273 #else
274 // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
275 document->uri = uri? g_strdup(uri) : NULL;
276 #endif
278 // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
279 // which is why we use g_get_current_dir() in calculating the abs path above
280 //This is NULL for a new document
281 if (base)
282 document->base = g_strdup(base);
283 else
284 document->base = NULL;
285 document->name = g_strdup(name);
287 document->root = sp_object_repr_build_tree(document, rroot);
289 sodipodi_version = SP_ROOT(document->root)->version.sodipodi;
291 /* fixme: Not sure about this, but lets assume ::build updates */
292 rroot->setAttribute("sodipodi:version", SODIPODI_VERSION);
293 rroot->setAttribute("inkscape:version", INKSCAPE_VERSION);
294 /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
296 /* Quick hack 2 - get default image size into document */
297 if (!rroot->attribute("width")) rroot->setAttribute("width", "100%");
298 if (!rroot->attribute("height")) rroot->setAttribute("height", "100%");
299 /* End of quick hack 2 */
301 /* Quick hack 3 - Set uri attributes */
302 if (uri) {
303 rroot->setAttribute("sodipodi:docname", uri);
304 }
305 /* End of quick hack 3 */
307 /* Eliminate obsolete sodipodi:docbase, for privacy reasons */
308 rroot->setAttribute("sodipodi:docbase", NULL);
310 /* Eliminate any claim to adhere to a profile, as we don't try to */
311 rroot->setAttribute("baseProfile", NULL);
313 // creating namedview
314 if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
315 // if there's none in the document already,
316 Inkscape::XML::Node *r = NULL;
317 Inkscape::XML::Node *rnew = NULL;
318 r = inkscape_get_repr(INKSCAPE, "template.base");
319 // see if there's a template with id="base" in the preferences
320 if (!r) {
321 // if there's none, create an empty element
322 rnew = rdoc->createElement("sodipodi:namedview");
323 rnew->setAttribute("id", "base");
324 } else {
325 // otherwise, take from preferences
326 rnew = r->duplicate(rroot->document());
327 }
328 // insert into the document
329 rroot->addChild(rnew, NULL);
330 // clean up
331 Inkscape::GC::release(rnew);
332 }
334 /* Defs */
335 if (!SP_ROOT(document->root)->defs) {
336 Inkscape::XML::Node *r;
337 r = rdoc->createElement("svg:defs");
338 rroot->addChild(r, NULL);
339 Inkscape::GC::release(r);
340 g_assert(SP_ROOT(document->root)->defs);
341 }
343 /* Default RDF */
344 rdf_set_defaults( document );
346 if (keepalive) {
347 inkscape_ref();
348 }
350 // Remark: Here, we used to create a "currentpersp3d" element in the document defs.
351 // But this is probably a bad idea since we need to adapt it for every change of selection, which will
352 // completely clutter the undo history. Maybe rather save it to prefs on exit and re-read it on startup?
354 document->current_persp3d = persp3d_document_first_persp(document);
355 if (!document->current_persp3d) {
356 document->current_persp3d = persp3d_create_xml_element (document);
357 }
359 sp_document_set_undo_sensitive(document, true);
361 // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
362 if (!Inkscape::NSApplication::Application::getNewGui()) {
363 g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
364 G_CALLBACK(sp_document_reset_key), document);
365 g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
366 G_CALLBACK(sp_document_reset_key), document);
367 } else {
368 document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
369 document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
370 }
372 return document;
373 }
375 /**
376 * Fetches document from URI, or creates new, if NULL; public document
377 * appears in document list.
378 */
379 SPDocument *
380 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
381 {
382 SPDocument *doc;
383 Inkscape::XML::Document *rdoc;
384 gchar *base = NULL;
385 gchar *name = NULL;
387 if (uri) {
388 Inkscape::XML::Node *rroot;
389 gchar *s, *p;
390 /* Try to fetch repr from file */
391 rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
392 /* If file cannot be loaded, return NULL without warning */
393 if (rdoc == NULL) return NULL;
394 rroot = rdoc->root();
395 /* If xml file is not svg, return NULL without warning */
396 /* fixme: destroy document */
397 if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
398 s = g_strdup(uri);
399 p = strrchr(s, '/');
400 if (p) {
401 name = g_strdup(p + 1);
402 p[1] = '\0';
403 base = g_strdup(s);
404 } else {
405 base = NULL;
406 name = g_strdup(uri);
407 }
408 g_free(s);
409 } else {
410 rdoc = sp_repr_document_new("svg:svg");
411 }
413 if (make_new) {
414 base = NULL;
415 uri = NULL;
416 name = g_strdup_printf(_("New document %d"), ++doc_count);
417 }
419 //# These should be set by now
420 g_assert(name);
422 doc = sp_document_create(rdoc, uri, base, name, keepalive);
424 g_free(base);
425 g_free(name);
427 return doc;
428 }
430 SPDocument *
431 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
432 {
433 SPDocument *doc;
434 Inkscape::XML::Document *rdoc;
435 Inkscape::XML::Node *rroot;
436 gchar *name;
438 rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
440 /* If it cannot be loaded, return NULL without warning */
441 if (rdoc == NULL) return NULL;
443 rroot = rdoc->root();
444 /* If xml file is not svg, return NULL without warning */
445 /* fixme: destroy document */
446 if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
448 name = g_strdup_printf(_("Memory document %d"), ++doc_count);
450 doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
452 return doc;
453 }
455 SPDocument *
456 sp_document_ref(SPDocument *doc)
457 {
458 g_return_val_if_fail(doc != NULL, NULL);
459 Inkscape::GC::anchor(doc);
460 return doc;
461 }
463 SPDocument *
464 sp_document_unref(SPDocument *doc)
465 {
466 g_return_val_if_fail(doc != NULL, NULL);
467 Inkscape::GC::release(doc);
468 return NULL;
469 }
471 gdouble sp_document_width(SPDocument *document)
472 {
473 g_return_val_if_fail(document != NULL, 0.0);
474 g_return_val_if_fail(document->priv != NULL, 0.0);
475 g_return_val_if_fail(document->root != NULL, 0.0);
477 SPRoot *root = SP_ROOT(document->root);
479 if (root->width.unit == SVGLength::PERCENT && root->viewBox_set)
480 return root->viewBox.x1 - root->viewBox.x0;
481 return root->width.computed;
482 }
484 void
485 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
486 {
487 SPRoot *root = SP_ROOT(document->root);
489 if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
490 root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
491 } else { // set to width=
492 root->width.computed = sp_units_get_pixels (width, *unit);
493 /* SVG does not support meters as a unit, so we must translate meters to
494 * cm when writing */
495 if (!strcmp(unit->abbr, "m")) {
496 root->width.value = 100*width;
497 root->width.unit = SVGLength::CM;
498 } else {
499 root->width.value = width;
500 root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
501 }
502 }
504 SP_OBJECT (root)->updateRepr();
505 }
507 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
508 {
509 SPRoot *root = SP_ROOT(document->root);
511 if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
512 root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
513 } else { // set to height=
514 root->height.computed = sp_units_get_pixels (height, *unit);
515 /* SVG does not support meters as a unit, so we must translate meters to
516 * cm when writing */
517 if (!strcmp(unit->abbr, "m")) {
518 root->height.value = 100*height;
519 root->height.unit = SVGLength::CM;
520 } else {
521 root->height.value = height;
522 root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
523 }
524 }
526 SP_OBJECT (root)->updateRepr();
527 }
529 gdouble sp_document_height(SPDocument *document)
530 {
531 g_return_val_if_fail(document != NULL, 0.0);
532 g_return_val_if_fail(document->priv != NULL, 0.0);
533 g_return_val_if_fail(document->root != NULL, 0.0);
535 SPRoot *root = SP_ROOT(document->root);
537 if (root->height.unit == SVGLength::PERCENT && root->viewBox_set)
538 return root->viewBox.y1 - root->viewBox.y0;
539 return root->height.computed;
540 }
542 /**
543 * Given a Geom::Rect that may, for example, correspond to the bbox of an object,
544 * this function fits the canvas to that rect by resizing the canvas
545 * and translating the document root into position.
546 */
547 void SPDocument::fitToRect(Geom::Rect const &rect)
548 {
549 g_return_if_fail(!rect.isEmpty());
551 double const w = rect.width();
552 double const h = rect.height();
554 double const old_height = sp_document_height(this);
555 SPUnit const &px(sp_unit_get_by_id(SP_UNIT_PX));
556 sp_document_set_width(this, w, &px);
557 sp_document_set_height(this, h, &px);
559 Geom::Translate const tr(Geom::Point(0, (old_height - h))
560 - to_2geom(rect.min()));
561 SP_GROUP(root)->translateChildItems(tr);
562 SPNamedView *nv = sp_document_namedview(this, 0);
563 if(nv) {
564 Geom::Translate tr2(-rect.min());
565 nv->translateGuides(tr2);
567 // update the viewport so the drawing appears to stay where it was
568 nv->scrollAllDesktops(-tr2[0], tr2[1], false);
569 }
570 }
572 void sp_document_set_uri(SPDocument *document, gchar const *uri)
573 {
574 g_return_if_fail(document != NULL);
576 if (document->name) {
577 g_free(document->name);
578 document->name = NULL;
579 }
580 if (document->base) {
581 g_free(document->base);
582 document->base = NULL;
583 }
584 if (document->uri) {
585 g_free(document->uri);
586 document->uri = NULL;
587 }
589 if (uri) {
591 #ifndef WIN32
592 prepend_current_dir_if_relative(&(document->uri), uri);
593 #else
594 // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
595 document->uri = g_strdup(uri);
596 #endif
598 /* fixme: Think, what this means for images (Lauris) */
599 document->base = g_path_get_dirname(document->uri);
600 document->name = g_path_get_basename(document->uri);
602 } else {
603 document->uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
604 document->base = NULL;
605 document->name = g_strdup(document->uri);
606 }
608 // Update saveable repr attributes.
609 Inkscape::XML::Node *repr = sp_document_repr_root(document);
610 // changing uri in the document repr must not be not undoable
611 bool saved = sp_document_get_undo_sensitive(document);
612 sp_document_set_undo_sensitive(document, false);
614 repr->setAttribute("sodipodi:docname", document->name);
615 sp_document_set_undo_sensitive(document, saved);
617 document->priv->uri_set_signal.emit(document->uri);
618 }
620 void
621 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
622 {
623 g_return_if_fail(doc != NULL);
625 doc->priv->resized_signal.emit(width, height);
626 }
628 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
629 {
630 return priv->modified_signal.connect(slot);
631 }
633 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
634 {
635 return priv->uri_set_signal.connect(slot);
636 }
638 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
639 {
640 return priv->resized_signal.connect(slot);
641 }
643 sigc::connection
644 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
645 {
646 return priv->_reconstruction_start_signal.connect(slot);
647 }
649 void
650 SPDocument::emitReconstructionStart(void)
651 {
652 // printf("Starting Reconstruction\n");
653 priv->_reconstruction_start_signal.emit();
654 return;
655 }
657 sigc::connection
658 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type slot)
659 {
660 return priv->_reconstruction_finish_signal.connect(slot);
661 }
663 void
664 SPDocument::emitReconstructionFinish(void)
665 {
666 // printf("Finishing Reconstruction\n");
667 priv->_reconstruction_finish_signal.emit();
668 return;
669 }
671 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
672 {
673 return priv->commit_signal.connect(slot);
674 }
678 void SPDocument::_emitModified() {
679 static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
680 root->emitModified(0);
681 priv->modified_signal.emit(flags);
682 }
684 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
685 GQuark idq = g_quark_from_string(id);
687 if (object) {
688 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
689 g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
690 } else {
691 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
692 g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
693 }
695 SPDocumentPrivate::IDChangedSignalMap::iterator pos;
697 pos = priv->id_changed_signals.find(idq);
698 if ( pos != priv->id_changed_signals.end() ) {
699 if (!(*pos).second.empty()) {
700 (*pos).second.emit(object);
701 } else { // discard unused signal
702 priv->id_changed_signals.erase(pos);
703 }
704 }
705 }
707 void
708 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
709 {
710 this->priv->undoStackObservers.add(observer);
711 }
713 void
714 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
715 {
716 this->priv->undoStackObservers.remove(observer);
717 }
719 SPObject *SPDocument::getObjectById(gchar const *id) {
720 g_return_val_if_fail(id != NULL, NULL);
722 GQuark idq = g_quark_from_string(id);
723 return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
724 }
726 sigc::connection SPDocument::connectIdChanged(gchar const *id,
727 SPDocument::IDChangedSignal::slot_type slot)
728 {
729 return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
730 }
732 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
733 if (object) {
734 g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
735 g_hash_table_insert(priv->reprdef, repr, object);
736 } else {
737 g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
738 g_hash_table_remove(priv->reprdef, repr);
739 }
740 }
742 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
743 g_return_val_if_fail(repr != NULL, NULL);
744 return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
745 }
747 Glib::ustring SPDocument::getLanguage() {
748 gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
749 if (document_language) {
750 while (isspace(*document_language))
751 document_language++;
752 }
753 if ( !document_language || 0 == *document_language) {
754 // retrieve system language
755 document_language = getenv("LC_ALL");
756 if ( NULL == document_language || *document_language == 0 ) {
757 document_language = getenv ("LC_MESSAGES");
758 }
759 if ( NULL == document_language || *document_language == 0 ) {
760 document_language = getenv ("LANG");
761 }
763 if ( NULL != document_language ) {
764 gchar *pos = strchr(document_language, '_');
765 if ( NULL != pos ) {
766 return Glib::ustring(document_language, pos - document_language);
767 }
768 }
769 }
771 if ( NULL == document_language )
772 return Glib::ustring();
773 return document_language;
774 }
776 /* Object modification root handler */
778 void
779 sp_document_request_modified(SPDocument *doc)
780 {
781 if (!doc->modified_id) {
782 doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
783 }
784 }
786 void
787 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
788 {
789 ctx->ctx.flags = 0;
790 ctx->i2doc = Geom::identity();
791 /* Set up viewport in case svg has it defined as percentages */
792 if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
793 ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
794 ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
795 ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
796 ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
797 } else { // as a last resort, set size to A4
798 ctx->vp.x0 = 0.0;
799 ctx->vp.y0 = 0.0;
800 ctx->vp.x1 = 210 * PX_PER_MM;
801 ctx->vp.y1 = 297 * PX_PER_MM;
802 }
803 ctx->i2vp = Geom::identity();
804 }
806 /**
807 * Tries to update the document state based on the modified and
808 * "update required" flags, and return true if the document has
809 * been brought fully up to date.
810 */
811 bool
812 SPDocument::_updateDocument()
813 {
814 /* Process updates */
815 if (this->root->uflags || this->root->mflags) {
816 if (this->root->uflags) {
817 SPItemCtx ctx;
818 sp_document_setup_viewport (this, &ctx);
820 bool saved = sp_document_get_undo_sensitive(this);
821 sp_document_set_undo_sensitive(this, false);
823 this->root->updateDisplay((SPCtx *)&ctx, 0);
825 sp_document_set_undo_sensitive(this, saved);
826 }
827 this->_emitModified();
828 }
830 return !(this->root->uflags || this->root->mflags);
831 }
834 /**
835 * Repeatedly works on getting the document updated, since sometimes
836 * it takes more than one pass to get the document updated. But it
837 * usually should not take more than a few loops, and certainly never
838 * more than 32 iterations. So we bail out if we hit 32 iterations,
839 * since this typically indicates we're stuck in an update loop.
840 */
841 gint
842 sp_document_ensure_up_to_date(SPDocument *doc)
843 {
844 int counter = 32;
845 while (!doc->_updateDocument()) {
846 if (counter == 0) {
847 g_warning("More than 32 iteration while updating document '%s'", doc->uri);
848 break;
849 }
850 counter--;
851 }
853 if (doc->modified_id) {
854 /* Remove handler */
855 gtk_idle_remove(doc->modified_id);
856 doc->modified_id = 0;
857 }
858 return counter>0;
859 }
861 /**
862 * An idle handler to update the document. Returns true if
863 * the document needs further updates.
864 */
865 static gint
866 sp_document_idle_handler(gpointer data)
867 {
868 SPDocument *doc = static_cast<SPDocument *>(data);
869 if (doc->_updateDocument()) {
870 doc->modified_id = 0;
871 return false;
872 } else {
873 return true;
874 }
875 }
877 static bool is_within(Geom::Rect const &area, Geom::Rect const &box)
878 {
879 return area.contains(box);
880 }
882 static bool overlaps(Geom::Rect const &area, Geom::Rect const &box)
883 {
884 return area.intersects(box);
885 }
887 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, Geom::Rect const &area,
888 bool (*test)(Geom::Rect const &, Geom::Rect const &), bool take_insensitive = false)
889 {
890 g_return_val_if_fail(SP_IS_GROUP(group), s);
892 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
893 if (!SP_IS_ITEM(o)) {
894 continue;
895 }
896 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
897 s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
898 } else {
899 SPItem *child = SP_ITEM(o);
900 boost::optional<Geom::Rect> box = to_2geom(sp_item_bbox_desktop(child));
901 if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
902 s = g_slist_append(s, child);
903 }
904 }
905 }
907 return s;
908 }
910 /**
911 Returns true if an item is among the descendants of group (recursively).
912 */
913 bool item_is_in_group(SPItem *item, SPGroup *group)
914 {
915 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
916 if (!SP_IS_ITEM(o)) continue;
917 if (SP_ITEM(o) == item)
918 return true;
919 if (SP_IS_GROUP(o))
920 if (item_is_in_group(item, SP_GROUP(o)))
921 return true;
922 }
923 return false;
924 }
926 /**
927 Returns the bottommost item from the list which is at the point, or NULL if none.
928 */
929 SPItem*
930 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
931 Geom::Point const p, bool take_insensitive)
932 {
933 g_return_val_if_fail(group, NULL);
935 gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
937 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
939 if (!SP_IS_ITEM(o)) continue;
941 SPItem *item = SP_ITEM(o);
942 NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
943 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
944 && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
945 if (g_slist_find((GSList *) list, item) != NULL)
946 return item;
947 }
949 if (SP_IS_GROUP(o)) {
950 SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
951 if (found)
952 return found;
953 }
955 }
956 return NULL;
957 }
959 /**
960 Returns the topmost (in z-order) item from the descendants of group (recursively) which
961 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
962 non-layer groups or not. Honors take_insensitive on whether to return insensitive
963 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
964 upwards in z-order and returns what it has found so far (i.e. the found item is
965 guaranteed to be lower than upto).
966 */
967 SPItem*
968 find_item_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
969 {
970 SPItem *seen = NULL, *newseen = NULL;
972 gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
974 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
975 if (!SP_IS_ITEM(o)) continue;
977 if (upto && SP_ITEM(o) == upto)
978 break;
980 if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
981 // if nothing found yet, recurse into the group
982 newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
983 if (newseen) {
984 seen = newseen;
985 newseen = NULL;
986 }
988 if (item_is_in_group(upto, SP_GROUP(o)))
989 break;
991 } else {
992 SPItem *child = SP_ITEM(o);
993 NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
995 // seen remembers the last (topmost) of items pickable at this point
996 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
997 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
998 seen = child;
999 }
1000 }
1001 }
1002 return seen;
1003 }
1005 /**
1006 Returns the topmost non-layer group from the descendants of group which is at point
1007 p, or NULL if none. Recurses into layers but not into groups.
1008 */
1009 SPItem*
1010 find_group_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p)
1011 {
1012 SPItem *seen = NULL;
1014 gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
1016 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1017 if (!SP_IS_ITEM(o)) continue;
1018 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1019 SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1020 if (newseen) {
1021 seen = newseen;
1022 }
1023 }
1024 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1025 SPItem *child = SP_ITEM(o);
1026 NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1028 // seen remembers the last (topmost) of groups pickable at this point
1029 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1030 seen = child;
1031 }
1032 }
1033 }
1034 return seen;
1035 }
1037 /*
1038 * Return list of items, contained in box
1039 *
1040 * Assumes box is normalized (and g_asserts it!)
1041 *
1042 */
1044 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1045 {
1046 g_return_val_if_fail(document != NULL, NULL);
1047 g_return_val_if_fail(document->priv != NULL, NULL);
1049 return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
1050 }
1052 /*
1053 * Return list of items, that the parts of the item contained in box
1054 *
1055 * Assumes box is normalized (and g_asserts it!)
1056 *
1057 */
1059 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, Geom::Rect const &box)
1060 {
1061 g_return_val_if_fail(document != NULL, NULL);
1062 g_return_val_if_fail(document->priv != NULL, NULL);
1064 return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1065 }
1067 GSList *
1068 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<Geom::Point> points)
1069 {
1070 GSList *items = NULL;
1072 // When picking along the path, we don't want small objects close together
1073 // (such as hatching strokes) to obscure each other by their deltas,
1074 // so we temporarily set delta to a small value
1075 gdouble saved_delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
1076 prefs_set_double_attribute ("options.cursortolerance", "value", 0.25);
1078 for(unsigned int i = 0; i < points.size(); i++) {
1079 SPItem *item = sp_document_item_at_point(document, key, points[i],
1080 false, NULL);
1081 if (item && !g_slist_find(items, item))
1082 items = g_slist_prepend (items, item);
1083 }
1085 // and now we restore it back
1086 prefs_set_double_attribute ("options.cursortolerance", "value", saved_delta);
1088 return items;
1089 }
1091 SPItem *
1092 sp_document_item_at_point(SPDocument *document, unsigned const key, Geom::Point const p,
1093 gboolean const into_groups, SPItem *upto)
1094 {
1095 g_return_val_if_fail(document != NULL, NULL);
1096 g_return_val_if_fail(document->priv != NULL, NULL);
1098 return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1099 }
1101 SPItem*
1102 sp_document_group_at_point(SPDocument *document, unsigned int key, Geom::Point const p)
1103 {
1104 g_return_val_if_fail(document != NULL, NULL);
1105 g_return_val_if_fail(document->priv != NULL, NULL);
1107 return find_group_at_point(key, SP_GROUP(document->root), p);
1108 }
1111 /* Resource management */
1113 gboolean
1114 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1115 {
1116 GSList *rlist;
1117 GQuark q = g_quark_from_string(key);
1119 g_return_val_if_fail(document != NULL, FALSE);
1120 g_return_val_if_fail(key != NULL, FALSE);
1121 g_return_val_if_fail(*key != '\0', FALSE);
1122 g_return_val_if_fail(object != NULL, FALSE);
1123 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1125 if (SP_OBJECT_IS_CLONED(object))
1126 return FALSE;
1128 rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1129 g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1130 rlist = g_slist_prepend(rlist, object);
1131 g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1133 document->priv->resources_changed_signals[q].emit();
1135 return TRUE;
1136 }
1138 gboolean
1139 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1140 {
1141 GSList *rlist;
1142 GQuark q = g_quark_from_string(key);
1144 g_return_val_if_fail(document != NULL, FALSE);
1145 g_return_val_if_fail(key != NULL, FALSE);
1146 g_return_val_if_fail(*key != '\0', FALSE);
1147 g_return_val_if_fail(object != NULL, FALSE);
1148 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1150 if (SP_OBJECT_IS_CLONED(object))
1151 return FALSE;
1153 rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1154 g_return_val_if_fail(rlist != NULL, FALSE);
1155 g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1156 rlist = g_slist_remove(rlist, object);
1157 g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1159 document->priv->resources_changed_signals[q].emit();
1161 return TRUE;
1162 }
1164 GSList const *
1165 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1166 {
1167 g_return_val_if_fail(document != NULL, NULL);
1168 g_return_val_if_fail(key != NULL, NULL);
1169 g_return_val_if_fail(*key != '\0', NULL);
1171 return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1172 }
1174 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1175 gchar const *key,
1176 SPDocument::ResourcesChangedSignal::slot_type slot)
1177 {
1178 GQuark q = g_quark_from_string(key);
1179 return document->priv->resources_changed_signals[q].connect(slot);
1180 }
1182 /* Helpers */
1184 gboolean
1185 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1186 {
1187 g_slist_free((GSList *) value);
1188 return TRUE;
1189 }
1191 unsigned int
1192 count_objects_recursive(SPObject *obj, unsigned int count)
1193 {
1194 count++; // obj itself
1196 for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1197 count = count_objects_recursive(i, count);
1198 }
1200 return count;
1201 }
1203 unsigned int
1204 objects_in_document(SPDocument *document)
1205 {
1206 return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1207 }
1209 void
1210 vacuum_document_recursive(SPObject *obj)
1211 {
1212 if (SP_IS_DEFS(obj)) {
1213 for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1214 /* fixme: some inkscape-internal nodes in the future might not be collectable */
1215 def->requestOrphanCollection();
1216 }
1217 } else {
1218 for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1219 vacuum_document_recursive(i);
1220 }
1221 }
1222 }
1224 unsigned int
1225 vacuum_document(SPDocument *document)
1226 {
1227 unsigned int start = objects_in_document(document);
1228 unsigned int end;
1229 unsigned int newend = start;
1231 unsigned int iterations = 0;
1233 do {
1234 end = newend;
1236 vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1237 document->collectOrphans();
1238 iterations++;
1240 newend = objects_in_document(document);
1242 } while (iterations < 100 && newend < end);
1244 return start - newend;
1245 }
1247 bool SPDocument::isSeeking() const {
1248 return priv->seeking;
1249 }
1252 /*
1253 Local Variables:
1254 mode:c++
1255 c-file-style:"stroustrup"
1256 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1257 indent-tabs-mode:nil
1258 fill-column:99
1259 End:
1260 */
1261 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :