Code

A simple layout document as to what, why and how is cppification.
[inkscape.git] / src / sp-text.cpp
1 /*
2  * SVG <text> and <tspan> implementation
3  *
4  * Author:
5  *   Lauris Kaplinski <lauris@kaplinski.com>
6  *   bulia byak <buliabyak@users.sf.net>
7  *
8  * Copyright (C) 1999-2002 Lauris Kaplinski
9  * Copyright (C) 2000-2001 Ximian, Inc.
10  *
11  * Released under GNU GPL, read the file 'COPYING' for more information
12  */
14 /*
15  * fixme:
16  *
17  * These subcomponents should not be items, or alternately
18  * we have to invent set of flags to mark, whether standard
19  * attributes are applicable to given item (I even like this
20  * idea somewhat - Lauris)
21  *
22  */
24 #ifdef HAVE_CONFIG_H
25 # include "config.h"
26 #endif
28 #include <2geom/matrix.h>
29 #include <libnr/nr-matrix-fns.h>
30 #include <libnrtype/FontFactory.h>
31 #include <libnrtype/font-instance.h>
32 #include <libnrtype/font-style-to-pos.h>
34 #include <glibmm/i18n.h>
35 #include "svg/svg.h"
36 #include "svg/stringstream.h"
37 #include "display/nr-arena-glyphs.h"
38 #include "attributes.h"
39 #include "document.h"
40 #include "desktop-handles.h"
41 #include "sp-namedview.h"
42 #include "style.h"
43 #include "inkscape.h"
44 #include "sp-metrics.h"
45 #include "xml/quote.h"
46 #include "xml/repr.h"
47 #include "mod360.h"
48 #include "sp-title.h"
49 #include "sp-desc.h"
51 #include "sp-textpath.h"
52 #include "sp-tref.h"
53 #include "sp-tspan.h"
55 #include "text-editing.h"
57 /*#####################################################
58 #  SPTEXT
59 #####################################################*/
61 static void sp_text_class_init (SPTextClass *classname);
62 static void sp_text_init (SPText *text);
63 static void sp_text_release (SPObject *object);
65 static void sp_text_build (SPObject *object, SPDocument *document, Inkscape::XML::Node *repr);
66 static void sp_text_set (SPObject *object, unsigned key, gchar const *value);
67 static void sp_text_child_added (SPObject *object, Inkscape::XML::Node *rch, Inkscape::XML::Node *ref);
68 static void sp_text_remove_child (SPObject *object, Inkscape::XML::Node *rch);
69 static void sp_text_update (SPObject *object, SPCtx *ctx, guint flags);
70 static void sp_text_modified (SPObject *object, guint flags);
71 static Inkscape::XML::Node *sp_text_write (SPObject *object, Inkscape::XML::Document *doc, Inkscape::XML::Node *repr, guint flags);
73 static void sp_text_bbox(SPItem const *item, NRRect *bbox, Geom::Matrix const &transform, unsigned const flags);
74 static NRArenaItem *sp_text_show (SPItem *item, NRArena *arena, unsigned key, unsigned flags);
75 static void sp_text_hide (SPItem *item, unsigned key);
76 static char *sp_text_description (SPItem *item);
77 static void sp_text_snappoints(SPItem const *item, std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const *snapprefs);
78 static Geom::Matrix sp_text_set_transform(SPItem *item, Geom::Matrix const &xform);
79 static void sp_text_print (SPItem *item, SPPrintContext *gpc);
81 static SPItemClass *text_parent_class;
83 GType
84 sp_text_get_type ()
85 {
86     static GType type = 0;
87     if (!type) {
88         GTypeInfo info = {
89             sizeof (SPTextClass),
90             NULL,    /* base_init */
91             NULL,    /* base_finalize */
92             (GClassInitFunc) sp_text_class_init,
93             NULL,    /* class_finalize */
94             NULL,    /* class_data */
95             sizeof (SPText),
96             16,    /* n_preallocs */
97             (GInstanceInitFunc) sp_text_init,
98             NULL,    /* value_table */
99         };
100         type = g_type_register_static (SP_TYPE_ITEM, "SPText", &info, (GTypeFlags)0);
101     }
102     return type;
105 static void
106 sp_text_class_init (SPTextClass *classname)
108     SPObjectClass *sp_object_class = (SPObjectClass *) classname;
109     SPItemClass *item_class = (SPItemClass *) classname;
111     text_parent_class = (SPItemClass*)g_type_class_ref (SP_TYPE_ITEM);
113     sp_object_class->release = sp_text_release;
114     sp_object_class->build = sp_text_build;
115     sp_object_class->set = sp_text_set;
116     sp_object_class->child_added = sp_text_child_added;
117     sp_object_class->remove_child = sp_text_remove_child;
118     sp_object_class->update = sp_text_update;
119     sp_object_class->modified = sp_text_modified;
120     sp_object_class->write = sp_text_write;
122     item_class->bbox = sp_text_bbox;
123     item_class->show = sp_text_show;
124     item_class->hide = sp_text_hide;
125     item_class->description = sp_text_description;
126     item_class->snappoints = sp_text_snappoints;
127     item_class->set_transform = sp_text_set_transform;
128     item_class->print = sp_text_print;
131 static void
132 sp_text_init (SPText *text)
134     new (&text->layout) Inkscape::Text::Layout;
135     new (&text->attributes) TextTagAttributes;
138 static void
139 sp_text_release (SPObject *object)
141     SPText *text = SP_TEXT(object);
142     text->attributes.~TextTagAttributes();
143     text->layout.~Layout();
145     if (((SPObjectClass *) text_parent_class)->release)
146         ((SPObjectClass *) text_parent_class)->release(object);
149 static void
150 sp_text_build (SPObject *object, SPDocument *doc, Inkscape::XML::Node *repr)
152     object->readAttr( "x");
153     object->readAttr( "y");
154     object->readAttr( "dx");
155     object->readAttr( "dy");
156     object->readAttr( "rotate");
158     if (((SPObjectClass *) text_parent_class)->build)
159         ((SPObjectClass *) text_parent_class)->build(object, doc, repr);
161     object->readAttr( "sodipodi:linespacing");    // has to happen after the styles are read
164 static void
165 sp_text_set(SPObject *object, unsigned key, gchar const *value)
167     SPText *text = SP_TEXT (object);
169     if (text->attributes.readSingleAttribute(key, value)) {
170         object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG);
171     } else {
172         switch (key) {
173             case SP_ATTR_SODIPODI_LINESPACING:
174                 // convert deprecated tag to css
175                 if (value) {
176                     text->style->line_height.set = TRUE;
177                     text->style->line_height.inherit = FALSE;
178                     text->style->line_height.normal = FALSE;
179                     text->style->line_height.unit = SP_CSS_UNIT_PERCENT;
180                     text->style->line_height.value = text->style->line_height.computed = sp_svg_read_percentage (value, 1.0);
181                 }
182                 object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_TEXT_LAYOUT_MODIFIED_FLAG);
183                 break;
184             default:
185                 if (((SPObjectClass *) text_parent_class)->set)
186                     ((SPObjectClass *) text_parent_class)->set (object, key, value);
187                 break;
188         }
189     }
192 static void
193 sp_text_child_added (SPObject *object, Inkscape::XML::Node *rch, Inkscape::XML::Node *ref)
195     SPText *text = SP_TEXT (object);
197     if (((SPObjectClass *) text_parent_class)->child_added)
198         ((SPObjectClass *) text_parent_class)->child_added (object, rch, ref);
200     text->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_TEXT_CONTENT_MODIFIED_FLAG | SP_TEXT_LAYOUT_MODIFIED_FLAG);
203 static void
204 sp_text_remove_child (SPObject *object, Inkscape::XML::Node *rch)
206     SPText *text = SP_TEXT (object);
208     if (((SPObjectClass *) text_parent_class)->remove_child)
209         ((SPObjectClass *) text_parent_class)->remove_child (object, rch);
211     text->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_TEXT_CONTENT_MODIFIED_FLAG | SP_TEXT_LAYOUT_MODIFIED_FLAG);
214 static void
215 sp_text_update (SPObject *object, SPCtx *ctx, guint flags)
217     SPText *text = SP_TEXT (object);
219     if (((SPObjectClass *) text_parent_class)->update)
220         ((SPObjectClass *) text_parent_class)->update (object, ctx, flags);
222     guint cflags = (flags & SP_OBJECT_MODIFIED_CASCADE);
223     if (flags & SP_OBJECT_MODIFIED_FLAG) cflags |= SP_OBJECT_PARENT_MODIFIED_FLAG;
226     /* Create temporary list of children */
227     GSList *l = NULL;
228     for (SPObject *child = object->first_child() ; child != NULL ; child = SP_OBJECT_NEXT(child) ) {
229         sp_object_ref (SP_OBJECT (child), object);
230         l = g_slist_prepend (l, child);
231     }
232     l = g_slist_reverse (l);
233     while (l) {
234         SPObject *child = SP_OBJECT (l->data);
235         l = g_slist_remove (l, child);
236         if (cflags || (child->uflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) {
237             /* fixme: Do we need transform? */
238             child->updateDisplay(ctx, cflags);
239         }
240         sp_object_unref (SP_OBJECT (child), object);
241     }
242     if (flags & ( SP_OBJECT_STYLE_MODIFIED_FLAG |
243                   SP_OBJECT_CHILD_MODIFIED_FLAG |
244                   SP_TEXT_LAYOUT_MODIFIED_FLAG   ) )
245     {
246         /* fixme: It is not nice to have it here, but otherwise children content changes does not work */
247         /* fixme: Even now it may not work, as we are delayed */
248         /* fixme: So check modification flag everywhere immediate state is used */
249         text->rebuildLayout();
251         NRRect paintbox;
252         text->invoke_bbox( &paintbox, Geom::identity(), TRUE);
253         for (SPItemView* v = text->display; v != NULL; v = v->next) {
254             text->_clearFlow(NR_ARENA_GROUP(v->arenaitem));
255             nr_arena_group_set_style(NR_ARENA_GROUP(v->arenaitem), SP_OBJECT_STYLE(object));
256             // pass the bbox of the text object as paintbox (used for paintserver fills)
257             text->layout.show(NR_ARENA_GROUP(v->arenaitem), &paintbox);
258         }
259     }
262 static void
263 sp_text_modified (SPObject *object, guint flags)
265     if (((SPObjectClass *) text_parent_class)->modified)
266         ((SPObjectClass *) text_parent_class)->modified (object, flags);
268     guint cflags = (flags & SP_OBJECT_MODIFIED_CASCADE);
269     if (flags & SP_OBJECT_MODIFIED_FLAG) cflags |= SP_OBJECT_PARENT_MODIFIED_FLAG;
271     // FIXME: all that we need to do here is nr_arena_glyphs_[group_]set_style, to set the changed
272     // style, but there's no easy way to access the arena glyphs or glyph groups corresponding to a
273     // text object. Therefore we do here the same as in _update, that is, destroy all arena items
274     // and create new ones. This is probably quite wasteful.
275     if (flags & ( SP_OBJECT_STYLE_MODIFIED_FLAG )) {
276         SPText *text = SP_TEXT (object);
277         NRRect paintbox;
278         text->invoke_bbox( &paintbox, Geom::identity(), TRUE);
279         for (SPItemView* v = text->display; v != NULL; v = v->next) {
280             text->_clearFlow(NR_ARENA_GROUP(v->arenaitem));
281             nr_arena_group_set_style(NR_ARENA_GROUP(v->arenaitem), SP_OBJECT_STYLE(object));
282             text->layout.show(NR_ARENA_GROUP(v->arenaitem), &paintbox);
283         }
284     }
286     /* Create temporary list of children */
287     GSList *l = NULL;
288     SPObject *child;
289     for (child = object->first_child() ; child != NULL ; child = SP_OBJECT_NEXT(child) ) {
290         sp_object_ref (SP_OBJECT (child), object);
291         l = g_slist_prepend (l, child);
292     }
293     l = g_slist_reverse (l);
294     while (l) {
295         child = SP_OBJECT (l->data);
296         l = g_slist_remove (l, child);
297         if (cflags || (child->mflags & (SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_CHILD_MODIFIED_FLAG))) {
298             child->emitModified(cflags);
299         }
300         sp_object_unref (SP_OBJECT (child), object);
301     }
304 static Inkscape::XML::Node *
305 sp_text_write (SPObject *object, Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags)
307     SPText *text = SP_TEXT (object);
309     if (flags & SP_OBJECT_WRITE_BUILD) {
310         if (!repr)
311             repr = xml_doc->createElement("svg:text");
312         GSList *l = NULL;
313         for (SPObject *child = object->first_child() ; child != NULL ; child = SP_OBJECT_NEXT(child) ) {
314             if (SP_IS_TITLE(child) || SP_IS_DESC(child)) continue;
315             Inkscape::XML::Node *crepr = NULL;
316             if (SP_IS_STRING(child)) {
317                 crepr = xml_doc->createTextNode(SP_STRING(child)->string.c_str());
318             } else {
319                 crepr = child->updateRepr(xml_doc, NULL, flags);
320             }
321             if (crepr) l = g_slist_prepend (l, crepr);
322         }
323         while (l) {
324             repr->addChild((Inkscape::XML::Node *) l->data, NULL);
325             Inkscape::GC::release((Inkscape::XML::Node *) l->data);
326             l = g_slist_remove (l, l->data);
327         }
328     } else {
329         for (SPObject *child = object->first_child() ; child != NULL ; child = SP_OBJECT_NEXT(child) ) {
330             if (SP_IS_TITLE(child) || SP_IS_DESC(child)) continue;
331             if (SP_IS_STRING(child)) {
332                 SP_OBJECT_REPR(child)->setContent(SP_STRING(child)->string.c_str());
333             } else {
334                 child->updateRepr(flags);
335             }
336         }
337     }
339     text->attributes.writeTo(repr);
341     // deprecated attribute, but keep it around for backwards compatibility
342     if (text->style->line_height.set && !text->style->line_height.inherit && !text->style->line_height.normal && text->style->line_height.unit == SP_CSS_UNIT_PERCENT) {
343         Inkscape::SVGOStringStream os;
344         os << (text->style->line_height.value * 100.0) << "%";
345         SP_OBJECT_REPR(text)->setAttribute("sodipodi:linespacing", os.str().c_str());
346     }
347     else
348         SP_OBJECT_REPR(text)->setAttribute("sodipodi:linespacing", NULL);
350     if (((SPObjectClass *) (text_parent_class))->write)
351         ((SPObjectClass *) (text_parent_class))->write (object, xml_doc, repr, flags);
353     return repr;
356 static void
357 sp_text_bbox(SPItem const *item, NRRect *bbox, Geom::Matrix const &transform, unsigned const /*flags*/)
359     SP_TEXT(item)->layout.getBoundingBox(bbox, transform);
361     // Add stroke width
362     SPStyle* style=SP_OBJECT_STYLE (item);
363     if (!style->stroke.isNone()) {
364         double const scale = transform.descrim();
365         if ( fabs(style->stroke_width.computed * scale) > 0.01 ) { // sinon c'est 0=oon veut pas de bord
366             double const width = MAX(0.125, style->stroke_width.computed * scale);
367             if ( fabs(bbox->x1 - bbox->x0) > -0.00001 && fabs(bbox->y1 - bbox->y0) > -0.00001 ) {
368                 bbox->x0-=0.5*width;
369                 bbox->x1+=0.5*width;
370                 bbox->y0-=0.5*width;
371                 bbox->y1+=0.5*width;
372             }
373         }
374     }
378 static NRArenaItem *
379 sp_text_show(SPItem *item, NRArena *arena, unsigned /* key*/, unsigned /*flags*/)
381     SPText *group = (SPText *) item;
383     NRArenaGroup *flowed = NRArenaGroup::create(arena);
384     nr_arena_group_set_transparent (flowed, FALSE);
386     nr_arena_group_set_style(flowed, group->style);
388     // pass the bbox of the text object as paintbox (used for paintserver fills)
389     NRRect paintbox;
390     item->invoke_bbox( &paintbox, Geom::identity(), TRUE);
391     group->layout.show(flowed, &paintbox);
393     return flowed;
396 static void
397 sp_text_hide(SPItem *item, unsigned key)
399     if (((SPItemClass *) text_parent_class)->hide)
400         ((SPItemClass *) text_parent_class)->hide (item, key);
403 static char *
404 sp_text_description(SPItem *item)
406     SPText *text = (SPText *) item;
407     SPStyle *style = SP_OBJECT_STYLE(text);
409     font_instance *tf = font_factory::Default()->FaceFromStyle(style);
411     char name_buf[256];
412     char *n;
413     if (tf) {
414         tf->Name(name_buf, sizeof(name_buf));
415         n = xml_quote_strdup(name_buf);
416         tf->Unref();
417     } else {
418         /* TRANSLATORS: For description of font with no name. */
419         n = g_strdup(_("&lt;no name found&gt;"));
420     }
422     GString *xs = SP_PX_TO_METRIC_STRING(style->font_size.computed, sp_desktop_namedview(SP_ACTIVE_DESKTOP)->getDefaultMetric());
424     char const *trunc = "";
425     Inkscape::Text::Layout const *layout = te_get_layout((SPItem *) item);
426     if (layout && layout->inputTruncated()) {
427         trunc = _(" [truncated]");
428     }
430     char *ret = ( SP_IS_TEXT_TEXTPATH(item)
431                   ? g_strdup_printf(_("<b>Text on path</b>%s (%s, %s)"), trunc, n, xs->str)
432                   : g_strdup_printf(_("<b>Text</b>%s (%s, %s)"), trunc, n, xs->str) );
433     g_free(n);
434     return ret;
437 static void sp_text_snappoints(SPItem const *item, std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const */*snapprefs*/)
439     // Choose a point on the baseline for snapping from or to, with the horizontal position
440     // of this point depending on the text alignment (left vs. right)
441     Inkscape::Text::Layout const *layout = te_get_layout((SPItem *) item);
442     if (layout != NULL && layout->outputExists()) {
443         boost::optional<Geom::Point> pt = layout->baselineAnchorPoint();
444         if (pt) {
445             p.push_back(Inkscape::SnapCandidatePoint((*pt) * item->i2d_affine(), Inkscape::SNAPSOURCE_TEXT_BASELINE, Inkscape::SNAPTARGET_TEXT_BASELINE));
446         }
447     }
450 static Geom::Matrix
451 sp_text_set_transform (SPItem *item, Geom::Matrix const &xform)
453     SPText *text = SP_TEXT(item);
455     // we cannot optimize textpath because changing its fontsize will break its match to the path
456     if (SP_IS_TEXT_TEXTPATH (text))
457         return xform;
459     /* This function takes care of scaling & translation only, we return whatever parts we can't
460        handle. */
462 // TODO: pjrm tried to use fontsize_expansion(xform) here and it works for text in that font size
463 // is scaled more intuitively when scaling non-uniformly; however this necessitated using
464 // fontsize_expansion instead of expansion in other places too, where it was not appropriate
465 // (e.g. it broke stroke width on copy/pasting of style from horizontally stretched to vertically
466 // stretched shape). Using fontsize_expansion only here broke setting the style via font
467 // dialog. This needs to be investigated further.
468     double const ex = xform.descrim();
469     if (ex == 0) {
470         return xform;
471     }
473     Geom::Matrix ret(Geom::Matrix(xform).without_translation());
474     ret[0] /= ex;
475     ret[1] /= ex;
476     ret[2] /= ex;
477     ret[3] /= ex;
479     // Adjust x/y, dx/dy
480     text->_adjustCoordsRecursive (item, xform * ret.inverse(), ex);
482     // Adjust font size
483     text->_adjustFontsizeRecursive (item, ex);
485     // Adjust stroke width
486     item->adjust_stroke_width_recursive (ex);
488     // Adjust pattern fill
489     item->adjust_pattern(xform * ret.inverse());
491     // Adjust gradient fill
492     item->adjust_gradient(xform * ret.inverse());
494     item->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_TEXT_LAYOUT_MODIFIED_FLAG);
496     return ret;
499 static void
500 sp_text_print (SPItem *item, SPPrintContext *ctx)
502     NRRect     pbox, dbox, bbox;
503     SPText *group = SP_TEXT (item);
505     item->invoke_bbox( &pbox, Geom::identity(), TRUE);
506     item->getBboxDesktop (&bbox);
507     dbox.x0 = 0.0;
508     dbox.y0 = 0.0;
509     dbox.x1 = SP_OBJECT_DOCUMENT (item)->getWidth ();
510     dbox.y1 = SP_OBJECT_DOCUMENT (item)->getHeight ();
511     Geom::Matrix const ctm (item->i2d_affine());
513     group->layout.print(ctx,&pbox,&dbox,&bbox,ctm);
516 /*
517  * Member functions
518  */
520 unsigned SPText::_buildLayoutInput(SPObject *root, Inkscape::Text::Layout::OptionalTextTagAttrs const &parent_optional_attrs, unsigned parent_attrs_offset, bool in_textpath)
522     unsigned length = 0;
523     int child_attrs_offset = 0;
524     Inkscape::Text::Layout::OptionalTextTagAttrs optional_attrs;
526     if (SP_IS_TEXT(root)) {
527         SP_TEXT(root)->attributes.mergeInto(&optional_attrs, parent_optional_attrs, parent_attrs_offset, true, true);
528     }
529     else if (SP_IS_TSPAN(root)) {
530         SPTSpan *tspan = SP_TSPAN(root);
531         // x, y attributes are stripped from some tspans as we do our own line layout
532         // This should be checked carefully, as it can undo line layout in imported SVG files.
533         bool use_xy = !in_textpath && (tspan->role == SP_TSPAN_ROLE_UNSPECIFIED || !tspan->attributes.singleXYCoordinates());
534         tspan->attributes.mergeInto(&optional_attrs, parent_optional_attrs, parent_attrs_offset, use_xy, true);
535     }
536     else if (SP_IS_TREF(root)) {
537         SP_TREF(root)->attributes.mergeInto(&optional_attrs, parent_optional_attrs, parent_attrs_offset, true, true);
538     }
539     else if (SP_IS_TEXTPATH(root)) {
540         in_textpath = true;
541         SP_TEXTPATH(root)->attributes.mergeInto(&optional_attrs, parent_optional_attrs, parent_attrs_offset, false, true);
542         optional_attrs.x.clear();
543         optional_attrs.y.clear();
544     }
545     else {
546         optional_attrs = parent_optional_attrs;
547         child_attrs_offset = parent_attrs_offset;
548     }
550     if (SP_IS_TSPAN(root))
551         if (SP_TSPAN(root)->role != SP_TSPAN_ROLE_UNSPECIFIED) {
552             // we need to allow the first line not to have role=line, but still set the source_cookie to the right value
553             SPObject *prev_object = SP_OBJECT_PREV(root);
554             if (prev_object && SP_IS_TSPAN(prev_object)) {
555                 if (!layout.inputExists())
556                     layout.appendText("", prev_object->style, prev_object, &optional_attrs);
557                 layout.appendControlCode(Inkscape::Text::Layout::PARAGRAPH_BREAK, prev_object);
558             }
559             if (!root->hasChildren())
560                 layout.appendText("", root->style, root, &optional_attrs);
561             length++;     // interpreting line breaks as a character for the purposes of x/y/etc attributes
562                           // is a liberal interpretation of the svg spec, but a strict reading would mean
563                           // that if the first line is empty the second line would take its place at the
564                           // start position. Very confusing.
565             child_attrs_offset--;
566         }
568     for (SPObject *child = root->first_child() ; child != NULL ; child = SP_OBJECT_NEXT(child) ) {
569         if (SP_IS_STRING(child)) {
570             Glib::ustring const &string = SP_STRING(child)->string;
571             layout.appendText(string, root->style, child, &optional_attrs, child_attrs_offset + length);
572             length += string.length();
573         } /*XML Tree being directly used here while it shouldn't be.*/ else if (!sp_repr_is_meta_element(child->getRepr())) {
574             length += _buildLayoutInput(child, optional_attrs, child_attrs_offset + length, in_textpath);
575         }
576     }
578     return length;
581 void SPText::rebuildLayout()
583     layout.clear();
584     Inkscape::Text::Layout::OptionalTextTagAttrs optional_attrs;
585     _buildLayoutInput(this, optional_attrs, 0, false);
586     layout.calculateFlow();
587     for (SPObject *child = firstChild() ; child != NULL ; child = SP_OBJECT_NEXT(child) ) {
588         if (SP_IS_TEXTPATH(child)) {
589             SPTextPath const *textpath = SP_TEXTPATH(child);
590             if (textpath->originalPath != NULL) {
591                 //g_print(layout.dumpAsText().c_str());
592                 layout.fitToPathAlign(textpath->startOffset, *textpath->originalPath);
593             }
594         }
595     }
596     //g_print(layout.dumpAsText().c_str());
598     // set the x,y attributes on role:line spans
599     for (SPObject *child = firstChild() ; child != NULL ; child = SP_OBJECT_NEXT(child) ) {
600         if (!SP_IS_TSPAN(child)) continue;
601         SPTSpan *tspan = SP_TSPAN(child);
602         if (tspan->role == SP_TSPAN_ROLE_UNSPECIFIED) continue;
603         if (!tspan->attributes.singleXYCoordinates()) continue;
604         Inkscape::Text::Layout::iterator iter = layout.sourceToIterator(tspan);
605         Geom::Point anchor_point = layout.chunkAnchorPoint(iter);
606         tspan->attributes.setFirstXY(anchor_point);
607     }
611 void SPText::_adjustFontsizeRecursive(SPItem *item, double ex, bool is_root)
613     SPStyle *style = SP_OBJECT_STYLE (item);
615     if (style && !NR_DF_TEST_CLOSE (ex, 1.0, NR_EPSILON)) {
616         if (!style->font_size.set && is_root) {
617             style->font_size.set = 1;
618         }
619         style->font_size.type = SP_FONT_SIZE_LENGTH;
620         style->font_size.computed *= ex;
621         style->letter_spacing.computed *= ex;
622         style->word_spacing.computed *= ex;
623         item->updateRepr();
624     }
626     for (SPObject *o = item->children; o != NULL; o = o->next) {
627         if (SP_IS_ITEM(o))
628             _adjustFontsizeRecursive(SP_ITEM(o), ex, false);
629     }
632 void SPText::_adjustCoordsRecursive(SPItem *item, Geom::Matrix const &m, double ex, bool is_root)
634     if (SP_IS_TSPAN(item))
635         SP_TSPAN(item)->attributes.transform(m, ex, ex, is_root);
636               // it doesn't matter if we change the x,y for role=line spans because we'll just overwrite them anyway
637     else if (SP_IS_TEXT(item))
638         SP_TEXT(item)->attributes.transform(m, ex, ex, is_root);
639     else if (SP_IS_TEXTPATH(item))
640         SP_TEXTPATH(item)->attributes.transform(m, ex, ex, is_root);
641     else if (SP_IS_TREF(item)) {
642         SP_TREF(item)->attributes.transform(m, ex, ex, is_root);
643     }
645     for (SPObject *o = item->children; o != NULL; o = o->next) {
646         if (SP_IS_ITEM(o))
647             _adjustCoordsRecursive(SP_ITEM(o), m, ex, false);
648     }
652 void SPText::_clearFlow(NRArenaGroup *in_arena)
654     nr_arena_item_request_render (in_arena);
655     for (NRArenaItem *child = in_arena->children; child != NULL; ) {
656         NRArenaItem *nchild = child->next;
658         nr_arena_glyphs_group_clear(NR_ARENA_GLYPHS_GROUP(child));
659         nr_arena_item_remove_child (in_arena, child);
661         child=nchild;
662     }
666 /*
667  * TextTagAttributes implementation
668  */
670 void TextTagAttributes::readFrom(Inkscape::XML::Node const *node)
672     readSingleAttribute(SP_ATTR_X, node->attribute("x"));
673     readSingleAttribute(SP_ATTR_Y, node->attribute("y"));
674     readSingleAttribute(SP_ATTR_DX, node->attribute("dx"));
675     readSingleAttribute(SP_ATTR_DY, node->attribute("dy"));
676     readSingleAttribute(SP_ATTR_ROTATE, node->attribute("rotate"));
679 bool TextTagAttributes::readSingleAttribute(unsigned key, gchar const *value)
681     std::vector<SVGLength> *attr_vector;
682     switch (key) {
683         case SP_ATTR_X:      attr_vector = &attributes.x; break;
684         case SP_ATTR_Y:      attr_vector = &attributes.y; break;
685         case SP_ATTR_DX:     attr_vector = &attributes.dx; break;
686         case SP_ATTR_DY:     attr_vector = &attributes.dy; break;
687         case SP_ATTR_ROTATE: attr_vector = &attributes.rotate; break;
688         default: return false;
689     }
691     // FIXME: sp_svg_length_list_read() amalgamates repeated separators. This prevents unset values.
692     *attr_vector = sp_svg_length_list_read(value);
693     return true;
696 void TextTagAttributes::writeTo(Inkscape::XML::Node *node) const
698     writeSingleAttribute(node, "x", attributes.x);
699     writeSingleAttribute(node, "y", attributes.y);
700     writeSingleAttribute(node, "dx", attributes.dx);
701     writeSingleAttribute(node, "dy", attributes.dy);
702     writeSingleAttribute(node, "rotate", attributes.rotate);
705 void TextTagAttributes::writeSingleAttribute(Inkscape::XML::Node *node, gchar const *key, std::vector<SVGLength> const &attr_vector)
707     if (attr_vector.empty())
708         node->setAttribute(key, NULL);
709     else {
710         Glib::ustring string;
711         gchar single_value_string[32];
713         // FIXME: this has no concept of unset values because sp_svg_length_list_read() can't read them back in
714         for (std::vector<SVGLength>::const_iterator it = attr_vector.begin() ; it != attr_vector.end() ; it++) {
715             g_ascii_formatd(single_value_string, sizeof (single_value_string), "%.8g", it->computed);
716             if (!string.empty()) string += ' ';
717             string += single_value_string;
718         }
719         node->setAttribute(key, string.c_str());
720     }
723 bool TextTagAttributes::singleXYCoordinates() const
725     return attributes.x.size() <= 1 && attributes.y.size() <= 1;
728 bool TextTagAttributes::anyAttributesSet() const
730     return !attributes.x.empty() || !attributes.y.empty() || !attributes.dx.empty() || !attributes.dy.empty() || !attributes.rotate.empty();
733 Geom::Point TextTagAttributes::firstXY() const
735     Geom::Point point;
736     if (attributes.x.empty()) point[Geom::X] = 0.0;
737     else point[Geom::X] = attributes.x[0].computed;
738     if (attributes.y.empty()) point[Geom::Y] = 0.0;
739     else point[Geom::Y] = attributes.y[0].computed;
740     return point;
743 void TextTagAttributes::setFirstXY(Geom::Point &point)
745     SVGLength zero_length;
746     zero_length = 0.0;
748     if (attributes.x.empty())
749         attributes.x.resize(1, zero_length);
750     if (attributes.y.empty())
751         attributes.y.resize(1, zero_length);
752     attributes.x[0].computed = point[Geom::X];
753     attributes.y[0].computed = point[Geom::Y];
756 void TextTagAttributes::mergeInto(Inkscape::Text::Layout::OptionalTextTagAttrs *output, Inkscape::Text::Layout::OptionalTextTagAttrs const &parent_attrs, unsigned parent_attrs_offset, bool copy_xy, bool copy_dxdyrotate) const
758     mergeSingleAttribute(&output->x,      parent_attrs.x,      parent_attrs_offset, copy_xy ? &attributes.x : NULL);
759     mergeSingleAttribute(&output->y,      parent_attrs.y,      parent_attrs_offset, copy_xy ? &attributes.y : NULL);
760     mergeSingleAttribute(&output->dx,     parent_attrs.dx,     parent_attrs_offset, copy_dxdyrotate ? &attributes.dx : NULL);
761     mergeSingleAttribute(&output->dy,     parent_attrs.dy,     parent_attrs_offset, copy_dxdyrotate ? &attributes.dy : NULL);
762     mergeSingleAttribute(&output->rotate, parent_attrs.rotate, parent_attrs_offset, copy_dxdyrotate ? &attributes.rotate : NULL);
765 void TextTagAttributes::mergeSingleAttribute(std::vector<SVGLength> *output_list, std::vector<SVGLength> const &parent_list, unsigned parent_offset, std::vector<SVGLength> const *overlay_list)
767     output_list->clear();
768     if (overlay_list == NULL) {
769         if (parent_list.size() > parent_offset)
770         {
771             output_list->reserve(parent_list.size() - parent_offset);
772             std::copy(parent_list.begin() + parent_offset, parent_list.end(), std::back_inserter(*output_list));
773         }
774     } else {
775         output_list->reserve(std::max((int)parent_list.size() - (int)parent_offset, (int)overlay_list->size()));
776         unsigned overlay_offset = 0;
777         while (parent_offset < parent_list.size() || overlay_offset < overlay_list->size()) {
778             SVGLength const *this_item;
779             if (overlay_offset < overlay_list->size()) {
780                 this_item = &(*overlay_list)[overlay_offset];
781                 overlay_offset++;
782                 parent_offset++;
783             } else {
784                 this_item = &parent_list[parent_offset];
785                 parent_offset++;
786             }
787             output_list->push_back(*this_item);
788         }
789     }
792 void TextTagAttributes::erase(unsigned start_index, unsigned n)
794     if (n == 0) return;
795     if (!singleXYCoordinates()) {
796         eraseSingleAttribute(&attributes.x, start_index, n);
797         eraseSingleAttribute(&attributes.y, start_index, n);
798     }
799     eraseSingleAttribute(&attributes.dx, start_index, n);
800     eraseSingleAttribute(&attributes.dy, start_index, n);
801     eraseSingleAttribute(&attributes.rotate, start_index, n);
804 void TextTagAttributes::eraseSingleAttribute(std::vector<SVGLength> *attr_vector, unsigned start_index, unsigned n)
806     if (attr_vector->size() <= start_index) return;
807     if (attr_vector->size() <= start_index + n)
808         attr_vector->erase(attr_vector->begin() + start_index, attr_vector->end());
809     else
810         attr_vector->erase(attr_vector->begin() + start_index, attr_vector->begin() + start_index + n);
813 void TextTagAttributes::insert(unsigned start_index, unsigned n)
815     if (n == 0) return;
816     if (!singleXYCoordinates()) {
817         insertSingleAttribute(&attributes.x, start_index, n, true);
818         insertSingleAttribute(&attributes.y, start_index, n, true);
819     }
820     insertSingleAttribute(&attributes.dx, start_index, n, false);
821     insertSingleAttribute(&attributes.dy, start_index, n, false);
822     insertSingleAttribute(&attributes.rotate, start_index, n, false);
825 void TextTagAttributes::insertSingleAttribute(std::vector<SVGLength> *attr_vector, unsigned start_index, unsigned n, bool is_xy)
827     if (attr_vector->size() <= start_index) return;
828     SVGLength zero_length;
829     zero_length = 0.0;
830     attr_vector->insert(attr_vector->begin() + start_index, n, zero_length);
831     if (is_xy) {
832         double begin = start_index == 0 ? (*attr_vector)[start_index + n].computed : (*attr_vector)[start_index - 1].computed;
833         double diff = ((*attr_vector)[start_index + n].computed - begin) / n;   // n tested for nonzero in insert()
834         for (unsigned i = 0 ; i < n ; i++)
835             (*attr_vector)[start_index + i] = begin + diff * i;
836     }
839 void TextTagAttributes::split(unsigned index, TextTagAttributes *second)
841     if (!singleXYCoordinates()) {
842         splitSingleAttribute(&attributes.x, index, &second->attributes.x, false);
843         splitSingleAttribute(&attributes.y, index, &second->attributes.y, false);
844     }
845     splitSingleAttribute(&attributes.dx, index, &second->attributes.dx, true);
846     splitSingleAttribute(&attributes.dy, index, &second->attributes.dy, true);
847     splitSingleAttribute(&attributes.rotate, index, &second->attributes.rotate, true);
850 void TextTagAttributes::splitSingleAttribute(std::vector<SVGLength> *first_vector, unsigned index, std::vector<SVGLength> *second_vector, bool trimZeros)
852     second_vector->clear();
853     if (first_vector->size() <= index) return;
854     second_vector->resize(first_vector->size() - index);
855     std::copy(first_vector->begin() + index, first_vector->end(), second_vector->begin());
856     first_vector->resize(index);
857     if (trimZeros)
858         while (!first_vector->empty() && (!first_vector->back()._set || first_vector->back().value == 0.0))
859             first_vector->resize(first_vector->size() - 1);
862 void TextTagAttributes::join(TextTagAttributes const &first, TextTagAttributes const &second, unsigned second_index)
864     if (second.singleXYCoordinates()) {
865         attributes.x = first.attributes.x;
866         attributes.y = first.attributes.y;
867     } else {
868         joinSingleAttribute(&attributes.x, first.attributes.x, second.attributes.x, second_index);
869         joinSingleAttribute(&attributes.y, first.attributes.y, second.attributes.y, second_index);
870     }
871     joinSingleAttribute(&attributes.dx, first.attributes.dx, second.attributes.dx, second_index);
872     joinSingleAttribute(&attributes.dy, first.attributes.dy, second.attributes.dy, second_index);
873     joinSingleAttribute(&attributes.rotate, first.attributes.rotate, second.attributes.rotate, second_index);
876 void TextTagAttributes::joinSingleAttribute(std::vector<SVGLength> *dest_vector, std::vector<SVGLength> const &first_vector, std::vector<SVGLength> const &second_vector, unsigned second_index)
878     if (second_vector.empty())
879         *dest_vector = first_vector;
880     else {
881         dest_vector->resize(second_index + second_vector.size());
882         if (first_vector.size() < second_index) {
883             std::copy(first_vector.begin(), first_vector.end(), dest_vector->begin());
884             SVGLength zero_length;
885             zero_length = 0.0;
886             std::fill(dest_vector->begin() + first_vector.size(), dest_vector->begin() + second_index, zero_length);
887         } else
888             std::copy(first_vector.begin(), first_vector.begin() + second_index, dest_vector->begin());
889         std::copy(second_vector.begin(), second_vector.end(), dest_vector->begin() + second_index);
890     }
893 void TextTagAttributes::transform(Geom::Matrix const &matrix, double scale_x, double scale_y, bool extend_zero_length)
895     SVGLength zero_length;
896     zero_length = 0.0;
898     /* edge testcases for this code:
899        1) moving text elements whose position is done entirely with transform="...", no x,y attributes
900        2) unflowing multi-line flowtext then moving it (it has x but not y)
901     */
902     unsigned points_count = std::max(attributes.x.size(), attributes.y.size());
903     if (extend_zero_length && points_count < 1)
904         points_count = 1;
905     for (unsigned i = 0 ; i < points_count ; i++) {
906         Geom::Point point;
907         if (i < attributes.x.size()) point[Geom::X] = attributes.x[i].computed;
908         else point[Geom::X] = 0.0;
909         if (i < attributes.y.size()) point[Geom::Y] = attributes.y[i].computed;
910         else point[Geom::Y] = 0.0;
911         point *= matrix;
912         if (i < attributes.x.size())
913             attributes.x[i] = point[Geom::X];
914         else if (point[Geom::X] != 0.0 && extend_zero_length) {
915             attributes.x.resize(i + 1, zero_length);
916             attributes.x[i] = point[Geom::X];
917         }
918         if (i < attributes.y.size())
919             attributes.y[i] = point[Geom::Y];
920         else if (point[Geom::Y] != 0.0 && extend_zero_length) {
921             attributes.y.resize(i + 1, zero_length);
922             attributes.y[i] = point[Geom::Y];
923         }
924     }
925     for (std::vector<SVGLength>::iterator it = attributes.dx.begin() ; it != attributes.dx.end() ; it++)
926         *it = it->computed * scale_x;
927     for (std::vector<SVGLength>::iterator it = attributes.dy.begin() ; it != attributes.dy.end() ; it++)
928         *it = it->computed * scale_y;
931 double TextTagAttributes::getDx(unsigned index)
933     if( attributes.dx.size() == 0 ) {
934         return 0.0;
935     }
936     if( index < attributes.dx.size() ) {
937         return attributes.dx[index].computed;
938     } else {
939         return 0.0; // attributes.dx.back().computed;
940     }
944 double TextTagAttributes::getDy(unsigned index)
946     if( attributes.dy.size() == 0 ) {
947         return 0.0;
948     }
949     if( index < attributes.dy.size() ) {
950         return attributes.dy[index].computed;
951     } else {
952         return 0.0; // attributes.dy.back().computed;
953     }
957 void TextTagAttributes::addToDx(unsigned index, double delta)
959     SVGLength zero_length;
960     zero_length = 0.0;
962     if (attributes.dx.size() < index + 1) attributes.dx.resize(index + 1, zero_length);
963     attributes.dx[index] = attributes.dx[index].computed + delta;
966 void TextTagAttributes::addToDy(unsigned index, double delta)
968     SVGLength zero_length;
969     zero_length = 0.0;
971     if (attributes.dy.size() < index + 1) attributes.dy.resize(index + 1, zero_length);
972     attributes.dy[index] = attributes.dy[index].computed + delta;
975 void TextTagAttributes::addToDxDy(unsigned index, Geom::Point const &adjust)
977     SVGLength zero_length;
978     zero_length = 0.0;
980     if (adjust[Geom::X] != 0.0) {
981         if (attributes.dx.size() < index + 1) attributes.dx.resize(index + 1, zero_length);
982         attributes.dx[index] = attributes.dx[index].computed + adjust[Geom::X];
983     }
984     if (adjust[Geom::Y] != 0.0) {
985         if (attributes.dy.size() < index + 1) attributes.dy.resize(index + 1, zero_length);
986         attributes.dy[index] = attributes.dy[index].computed + adjust[Geom::Y];
987     }
990 double TextTagAttributes::getRotate(unsigned index)
992     if( attributes.rotate.size() == 0 ) {
993         return 0.0;
994     }
995     if( index < attributes.rotate.size() ) {
996         return attributes.rotate[index].computed;
997     } else {
998         return attributes.rotate.back().computed;
999     }
1003 void TextTagAttributes::addToRotate(unsigned index, double delta)
1005     SVGLength zero_length;
1006     zero_length = 0.0;
1008     if (attributes.rotate.size() < index + 2) {
1009         if (attributes.rotate.empty())
1010             attributes.rotate.resize(index + 2, zero_length);
1011         else
1012             attributes.rotate.resize(index + 2, attributes.rotate.back());
1013     }
1014     attributes.rotate[index] = mod360(attributes.rotate[index].computed + delta);
1018 void TextTagAttributes::setRotate(unsigned index, double angle)
1020     SVGLength zero_length;
1021     zero_length = 0.0;
1023     if (attributes.rotate.size() < index + 2) {
1024         if (attributes.rotate.empty())
1025             attributes.rotate.resize(index + 2, zero_length);
1026         else
1027             attributes.rotate.resize(index + 2, attributes.rotate.back());
1028     }
1029     attributes.rotate[index] = mod360(angle);
1033 /*
1034   Local Variables:
1035   mode:c++
1036   c-file-style:"stroustrup"
1037   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1038   indent-tabs-mode:nil
1039   fill-column:99
1040   End:
1041 */
1042 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :