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(NR::Rect const &rect)
550 {
551 g_return_if_fail(!rect.isEmpty());
553 using NR::X; using NR::Y;
554 double const w = rect.extent(X);
555 double const h = rect.extent(Y);
557 double const old_height = sp_document_height(this);
558 SPUnit const &px(sp_unit_get_by_id(SP_UNIT_PX));
559 sp_document_set_width(this, w, &px);
560 sp_document_set_height(this, h, &px);
562 NR::translate const tr(NR::Point(0, (old_height - h))
563 - rect.min());
564 SP_GROUP(root)->translateChildItems(tr);
565 SPNamedView *nv = sp_document_namedview(this, 0);
566 if(nv) {
567 NR::translate tr2(-rect.min());
568 nv->translateGuides(tr2);
570 // update the viewport so the drawing appears to stay where it was
571 nv->scrollAllDesktops(-tr2[0], tr2[1], false);
572 }
573 }
575 void sp_document_set_uri(SPDocument *document, gchar const *uri)
576 {
577 g_return_if_fail(document != NULL);
579 if (document->name) {
580 g_free(document->name);
581 document->name = NULL;
582 }
583 if (document->base) {
584 g_free(document->base);
585 document->base = NULL;
586 }
587 if (document->uri) {
588 g_free(document->uri);
589 document->uri = NULL;
590 }
592 if (uri) {
594 #ifndef WIN32
595 prepend_current_dir_if_relative(&(document->uri), uri);
596 #else
597 // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
598 document->uri = g_strdup(uri);
599 #endif
601 /* fixme: Think, what this means for images (Lauris) */
602 document->base = g_path_get_dirname(document->uri);
603 document->name = g_path_get_basename(document->uri);
605 } else {
606 document->uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
607 document->base = NULL;
608 document->name = g_strdup(document->uri);
609 }
611 // Update saveable repr attributes.
612 Inkscape::XML::Node *repr = sp_document_repr_root(document);
613 // changing uri in the document repr must not be not undoable
614 bool saved = sp_document_get_undo_sensitive(document);
615 sp_document_set_undo_sensitive(document, false);
617 repr->setAttribute("sodipodi:docname", document->name);
618 sp_document_set_undo_sensitive(document, saved);
620 document->priv->uri_set_signal.emit(document->uri);
621 }
623 void
624 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
625 {
626 g_return_if_fail(doc != NULL);
628 doc->priv->resized_signal.emit(width, height);
629 }
631 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
632 {
633 return priv->modified_signal.connect(slot);
634 }
636 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
637 {
638 return priv->uri_set_signal.connect(slot);
639 }
641 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
642 {
643 return priv->resized_signal.connect(slot);
644 }
646 sigc::connection
647 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
648 {
649 return priv->_reconstruction_start_signal.connect(slot);
650 }
652 void
653 SPDocument::emitReconstructionStart(void)
654 {
655 // printf("Starting Reconstruction\n");
656 priv->_reconstruction_start_signal.emit();
657 return;
658 }
660 sigc::connection
661 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type slot)
662 {
663 return priv->_reconstruction_finish_signal.connect(slot);
664 }
666 void
667 SPDocument::emitReconstructionFinish(void)
668 {
669 // printf("Finishing Reconstruction\n");
670 priv->_reconstruction_finish_signal.emit();
671 return;
672 }
674 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
675 {
676 return priv->commit_signal.connect(slot);
677 }
681 void SPDocument::_emitModified() {
682 static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
683 root->emitModified(0);
684 priv->modified_signal.emit(flags);
685 }
687 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
688 GQuark idq = g_quark_from_string(id);
690 if (object) {
691 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
692 g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
693 } else {
694 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
695 g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
696 }
698 SPDocumentPrivate::IDChangedSignalMap::iterator pos;
700 pos = priv->id_changed_signals.find(idq);
701 if ( pos != priv->id_changed_signals.end() ) {
702 if (!(*pos).second.empty()) {
703 (*pos).second.emit(object);
704 } else { // discard unused signal
705 priv->id_changed_signals.erase(pos);
706 }
707 }
708 }
710 void
711 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
712 {
713 this->priv->undoStackObservers.add(observer);
714 }
716 void
717 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
718 {
719 this->priv->undoStackObservers.remove(observer);
720 }
722 SPObject *SPDocument::getObjectById(gchar const *id) {
723 g_return_val_if_fail(id != NULL, NULL);
725 GQuark idq = g_quark_from_string(id);
726 return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
727 }
729 sigc::connection SPDocument::connectIdChanged(gchar const *id,
730 SPDocument::IDChangedSignal::slot_type slot)
731 {
732 return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
733 }
735 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
736 if (object) {
737 g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
738 g_hash_table_insert(priv->reprdef, repr, object);
739 } else {
740 g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
741 g_hash_table_remove(priv->reprdef, repr);
742 }
743 }
745 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
746 g_return_val_if_fail(repr != NULL, NULL);
747 return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
748 }
750 Glib::ustring SPDocument::getLanguage() {
751 gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
752 if (document_language) {
753 while (isspace(*document_language))
754 document_language++;
755 }
756 if ( !document_language || 0 == *document_language) {
757 // retrieve system language
758 document_language = getenv("LC_ALL");
759 if ( NULL == document_language || *document_language == 0 ) {
760 document_language = getenv ("LC_MESSAGES");
761 }
762 if ( NULL == document_language || *document_language == 0 ) {
763 document_language = getenv ("LANG");
764 }
766 if ( NULL != document_language ) {
767 gchar *pos = strchr(document_language, '_');
768 if ( NULL != pos ) {
769 return Glib::ustring(document_language, pos - document_language);
770 }
771 }
772 }
774 if ( NULL == document_language )
775 return Glib::ustring();
776 return document_language;
777 }
779 /* Object modification root handler */
781 void
782 sp_document_request_modified(SPDocument *doc)
783 {
784 if (!doc->modified_id) {
785 doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
786 }
787 }
789 void
790 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
791 {
792 ctx->ctx.flags = 0;
793 ctx->i2doc = NR::identity();
794 /* Set up viewport in case svg has it defined as percentages */
795 if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
796 ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
797 ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
798 ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
799 ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
800 } else { // as a last resort, set size to A4
801 ctx->vp.x0 = 0.0;
802 ctx->vp.y0 = 0.0;
803 ctx->vp.x1 = 210 * PX_PER_MM;
804 ctx->vp.y1 = 297 * PX_PER_MM;
805 }
806 ctx->i2vp = NR::identity();
807 }
809 /**
810 * Tries to update the document state based on the modified and
811 * "update required" flags, and return true if the document has
812 * been brought fully up to date.
813 */
814 bool
815 SPDocument::_updateDocument()
816 {
817 /* Process updates */
818 if (this->root->uflags || this->root->mflags) {
819 if (this->root->uflags) {
820 SPItemCtx ctx;
821 sp_document_setup_viewport (this, &ctx);
823 bool saved = sp_document_get_undo_sensitive(this);
824 sp_document_set_undo_sensitive(this, false);
826 this->root->updateDisplay((SPCtx *)&ctx, 0);
828 sp_document_set_undo_sensitive(this, saved);
829 }
830 this->_emitModified();
831 }
833 return !(this->root->uflags || this->root->mflags);
834 }
837 /**
838 * Repeatedly works on getting the document updated, since sometimes
839 * it takes more than one pass to get the document updated. But it
840 * usually should not take more than a few loops, and certainly never
841 * more than 32 iterations. So we bail out if we hit 32 iterations,
842 * since this typically indicates we're stuck in an update loop.
843 */
844 gint
845 sp_document_ensure_up_to_date(SPDocument *doc)
846 {
847 int counter = 32;
848 while (!doc->_updateDocument()) {
849 if (counter == 0) {
850 g_warning("More than 32 iteration while updating document '%s'", doc->uri);
851 break;
852 }
853 counter--;
854 }
856 if (doc->modified_id) {
857 /* Remove handler */
858 gtk_idle_remove(doc->modified_id);
859 doc->modified_id = 0;
860 }
861 return counter>0;
862 }
864 /**
865 * An idle handler to update the document. Returns true if
866 * the document needs further updates.
867 */
868 static gint
869 sp_document_idle_handler(gpointer data)
870 {
871 SPDocument *doc = static_cast<SPDocument *>(data);
872 if (doc->_updateDocument()) {
873 doc->modified_id = 0;
874 return false;
875 } else {
876 return true;
877 }
878 }
880 static bool is_within(NR::Rect const &area, NR::Rect const &box)
881 {
882 return area.contains(box);
883 }
885 static bool overlaps(NR::Rect const &area, NR::Rect const &box)
886 {
887 return area.intersects(box);
888 }
890 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, NR::Rect const &area,
891 bool (*test)(NR::Rect const &, NR::Rect const &), bool take_insensitive = false)
892 {
893 g_return_val_if_fail(SP_IS_GROUP(group), s);
895 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
896 if (!SP_IS_ITEM(o)) {
897 continue;
898 }
899 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
900 s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
901 } else {
902 SPItem *child = SP_ITEM(o);
903 NR::Maybe<NR::Rect> box = sp_item_bbox_desktop(child);
904 if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
905 s = g_slist_append(s, child);
906 }
907 }
908 }
910 return s;
911 }
913 /**
914 Returns true if an item is among the descendants of group (recursively).
915 */
916 bool item_is_in_group(SPItem *item, SPGroup *group)
917 {
918 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
919 if (!SP_IS_ITEM(o)) continue;
920 if (SP_ITEM(o) == item)
921 return true;
922 if (SP_IS_GROUP(o))
923 if (item_is_in_group(item, SP_GROUP(o)))
924 return true;
925 }
926 return false;
927 }
929 /**
930 Returns the bottommost item from the list which is at the point, or NULL if none.
931 */
932 SPItem*
933 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
934 NR::Point const p, bool take_insensitive)
935 {
936 g_return_val_if_fail(group, NULL);
938 gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
940 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
942 if (!SP_IS_ITEM(o)) continue;
944 SPItem *item = SP_ITEM(o);
945 NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
946 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
947 && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
948 if (g_slist_find((GSList *) list, item) != NULL)
949 return item;
950 }
952 if (SP_IS_GROUP(o)) {
953 SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
954 if (found)
955 return found;
956 }
958 }
959 return NULL;
960 }
962 /**
963 Returns the topmost (in z-order) item from the descendants of group (recursively) which
964 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
965 non-layer groups or not. Honors take_insensitive on whether to return insensitive
966 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
967 upwards in z-order and returns what it has found so far (i.e. the found item is
968 guaranteed to be lower than upto).
969 */
970 SPItem*
971 find_item_at_point(unsigned int dkey, SPGroup *group, NR::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
972 {
973 SPItem *seen = NULL, *newseen = NULL;
975 gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
977 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
978 if (!SP_IS_ITEM(o)) continue;
980 if (upto && SP_ITEM(o) == upto)
981 break;
983 if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
984 // if nothing found yet, recurse into the group
985 newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
986 if (newseen) {
987 seen = newseen;
988 newseen = NULL;
989 }
991 if (item_is_in_group(upto, SP_GROUP(o)))
992 break;
994 } else {
995 SPItem *child = SP_ITEM(o);
996 NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
998 // seen remembers the last (topmost) of items pickable at this point
999 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1000 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1001 seen = child;
1002 }
1003 }
1004 }
1005 return seen;
1006 }
1008 /**
1009 Returns the topmost non-layer group from the descendants of group which is at point
1010 p, or NULL if none. Recurses into layers but not into groups.
1011 */
1012 SPItem*
1013 find_group_at_point(unsigned int dkey, SPGroup *group, NR::Point const p)
1014 {
1015 SPItem *seen = NULL;
1017 gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
1019 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1020 if (!SP_IS_ITEM(o)) continue;
1021 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1022 SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1023 if (newseen) {
1024 seen = newseen;
1025 }
1026 }
1027 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1028 SPItem *child = SP_ITEM(o);
1029 NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1031 // seen remembers the last (topmost) of groups pickable at this point
1032 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1033 seen = child;
1034 }
1035 }
1036 }
1037 return seen;
1038 }
1040 /*
1041 * Return list of items, contained in box
1042 *
1043 * Assumes box is normalized (and g_asserts it!)
1044 *
1045 */
1047 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
1048 {
1049 g_return_val_if_fail(document != NULL, NULL);
1050 g_return_val_if_fail(document->priv != NULL, NULL);
1052 return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
1053 }
1055 /*
1056 * Return list of items, that the parts of the item contained in box
1057 *
1058 * Assumes box is normalized (and g_asserts it!)
1059 *
1060 */
1062 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
1063 {
1064 g_return_val_if_fail(document != NULL, NULL);
1065 g_return_val_if_fail(document->priv != NULL, NULL);
1067 return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1068 }
1070 GSList *
1071 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<NR::Point> points)
1072 {
1073 GSList *items = NULL;
1075 // When picking along the path, we don't want small objects close together
1076 // (such as hatching strokes) to obscure each other by their deltas,
1077 // so we temporarily set delta to a small value
1078 gdouble saved_delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
1079 prefs_set_double_attribute ("options.cursortolerance", "value", 0.25);
1081 for(unsigned int i = 0; i < points.size(); i++) {
1082 SPItem *item = sp_document_item_at_point(document, key, points[i],
1083 false, NULL);
1084 if (item && !g_slist_find(items, item))
1085 items = g_slist_prepend (items, item);
1086 }
1088 // and now we restore it back
1089 prefs_set_double_attribute ("options.cursortolerance", "value", saved_delta);
1091 return items;
1092 }
1094 SPItem *
1095 sp_document_item_at_point(SPDocument *document, unsigned const key, NR::Point const p,
1096 gboolean const into_groups, SPItem *upto)
1097 {
1098 g_return_val_if_fail(document != NULL, NULL);
1099 g_return_val_if_fail(document->priv != NULL, NULL);
1101 return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1102 }
1104 SPItem*
1105 sp_document_group_at_point(SPDocument *document, unsigned int key, NR::Point const p)
1106 {
1107 g_return_val_if_fail(document != NULL, NULL);
1108 g_return_val_if_fail(document->priv != NULL, NULL);
1110 return find_group_at_point(key, SP_GROUP(document->root), p);
1111 }
1114 /* Resource management */
1116 gboolean
1117 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1118 {
1119 GSList *rlist;
1120 GQuark q = g_quark_from_string(key);
1122 g_return_val_if_fail(document != NULL, FALSE);
1123 g_return_val_if_fail(key != NULL, FALSE);
1124 g_return_val_if_fail(*key != '\0', FALSE);
1125 g_return_val_if_fail(object != NULL, FALSE);
1126 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1128 if (SP_OBJECT_IS_CLONED(object))
1129 return FALSE;
1131 rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1132 g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1133 rlist = g_slist_prepend(rlist, object);
1134 g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1136 document->priv->resources_changed_signals[q].emit();
1138 return TRUE;
1139 }
1141 gboolean
1142 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1143 {
1144 GSList *rlist;
1145 GQuark q = g_quark_from_string(key);
1147 g_return_val_if_fail(document != NULL, FALSE);
1148 g_return_val_if_fail(key != NULL, FALSE);
1149 g_return_val_if_fail(*key != '\0', FALSE);
1150 g_return_val_if_fail(object != NULL, FALSE);
1151 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1153 if (SP_OBJECT_IS_CLONED(object))
1154 return FALSE;
1156 rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1157 g_return_val_if_fail(rlist != NULL, FALSE);
1158 g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1159 rlist = g_slist_remove(rlist, object);
1160 g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1162 document->priv->resources_changed_signals[q].emit();
1164 return TRUE;
1165 }
1167 GSList const *
1168 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1169 {
1170 g_return_val_if_fail(document != NULL, NULL);
1171 g_return_val_if_fail(key != NULL, NULL);
1172 g_return_val_if_fail(*key != '\0', NULL);
1174 return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1175 }
1177 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1178 gchar const *key,
1179 SPDocument::ResourcesChangedSignal::slot_type slot)
1180 {
1181 GQuark q = g_quark_from_string(key);
1182 return document->priv->resources_changed_signals[q].connect(slot);
1183 }
1185 /* Helpers */
1187 gboolean
1188 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1189 {
1190 g_slist_free((GSList *) value);
1191 return TRUE;
1192 }
1194 unsigned int
1195 count_objects_recursive(SPObject *obj, unsigned int count)
1196 {
1197 count++; // obj itself
1199 for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1200 count = count_objects_recursive(i, count);
1201 }
1203 return count;
1204 }
1206 unsigned int
1207 objects_in_document(SPDocument *document)
1208 {
1209 return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1210 }
1212 void
1213 vacuum_document_recursive(SPObject *obj)
1214 {
1215 if (SP_IS_DEFS(obj)) {
1216 for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1217 /* fixme: some inkscape-internal nodes in the future might not be collectable */
1218 def->requestOrphanCollection();
1219 }
1220 } else {
1221 for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1222 vacuum_document_recursive(i);
1223 }
1224 }
1225 }
1227 unsigned int
1228 vacuum_document(SPDocument *document)
1229 {
1230 unsigned int start = objects_in_document(document);
1231 unsigned int end;
1232 unsigned int newend = start;
1234 unsigned int iterations = 0;
1236 do {
1237 end = newend;
1239 vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1240 document->collectOrphans();
1241 iterations++;
1243 newend = objects_in_document(document);
1245 } while (iterations < 100 && newend < end);
1247 return start - newend;
1248 }
1250 bool SPDocument::isSeeking() const {
1251 return priv->seeking;
1252 }
1255 /*
1256 Local Variables:
1257 mode:c++
1258 c-file-style:"stroustrup"
1259 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1260 indent-tabs-mode:nil
1261 fill-column:99
1262 End:
1263 */
1264 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :