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 any claim to adhere to a profile, as we don't try to */
310 rroot->setAttribute("baseProfile", NULL);
312 // creating namedview
313 if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
314 // if there's none in the document already,
315 Inkscape::XML::Node *r = NULL;
316 Inkscape::XML::Node *rnew = NULL;
317 r = inkscape_get_repr(INKSCAPE, "template.base");
318 // see if there's a template with id="base" in the preferences
319 if (!r) {
320 // if there's none, create an empty element
321 rnew = rdoc->createElement("sodipodi:namedview");
322 rnew->setAttribute("id", "base");
323 } else {
324 // otherwise, take from preferences
325 rnew = r->duplicate(rroot->document());
326 }
327 // insert into the document
328 rroot->addChild(rnew, NULL);
329 // clean up
330 Inkscape::GC::release(rnew);
331 }
333 /* Defs */
334 if (!SP_ROOT(document->root)->defs) {
335 Inkscape::XML::Node *r;
336 r = rdoc->createElement("svg:defs");
337 rroot->addChild(r, NULL);
338 Inkscape::GC::release(r);
339 g_assert(SP_ROOT(document->root)->defs);
340 }
342 /* Default RDF */
343 rdf_set_defaults( document );
345 if (keepalive) {
346 inkscape_ref();
347 }
349 // Remark: Here, we used to create a "currentpersp3d" element in the document defs.
350 // But this is probably a bad idea since we need to adapt it for every change of selection, which will
351 // completely clutter the undo history. Maybe rather save it to prefs on exit and re-read it on startup?
353 document->current_persp3d = persp3d_document_first_persp(document);
354 if (!document->current_persp3d) {
355 document->current_persp3d = persp3d_create_xml_element (document);
356 }
358 sp_document_set_undo_sensitive(document, true);
360 // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
361 if (!Inkscape::NSApplication::Application::getNewGui()) {
362 g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
363 G_CALLBACK(sp_document_reset_key), document);
364 g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
365 G_CALLBACK(sp_document_reset_key), document);
366 } else {
367 document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
368 document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
369 }
371 return document;
372 }
374 /**
375 * Fetches document from URI, or creates new, if NULL; public document
376 * appears in document list.
377 */
378 SPDocument *
379 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
380 {
381 SPDocument *doc;
382 Inkscape::XML::Document *rdoc;
383 gchar *base = NULL;
384 gchar *name = NULL;
386 if (uri) {
387 Inkscape::XML::Node *rroot;
388 gchar *s, *p;
389 /* Try to fetch repr from file */
390 rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
391 /* If file cannot be loaded, return NULL without warning */
392 if (rdoc == NULL) return NULL;
393 rroot = rdoc->root();
394 /* If xml file is not svg, return NULL without warning */
395 /* fixme: destroy document */
396 if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
397 s = g_strdup(uri);
398 p = strrchr(s, '/');
399 if (p) {
400 name = g_strdup(p + 1);
401 p[1] = '\0';
402 base = g_strdup(s);
403 } else {
404 base = NULL;
405 name = g_strdup(uri);
406 }
407 g_free(s);
408 } else {
409 rdoc = sp_repr_document_new("svg:svg");
410 }
412 if (make_new) {
413 base = NULL;
414 uri = NULL;
415 name = g_strdup_printf(_("New document %d"), ++doc_count);
416 }
418 //# These should be set by now
419 g_assert(name);
421 doc = sp_document_create(rdoc, uri, base, name, keepalive);
423 g_free(base);
424 g_free(name);
426 return doc;
427 }
429 SPDocument *
430 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
431 {
432 SPDocument *doc;
433 Inkscape::XML::Document *rdoc;
434 Inkscape::XML::Node *rroot;
435 gchar *name;
437 rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
439 /* If it cannot be loaded, return NULL without warning */
440 if (rdoc == NULL) return NULL;
442 rroot = rdoc->root();
443 /* If xml file is not svg, return NULL without warning */
444 /* fixme: destroy document */
445 if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
447 name = g_strdup_printf(_("Memory document %d"), ++doc_count);
449 doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
451 return doc;
452 }
454 SPDocument *
455 sp_document_ref(SPDocument *doc)
456 {
457 g_return_val_if_fail(doc != NULL, NULL);
458 Inkscape::GC::anchor(doc);
459 return doc;
460 }
462 SPDocument *
463 sp_document_unref(SPDocument *doc)
464 {
465 g_return_val_if_fail(doc != NULL, NULL);
466 Inkscape::GC::release(doc);
467 return NULL;
468 }
470 gdouble sp_document_width(SPDocument *document)
471 {
472 g_return_val_if_fail(document != NULL, 0.0);
473 g_return_val_if_fail(document->priv != NULL, 0.0);
474 g_return_val_if_fail(document->root != NULL, 0.0);
476 SPRoot *root = SP_ROOT(document->root);
478 if (root->width.unit == SVGLength::PERCENT && root->viewBox_set)
479 return root->viewBox.x1 - root->viewBox.x0;
480 return root->width.computed;
481 }
483 void
484 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
485 {
486 SPRoot *root = SP_ROOT(document->root);
488 if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
489 root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
490 } else { // set to width=
491 root->width.computed = sp_units_get_pixels (width, *unit);
492 /* SVG does not support meters as a unit, so we must translate meters to
493 * cm when writing */
494 if (!strcmp(unit->abbr, "m")) {
495 root->width.value = 100*width;
496 root->width.unit = SVGLength::CM;
497 } else {
498 root->width.value = width;
499 root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
500 }
501 }
503 SP_OBJECT (root)->updateRepr();
504 }
506 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
507 {
508 SPRoot *root = SP_ROOT(document->root);
510 if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
511 root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
512 } else { // set to height=
513 root->height.computed = sp_units_get_pixels (height, *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->height.value = 100*height;
518 root->height.unit = SVGLength::CM;
519 } else {
520 root->height.value = height;
521 root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
522 }
523 }
525 SP_OBJECT (root)->updateRepr();
526 }
528 gdouble sp_document_height(SPDocument *document)
529 {
530 g_return_val_if_fail(document != NULL, 0.0);
531 g_return_val_if_fail(document->priv != NULL, 0.0);
532 g_return_val_if_fail(document->root != NULL, 0.0);
534 SPRoot *root = SP_ROOT(document->root);
536 if (root->height.unit == SVGLength::PERCENT && root->viewBox_set)
537 return root->viewBox.y1 - root->viewBox.y0;
538 return root->height.computed;
539 }
541 /**
542 * Given an NR::Rect that may, for example, correspond to the bbox of an object,
543 * this function fits the canvas to that rect by resizing the canvas
544 * and translating the document root into position.
545 */
546 void SPDocument::fitToRect(NR::Rect const &rect)
547 {
548 g_return_if_fail(!rect.isEmpty());
550 using NR::X; using NR::Y;
551 double const w = rect.extent(X);
552 double const h = rect.extent(Y);
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 NR::translate const tr(NR::Point(0, (old_height - h))
560 - rect.min());
561 SP_GROUP(root)->translateChildItems(tr);
562 SPNamedView *nv = sp_document_namedview(this, 0);
563 if(nv) {
564 NR::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 = NR::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 = NR::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(NR::Rect const &area, NR::Rect const &box)
878 {
879 return area.contains(box);
880 }
882 static bool overlaps(NR::Rect const &area, NR::Rect const &box)
883 {
884 return area.intersects(box);
885 }
887 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, NR::Rect const &area,
888 bool (*test)(NR::Rect const &, NR::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 NR::Maybe<NR::Rect> box = 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 NR::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, NR::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, NR::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, NR::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, NR::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<NR::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, NR::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, NR::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 :