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