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"
57 #include "display/nr-arena-item.h"
59 #include "dialogs/rdf.h"
61 #define A4_WIDTH_STR "210mm"
62 #define A4_HEIGHT_STR "297mm"
64 #define SP_DOCUMENT_UPDATE_PRIORITY (G_PRIORITY_HIGH_IDLE - 1)
67 static gint sp_document_idle_handler(gpointer data);
69 gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data);
71 static gint doc_count = 0;
73 SPDocument::SPDocument() {
74 SPDocumentPrivate *p;
76 keepalive = FALSE;
77 virgin = TRUE;
79 modified_id = 0;
81 rdoc = NULL;
82 rroot = NULL;
83 root = NULL;
84 style_cascade = cr_cascade_new(NULL, NULL, NULL);
86 uri = NULL;
87 base = NULL;
88 name = NULL;
90 _collection_queue = NULL;
92 // Initialise instance of connector router.
93 router = new Avoid::Router();
94 // Don't use the Consolidate moves optimisation.
95 router->ConsolidateMoves = false;
97 p = new SPDocumentPrivate();
99 p->iddef = g_hash_table_new(g_direct_hash, g_direct_equal);
100 p->reprdef = g_hash_table_new(g_direct_hash, g_direct_equal);
102 p->resources = g_hash_table_new(g_str_hash, g_str_equal);
104 p->sensitive = FALSE;
105 p->partial = NULL;
106 p->history_size = 0;
107 p->undo = NULL;
108 p->redo = NULL;
110 p->undoStackObservers.add(p->event_log);
111 p->event_log.setDocument(this);
113 priv = p;
115 // XXX only for testing!
116 priv->undoStackObservers.add(p->console_output_undo_observer);
117 }
119 SPDocument::~SPDocument() {
120 collectOrphans();
122 if (priv) {
123 inkscape_remove_document(this);
125 if (priv->partial) {
126 sp_repr_free_log(priv->partial);
127 priv->partial = NULL;
128 }
130 sp_document_clear_redo(this);
131 sp_document_clear_undo(this);
133 if (root) {
134 root->releaseReferences();
135 sp_object_unref(root);
136 root = NULL;
137 }
139 if (priv->iddef) g_hash_table_destroy(priv->iddef);
140 if (priv->reprdef) g_hash_table_destroy(priv->reprdef);
142 if (rdoc) Inkscape::GC::release(rdoc);
144 /* Free resources */
145 g_hash_table_foreach_remove(priv->resources, sp_document_resource_list_free, this);
146 g_hash_table_destroy(priv->resources);
148 delete priv;
149 priv = NULL;
150 }
152 cr_cascade_unref(style_cascade);
153 style_cascade = NULL;
155 if (name) {
156 g_free(name);
157 name = NULL;
158 }
159 if (base) {
160 g_free(base);
161 base = NULL;
162 }
163 if (uri) {
164 g_free(uri);
165 uri = NULL;
166 }
168 if (modified_id) {
169 gtk_idle_remove(modified_id);
170 modified_id = 0;
171 }
173 _selection_changed_connection.disconnect();
174 _desktop_activated_connection.disconnect();
176 if (keepalive) {
177 inkscape_unref();
178 keepalive = FALSE;
179 }
181 if (router) {
182 delete router;
183 router = NULL;
184 }
186 //delete this->_whiteboard_session_manager;
187 }
189 void SPDocument::queueForOrphanCollection(SPObject *object) {
190 g_return_if_fail(object != NULL);
191 g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
193 sp_object_ref(object, NULL);
194 _collection_queue = g_slist_prepend(_collection_queue, object);
195 }
197 void SPDocument::collectOrphans() {
198 while (_collection_queue) {
199 GSList *objects=_collection_queue;
200 _collection_queue = NULL;
201 for ( GSList *iter=objects ; iter ; iter = iter->next ) {
202 SPObject *object=reinterpret_cast<SPObject *>(iter->data);
203 object->collectOrphan();
204 sp_object_unref(object, NULL);
205 }
206 g_slist_free(objects);
207 }
208 }
210 void SPDocument::reset_key (void *dummy)
211 {
212 actionkey = NULL;
213 }
215 SPDocument *
216 sp_document_create(Inkscape::XML::Document *rdoc,
217 gchar const *uri,
218 gchar const *base,
219 gchar const *name,
220 unsigned int keepalive)
221 {
222 SPDocument *document;
223 Inkscape::XML::Node *rroot;
224 Inkscape::Version sodipodi_version;
226 rroot = sp_repr_document_root(rdoc);
228 document = new SPDocument();
230 document->keepalive = keepalive;
232 document->rdoc = rdoc;
233 document->rroot = rroot;
235 #ifndef WIN32
236 prepend_current_dir_if_relative(&(document->uri), uri);
237 #else
238 // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
239 document->uri = uri? g_strdup(uri) : NULL;
240 #endif
242 // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
243 // which is why we use g_get_current_dir() in calculating the abs path above
244 //This is NULL for a new document
245 if (base)
246 document->base = g_strdup(base);
247 else
248 document->base = NULL;
249 document->name = g_strdup(name);
251 document->root = sp_object_repr_build_tree(document, rroot);
253 sodipodi_version = SP_ROOT(document->root)->version.sodipodi;
255 /* fixme: Not sure about this, but lets assume ::build updates */
256 rroot->setAttribute("sodipodi:version", SODIPODI_VERSION);
257 rroot->setAttribute("inkscape:version", INKSCAPE_VERSION);
258 /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
260 /* Quick hack 2 - get default image size into document */
261 if (!rroot->attribute("width")) rroot->setAttribute("width", A4_WIDTH_STR);
262 if (!rroot->attribute("height")) rroot->setAttribute("height", A4_HEIGHT_STR);
263 /* End of quick hack 2 */
265 /* Quick hack 3 - Set uri attributes */
266 if (uri) {
267 /* fixme: Think, what this means for images (Lauris) */
268 rroot->setAttribute("sodipodi:docname", uri);
269 if (document->base)
270 rroot->setAttribute("sodipodi:docbase", document->base);
271 }
272 /* End of quick hack 3 */
274 // creating namedview
275 if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
276 // if there's none in the document already,
277 Inkscape::XML::Node *r = NULL;
278 Inkscape::XML::Node *rnew = NULL;
279 r = inkscape_get_repr(INKSCAPE, "template.base");
280 // see if there's a template with id="base" in the preferences
281 if (!r) {
282 // if there's none, create an empty element
283 rnew = sp_repr_new("sodipodi:namedview");
284 rnew->setAttribute("id", "base");
285 } else {
286 // otherwise, take from preferences
287 rnew = r->duplicate();
288 }
289 // insert into the document
290 rroot->addChild(rnew, NULL);
291 // clean up
292 Inkscape::GC::release(rnew);
293 }
295 /* Defs */
296 if (!SP_ROOT(document->root)->defs) {
297 Inkscape::XML::Node *r;
298 r = sp_repr_new("svg:defs");
299 rroot->addChild(r, NULL);
300 Inkscape::GC::release(r);
301 g_assert(SP_ROOT(document->root)->defs);
302 }
304 /* Default RDF */
305 rdf_set_defaults( document );
307 if (keepalive) {
308 inkscape_ref();
309 }
311 sp_document_set_undo_sensitive(document, true);
313 // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
314 if (!Inkscape::NSApplication::Application::getNewGui()) {
315 g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
316 G_CALLBACK(sp_document_reset_key), document);
317 g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
318 G_CALLBACK(sp_document_reset_key), document);
319 } else {
320 document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
321 document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
322 }
323 inkscape_add_document(document);
325 return document;
326 }
328 /**
329 * Fetches document from URI, or creates new, if NULL; public document
330 * appears in document list.
331 */
332 SPDocument *
333 sp_document_new(gchar const *uri, unsigned int keepalive, bool make_new)
334 {
335 SPDocument *doc;
336 Inkscape::XML::Document *rdoc;
337 gchar *base = NULL;
338 gchar *name = NULL;
340 if (uri) {
341 Inkscape::XML::Node *rroot;
342 gchar *s, *p;
343 /* Try to fetch repr from file */
344 rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
345 /* If file cannot be loaded, return NULL without warning */
346 if (rdoc == NULL) return NULL;
347 rroot = sp_repr_document_root(rdoc);
348 /* If xml file is not svg, return NULL without warning */
349 /* fixme: destroy document */
350 if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
351 s = g_strdup(uri);
352 p = strrchr(s, '/');
353 if (p) {
354 name = g_strdup(p + 1);
355 p[1] = '\0';
356 base = g_strdup(s);
357 } else {
358 base = NULL;
359 name = g_strdup(uri);
360 }
361 g_free(s);
362 } else {
363 rdoc = sp_repr_document_new("svg:svg");
364 }
366 if (make_new) {
367 base = NULL;
368 uri = NULL;
369 name = g_strdup_printf(_("New document %d"), ++doc_count);
370 }
372 //# These should be set by now
373 g_assert(name);
375 doc = sp_document_create(rdoc, uri, base, name, keepalive);
377 g_free(base);
378 g_free(name);
380 return doc;
381 }
383 SPDocument *
384 sp_document_new_from_mem(gchar const *buffer, gint length, unsigned int keepalive)
385 {
386 SPDocument *doc;
387 Inkscape::XML::Document *rdoc;
388 Inkscape::XML::Node *rroot;
389 gchar *name;
391 rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
393 /* If it cannot be loaded, return NULL without warning */
394 if (rdoc == NULL) return NULL;
396 rroot = sp_repr_document_root(rdoc);
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;
401 name = g_strdup_printf(_("Memory document %d"), ++doc_count);
403 doc = sp_document_create(rdoc, NULL, NULL, name, keepalive);
405 return doc;
406 }
408 SPDocument *sp_document_new_dummy() {
409 SPDocument *document = new SPDocument();
410 inkscape_add_document(document);
411 return document;
412 }
414 SPDocument *
415 sp_document_ref(SPDocument *doc)
416 {
417 g_return_val_if_fail(doc != NULL, NULL);
418 Inkscape::GC::anchor(doc);
419 return doc;
420 }
422 SPDocument *
423 sp_document_unref(SPDocument *doc)
424 {
425 g_return_val_if_fail(doc != NULL, NULL);
426 Inkscape::GC::release(doc);
427 return NULL;
428 }
430 gdouble sp_document_width(SPDocument *document)
431 {
432 g_return_val_if_fail(document != NULL, 0.0);
433 g_return_val_if_fail(document->priv != NULL, 0.0);
434 g_return_val_if_fail(document->root != NULL, 0.0);
436 return SP_ROOT(document->root)->width.computed;
437 }
439 void
440 sp_document_set_width (SPDocument *document, gdouble width, const SPUnit *unit)
441 {
442 SPRoot *root = SP_ROOT(document->root);
444 if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
445 root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
446 } else { // set to width=
447 root->width.computed = sp_units_get_pixels (width, *unit);
448 /* SVG does not support meters as a unit, so we must translate meters to
449 * cm when writing */
450 if (!strcmp(unit->abbr, "m")) {
451 root->width.value = 100*width;
452 root->width.unit = SVGLength::CM;
453 } else {
454 root->width.value = width;
455 root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
456 }
457 }
459 SP_OBJECT (root)->updateRepr();
460 }
462 void sp_document_set_height (SPDocument * document, gdouble height, const SPUnit *unit)
463 {
464 SPRoot *root = SP_ROOT(document->root);
466 if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
467 root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
468 } else { // set to height=
469 root->height.computed = sp_units_get_pixels (height, *unit);
470 /* SVG does not support meters as a unit, so we must translate meters to
471 * cm when writing */
472 if (!strcmp(unit->abbr, "m")) {
473 root->height.value = 100*height;
474 root->height.unit = SVGLength::CM;
475 } else {
476 root->height.value = height;
477 root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
478 }
479 }
481 SP_OBJECT (root)->updateRepr();
482 }
484 gdouble sp_document_height(SPDocument *document)
485 {
486 g_return_val_if_fail(document != NULL, 0.0);
487 g_return_val_if_fail(document->priv != NULL, 0.0);
488 g_return_val_if_fail(document->root != NULL, 0.0);
490 return SP_ROOT(document->root)->height.computed;
491 }
493 /**
494 * Given an NRRect that may, for example, correspond to the bbox of an object
495 * this function fits the canvas to that rect by resizing the canvas
496 * and translating the document root into position.
497 */
498 void SPDocument::fitToRect(NRRect const & rect)
499 {
500 g_return_if_fail(!empty(rect));
502 gdouble w = rect.x1 - rect.x0;
503 gdouble h = rect.y1 - rect.y0;
504 gdouble old_height = sp_document_height(this);
505 SPUnit unit = sp_unit_get_by_id(SP_UNIT_PX);
506 sp_document_set_width(this, w, &unit);
507 sp_document_set_height(this, h, &unit);
509 NR::translate tr = NR::translate::translate(-rect.x0,-(rect.y0 + (h - old_height)));
510 static_cast<SPGroup *>(root)->translateChildItems(tr);
511 }
513 void sp_document_set_uri(SPDocument *document, gchar const *uri)
514 {
515 g_return_if_fail(document != NULL);
517 if (document->name) {
518 g_free(document->name);
519 document->name = NULL;
520 }
521 if (document->base) {
522 g_free(document->base);
523 document->base = NULL;
524 }
525 if (document->uri) {
526 g_free(document->uri);
527 document->uri = NULL;
528 }
530 if (uri) {
532 #ifndef WIN32
533 prepend_current_dir_if_relative(&(document->uri), uri);
534 #else
535 // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
536 document->uri = g_strdup(uri);
537 #endif
539 /* fixme: Think, what this means for images (Lauris) */
540 document->base = g_path_get_dirname(document->uri);
541 document->name = g_path_get_basename(document->uri);
543 } else {
544 document->uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
545 document->base = NULL;
546 document->name = g_strdup(document->uri);
547 }
549 // Update saveable repr attributes.
550 Inkscape::XML::Node *repr = sp_document_repr_root(document);
551 // changing uri in the document repr must not be not undoable
552 bool saved = sp_document_get_undo_sensitive(document);
553 sp_document_set_undo_sensitive(document, false);
554 if (document->base)
555 repr->setAttribute("sodipodi:docbase", document->base);
557 repr->setAttribute("sodipodi:docname", document->name);
558 sp_document_set_undo_sensitive(document, saved);
560 document->priv->uri_set_signal.emit(document->uri);
561 }
563 void
564 sp_document_resized_signal_emit(SPDocument *doc, gdouble width, gdouble height)
565 {
566 g_return_if_fail(doc != NULL);
568 doc->priv->resized_signal.emit(width, height);
569 }
571 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
572 {
573 return priv->modified_signal.connect(slot);
574 }
576 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
577 {
578 return priv->uri_set_signal.connect(slot);
579 }
581 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
582 {
583 return priv->resized_signal.connect(slot);
584 }
586 sigc::connection
587 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
588 {
589 return priv->_reconstruction_start_signal.connect(slot);
590 }
592 void
593 SPDocument::emitReconstructionStart(void)
594 {
595 // printf("Starting Reconstruction\n");
596 priv->_reconstruction_start_signal.emit();
597 return;
598 }
600 sigc::connection
601 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type slot)
602 {
603 return priv->_reconstruction_finish_signal.connect(slot);
604 }
606 void
607 SPDocument::emitReconstructionFinish(void)
608 {
609 // printf("Finishing Reconstruction\n");
610 priv->_reconstruction_finish_signal.emit();
611 return;
612 }
614 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
615 {
616 return priv->commit_signal.connect(slot);
617 }
621 void SPDocument::_emitModified() {
622 static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
623 root->emitModified(0);
624 priv->modified_signal.emit(flags);
625 }
627 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
628 GQuark idq = g_quark_from_string(id);
630 if (object) {
631 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
632 g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
633 } else {
634 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
635 g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
636 }
638 SPDocumentPrivate::IDChangedSignalMap::iterator pos;
640 pos = priv->id_changed_signals.find(idq);
641 if ( pos != priv->id_changed_signals.end() ) {
642 if (!(*pos).second.empty()) {
643 (*pos).second.emit(object);
644 } else { // discard unused signal
645 priv->id_changed_signals.erase(pos);
646 }
647 }
648 }
650 void
651 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
652 {
653 this->priv->undoStackObservers.add(observer);
654 }
656 void
657 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
658 {
659 this->priv->undoStackObservers.remove(observer);
660 }
662 Inkscape::EventLog&
663 SPDocument::getEventLog() const
664 {
665 return priv->event_log;
666 }
668 SPObject *SPDocument::getObjectById(gchar const *id) {
669 g_return_val_if_fail(id != NULL, NULL);
671 GQuark idq = g_quark_from_string(id);
672 return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
673 }
675 sigc::connection SPDocument::connectIdChanged(gchar const *id,
676 SPDocument::IDChangedSignal::slot_type slot)
677 {
678 return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
679 }
681 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
682 if (object) {
683 g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
684 g_hash_table_insert(priv->reprdef, repr, object);
685 } else {
686 g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
687 g_hash_table_remove(priv->reprdef, repr);
688 }
689 }
691 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
692 g_return_val_if_fail(repr != NULL, NULL);
693 return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
694 }
696 Glib::ustring SPDocument::getLanguage() {
697 gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
698 if (document_language) {
699 while (isspace(*document_language))
700 document_language++;
701 }
702 if ( !document_language || 0 == *document_language) {
703 // retrieve system language
704 document_language = getenv("LC_ALL");
705 if ( NULL == document_language || *document_language == 0 ) {
706 document_language = getenv ("LC_MESSAGES");
707 }
708 if ( NULL == document_language || *document_language == 0 ) {
709 document_language = getenv ("LANG");
710 }
712 if ( NULL != document_language ) {
713 gchar *pos = strchr(document_language, '_');
714 if ( NULL != pos ) {
715 return Glib::ustring(document_language, pos - document_language);
716 }
717 }
718 }
720 if ( NULL == document_language )
721 return Glib::ustring();
722 return document_language;
723 }
725 /* Object modification root handler */
727 void
728 sp_document_request_modified(SPDocument *doc)
729 {
730 if (!doc->modified_id) {
731 doc->modified_id = gtk_idle_add_priority(SP_DOCUMENT_UPDATE_PRIORITY, sp_document_idle_handler, doc);
732 }
733 }
735 void
736 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
737 {
738 ctx->ctx.flags = 0;
739 ctx->i2doc = NR::identity();
740 /* Set up viewport in case svg has it defined as percentages */
741 if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
742 ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
743 ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
744 ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
745 ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
746 } else { // as a last resort, set size to A4
747 ctx->vp.x0 = 0.0;
748 ctx->vp.y0 = 0.0;
749 ctx->vp.x1 = 210 * PX_PER_MM;
750 ctx->vp.y1 = 297 * PX_PER_MM;
751 }
752 ctx->i2vp = NR::identity();
753 }
755 /**
756 * Tries to update the document state based on the modified and
757 * "update required" flags, and return true if the document has
758 * been brought fully up to date.
759 */
760 bool
761 SPDocument::_updateDocument()
762 {
763 /* Process updates */
764 if (this->root->uflags || this->root->mflags) {
765 if (this->root->uflags) {
766 SPItemCtx ctx;
767 sp_document_setup_viewport (this, &ctx);
769 bool saved = sp_document_get_undo_sensitive(this);
770 sp_document_set_undo_sensitive(this, false);
772 this->root->updateDisplay((SPCtx *)&ctx, 0);
774 sp_document_set_undo_sensitive(this, saved);
775 }
776 this->_emitModified();
777 }
779 return !(this->root->uflags || this->root->mflags);
780 }
783 /**
784 * Repeatedly works on getting the document updated, since sometimes
785 * it takes more than one pass to get the document updated. But it
786 * usually should not take more than a few loops, and certainly never
787 * more than 32 iterations. So we bail out if we hit 32 iterations,
788 * since this typically indicates we're stuck in an update loop.
789 */
790 gint
791 sp_document_ensure_up_to_date(SPDocument *doc)
792 {
793 int counter = 32;
794 while (!doc->_updateDocument()) {
795 if (counter == 0) {
796 g_warning("More than 32 iteration while updating document '%s'", doc->uri);
797 break;
798 }
799 counter--;
800 }
802 if (doc->modified_id) {
803 /* Remove handler */
804 gtk_idle_remove(doc->modified_id);
805 doc->modified_id = 0;
806 }
807 return counter>0;
808 }
810 /**
811 * An idle handler to update the document. Returns true if
812 * the document needs further updates.
813 */
814 static gint
815 sp_document_idle_handler(gpointer data)
816 {
817 SPDocument *doc = static_cast<SPDocument *>(data);
818 if (doc->_updateDocument()) {
819 doc->modified_id = 0;
820 return false;
821 } else {
822 return true;
823 }
824 }
826 static bool is_within(NR::Rect const &area, NR::Rect const &box)
827 {
828 return area.contains(box);
829 }
831 static bool overlaps(NR::Rect const &area, NR::Rect const &box)
832 {
833 return area.intersects(box);
834 }
836 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, NR::Rect const &area,
837 bool (*test)(NR::Rect const &, NR::Rect const &), bool take_insensitive = false)
838 {
839 g_return_val_if_fail(SP_IS_GROUP(group), s);
841 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
842 if (!SP_IS_ITEM(o)) {
843 continue;
844 }
845 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
846 s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
847 } else {
848 SPItem *child = SP_ITEM(o);
849 NR::Rect box = sp_item_bbox_desktop(child);
850 if (test(area, box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
851 s = g_slist_append(s, child);
852 }
853 }
854 }
856 return s;
857 }
859 /**
860 Returns true if an item is among the descendants of group (recursively).
861 */
862 bool item_is_in_group(SPItem *item, SPGroup *group)
863 {
864 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
865 if (!SP_IS_ITEM(o)) continue;
866 if (SP_ITEM(o) == item)
867 return true;
868 if (SP_IS_GROUP(o))
869 if (item_is_in_group(item, SP_GROUP(o)))
870 return true;
871 }
872 return false;
873 }
875 /**
876 Returns the bottommost item from the list which is at the point, or NULL if none.
877 */
878 SPItem*
879 sp_document_item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,
880 NR::Point const p, bool take_insensitive)
881 {
882 g_return_val_if_fail(group, NULL);
884 gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
886 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
888 if (!SP_IS_ITEM(o)) continue;
890 SPItem *item = SP_ITEM(o);
891 NRArenaItem *arenaitem = sp_item_get_arenaitem(item, dkey);
892 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
893 && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
894 if (g_slist_find((GSList *) list, item) != NULL)
895 return item;
896 }
898 if (SP_IS_GROUP(o)) {
899 SPItem *found = sp_document_item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
900 if (found)
901 return found;
902 }
904 }
905 return NULL;
906 }
908 /**
909 Returns the topmost (in z-order) item from the descendants of group (recursively) which
910 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
911 non-layer groups or not. Honors take_insensitive on whether to return insensitive
912 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
913 upwards in z-order and returns what it has found so far (i.e. the found item is
914 guaranteed to be lower than upto).
915 */
916 SPItem*
917 find_item_at_point(unsigned int dkey, SPGroup *group, NR::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
918 {
919 SPItem *seen = NULL, *newseen = NULL;
921 gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
923 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
924 if (!SP_IS_ITEM(o)) continue;
926 if (upto && SP_ITEM(o) == upto)
927 break;
929 if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
930 // if nothing found yet, recurse into the group
931 newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
932 if (newseen) {
933 seen = newseen;
934 newseen = NULL;
935 }
937 if (item_is_in_group(upto, SP_GROUP(o)))
938 break;
940 } else {
941 SPItem *child = SP_ITEM(o);
942 NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
944 // seen remembers the last (topmost) of items pickable at this point
945 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
946 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
947 seen = child;
948 }
949 }
950 }
951 return seen;
952 }
954 /**
955 Returns the topmost non-layer group from the descendants of group which is at point
956 p, or NULL if none. Recurses into layers but not into groups.
957 */
958 SPItem*
959 find_group_at_point(unsigned int dkey, SPGroup *group, NR::Point const p)
960 {
961 SPItem *seen = NULL;
963 gdouble delta = prefs_get_double_attribute ("options.cursortolerance", "value", 1.0);
965 for (SPObject *o = sp_object_first_child(SP_OBJECT(group)) ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
966 if (!SP_IS_ITEM(o)) continue;
967 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
968 SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
969 if (newseen) {
970 seen = newseen;
971 }
972 }
973 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
974 SPItem *child = SP_ITEM(o);
975 NRArenaItem *arenaitem = sp_item_get_arenaitem(child, dkey);
977 // seen remembers the last (topmost) of groups pickable at this point
978 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
979 seen = child;
980 }
981 }
982 }
983 return seen;
984 }
986 /*
987 * Return list of items, contained in box
988 *
989 * Assumes box is normalized (and g_asserts it!)
990 *
991 */
993 GSList *sp_document_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
994 {
995 g_return_val_if_fail(document != NULL, NULL);
996 g_return_val_if_fail(document->priv != NULL, NULL);
998 return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, is_within);
999 }
1001 /*
1002 * Return list of items, that the parts of the item contained in box
1003 *
1004 * Assumes box is normalized (and g_asserts it!)
1005 *
1006 */
1008 GSList *sp_document_partial_items_in_box(SPDocument *document, unsigned int dkey, NR::Rect const &box)
1009 {
1010 g_return_val_if_fail(document != NULL, NULL);
1011 g_return_val_if_fail(document->priv != NULL, NULL);
1013 return find_items_in_area(NULL, SP_GROUP(document->root), dkey, box, overlaps);
1014 }
1016 SPItem *
1017 sp_document_item_at_point(SPDocument *document, unsigned const key, NR::Point const p,
1018 gboolean const into_groups, SPItem *upto)
1019 {
1020 g_return_val_if_fail(document != NULL, NULL);
1021 g_return_val_if_fail(document->priv != NULL, NULL);
1023 return find_item_at_point(key, SP_GROUP(document->root), p, into_groups, false, upto);
1024 }
1026 SPItem*
1027 sp_document_group_at_point(SPDocument *document, unsigned int key, NR::Point const p)
1028 {
1029 g_return_val_if_fail(document != NULL, NULL);
1030 g_return_val_if_fail(document->priv != NULL, NULL);
1032 return find_group_at_point(key, SP_GROUP(document->root), p);
1033 }
1036 /* Resource management */
1038 gboolean
1039 sp_document_add_resource(SPDocument *document, gchar const *key, SPObject *object)
1040 {
1041 GSList *rlist;
1042 GQuark q = g_quark_from_string(key);
1044 g_return_val_if_fail(document != NULL, FALSE);
1045 g_return_val_if_fail(key != NULL, FALSE);
1046 g_return_val_if_fail(*key != '\0', FALSE);
1047 g_return_val_if_fail(object != NULL, FALSE);
1048 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1050 if (SP_OBJECT_IS_CLONED(object))
1051 return FALSE;
1053 rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1054 g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1055 rlist = g_slist_prepend(rlist, object);
1056 g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1058 document->priv->resources_changed_signals[q].emit();
1060 return TRUE;
1061 }
1063 gboolean
1064 sp_document_remove_resource(SPDocument *document, gchar const *key, SPObject *object)
1065 {
1066 GSList *rlist;
1067 GQuark q = g_quark_from_string(key);
1069 g_return_val_if_fail(document != NULL, FALSE);
1070 g_return_val_if_fail(key != NULL, FALSE);
1071 g_return_val_if_fail(*key != '\0', FALSE);
1072 g_return_val_if_fail(object != NULL, FALSE);
1073 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1075 if (SP_OBJECT_IS_CLONED(object))
1076 return FALSE;
1078 rlist = (GSList*)g_hash_table_lookup(document->priv->resources, key);
1079 g_return_val_if_fail(rlist != NULL, FALSE);
1080 g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1081 rlist = g_slist_remove(rlist, object);
1082 g_hash_table_insert(document->priv->resources, (gpointer) key, rlist);
1084 document->priv->resources_changed_signals[q].emit();
1086 return TRUE;
1087 }
1089 GSList const *
1090 sp_document_get_resource_list(SPDocument *document, gchar const *key)
1091 {
1092 g_return_val_if_fail(document != NULL, NULL);
1093 g_return_val_if_fail(key != NULL, NULL);
1094 g_return_val_if_fail(*key != '\0', NULL);
1096 return (GSList*)g_hash_table_lookup(document->priv->resources, key);
1097 }
1099 sigc::connection sp_document_resources_changed_connect(SPDocument *document,
1100 gchar const *key,
1101 SPDocument::ResourcesChangedSignal::slot_type slot)
1102 {
1103 GQuark q = g_quark_from_string(key);
1104 return document->priv->resources_changed_signals[q].connect(slot);
1105 }
1107 /* Helpers */
1109 gboolean
1110 sp_document_resource_list_free(gpointer key, gpointer value, gpointer data)
1111 {
1112 g_slist_free((GSList *) value);
1113 return TRUE;
1114 }
1116 unsigned int
1117 count_objects_recursive(SPObject *obj, unsigned int count)
1118 {
1119 count++; // obj itself
1121 for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1122 count = count_objects_recursive(i, count);
1123 }
1125 return count;
1126 }
1128 unsigned int
1129 objects_in_document(SPDocument *document)
1130 {
1131 return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1132 }
1134 void
1135 vacuum_document_recursive(SPObject *obj)
1136 {
1137 if (SP_IS_DEFS(obj)) {
1138 for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1139 /* fixme: some inkscape-internal nodes in the future might not be collectable */
1140 def->requestOrphanCollection();
1141 }
1142 } else {
1143 for (SPObject *i = sp_object_first_child(obj); i != NULL; i = SP_OBJECT_NEXT(i)) {
1144 vacuum_document_recursive(i);
1145 }
1146 }
1147 }
1149 unsigned int
1150 vacuum_document(SPDocument *document)
1151 {
1152 unsigned int start = objects_in_document(document);
1153 unsigned int end;
1154 unsigned int newend = start;
1156 unsigned int iterations = 0;
1158 do {
1159 end = newend;
1161 vacuum_document_recursive(SP_DOCUMENT_ROOT(document));
1162 document->collectOrphans();
1163 iterations++;
1165 newend = objects_in_document(document);
1167 } while (iterations < 100 && newend < end);
1169 return start - newend;
1170 }
1173 /*
1174 Local Variables:
1175 mode:c++
1176 c-file-style:"stroustrup"
1177 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1178 indent-tabs-mode:nil
1179 fill-column:99
1180 End:
1181 */
1182 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :