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 "application/application.h"
42 #include "application/editor.h"
43 #include "libnr/nr-matrix-fns.h"
44 #include "xml/repr.h"
45 #include "helper/units.h"
46 #include "inkscape-private.h"
47 #include "inkscape_version.h"
48 #include "sp-object-repr.h"
49 #include "document-private.h"
50 #include "dir-util.h"
51 #include "unit-constants.h"
52 #include "prefs-utils.h"
53 #include "libavoid/router.h"
54 #include "libnr/nr-rect.h"
55 #include "sp-item-group.h"
56 #include "profile-manager.h"
57 #include "persp3d.h"
59 #include "display/nr-arena-item.h"
61 #include "dialogs/rdf.h"
63 #include "transf_mat_3x4.h"
65 #define A4_WIDTH_STR "210mm"
66 #define A4_HEIGHT_STR "297mm"
68 #define SP_DOCUMENT_UPDATE_PRIORITY (G_PRIORITY_HIGH_IDLE - 1)
71 static gint sp_document_idle_handler(gpointer data);
73 gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data);
75 static gint doc_count = 0;
77 static unsigned long next_serial = 0;
79 SPDocument::SPDocument() {
80 SPDocumentPrivate *p;
82 keepalive = FALSE;
83 virgin = TRUE;
85 modified_id = 0;
87 rdoc = NULL;
88 rroot = NULL;
89 root = NULL;
90 style_cascade = cr_cascade_new(NULL, NULL, NULL);
92 uri = NULL;
93 base = NULL;
94 name = NULL;
96 _collection_queue = NULL;
98 // Initialise instance of connector router.
99 router = new Avoid::Router();
100 // Don't use the Consolidate moves optimisation.
101 router->ConsolidateMoves = false;
103 perspectives = NULL;
105 p = new SPDocumentPrivate();
107 p->serial = next_serial++;
109 p->iddef = g_hash_table_new(g_direct_hash, g_direct_equal);
110 p->reprdef = g_hash_table_new(g_direct_hash, g_direct_equal);
112 p->resources = g_hash_table_new(g_str_hash, g_str_equal);
114 p->sensitive = FALSE;
115 p->partial = NULL;
116 p->history_size = 0;
117 p->undo = NULL;
118 p->redo = NULL;
119 p->seeking = false;
121 priv = p;
123 // Once things are set, hook in the manager
124 profileManager = new Inkscape::ProfileManager(this);
126 // XXX only for testing!
127 priv->undoStackObservers.add(p->console_output_undo_observer);
128 }
130 SPDocument::~SPDocument() {
131 collectOrphans();
133 // kill/unhook this first
134 if ( profileManager ) {
135 delete profileManager;
136 profileManager = 0;
137 }
139 if (priv) {
140 if (priv->partial) {
141 sp_repr_free_log(priv->partial);
142 priv->partial = NULL;
143 }
145 sp_document_clear_redo(this);
146 sp_document_clear_undo(this);
148 if (root) {
149 root->releaseReferences();
150 sp_object_unref(root);
151 root = NULL;
152 }
154 if (priv->iddef) g_hash_table_destroy(priv->iddef);
155 if (priv->reprdef) g_hash_table_destroy(priv->reprdef);
157 if (rdoc) Inkscape::GC::release(rdoc);
159 /* Free resources */
160 g_hash_table_foreach_remove(priv->resources, sp_document_resource_list_free, this);
161 g_hash_table_destroy(priv->resources);
163 delete priv;
164 priv = NULL;
165 }
167 cr_cascade_unref(style_cascade);
168 style_cascade = NULL;
170 if (name) {
171 g_free(name);
172 name = NULL;
173 }
174 if (base) {
175 g_free(base);
176 base = NULL;
177 }
178 if (uri) {
179 g_free(uri);
180 uri = NULL;
181 }
183 if (modified_id) {
184 gtk_idle_remove(modified_id);
185 modified_id = 0;
186 }
188 _selection_changed_connection.disconnect();
189 _desktop_activated_connection.disconnect();
191 if (keepalive) {
192 inkscape_unref();
193 keepalive = FALSE;
194 }
196 if (router) {
197 delete router;
198 router = NULL;
199 }
201 //delete this->_whiteboard_session_manager;
203 }
205 void SPDocument::add_persp3d (Persp3D * const persp)
206 {
207 SPDefs *defs = SP_ROOT(this->root)->defs;
208 for (SPObject *i = sp_object_first_child(SP_OBJECT(defs)); i != NULL; i = SP_OBJECT_NEXT(i) ) {
209 if (SP_IS_PERSP3D(i)) {
210 g_print ("Encountered a Persp3D in defs\n");
211 }
212 }
214 g_print ("Adding Persp3D to defs\n");
215 persp3d_create_xml_element (this);
216 }
218 void SPDocument::remove_persp3d (Persp3D * const persp)
219 {
220 // TODO: Delete the repr, maybe perform a check if any boxes are still linked to the perspective.
221 // Anything else?
222 g_print ("Please implement deletion of perspectives here.\n");
223 }
225 unsigned long SPDocument::serial() const {
226 return priv->serial;
227 }
229 void SPDocument::queueForOrphanCollection(SPObject *object) {
230 g_return_if_fail(object != NULL);
231 g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
233 sp_object_ref(object, NULL);
234 _collection_queue = g_slist_prepend(_collection_queue, object);
235 }
237 void SPDocument::collectOrphans() {
238 while (_collection_queue) {
239 GSList *objects=_collection_queue;
240 _collection_queue = NULL;
241 for ( GSList *iter=objects ; iter ; iter = iter->next ) {
242 SPObject *object=reinterpret_cast<SPObject *>(iter->data);
243 object->collectOrphan();
244 sp_object_unref(object, NULL);
245 }
246 g_slist_free(objects);
247 }
248 }
250 void SPDocument::reset_key (void */*dummy*/)
251 {
252 actionkey = NULL;
253 }
255 SPDocument *
256 sp_document_create(Inkscape::XML::Document *rdoc,
257 gchar const *uri,
258 gchar const *base,
259 gchar const *name,
260 unsigned int keepalive)
261 {
262 SPDocument *document;
263 Inkscape::XML::Node *rroot;
264 Inkscape::Version sodipodi_version;
266 rroot = rdoc->root();
268 document = new SPDocument();
270 document->keepalive = keepalive;
272 document->rdoc = rdoc;
273 document->rroot = rroot;
275 #ifndef WIN32
276 prepend_current_dir_if_relative(&(document->uri), uri);
277 #else
278 // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
279 document->uri = uri? g_strdup(uri) : NULL;
280 #endif
282 // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
283 // which is why we use g_get_current_dir() in calculating the abs path above
284 //This is NULL for a new document
285 if (base)
286 document->base = g_strdup(base);
287 else
288 document->base = NULL;
289 document->name = g_strdup(name);
291 document->root = sp_object_repr_build_tree(document, rroot);
293 sodipodi_version = SP_ROOT(document->root)->version.sodipodi;
295 /* fixme: Not sure about this, but lets assume ::build updates */
296 rroot->setAttribute("sodipodi:version", SODIPODI_VERSION);
297 rroot->setAttribute("inkscape:version", INKSCAPE_VERSION);
298 /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
300 /* Quick hack 2 - get default image size into document */
301 if (!rroot->attribute("width")) rroot->setAttribute("width", A4_WIDTH_STR);
302 if (!rroot->attribute("height")) rroot->setAttribute("height", A4_HEIGHT_STR);
303 /* End of quick hack 2 */
305 /* Quick hack 3 - Set uri attributes */
306 if (uri) {
307 rroot->setAttribute("sodipodi:docname", uri);
308 }
309 /* End of quick hack 3 */
311 // creating namedview
312 if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
313 // if there's none in the document already,
314 Inkscape::XML::Node *r = NULL;
315 Inkscape::XML::Node *rnew = NULL;
316 r = inkscape_get_repr(INKSCAPE, "template.base");
317 // see if there's a template with id="base" in the preferences
318 if (!r) {
319 // if there's none, create an empty element
320 rnew = rdoc->createElement("sodipodi:namedview");
321 rnew->setAttribute("id", "base");
322 } else {
323 // otherwise, take from preferences
324 rnew = r->duplicate(rroot->document());
325 }
326 // insert into the document
327 rroot->addChild(rnew, NULL);
328 // clean up
329 Inkscape::GC::release(rnew);
330 }
332 /* Defs */
333 if (!SP_ROOT(document->root)->defs) {
334 Inkscape::XML::Node *r;
335 r = rdoc->createElement("svg:defs");
336 rroot->addChild(r, NULL);
337 Inkscape::GC::release(r);
338 g_assert(SP_ROOT(document->root)->defs);
339 }
341 /* Default RDF */
342 rdf_set_defaults( document );
344 if (keepalive) {
345 inkscape_ref();
346 }
348 /* Create an initial perspective, make it current and append it to the list of existing perspectives */
349 /***
350 document->current_perspective = new Box3D::Perspective3D (
351 // VP in x-direction
352 Box3D::VanishingPoint( NR::Point(-50.0, 600.0),
353 NR::Point( -1.0, 0.0), Box3D::VP_FINITE),
354 // VP in y-direction
355 Box3D::VanishingPoint( NR::Point(500.0,1000.0),
356 NR::Point( 0.0, 1.0), Box3D::VP_INFINITE),
357 // VP in z-direction
358 Box3D::VanishingPoint( NR::Point(700.0, 600.0),
359 NR::Point(sqrt(3.0),1.0), Box3D::VP_FINITE),
360 document);
362 document->add_perspective (document->current_perspective);
363 ***/
365 // Remark: Here, we used to create a "currentpersp3d" element in the document defs.
366 // But this is probably a bad idea since we need to adapt it for every change of selection, which will
367 // completely clutter the undo history. Maybe rather save it to prefs on exit and re-read it on startup?
369 Proj::Pt2 proj_vp_x = Proj::Pt2 (-50.0, 600.0, 1.0);
370 Proj::Pt2 proj_vp_y = Proj::Pt2 ( 0.0,1000.0, 0.0);
371 Proj::Pt2 proj_vp_z = Proj::Pt2 (700.0, 600.0, 1.0);
372 Proj::Pt2 proj_origin = Proj::Pt2 (300.0, 400.0, 1.0);
374 document->current_persp3d = (Persp3D *) persp3d_create_xml_element (document);
375 Inkscape::XML::Node *repr = SP_OBJECT_REPR(document->current_persp3d);
377 gchar *str = NULL;
378 str = proj_vp_x.coord_string();
379 repr->setAttribute("inkscape:vp_x", str);
380 g_free (str);
381 str = proj_vp_y.coord_string();
382 repr->setAttribute("inkscape:vp_y", str);
383 g_free (str);
384 str = proj_vp_z.coord_string();
385 repr->setAttribute("inkscape:vp_z", str);
386 g_free (str);
387 str = proj_origin.coord_string();
388 repr->setAttribute("inkscape:persp3d-origin", str);
389 g_free (str);
390 Inkscape::GC::release(repr);
392 /***
393 document->current_persp3d = (Persp3D *) sp_object_get_child_by_repr (SP_OBJECT(defs), repr);
394 g_assert (document->current_persp3d != NULL);
395 persp3d_update_with_point (document->current_persp3d, Proj::X, proj_vp_x);
396 persp3d_update_with_point (document->current_persp3d, Proj::Y, proj_vp_y);
397 persp3d_update_with_point (document->current_persp3d, Proj::Z, proj_vp_z);
398 persp3d_update_with_point (document->current_persp3d, Proj::W, proj_origin);
399 ***/
401 sp_document_set_undo_sensitive(document, true);
403 // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
404 if (!Inkscape::NSApplication::Application::getNewGui()) {
405 g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
406 G_CALLBACK(sp_document_reset_key), document);
407 g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
408 G_CALLBACK(sp_document_reset_key), document);
409 } else {
410 document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
411 document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
412 }
414 return document;
415 }
417 /**
418 * Fetches document from URI, or creates new, if NULL; public document
419 * appears in document list.
420 */
421 SPDocument *
422 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
423 {
424 SPDocument *doc;
425 Inkscape::XML::Document *rdoc;
426 gchar *base = NULL;
427 gchar *name = NULL;
429 if (uri) {
430 Inkscape::XML::Node *rroot;
431 gchar *s, *p;
432 /* Try to fetch repr from file */
433 rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
434 /* If file cannot be loaded, return NULL without warning */
435 if (rdoc == NULL) return NULL;
436 rroot = rdoc->root();
437 /* If xml file is not svg, return NULL without warning */
438 /* fixme: destroy document */
439 if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
440 s = g_strdup(uri);
441 p = strrchr(s, '/');
442 if (p) {
443 name = g_strdup(p + 1);
444 p[1] = '\0';
445 base = g_strdup(s);
446 } else {
447 base = NULL;
448 name = g_strdup(uri);
449 }
450 g_free(s);
451 } else {
452 rdoc = sp_repr_document_new("svg:svg");
453 }
455 if (make_new) {
456 base = NULL;
457 uri = NULL;
458 name = g_strdup_printf(_("New document %d"), ++doc_count);
459 }
461 //# These should be set by now
462 g_assert(name);
464 doc = sp_document_create(rdoc, uri, base, name, keepalive);
466 g_free(base);
467 g_free(name);
469 return doc;
470 }
472 SPDocument *
473 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
474 {
475 SPDocument *doc;
476 Inkscape::XML::Document *rdoc;
477 Inkscape::XML::Node *rroot;
478 gchar *name;
480 rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
482 /* If it cannot be loaded, return NULL without warning */
483 if (rdoc == NULL) return NULL;
485 rroot = rdoc->root();
486 /* If xml file is not svg, return NULL without warning */
487 /* fixme: destroy document */
488 if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
490 name = g_strdup_printf(_("Memory document %d"), ++doc_count);
492 doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
494 return doc;
495 }
497 SPDocument *
498 sp_document_ref(SPDocument *doc)
499 {
500 g_return_val_if_fail(doc != NULL, NULL);
501 Inkscape::GC::anchor(doc);
502 return doc;
503 }
505 SPDocument *
506 sp_document_unref(SPDocument *doc)
507 {
508 g_return_val_if_fail(doc != NULL, NULL);
509 Inkscape::GC::release(doc);
510 return NULL;
511 }
513 gdouble sp_document_width(SPDocument *document)
514 {
515 g_return_val_if_fail(document != NULL, 0.0);
516 g_return_val_if_fail(document->priv != NULL, 0.0);
517 g_return_val_if_fail(document->root != NULL, 0.0);
519 return SP_ROOT(document->root)->width.computed;
520 }
522 void
523 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
524 {
525 SPRoot *root = SP_ROOT(document->root);
527 if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
528 root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
529 } else { // set to width=
530 root->width.computed = sp_units_get_pixels (width, *unit);
531 /* SVG does not support meters as a unit, so we must translate meters to
532 * cm when writing */
533 if (!strcmp(unit->abbr, "m")) {
534 root->width.value = 100*width;
535 root->width.unit = SVGLength::CM;
536 } else {
537 root->width.value = width;
538 root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
539 }
540 }
542 SP_OBJECT (root)->updateRepr();
543 }
545 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
546 {
547 SPRoot *root = SP_ROOT(document->root);
549 if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
550 root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
551 } else { // set to height=
552 root->height.computed = sp_units_get_pixels (height, *unit);
553 /* SVG does not support meters as a unit, so we must translate meters to
554 * cm when writing */
555 if (!strcmp(unit->abbr, "m")) {
556 root->height.value = 100*height;
557 root->height.unit = SVGLength::CM;
558 } else {
559 root->height.value = height;
560 root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
561 }
562 }
564 SP_OBJECT (root)->updateRepr();
565 }
567 gdouble sp_document_height(SPDocument *document)
568 {
569 g_return_val_if_fail(document != NULL, 0.0);
570 g_return_val_if_fail(document->priv != NULL, 0.0);
571 g_return_val_if_fail(document->root != NULL, 0.0);
573 return SP_ROOT(document->root)->height.computed;
574 }
576 /**
577 * Given an NR::Rect that may, for example, correspond to the bbox of an object,
578 * this function fits the canvas to that rect by resizing the canvas
579 * and translating the document root into position.
580 */
581 void SPDocument::fitToRect(NR::Rect const &rect)
582 {
583 g_return_if_fail(!rect.isEmpty());
585 using NR::X; using NR::Y;
586 double const w = rect.extent(X);
587 double const h = rect.extent(Y);
589 double const old_height = sp_document_height(this);
590 SPUnit const &px(sp_unit_get_by_id(SP_UNIT_PX));
591 sp_document_set_width(this, w, &px);
592 sp_document_set_height(this, h, &px);
594 NR::translate const tr(NR::Point(0, (old_height - h))
595 - rect.min());
596 SP_GROUP(root)->translateChildItems(tr);
597 }
599 void sp_document_set_uri(SPDocument *document, gchar const *uri)
600 {
601 g_return_if_fail(document != NULL);
603 if (document->name) {
604 g_free(document->name);
605 document->name = NULL;
606 }
607 if (document->base) {
608 g_free(document->base);
609 document->base = NULL;
610 }
611 if (document->uri) {
612 g_free(document->uri);
613 document->uri = NULL;
614 }
616 if (uri) {
618 #ifndef WIN32
619 prepend_current_dir_if_relative(&(document->uri), uri);
620 #else
621 // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
622 document->uri = g_strdup(uri);
623 #endif
625 /* fixme: Think, what this means for images (Lauris) */
626 document->base = g_path_get_dirname(document->uri);
627 document->name = g_path_get_basename(document->uri);
629 } else {
630 document->uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
631 document->base = NULL;
632 document->name = g_strdup(document->uri);
633 }
635 // Update saveable repr attributes.
636 Inkscape::XML::Node *repr = sp_document_repr_root(document);
637 // changing uri in the document repr must not be not undoable
638 bool saved = sp_document_get_undo_sensitive(document);
639 sp_document_set_undo_sensitive(document, false);
641 repr->setAttribute("sodipodi:docname", document->name);
642 sp_document_set_undo_sensitive(document, saved);
644 document->priv->uri_set_signal.emit(document->uri);
645 }
647 void
648 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
649 {
650 g_return_if_fail(doc != NULL);
652 doc->priv->resized_signal.emit(width, height);
653 }
655 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
656 {
657 return priv->modified_signal.connect(slot);
658 }
660 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
661 {
662 return priv->uri_set_signal.connect(slot);
663 }
665 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
666 {
667 return priv->resized_signal.connect(slot);
668 }
670 sigc::connection
671 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
672 {
673 return priv->_reconstruction_start_signal.connect(slot);
674 }
676 void
677 SPDocument::emitReconstructionStart(void)
678 {
679 // printf("Starting Reconstruction\n");
680 priv->_reconstruction_start_signal.emit();
681 return;
682 }
684 sigc::connection
685 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type slot)
686 {
687 return priv->_reconstruction_finish_signal.connect(slot);
688 }
690 void
691 SPDocument::emitReconstructionFinish(void)
692 {
693 // printf("Finishing Reconstruction\n");
694 priv->_reconstruction_finish_signal.emit();
695 return;
696 }
698 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
699 {
700 return priv->commit_signal.connect(slot);
701 }
705 void SPDocument::_emitModified() {
706 static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
707 root->emitModified(0);
708 priv->modified_signal.emit(flags);
709 }
711 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
712 GQuark idq = g_quark_from_string(id);
714 if (object) {
715 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
716 g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
717 } else {
718 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
719 g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
720 }
722 SPDocumentPrivate::IDChangedSignalMap::iterator pos;
724 pos = priv->id_changed_signals.find(idq);
725 if ( pos != priv->id_changed_signals.end() ) {
726 if (!(*pos).second.empty()) {
727 (*pos).second.emit(object);
728 } else { // discard unused signal
729 priv->id_changed_signals.erase(pos);
730 }
731 }
732 }
734 void
735 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
736 {
737 this->priv->undoStackObservers.add(observer);
738 }
740 void
741 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
742 {
743 this->priv->undoStackObservers.remove(observer);
744 }
746 SPObject *SPDocument::getObjectById(gchar const *id) {
747 g_return_val_if_fail(id != NULL, NULL);
749 GQuark idq = g_quark_from_string(id);
750 return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
751 }
753 sigc::connection SPDocument::connectIdChanged(gchar const *id,
754 SPDocument::IDChangedSignal::slot_type slot)
755 {
756 return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
757 }
759 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
760 if (object) {
761 g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
762 g_hash_table_insert(priv->reprdef, repr, object);
763 } else {
764 g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
765 g_hash_table_remove(priv->reprdef, repr);
766 }
767 }
769 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
770 g_return_val_if_fail(repr != NULL, NULL);
771 return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
772 }
774 Glib::ustring SPDocument::getLanguage() {
775 gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
776 if (document_language) {
777 while (isspace(*document_language))
778 document_language++;
779 }
780 if ( !document_language || 0 == *document_language) {
781 // retrieve system language
782 document_language = getenv("LC_ALL");
783 if ( NULL == document_language || *document_language == 0 ) {
784 document_language = getenv ("LC_MESSAGES");
785 }
786 if ( NULL == document_language || *document_language == 0 ) {
787 document_language = getenv ("LANG");
788 }
790 if ( NULL != document_language ) {
791 gchar *pos = strchr(document_language, '_');
792 if ( NULL != pos ) {
793 return Glib::ustring(document_language, pos - document_language);
794 }
795 }
796 }
798 if ( NULL == document_language )
799 return Glib::ustring();
800 return document_language;
801 }
803 /* Object modification root handler */
805 void
806 sp_document_request_modified(SPDocument *doc)
807 {
808 if (!doc->modified_id) {
809 doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
810 }
811 }
813 void
814 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
815 {
816 ctx->ctx.flags = 0;
817 ctx->i2doc = NR::identity();
818 /* Set up viewport in case svg has it defined as percentages */
819 if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
820 ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
821 ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
822 ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
823 ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
824 } else { // as a last resort, set size to A4
825 ctx->vp.x0 = 0.0;
826 ctx->vp.y0 = 0.0;
827 ctx->vp.x1 = 210 * PX_PER_MM;
828 ctx->vp.y1 = 297 * PX_PER_MM;
829 }
830 ctx->i2vp = NR::identity();
831 }
833 /**
834 * Tries to update the document state based on the modified and
835 * "update required" flags, and return true if the document has
836 * been brought fully up to date.
837 */
838 bool
839 SPDocument::_updateDocument()
840 {
841 /* Process updates */
842 if (this->root->uflags || this->root->mflags) {
843 if (this->root->uflags) {
844 SPItemCtx ctx;
845 sp_document_setup_viewport (this, &ctx);
847 bool saved = sp_document_get_undo_sensitive(this);
848 sp_document_set_undo_sensitive(this, false);
850 this->root->updateDisplay((SPCtx *)&ctx, 0);
852 sp_document_set_undo_sensitive(this, saved);
853 }
854 this->_emitModified();
855 }
857 return !(this->root->uflags || this->root->mflags);
858 }
861 /**
862 * Repeatedly works on getting the document updated, since sometimes
863 * it takes more than one pass to get the document updated. But it
864 * usually should not take more than a few loops, and certainly never
865 * more than 32 iterations. So we bail out if we hit 32 iterations,
866 * since this typically indicates we're stuck in an update loop.
867 */
868 gint
869 sp_document_ensure_up_to_date(SPDocument *doc)
870 {
871 int counter = 32;
872 while (!doc->_updateDocument()) {
873 if (counter == 0) {
874 g_warning("More than 32 iteration while updating document '%s'", doc->uri);
875 break;
876 }
877 counter--;
878 }
880 if (doc->modified_id) {
881 /* Remove handler */
882 gtk_idle_remove(doc->modified_id);
883 doc->modified_id = 0;
884 }
885 return counter>0;
886 }
888 /**
889 * An idle handler to update the document. Returns true if
890 * the document needs further updates.
891 */
892 static gint
893 sp_document_idle_handler(gpointer data)
894 {
895 SPDocument *doc = static_cast<SPDocument *>(data);
896 if (doc->_updateDocument()) {
897 doc->modified_id = 0;
898 return false;
899 } else {
900 return true;
901 }
902 }
904 static bool is_within(NR::Rect const &area, NR::Rect const &box)
905 {
906 return area.contains(box);
907 }
909 static bool overlaps(NR::Rect const &area, NR::Rect const &box)
910 {
911 return area.intersects(box);
912 }
914 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, NR::Rect const &area,
915 bool (*test)(NR::Rect const &, NR::Rect const &), bool take_insensitive = false)
916 {
917 g_return_val_if_fail(SP_IS_GROUP(group), s);
919 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
920 if (!SP_IS_ITEM(o)) {
921 continue;
922 }
923 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
924 s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
925 } else {
926 SPItem *child = SP_ITEM(o);
927 NR::Maybe<NR::Rect> box = sp_item_bbox_desktop(child);
928 if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
929 s = g_slist_append(s, child);
930 }
931 }
932 }
934 return s;
935 }
937 /**
938 Returns true if an item is among the descendants of group (recursively).
939 */
940 bool item_is_in_group(SPItem *item, SPGroup *group)
941 {
942 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
943 if (!SP_IS_ITEM(o)) continue;
944 if (SP_ITEM(o) == item)
945 return true;
946 if (SP_IS_GROUP(o))
947 if (item_is_in_group(item, SP_GROUP(o)))
948 return true;
949 }
950 return false;
951 }
953 /**
954 Returns the bottommost item from the list which is at the point, or NULL if none.
955 */
956 SPItem*
957 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
958 NR::Point const p, bool take_insensitive)
959 {
960 g_return_val_if_fail(group, NULL);
962 gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
964 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
966 if (!SP_IS_ITEM(o)) continue;
968 SPItem *item = SP_ITEM(o);
969 NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
970 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
971 && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
972 if (g_slist_find((GSList *) list, item) != NULL)
973 return item;
974 }
976 if (SP_IS_GROUP(o)) {
977 SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
978 if (found)
979 return found;
980 }
982 }
983 return NULL;
984 }
986 /**
987 Returns the topmost (in z-order) item from the descendants of group (recursively) which
988 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
989 non-layer groups or not. Honors take_insensitive on whether to return insensitive
990 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
991 upwards in z-order and returns what it has found so far (i.e. the found item is
992 guaranteed to be lower than upto).
993 */
994 SPItem*
995 find_item_at_point(unsigned int dkey, SPGroup *group, NR::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
996 {
997 SPItem *seen = NULL, *newseen = NULL;
999 gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
1001 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1002 if (!SP_IS_ITEM(o)) continue;
1004 if (upto && SP_ITEM(o) == upto)
1005 break;
1007 if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
1008 // if nothing found yet, recurse into the group
1009 newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
1010 if (newseen) {
1011 seen = newseen;
1012 newseen = NULL;
1013 }
1015 if (item_is_in_group(upto, SP_GROUP(o)))
1016 break;
1018 } else {
1019 SPItem *child = SP_ITEM(o);
1020 NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1022 // seen remembers the last (topmost) of items pickable at this point
1023 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1024 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1025 seen = child;
1026 }
1027 }
1028 }
1029 return seen;
1030 }
1032 /**
1033 Returns the topmost non-layer group from the descendants of group which is at point
1034 p, or NULL if none. Recurses into layers but not into groups.
1035 */
1036 SPItem*
1037 find_group_at_point(unsigned int dkey, SPGroup *group, NR::Point const p)
1038 {
1039 SPItem *seen = NULL;
1041 gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
1043 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1044 if (!SP_IS_ITEM(o)) continue;
1045 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1046 SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1047 if (newseen) {
1048 seen = newseen;
1049 }
1050 }
1051 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1052 SPItem *child = SP_ITEM(o);
1053 NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
1055 // seen remembers the last (topmost) of groups pickable at this point
1056 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1057 seen = child;
1058 }
1059 }
1060 }
1061 return seen;
1062 }
1064 /*
1065 * Return list of items, contained in box
1066 *
1067 * Assumes box is normalized (and g_asserts it!)
1068 *
1069 */
1071 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
1072 {
1073 g_return_val_if_fail(document != NULL, NULL);
1074 g_return_val_if_fail(document->priv != NULL, NULL);
1076 return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
1077 }
1079 /*
1080 * Return list of items, that the parts of the item contained in box
1081 *
1082 * Assumes box is normalized (and g_asserts it!)
1083 *
1084 */
1086 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
1087 {
1088 g_return_val_if_fail(document != NULL, NULL);
1089 g_return_val_if_fail(document->priv != NULL, NULL);
1091 return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1092 }
1094 GSList *
1095 sp_document_items_at_points(SPDocument *document, unsigned const key, std::vector<NR::Point> points)
1096 {
1097 GSList *items = NULL;
1099 // When picking along the path, we don't want small objects close together
1100 // (such as hatching strokes) to obscure each other by their deltas,
1101 // so we temporarily set delta to a small value
1102 gdouble saved_delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
1103 prefs_set_double_attribute ("options.cursortolerance", "value", 0.25);
1105 for(unsigned int i = 0; i < points.size(); i++) {
1106 SPItem *item = sp_document_item_at_point(document, key, points[i],
1107 false, NULL);
1108 if (item && !g_slist_find(items, item))
1109 items = g_slist_prepend (items, item);
1110 }
1112 // and now we restore it back
1113 prefs_set_double_attribute ("options.cursortolerance", "value", saved_delta);
1115 return items;
1116 }
1118 SPItem *
1119 sp_document_item_at_point(SPDocument *document, unsigned const key, NR::Point const p,
1120 gboolean const into_groups, SPItem *upto)
1121 {
1122 g_return_val_if_fail(document != NULL, NULL);
1123 g_return_val_if_fail(document->priv != NULL, NULL);
1125 return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1126 }
1128 SPItem*
1129 sp_document_group_at_point(SPDocument *document, unsigned int key, NR::Point const p)
1130 {
1131 g_return_val_if_fail(document != NULL, NULL);
1132 g_return_val_if_fail(document->priv != NULL, NULL);
1134 return find_group_at_point(key, SP_GROUP(document->root), p);
1135 }
1138 /* Resource management */
1140 gboolean
1141 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1142 {
1143 GSList *rlist;
1144 GQuark q = g_quark_from_string(key);
1146 g_return_val_if_fail(document != NULL, FALSE);
1147 g_return_val_if_fail(key != NULL, FALSE);
1148 g_return_val_if_fail(*key != '\0', FALSE);
1149 g_return_val_if_fail(object != NULL, FALSE);
1150 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1152 if (SP_OBJECT_IS_CLONED(object))
1153 return FALSE;
1155 rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1156 g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1157 rlist = g_slist_prepend(rlist, object);
1158 g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1160 document->priv->resources_changed_signals[q].emit();
1162 return TRUE;
1163 }
1165 gboolean
1166 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1167 {
1168 GSList *rlist;
1169 GQuark q = g_quark_from_string(key);
1171 g_return_val_if_fail(document != NULL, FALSE);
1172 g_return_val_if_fail(key != NULL, FALSE);
1173 g_return_val_if_fail(*key != '\0', FALSE);
1174 g_return_val_if_fail(object != NULL, FALSE);
1175 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1177 if (SP_OBJECT_IS_CLONED(object))
1178 return FALSE;
1180 rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1181 g_return_val_if_fail(rlist != NULL, FALSE);
1182 g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1183 rlist = g_slist_remove(rlist, object);
1184 g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1186 document->priv->resources_changed_signals[q].emit();
1188 return TRUE;
1189 }
1191 GSList const *
1192 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1193 {
1194 g_return_val_if_fail(document != NULL, NULL);
1195 g_return_val_if_fail(key != NULL, NULL);
1196 g_return_val_if_fail(*key != '\0', NULL);
1198 return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1199 }
1201 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1202 gchar const *key,
1203 SPDocument::ResourcesChangedSignal::slot_type slot)
1204 {
1205 GQuark q = g_quark_from_string(key);
1206 return document->priv->resources_changed_signals[q].connect(slot);
1207 }
1209 /* Helpers */
1211 gboolean
1212 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1213 {
1214 g_slist_free((GSList *) value);
1215 return TRUE;
1216 }
1218 unsigned int
1219 count_objects_recursive(SPObject *obj, unsigned int count)
1220 {
1221 count++; // obj itself
1223 for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1224 count = count_objects_recursive(i, count);
1225 }
1227 return count;
1228 }
1230 unsigned int
1231 objects_in_document(SPDocument *document)
1232 {
1233 return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1234 }
1236 void
1237 vacuum_document_recursive(SPObject *obj)
1238 {
1239 if (SP_IS_DEFS(obj)) {
1240 for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1241 /* fixme: some inkscape-internal nodes in the future might not be collectable */
1242 def->requestOrphanCollection();
1243 }
1244 } else {
1245 for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1246 vacuum_document_recursive(i);
1247 }
1248 }
1249 }
1251 unsigned int
1252 vacuum_document(SPDocument *document)
1253 {
1254 unsigned int start = objects_in_document(document);
1255 unsigned int end;
1256 unsigned int newend = start;
1258 unsigned int iterations = 0;
1260 do {
1261 end = newend;
1263 vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1264 document->collectOrphans();
1265 iterations++;
1267 newend = objects_in_document(document);
1269 } while (iterations < 100 && newend < end);
1271 return start - newend;
1272 }
1274 bool SPDocument::isSeeking() const {
1275 return priv->seeking;
1276 }
1279 /*
1280 Local Variables:
1281 mode:c++
1282 c-file-style:"stroustrup"
1283 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1284 indent-tabs-mode:nil
1285 fill-column:99
1286 End:
1287 */
1288 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :