1 #define __SP_DOCUMENT_C__
3 /** \file
4 * SPDocument manipulation
5 *
6 * Authors:
7 * Lauris Kaplinski <lauris@kaplinski.com>
8 * MenTaLguY <mental@rydia.net>
9 * bulia byak <buliabyak@users.sf.net>
10 *
11 * Copyright (C) 2004-2005 MenTaLguY
12 * Copyright (C) 1999-2002 Lauris Kaplinski
13 * Copyright (C) 2000-2001 Ximian, Inc.
14 *
15 * Released under GNU GPL, read the file 'COPYING' for more information
16 */
18 /** \class SPDocument
19 * SPDocument serves as the container of both model trees (agnostic XML
20 * and typed object tree), and implements all of the document-level
21 * functionality used by the program. Many document level operations, like
22 * load, save, print, export and so on, use SPDocument as their basic datatype.
23 *
24 * SPDocument implements undo and redo stacks and an id-based object
25 * dictionary. Thanks to unique id attributes, the latter can be used to
26 * map from the XML tree back to the object tree.
27 *
28 * SPDocument performs the basic operations needed for asynchronous
29 * update notification (SPObject ::modified virtual method), and implements
30 * the 'modified' signal, as well.
31 */
34 #define noSP_DOCUMENT_DEBUG_IDLE
35 #define noSP_DOCUMENT_DEBUG_UNDO
37 #ifdef HAVE_CONFIG_H
38 # include "config.h"
39 #endif
40 #include <gtk/gtkmain.h>
41 #include <string>
42 #include <cstring>
44 #include "application/application.h"
45 #include "application/editor.h"
46 #include "desktop.h"
47 #include "dir-util.h"
48 #include "display/nr-arena-item.h"
49 #include "document-private.h"
50 #include "helper/units.h"
51 #include "inkscape-private.h"
52 #include "inkscape-version.h"
53 #include "libavoid/router.h"
54 #include "persp3d.h"
55 #include "preferences.h"
56 #include "profile-manager.h"
57 #include "rdf.h"
58 #include "sp-item-group.h"
59 #include "sp-namedview.h"
60 #include "sp-object-repr.h"
61 #include "transf_mat_3x4.h"
62 #include "unit-constants.h"
63 #include "xml/repr.h"
64 #include "xml/rebase-hrefs.h"
66 // Higher number means lower priority.
67 #define SP_DOCUMENT_UPDATE_PRIORITY (G_PRIORITY_HIGH_IDLE - 2)
69 // Should have a lower priority than SP_DOCUMENT_UPDATE_PRIORITY,
70 // since we want it to happen when there are no more updates.
71 #define SP_DOCUMENT_REROUTING_PRIORITY (G_PRIORITY_HIGH_IDLE - 1)
74 static gint sp_document_idle_handler(gpointer data);
75 static gint sp_document_rerouting_handler(gpointer data);
77 gboolean sp_document_resource_list_free(gpointer key, gpointer value, gpointer data);
79 static gint doc_count = 0;
81 static unsigned long next_serial = 0;
83 SPDocument::SPDocument() :
84 keepalive(FALSE),
85 virgin(TRUE),
86 modified_since_save(FALSE),
87 rdoc(0),
88 rroot(0),
89 root(0),
90 style_cascade(cr_cascade_new(NULL, NULL, NULL)),
91 uri(0),
92 base(0),
93 name(0),
94 priv(0), // reset in ctor
95 actionkey(0),
96 modified_id(0),
97 rerouting_handler_id(0),
98 profileManager(0), // deferred until after other initialization
99 router(new Avoid::Router(Avoid::PolyLineRouting|Avoid::OrthogonalRouting)),
100 _collection_queue(0),
101 oldSignalsConnected(false),
102 current_persp3d(0)
103 {
104 // Penalise libavoid for choosing paths with needless extra segments.
105 // This results in much better looking orthogonal connector paths.
106 router->setRoutingPenalty(Avoid::segmentPenalty);
108 SPDocumentPrivate *p = new SPDocumentPrivate();
110 p->serial = next_serial++;
112 p->iddef = g_hash_table_new(g_direct_hash, g_direct_equal);
113 p->reprdef = g_hash_table_new(g_direct_hash, g_direct_equal);
115 p->resources = g_hash_table_new(g_str_hash, g_str_equal);
117 p->sensitive = FALSE;
118 p->partial = NULL;
119 p->history_size = 0;
120 p->undo = NULL;
121 p->redo = NULL;
122 p->seeking = false;
124 priv = p;
126 // Once things are set, hook in the manager
127 profileManager = new Inkscape::ProfileManager(this);
129 // XXX only for testing!
130 priv->undoStackObservers.add(p->console_output_undo_observer);
131 }
133 SPDocument::~SPDocument() {
134 collectOrphans();
136 // kill/unhook this first
137 if ( profileManager ) {
138 delete profileManager;
139 profileManager = 0;
140 }
142 if (router) {
143 delete router;
144 router = NULL;
145 }
147 if (priv) {
148 if (priv->partial) {
149 sp_repr_free_log(priv->partial);
150 priv->partial = NULL;
151 }
153 SPDocumentUndo::clear_redo(this);
154 SPDocumentUndo::clear_undo(this);
156 if (root) {
157 root->releaseReferences();
158 sp_object_unref(root);
159 root = NULL;
160 }
162 if (priv->iddef) g_hash_table_destroy(priv->iddef);
163 if (priv->reprdef) g_hash_table_destroy(priv->reprdef);
165 if (rdoc) Inkscape::GC::release(rdoc);
167 /* Free resources */
168 g_hash_table_foreach_remove(priv->resources, sp_document_resource_list_free, this);
169 g_hash_table_destroy(priv->resources);
171 delete priv;
172 priv = NULL;
173 }
175 cr_cascade_unref(style_cascade);
176 style_cascade = NULL;
178 if (name) {
179 g_free(name);
180 name = NULL;
181 }
182 if (base) {
183 g_free(base);
184 base = NULL;
185 }
186 if (uri) {
187 g_free(uri);
188 uri = NULL;
189 }
191 if (modified_id) {
192 g_source_remove(modified_id);
193 modified_id = 0;
194 }
196 if (rerouting_handler_id) {
197 g_source_remove(rerouting_handler_id);
198 rerouting_handler_id = 0;
199 }
201 if (oldSignalsConnected) {
202 g_signal_handlers_disconnect_by_func(G_OBJECT(INKSCAPE),
203 reinterpret_cast<gpointer>(SPDocumentUndo::reset_key),
204 static_cast<gpointer>(this));
205 } else {
206 _selection_changed_connection.disconnect();
207 _desktop_activated_connection.disconnect();
208 }
210 if (keepalive) {
211 inkscape_unref();
212 keepalive = FALSE;
213 }
215 //delete this->_whiteboard_session_manager;
216 }
218 Persp3D *
219 SPDocument::getCurrentPersp3D() {
220 // Check if current_persp3d is still valid
221 std::vector<Persp3D*> plist;
222 getPerspectivesInDefs(plist);
223 for (unsigned int i = 0; i < plist.size(); ++i) {
224 if (current_persp3d == plist[i])
225 return current_persp3d;
226 }
228 // If not, return the first perspective in defs (which may be NULL of none exists)
229 current_persp3d = persp3d_document_first_persp (this);
231 return current_persp3d;
232 }
234 Persp3DImpl *
235 SPDocument::getCurrentPersp3DImpl() {
236 return current_persp3d_impl;
237 }
239 void
240 SPDocument::setCurrentPersp3D(Persp3D * const persp) {
241 current_persp3d = persp;
242 //current_persp3d_impl = persp->perspective_impl;
243 }
245 void
246 SPDocument::getPerspectivesInDefs(std::vector<Persp3D*> &list) {
247 SPDefs *defs = SP_ROOT(this->root)->defs;
248 for (SPObject *i = SP_OBJECT(defs)->first_child(); i != NULL; i = SP_OBJECT_NEXT(i) ) {
249 if (SP_IS_PERSP3D(i))
250 list.push_back(SP_PERSP3D(i));
251 }
252 }
254 /**
255 void SPDocument::initialize_current_persp3d()
256 {
257 this->current_persp3d = persp3d_document_first_persp(this);
258 if (!this->current_persp3d) {
259 this->current_persp3d = persp3d_create_xml_element(this);
260 }
261 }
262 **/
264 unsigned long SPDocument::serial() const {
265 return priv->serial;
266 }
268 void SPDocument::queueForOrphanCollection(SPObject *object) {
269 g_return_if_fail(object != NULL);
270 g_return_if_fail(SP_OBJECT_DOCUMENT(object) == this);
272 sp_object_ref(object, NULL);
273 _collection_queue = g_slist_prepend(_collection_queue, object);
274 }
276 void SPDocument::collectOrphans() {
277 while (_collection_queue) {
278 GSList *objects=_collection_queue;
279 _collection_queue = NULL;
280 for ( GSList *iter=objects ; iter ; iter = iter->next ) {
281 SPObject *object=reinterpret_cast<SPObject *>(iter->data);
282 object->collectOrphan();
283 sp_object_unref(object, NULL);
284 }
285 g_slist_free(objects);
286 }
287 }
289 void SPDocument::reset_key (void */*dummy*/)
290 {
291 actionkey = NULL;
292 }
294 SPDocument *
295 SPDocument::createDoc(Inkscape::XML::Document *rdoc,
296 gchar const *uri,
297 gchar const *base,
298 gchar const *name,
299 unsigned int keepalive)
300 {
301 SPDocument *document;
302 Inkscape::XML::Node *rroot;
303 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
305 rroot = rdoc->root();
307 document = new SPDocument();
309 document->keepalive = keepalive;
311 document->rdoc = rdoc;
312 document->rroot = rroot;
314 #ifndef WIN32
315 document->uri = prepend_current_dir_if_relative(uri);
316 #else
317 // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
318 document->uri = uri? g_strdup(uri) : NULL;
319 #endif
321 // base is simply the part of the path before filename; e.g. when running "inkscape ../file.svg" the base is "../"
322 // which is why we use g_get_current_dir() in calculating the abs path above
323 //This is NULL for a new document
324 if (base)
325 document->base = g_strdup(base);
326 else
327 document->base = NULL;
328 document->name = g_strdup(name);
330 document->root = sp_object_repr_build_tree(document, rroot);
332 /* fixme: Not sure about this, but lets assume ::build updates */
333 rroot->setAttribute("inkscape:version", Inkscape::version_string);
334 /* fixme: Again, I moved these here to allow version determining in ::build (Lauris) */
336 /* Quick hack 2 - get default image size into document */
337 if (!rroot->attribute("width")) rroot->setAttribute("width", "100%");
338 if (!rroot->attribute("height")) rroot->setAttribute("height", "100%");
339 /* End of quick hack 2 */
341 /* Quick hack 3 - Set uri attributes */
342 if (uri) {
343 rroot->setAttribute("sodipodi:docname", uri);
344 }
345 /* End of quick hack 3 */
347 /* Eliminate obsolete sodipodi:docbase, for privacy reasons */
348 rroot->setAttribute("sodipodi:docbase", NULL);
350 /* Eliminate any claim to adhere to a profile, as we don't try to */
351 rroot->setAttribute("baseProfile", NULL);
353 // creating namedview
354 if (!sp_item_group_get_child_by_name((SPGroup *) document->root, NULL, "sodipodi:namedview")) {
355 // if there's none in the document already,
356 Inkscape::XML::Node *rnew = NULL;
358 rnew = rdoc->createElement("sodipodi:namedview");
359 //rnew->setAttribute("id", "base");
361 // Add namedview data from the preferences
362 // we can't use getAllEntries because this could produce non-SVG doubles
363 Glib::ustring pagecolor = prefs->getString("/template/base/pagecolor");
364 if (!pagecolor.empty()) {
365 rnew->setAttribute("pagecolor", pagecolor.data());
366 }
367 Glib::ustring bordercolor = prefs->getString("/template/base/bordercolor");
368 if (!bordercolor.empty()) {
369 rnew->setAttribute("bordercolor", bordercolor.data());
370 }
371 sp_repr_set_svg_double(rnew, "borderopacity",
372 prefs->getDouble("/template/base/borderopacity", 1.0));
373 sp_repr_set_svg_double(rnew, "objecttolerance",
374 prefs->getDouble("/template/base/objecttolerance", 10.0));
375 sp_repr_set_svg_double(rnew, "gridtolerance",
376 prefs->getDouble("/template/base/gridtolerance", 10.0));
377 sp_repr_set_svg_double(rnew, "guidetolerance",
378 prefs->getDouble("/template/base/guidetolerance", 10.0));
379 sp_repr_set_svg_double(rnew, "inkscape:pageopacity",
380 prefs->getDouble("/template/base/inkscape:pageopacity", 0.0));
381 sp_repr_set_int(rnew, "inkscape:pageshadow",
382 prefs->getInt("/template/base/inkscape:pageshadow", 2));
383 sp_repr_set_int(rnew, "inkscape:window-width",
384 prefs->getInt("/template/base/inkscape:window-width", 640));
385 sp_repr_set_int(rnew, "inkscape:window-height",
386 prefs->getInt("/template/base/inkscape:window-height", 480));
388 // insert into the document
389 rroot->addChild(rnew, NULL);
390 // clean up
391 Inkscape::GC::release(rnew);
392 }
394 /* Defs */
395 if (!SP_ROOT(document->root)->defs) {
396 Inkscape::XML::Node *r;
397 r = rdoc->createElement("svg:defs");
398 rroot->addChild(r, NULL);
399 Inkscape::GC::release(r);
400 g_assert(SP_ROOT(document->root)->defs);
401 }
403 /* Default RDF */
404 rdf_set_defaults( document );
406 if (keepalive) {
407 inkscape_ref();
408 }
410 // Check if the document already has a perspective (e.g., when opening an existing
411 // document). If not, create a new one and set it as the current perspective.
412 document->setCurrentPersp3D(persp3d_document_first_persp(document));
413 if (!document->getCurrentPersp3D()) {
414 //document->setCurrentPersp3D(persp3d_create_xml_element (document));
415 Persp3DImpl *persp_impl = new Persp3DImpl();
416 document->setCurrentPersp3DImpl(persp_impl);
417 }
419 SPDocumentUndo::set_undo_sensitive(document, true);
421 // reset undo key when selection changes, so that same-key actions on different objects are not coalesced
422 if (!Inkscape::NSApplication::Application::getNewGui()) {
423 g_signal_connect(G_OBJECT(INKSCAPE), "change_selection",
424 G_CALLBACK(SPDocumentUndo::reset_key), document);
425 g_signal_connect(G_OBJECT(INKSCAPE), "activate_desktop",
426 G_CALLBACK(SPDocumentUndo::reset_key), document);
427 document->oldSignalsConnected = true;
428 } else {
429 document->_selection_changed_connection = Inkscape::NSApplication::Editor::connectSelectionChanged (sigc::mem_fun (*document, &SPDocument::reset_key));
430 document->_desktop_activated_connection = Inkscape::NSApplication::Editor::connectDesktopActivated (sigc::mem_fun (*document, &SPDocument::reset_key));
431 document->oldSignalsConnected = false;
432 }
434 return document;
435 }
437 /**
438 * Fetches document from URI, or creates new, if NULL; public document
439 * appears in document list.
440 */
441 SPDocument *
442 SPDocument::createNewDoc(gchar const *uri, unsigned int keepalive, bool make_new)
443 {
444 SPDocument *doc;
445 Inkscape::XML::Document *rdoc;
446 gchar *base = NULL;
447 gchar *name = NULL;
449 if (uri) {
450 Inkscape::XML::Node *rroot;
451 gchar *s, *p;
452 /* Try to fetch repr from file */
453 rdoc = sp_repr_read_file(uri, SP_SVG_NS_URI);
454 /* If file cannot be loaded, return NULL without warning */
455 if (rdoc == NULL) return NULL;
456 rroot = rdoc->root();
457 /* If xml file is not svg, return NULL without warning */
458 /* fixme: destroy document */
459 if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
460 s = g_strdup(uri);
461 p = strrchr(s, '/');
462 if (p) {
463 name = g_strdup(p + 1);
464 p[1] = '\0';
465 base = g_strdup(s);
466 } else {
467 base = NULL;
468 name = g_strdup(uri);
469 }
470 g_free(s);
471 } else {
472 rdoc = sp_repr_document_new("svg:svg");
473 }
475 if (make_new) {
476 base = NULL;
477 uri = NULL;
478 name = g_strdup_printf(_("New document %d"), ++doc_count);
479 }
481 //# These should be set by now
482 g_assert(name);
484 doc = createDoc(rdoc, uri, base, name, keepalive);
486 g_free(base);
487 g_free(name);
489 return doc;
490 }
492 SPDocument *
493 SPDocument::createNewDocFromMem(gchar const *buffer, gint length, unsigned int keepalive)
494 {
495 SPDocument *doc;
496 Inkscape::XML::Document *rdoc;
497 Inkscape::XML::Node *rroot;
498 gchar *name;
500 rdoc = sp_repr_read_mem(buffer, length, SP_SVG_NS_URI);
502 /* If it cannot be loaded, return NULL without warning */
503 if (rdoc == NULL) return NULL;
505 rroot = rdoc->root();
506 /* If xml file is not svg, return NULL without warning */
507 /* fixme: destroy document */
508 if (strcmp(rroot->name(), "svg:svg") != 0) return NULL;
510 name = g_strdup_printf(_("Memory document %d"), ++doc_count);
512 doc = createDoc(rdoc, NULL, NULL, name, keepalive);
514 return doc;
515 }
517 SPDocument *
518 SPDocument::doRef()
519 {
520 g_return_val_if_fail(this != NULL, NULL);
521 Inkscape::GC::anchor(this);
522 return this;
523 }
525 SPDocument *
526 SPDocument::doUnref()
527 {
528 g_return_val_if_fail(this != NULL, NULL);
529 Inkscape::GC::release(this);
530 return NULL;
531 }
533 gdouble SPDocument::getWidth()
534 {
535 g_return_val_if_fail(this != NULL, 0.0);
536 g_return_val_if_fail(this->priv != NULL, 0.0);
537 g_return_val_if_fail(this->root != NULL, 0.0);
539 SPRoot *root = SP_ROOT(this->root);
541 if (root->width.unit == SVGLength::PERCENT && root->viewBox_set)
542 return root->viewBox.x1 - root->viewBox.x0;
543 return root->width.computed;
544 }
546 void
547 SPDocument::setWidth (gdouble width, const SPUnit *unit)
548 {
549 SPRoot *root = SP_ROOT(this->root);
551 if (root->width.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
552 root->viewBox.x1 = root->viewBox.x0 + sp_units_get_pixels (width, *unit);
553 } else { // set to width=
554 gdouble old_computed = root->width.computed;
555 root->width.computed = sp_units_get_pixels (width, *unit);
556 /* SVG does not support meters as a unit, so we must translate meters to
557 * cm when writing */
558 if (!strcmp(unit->abbr, "m")) {
559 root->width.value = 100*width;
560 root->width.unit = SVGLength::CM;
561 } else {
562 root->width.value = width;
563 root->width.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
564 }
566 if (root->viewBox_set)
567 root->viewBox.x1 = root->viewBox.x0 + (root->width.computed / old_computed) * (root->viewBox.x1 - root->viewBox.x0);
568 }
570 SP_OBJECT (root)->updateRepr();
571 }
573 void SPDocument::setHeight (gdouble height, const SPUnit *unit)
574 {
575 SPRoot *root = SP_ROOT(this->root);
577 if (root->height.unit == SVGLength::PERCENT && root->viewBox_set) { // set to viewBox=
578 root->viewBox.y1 = root->viewBox.y0 + sp_units_get_pixels (height, *unit);
579 } else { // set to height=
580 gdouble old_computed = root->height.computed;
581 root->height.computed = sp_units_get_pixels (height, *unit);
582 /* SVG does not support meters as a unit, so we must translate meters to
583 * cm when writing */
584 if (!strcmp(unit->abbr, "m")) {
585 root->height.value = 100*height;
586 root->height.unit = SVGLength::CM;
587 } else {
588 root->height.value = height;
589 root->height.unit = (SVGLength::Unit) sp_unit_get_svg_unit(unit);
590 }
592 if (root->viewBox_set)
593 root->viewBox.y1 = root->viewBox.y0 + (root->height.computed / old_computed) * (root->viewBox.y1 - root->viewBox.y0);
594 }
596 SP_OBJECT (root)->updateRepr();
597 }
599 gdouble SPDocument::getHeight()
600 {
601 g_return_val_if_fail(this != NULL, 0.0);
602 g_return_val_if_fail(this->priv != NULL, 0.0);
603 g_return_val_if_fail(this->root != NULL, 0.0);
605 SPRoot *root = SP_ROOT(this->root);
607 if (root->height.unit == SVGLength::PERCENT && root->viewBox_set)
608 return root->viewBox.y1 - root->viewBox.y0;
609 return root->height.computed;
610 }
612 Geom::Point SPDocument::getDimensions()
613 {
614 return Geom::Point(getWidth(), getHeight());
615 }
617 /**
618 * Gets page fitting margin information from the namedview node in the XML.
619 * \param nv_repr reference to this document's namedview
620 * \param key the same key used by the RegisteredScalarUnit in
621 * ui/widget/page-sizer.cpp
622 * \param margin_units units for the margin
623 * \param return_units units to return the result in
624 * \param width width in px (for percentage margins)
625 * \param height height in px (for percentage margins)
626 * \param use_width true if the this key is left or right margins, false
627 * otherwise. Used for percentage margins.
628 * \return the margin size in px, else 0.0 if anything is invalid.
629 */
630 //static double getMarginLength(/*Inkscape::XML::Node * const nv_repr*/
631 /* gchar const * const key,
632 SPUnit const * const margin_units,
633 SPUnit const * const return_units,
634 double const width,
635 double const height,
636 bool const use_width)*/
637 //{
638 // double value;
639 /*if (!sp_repr_get_double (nv_repr, key, &value)) {
640 return 0.0;
641 }*/
642 /* if(!this->storeAsDouble(key,&value)) {
643 return 0.0;
644 }
645 if (margin_units == &sp_unit_get_by_id (SP_UNIT_PERCENT)) {
646 return (use_width)? width * value : height * value;
647 }
648 if (!sp_convert_distance (&value, margin_units, return_units)) {
649 return 0.0;
650 }
651 return value;
652 }*/
654 /**
655 * Given a Geom::Rect that may, for example, correspond to the bbox of an object,
656 * this function fits the canvas to that rect by resizing the canvas
657 * and translating the document root into position.
658 * \param rect fit document size to this
659 * \param with_margins add margins to rect, by taking margins from this
660 * document's namedview (<sodipodi:namedview> "fit-margin-..."
661 * attributes, and "units")
662 */
663 void SPDocument::fitToRect(Geom::Rect const &rect, bool with_margins)
664 {
665 double const w = rect.width();
666 double const h = rect.height();
668 double const old_height = getHeight();
669 SPUnit const &px(sp_unit_get_by_id(SP_UNIT_PX));
671 /* in px */
672 double margin_top = 0.0;
673 double margin_left = 0.0;
674 double margin_right = 0.0;
675 double margin_bottom = 0.0;
677 SPNamedView *nv = sp_document_namedview(this, 0);
679 if (with_margins && nv) {
680 //Inkscape::XML::Node *nv_repr = SP_OBJECT_REPR (nv);
681 if (nv != NULL) {
682 //gchar const * const units_abbr = nv_repr->attribute("units");
683 gchar const * const units_abbr = nv->getAttribute("units");
684 SPUnit const *margin_units = NULL;
685 if (units_abbr != NULL) {
686 margin_units = sp_unit_get_by_abbreviation(units_abbr);
687 }
688 if (margin_units == NULL) {
689 margin_units = &px;
690 }
691 /*
692 margin_top = getMarginLength(nv_repr, "fit-margin-top",
693 margin_units, &px, w, h, false);
694 margin_left = getMarginLength(nv_repr, "fit-margin-left",
695 margin_units, &px, w, h, true);
696 margin_right = getMarginLength(nv_repr, "fit-margin-right",
697 margin_units, &px, w, h, true);
698 margin_bottom = getMarginLength(nv_repr, "fit-margin-bottom",
699 margin_units, &px, w, h, false);*/
700 margin_top = nv->getMarginLength("fit-margin-top",margin_units, &px, w, h, false);
701 margin_top = nv->getMarginLength("fit-margin-left",margin_units, &px, w, h, true);
702 margin_top = nv->getMarginLength("fit-margin-right",margin_units, &px, w, h, true);
703 margin_top = nv->getMarginLength("fit-margin-bottom",margin_units, &px, w, h, false);
706 }
707 }
709 Geom::Rect const rect_with_margins(
710 rect.min() - Geom::Point(margin_left, margin_bottom),
711 rect.max() + Geom::Point(margin_right, margin_top));
714 setWidth(rect_with_margins.width(), &px);
715 setHeight(rect_with_margins.height(), &px);
717 Geom::Translate const tr(
718 Geom::Point(0, old_height - rect_with_margins.height())
719 - to_2geom(rect_with_margins.min()));
720 SP_GROUP(root)->translateChildItems(tr);
722 if(nv) {
723 Geom::Translate tr2(-rect_with_margins.min());
724 nv->translateGuides(tr2);
726 // update the viewport so the drawing appears to stay where it was
727 nv->scrollAllDesktops(-tr2[0], tr2[1], false);
728 }
729 }
731 void
732 SPDocument::do_change_uri(gchar const *const filename, bool const rebase)
733 {
734 //g_return_if_fail(this != NULL);
736 gchar *new_base;
737 gchar *new_name;
738 gchar *new_uri;
739 if (filename) {
741 #ifndef WIN32
742 new_uri = prepend_current_dir_if_relative(filename);
743 #else
744 // FIXME: it may be that prepend_current_dir_if_relative works OK on windows too, test!
745 new_uri = g_strdup(filename);
746 #endif
748 new_base = g_path_get_dirname(new_uri);
749 new_name = g_path_get_basename(new_uri);
750 } else {
751 new_uri = g_strdup_printf(_("Unnamed document %d"), ++doc_count);
752 new_base = NULL;
753 new_name = g_strdup(this->uri);
754 }
756 // Update saveable repr attributes.
757 Inkscape::XML::Node *repr = sp_document_repr_root(this);
759 // Changing uri in the document repr must not be not undoable.
760 bool const saved = SPDocumentUndo::get_undo_sensitive(this);
761 SPDocumentUndo::set_undo_sensitive(this, false);
763 if (rebase) {
764 Inkscape::XML::rebase_hrefs(this, new_base, true);
765 }
767 repr->setAttribute("sodipodi:docname", this->name);
768 SPDocumentUndo::set_undo_sensitive(this, saved);
771 g_free(this->name);
772 g_free(this->base);
773 g_free(this->uri);
774 this->name = new_name;
775 this->base = new_base;
776 this->uri = new_uri;
778 this->priv->uri_set_signal.emit(this->uri);
779 }
781 /**
782 * Sets base, name and uri members of \a document. Doesn't update
783 * any relative hrefs in the document: thus, this is primarily for
784 * newly-created documents.
785 *
786 * \see sp_document_change_uri_and_hrefs
787 */
788 void SPDocument::setUri(gchar const *filename)
789 {
790 //g_return_if_fail(this != NULL);
792 do_change_uri(filename, false);
793 }
795 /**
796 * Changes the base, name and uri members of \a document, and updates any
797 * relative hrefs in the document to be relative to the new base.
798 *
799 * \see sp_document_set_uri
800 */
801 void SPDocument::change_uri_and_hrefs(gchar const *filename)
802 {
803 //g_return_if_fail(this != NULL);
805 do_change_uri(filename, true);
806 }
808 void
809 SPDocument::resized_signal_emit(gdouble width, gdouble height)
810 {
811 //g_return_if_fail(this != NULL);
813 this->priv->resized_signal.emit(width, height);
814 }
816 sigc::connection SPDocument::connectModified(SPDocument::ModifiedSignal::slot_type slot)
817 {
818 return priv->modified_signal.connect(slot);
819 }
821 sigc::connection SPDocument::connectURISet(SPDocument::URISetSignal::slot_type slot)
822 {
823 return priv->uri_set_signal.connect(slot);
824 }
826 sigc::connection SPDocument::connectResized(SPDocument::ResizedSignal::slot_type slot)
827 {
828 return priv->resized_signal.connect(slot);
829 }
831 sigc::connection
832 SPDocument::connectReconstructionStart(SPDocument::ReconstructionStart::slot_type slot)
833 {
834 return priv->_reconstruction_start_signal.connect(slot);
835 }
837 void
838 SPDocument::emitReconstructionStart(void)
839 {
840 // printf("Starting Reconstruction\n");
841 priv->_reconstruction_start_signal.emit();
842 return;
843 }
845 sigc::connection
846 SPDocument::connectReconstructionFinish(SPDocument::ReconstructionFinish::slot_type slot)
847 {
848 return priv->_reconstruction_finish_signal.connect(slot);
849 }
851 void
852 SPDocument::emitReconstructionFinish(void)
853 {
854 // printf("Finishing Reconstruction\n");
855 priv->_reconstruction_finish_signal.emit();
857 /**
858 // Reference to the old persp3d object is invalid after reconstruction.
859 initialize_current_persp3d();
861 return;
862 **/
863 }
865 sigc::connection SPDocument::connectCommit(SPDocument::CommitSignal::slot_type slot)
866 {
867 return priv->commit_signal.connect(slot);
868 }
872 void SPDocument::_emitModified() {
873 static guint const flags = SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_PARENT_MODIFIED_FLAG;
874 root->emitModified(0);
875 priv->modified_signal.emit(flags);
876 }
878 void SPDocument::bindObjectToId(gchar const *id, SPObject *object) {
879 GQuark idq = g_quark_from_string(id);
881 if (object) {
882 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) == NULL);
883 g_hash_table_insert(priv->iddef, GINT_TO_POINTER(idq), object);
884 } else {
885 g_assert(g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq)) != NULL);
886 g_hash_table_remove(priv->iddef, GINT_TO_POINTER(idq));
887 }
889 SPDocumentPrivate::IDChangedSignalMap::iterator pos;
891 pos = priv->id_changed_signals.find(idq);
892 if ( pos != priv->id_changed_signals.end() ) {
893 if (!(*pos).second.empty()) {
894 (*pos).second.emit(object);
895 } else { // discard unused signal
896 priv->id_changed_signals.erase(pos);
897 }
898 }
899 }
901 void
902 SPDocument::addUndoObserver(Inkscape::UndoStackObserver& observer)
903 {
904 this->priv->undoStackObservers.add(observer);
905 }
907 void
908 SPDocument::removeUndoObserver(Inkscape::UndoStackObserver& observer)
909 {
910 this->priv->undoStackObservers.remove(observer);
911 }
913 SPObject *SPDocument::getObjectById(gchar const *id) {
914 g_return_val_if_fail(id != NULL, NULL);
916 GQuark idq = g_quark_from_string(id);
917 return (SPObject*)g_hash_table_lookup(priv->iddef, GINT_TO_POINTER(idq));
918 }
920 sigc::connection SPDocument::connectIdChanged(gchar const *id,
921 SPDocument::IDChangedSignal::slot_type slot)
922 {
923 return priv->id_changed_signals[g_quark_from_string(id)].connect(slot);
924 }
926 void SPDocument::bindObjectToRepr(Inkscape::XML::Node *repr, SPObject *object) {
927 if (object) {
928 g_assert(g_hash_table_lookup(priv->reprdef, repr) == NULL);
929 g_hash_table_insert(priv->reprdef, repr, object);
930 } else {
931 g_assert(g_hash_table_lookup(priv->reprdef, repr) != NULL);
932 g_hash_table_remove(priv->reprdef, repr);
933 }
934 }
936 SPObject *SPDocument::getObjectByRepr(Inkscape::XML::Node *repr) {
937 g_return_val_if_fail(repr != NULL, NULL);
938 return (SPObject*)g_hash_table_lookup(priv->reprdef, repr);
939 }
941 Glib::ustring SPDocument::getLanguage() {
942 gchar const *document_language = rdf_get_work_entity(this, rdf_find_entity("language"));
943 if (document_language) {
944 while (isspace(*document_language))
945 document_language++;
946 }
947 if ( !document_language || 0 == *document_language) {
948 // retrieve system language
949 document_language = getenv("LC_ALL");
950 if ( NULL == document_language || *document_language == 0 ) {
951 document_language = getenv ("LC_MESSAGES");
952 }
953 if ( NULL == document_language || *document_language == 0 ) {
954 document_language = getenv ("LANG");
955 }
957 if ( NULL != document_language ) {
958 const char *pos = strchr(document_language, '_');
959 if ( NULL != pos ) {
960 return Glib::ustring(document_language, pos - document_language);
961 }
962 }
963 }
965 if ( NULL == document_language )
966 return Glib::ustring();
967 return document_language;
968 }
970 /* Object modification root handler */
972 void
973 SPDocument::request_modified()
974 {
975 if (!modified_id) {
976 modified_id = g_idle_add_full(SP_DOCUMENT_UPDATE_PRIORITY,
977 sp_document_idle_handler, this, NULL);
978 }
979 if (!rerouting_handler_id) {
980 rerouting_handler_id = g_idle_add_full(SP_DOCUMENT_REROUTING_PRIORITY,
981 sp_document_rerouting_handler, this, NULL);
982 }
983 }
985 void
986 sp_document_setup_viewport (SPDocument *doc, SPItemCtx *ctx)
987 {
988 ctx->ctx.flags = 0;
989 ctx->i2doc = Geom::identity();
990 /* Set up viewport in case svg has it defined as percentages */
991 if (SP_ROOT(doc->root)->viewBox_set) { // if set, take from viewBox
992 ctx->vp.x0 = SP_ROOT(doc->root)->viewBox.x0;
993 ctx->vp.y0 = SP_ROOT(doc->root)->viewBox.y0;
994 ctx->vp.x1 = SP_ROOT(doc->root)->viewBox.x1;
995 ctx->vp.y1 = SP_ROOT(doc->root)->viewBox.y1;
996 } else { // as a last resort, set size to A4
997 ctx->vp.x0 = 0.0;
998 ctx->vp.y0 = 0.0;
999 ctx->vp.x1 = 210 * PX_PER_MM;
1000 ctx->vp.y1 = 297 * PX_PER_MM;
1001 }
1002 ctx->i2vp = Geom::identity();
1003 }
1005 /**
1006 * Tries to update the document state based on the modified and
1007 * "update required" flags, and return true if the document has
1008 * been brought fully up to date.
1009 */
1010 bool
1011 SPDocument::_updateDocument()
1012 {
1013 /* Process updates */
1014 if (this->root->uflags || this->root->mflags) {
1015 if (this->root->uflags) {
1016 SPItemCtx ctx;
1017 sp_document_setup_viewport (this, &ctx);
1019 bool saved = SPDocumentUndo::get_undo_sensitive(this);
1020 SPDocumentUndo::set_undo_sensitive(this, false);
1022 this->root->updateDisplay((SPCtx *)&ctx, 0);
1024 SPDocumentUndo::set_undo_sensitive(this, saved);
1025 }
1026 this->_emitModified();
1027 }
1029 return !(this->root->uflags || this->root->mflags);
1030 }
1033 /**
1034 * Repeatedly works on getting the document updated, since sometimes
1035 * it takes more than one pass to get the document updated. But it
1036 * usually should not take more than a few loops, and certainly never
1037 * more than 32 iterations. So we bail out if we hit 32 iterations,
1038 * since this typically indicates we're stuck in an update loop.
1039 */
1040 gint
1041 SPDocument::ensure_up_to_date()
1042 {
1043 // Bring the document up-to-date, specifically via the following:
1044 // 1a) Process all document updates.
1045 // 1b) When completed, process connector routing changes.
1046 // 2a) Process any updates resulting from connector reroutings.
1047 int counter = 32;
1048 for (unsigned int pass = 1; pass <= 2; ++pass) {
1049 // Process document updates.
1050 while (!_updateDocument()) {
1051 if (counter == 0) {
1052 g_warning("More than 32 iteration while updating document '%s'", uri);
1053 break;
1054 }
1055 counter--;
1056 }
1057 if (counter == 0)
1058 {
1059 break;
1060 }
1062 // After updates on the first pass we get libavoid to process all the
1063 // changed objects and provide new routings. This may cause some objects
1064 // to be modified, hence the second update pass.
1065 if (pass == 1) {
1066 router->processTransaction();
1067 }
1068 }
1070 if (modified_id) {
1071 /* Remove handler */
1072 g_source_remove(modified_id);
1073 modified_id = 0;
1074 }
1075 if (rerouting_handler_id) {
1076 /* Remove handler */
1077 g_source_remove(rerouting_handler_id);
1078 rerouting_handler_id = 0;
1079 }
1080 return counter>0;
1081 }
1083 /**
1084 * An idle handler to update the document. Returns true if
1085 * the document needs further updates.
1086 */
1087 static gint
1088 sp_document_idle_handler(gpointer data)
1089 {
1090 SPDocument *doc = static_cast<SPDocument *>(data);
1091 if (doc->_updateDocument()) {
1092 doc->modified_id = 0;
1093 return false;
1094 } else {
1095 return true;
1096 }
1097 }
1099 /**
1100 * An idle handler to reroute connectors in the document.
1101 */
1102 static gint
1103 sp_document_rerouting_handler(gpointer data)
1104 {
1105 // Process any queued movement actions and determine new routings for
1106 // object-avoiding connectors. Callbacks will be used to update and
1107 // redraw affected connectors.
1108 SPDocument *doc = static_cast<SPDocument *>(data);
1109 doc->router->processTransaction();
1111 // We don't need to handle rerouting again until there are further
1112 // diagram updates.
1113 doc->rerouting_handler_id = 0;
1114 return false;
1115 }
1117 static bool is_within(Geom::Rect const &area, Geom::Rect const &box)
1118 {
1119 return area.contains(box);
1120 }
1122 static bool overlaps(Geom::Rect const &area, Geom::Rect const &box)
1123 {
1124 return area.intersects(box);
1125 }
1127 static GSList *find_items_in_area(GSList *s, SPGroup *group, unsigned int dkey, Geom::Rect const &area,
1128 bool (*test)(Geom::Rect const &, Geom::Rect const &), bool take_insensitive = false)
1129 {
1130 g_return_val_if_fail(SP_IS_GROUP(group), s);
1132 for (SPObject *o = SP_OBJECT(group)->first_child() ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1133 if (!SP_IS_ITEM(o)) {
1134 continue;
1135 }
1136 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER ) {
1137 s = find_items_in_area(s, SP_GROUP(o), dkey, area, test);
1138 } else {
1139 SPItem *child = SP_ITEM(o);
1140 Geom::OptRect box = child->getBboxDesktop();
1141 if ( box && test(area, *box) && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1142 s = g_slist_append(s, child);
1143 }
1144 }
1145 }
1147 return s;
1148 }
1150 /**
1151 Returns true if an item is among the descendants of group (recursively).
1152 */
1153 bool item_is_in_group(SPItem *item, SPGroup *group)
1154 {
1155 for (SPObject *o = SP_OBJECT(group)->first_child() ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1156 if (!SP_IS_ITEM(o)) continue;
1157 if (SP_ITEM(o) == item)
1158 return true;
1159 if (SP_IS_GROUP(o))
1160 if (item_is_in_group(item, SP_GROUP(o)))
1161 return true;
1162 }
1163 return false;
1164 }
1166 /**
1167 Returns the bottommost item from the list which is at the point, or NULL if none.
1168 */
1169 SPItem*
1170 SPDocument::item_from_list_at_point_bottom(unsigned int dkey, SPGroup *group, GSList const *list,Geom::Point const p, bool take_insensitive)
1171 {
1172 g_return_val_if_fail(group, NULL);
1173 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1174 gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1176 for (SPObject *o = SP_OBJECT(group)->first_child() ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1178 if (!SP_IS_ITEM(o)) continue;
1180 SPItem *item = SP_ITEM(o);
1181 NRArenaItem *arenaitem = item->get_arenaitem(dkey);
1182 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1183 && (take_insensitive || item->isVisibleAndUnlocked(dkey))) {
1184 if (g_slist_find((GSList *) list, item) != NULL)
1185 return item;
1186 }
1188 if (SP_IS_GROUP(o)) {
1189 SPItem *found = item_from_list_at_point_bottom(dkey, SP_GROUP(o), list, p, take_insensitive);
1190 if (found)
1191 return found;
1192 }
1194 }
1195 return NULL;
1196 }
1198 /**
1199 Returns the topmost (in z-order) item from the descendants of group (recursively) which
1200 is at the point p, or NULL if none. Honors into_groups on whether to recurse into
1201 non-layer groups or not. Honors take_insensitive on whether to return insensitive
1202 items. If upto != NULL, then if item upto is encountered (at any level), stops searching
1203 upwards in z-order and returns what it has found so far (i.e. the found item is
1204 guaranteed to be lower than upto).
1205 */
1206 SPItem*
1207 find_item_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p, gboolean into_groups, bool take_insensitive = false, SPItem *upto = NULL)
1208 {
1209 SPItem *seen = NULL, *newseen = NULL;
1210 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1211 gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1213 for (SPObject *o = SP_OBJECT(group)->first_child() ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1214 if (!SP_IS_ITEM(o)) continue;
1216 if (upto && SP_ITEM(o) == upto)
1217 break;
1219 if (SP_IS_GROUP(o) && (SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER || into_groups)) {
1220 // if nothing found yet, recurse into the group
1221 newseen = find_item_at_point(dkey, SP_GROUP(o), p, into_groups, take_insensitive, upto);
1222 if (newseen) {
1223 seen = newseen;
1224 newseen = NULL;
1225 }
1227 if (item_is_in_group(upto, SP_GROUP(o)))
1228 break;
1230 } else {
1231 SPItem *child = SP_ITEM(o);
1232 NRArenaItem *arenaitem = child->get_arenaitem(dkey);
1234 // seen remembers the last (topmost) of items pickable at this point
1235 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL
1236 && (take_insensitive || child->isVisibleAndUnlocked(dkey))) {
1237 seen = child;
1238 }
1239 }
1240 }
1241 return seen;
1242 }
1244 /**
1245 Returns the topmost non-layer group from the descendants of group which is at point
1246 p, or NULL if none. Recurses into layers but not into groups.
1247 */
1248 SPItem*
1249 find_group_at_point(unsigned int dkey, SPGroup *group, Geom::Point const p)
1250 {
1251 SPItem *seen = NULL;
1252 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1253 gdouble delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1255 for (SPObject *o = SP_OBJECT(group)->first_child() ; o != NULL ; o = SP_OBJECT_NEXT(o) ) {
1256 if (!SP_IS_ITEM(o)) continue;
1257 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) == SPGroup::LAYER) {
1258 SPItem *newseen = find_group_at_point(dkey, SP_GROUP(o), p);
1259 if (newseen) {
1260 seen = newseen;
1261 }
1262 }
1263 if (SP_IS_GROUP(o) && SP_GROUP(o)->effectiveLayerMode(dkey) != SPGroup::LAYER ) {
1264 SPItem *child = SP_ITEM(o);
1265 NRArenaItem *arenaitem = child->get_arenaitem(dkey);
1267 // seen remembers the last (topmost) of groups pickable at this point
1268 if (arenaitem && nr_arena_item_invoke_pick(arenaitem, p, delta, 1) != NULL) {
1269 seen = child;
1270 }
1271 }
1272 }
1273 return seen;
1274 }
1276 /*
1277 * Return list of items, contained in box
1278 *
1279 * Assumes box is normalized (and g_asserts it!)
1280 *
1281 */
1283 GSList *SPDocument::items_in_box(unsigned int dkey, Geom::Rect const &box)
1284 {
1285 //g_return_val_if_fail(this != NULL, NULL);
1286 g_return_val_if_fail(this->priv != NULL, NULL);
1288 return find_items_in_area(NULL, SP_GROUP(this->root), dkey, box, is_within);
1289 }
1291 /*
1292 * Return list of items, that the parts of the item contained in box
1293 *
1294 * Assumes box is normalized (and g_asserts it!)
1295 *
1296 */
1298 GSList *SPDocument::partial_items_in_box(unsigned int dkey, Geom::Rect const &box)
1299 {
1300 //g_return_val_if_fail(this != NULL, NULL);
1301 g_return_val_if_fail(this->priv != NULL, NULL);
1303 return find_items_in_area(NULL, SP_GROUP(this->root), dkey, box, overlaps);
1304 }
1306 GSList *
1307 SPDocument::items_at_points(unsigned const key, std::vector<Geom::Point> points)
1308 {
1309 GSList *items = NULL;
1310 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
1312 // When picking along the path, we don't want small objects close together
1313 // (such as hatching strokes) to obscure each other by their deltas,
1314 // so we temporarily set delta to a small value
1315 gdouble saved_delta = prefs->getDouble("/options/cursortolerance/value", 1.0);
1316 prefs->setDouble("/options/cursortolerance/value", 0.25);
1318 for(unsigned int i = 0; i < points.size(); i++) {
1319 SPItem *item = item_at_point(key, points[i],
1320 false, NULL);
1321 if (item && !g_slist_find(items, item))
1322 items = g_slist_prepend (items, item);
1323 }
1325 // and now we restore it back
1326 prefs->setDouble("/options/cursortolerance/value", saved_delta);
1328 return items;
1329 }
1331 SPItem *
1332 SPDocument::item_at_point( unsigned const key, Geom::Point const p,
1333 gboolean const into_groups, SPItem *upto)
1334 {
1335 //g_return_val_if_fail(this != NULL, NULL);
1336 g_return_val_if_fail(this->priv != NULL, NULL);
1338 return find_item_at_point(key, SP_GROUP(this->root), p, into_groups, false, upto);
1339 }
1341 SPItem*
1342 SPDocument::group_at_point(unsigned int key, Geom::Point const p)
1343 {
1344 //g_return_val_if_fail(this != NULL, NULL);
1345 g_return_val_if_fail(this->priv != NULL, NULL);
1347 return find_group_at_point(key, SP_GROUP(this->root), p);
1348 }
1351 /* Resource management */
1353 gboolean
1354 SPDocument::add_resource(gchar const *key, SPObject *object)
1355 {
1356 GSList *rlist;
1357 GQuark q = g_quark_from_string(key);
1359 //g_return_val_if_fail(this != NULL, FALSE);
1360 g_return_val_if_fail(key != NULL, FALSE);
1361 g_return_val_if_fail(*key != '\0', FALSE);
1362 g_return_val_if_fail(object != NULL, FALSE);
1363 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1365 if (SP_OBJECT_IS_CLONED(object))
1366 return FALSE;
1368 rlist = (GSList*)g_hash_table_lookup(this->priv->resources, key);
1369 g_return_val_if_fail(!g_slist_find(rlist, object), FALSE);
1370 rlist = g_slist_prepend(rlist, object);
1371 g_hash_table_insert(this->priv->resources, (gpointer) key, rlist);
1373 this->priv->resources_changed_signals[q].emit();
1375 return TRUE;
1376 }
1378 gboolean
1379 SPDocument::remove_resource(gchar const *key, SPObject *object)
1380 {
1381 GSList *rlist;
1382 GQuark q = g_quark_from_string(key);
1384 //g_return_val_if_fail(this != NULL, FALSE);
1385 g_return_val_if_fail(key != NULL, FALSE);
1386 g_return_val_if_fail(*key != '\0', FALSE);
1387 g_return_val_if_fail(object != NULL, FALSE);
1388 g_return_val_if_fail(SP_IS_OBJECT(object), FALSE);
1390 if (SP_OBJECT_IS_CLONED(object))
1391 return FALSE;
1393 rlist = (GSList*)g_hash_table_lookup(this->priv->resources, key);
1394 g_return_val_if_fail(rlist != NULL, FALSE);
1395 g_return_val_if_fail(g_slist_find(rlist, object), FALSE);
1396 rlist = g_slist_remove(rlist, object);
1397 g_hash_table_insert(this->priv->resources, (gpointer) key, rlist);
1399 this->priv->resources_changed_signals[q].emit();
1401 return TRUE;
1402 }
1404 GSList const *
1405 SPDocument::get_resource_list(gchar const *key)
1406 {
1407 //g_return_val_if_fail(this != NULL, NULL);
1408 g_return_val_if_fail(key != NULL, NULL);
1409 g_return_val_if_fail(*key != '\0', NULL);
1411 return (GSList*)g_hash_table_lookup(this->priv->resources, key);
1412 }
1414 sigc::connection SPDocument::resources_changed_connect(gchar const *key,
1415 SPDocument::ResourcesChangedSignal::slot_type slot)
1416 {
1417 GQuark q = g_quark_from_string(key);
1418 return this->priv->resources_changed_signals[q].connect(slot);
1419 }
1421 /* Helpers */
1423 gboolean
1424 sp_document_resource_list_free(gpointer /*key*/, gpointer value, gpointer /*data*/)
1425 {
1426 g_slist_free((GSList *) value);
1427 return TRUE;
1428 }
1430 unsigned int
1431 count_objects_recursive(SPObject *obj, unsigned int count)
1432 {
1433 count++; // obj itself
1435 for (SPObject *i = obj->first_child(); i != NULL; i = SP_OBJECT_NEXT(i)) {
1436 count = count_objects_recursive(i, count);
1437 }
1439 return count;
1440 }
1442 unsigned int
1443 objects_in_document(SPDocument *document)
1444 {
1445 return count_objects_recursive(SP_DOCUMENT_ROOT(document), 0);
1446 }
1448 void
1449 vacuum_document_recursive(SPObject *obj)
1450 {
1451 if (SP_IS_DEFS(obj)) {
1452 for (SPObject *def = obj->firstChild(); def; def = SP_OBJECT_NEXT(def)) {
1453 /* fixme: some inkscape-internal nodes in the future might not be collectable */
1454 def->requestOrphanCollection();
1455 }
1456 } else {
1457 for (SPObject *i = obj->first_child(); i != NULL; i = SP_OBJECT_NEXT(i)) {
1458 vacuum_document_recursive(i);
1459 }
1460 }
1461 }
1463 unsigned int
1464 SPDocument::vacuum_document()
1465 {
1466 unsigned int start = objects_in_document(this);
1467 unsigned int end;
1468 unsigned int newend = start;
1470 unsigned int iterations = 0;
1472 do {
1473 end = newend;
1475 vacuum_document_recursive(SP_DOCUMENT_ROOT(this));
1476 this->collectOrphans();
1477 iterations++;
1479 newend = objects_in_document(this);
1481 } while (iterations < 100 && newend < end);
1483 return start - newend;
1484 }
1486 bool SPDocument::isSeeking() const {
1487 return priv->seeking;
1488 }
1491 /*
1492 Local Variables:
1493 mode:c++
1494 c-file-style:"stroustrup"
1495 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1496 indent-tabs-mode:nil
1497 fill-column:99
1498 End:
1499 */
1500 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :