Code

(no commit message)
[inkscape.git] / src / libnrtype / Layout-TNG-Output.cpp
1 /*
2  * Inkscape::Text::Layout - text layout engine output functions
3  *
4  * Authors:
5  *   Richard Hughes <cyreve@users.sf.net>
6  *
7  * Copyright (C) 2005 Richard Hughes
8  *
9  * Released under GNU GPL, read the file 'COPYING' for more information
10  */
11 #include "Layout-TNG.h"
12 #include "display/nr-arena-glyphs.h"
13 #include "style.h"
14 #include "print.h"
15 #include "extension/print.h"
16 #include "livarot/Path.h"
17 #include "libnr/nr-scale-matrix-ops.h"
18 #include "font-instance.h"
19 #include "svg/svg-length.h"
21 namespace Inkscape {
22 namespace Text {
24 void Layout::_clearOutputObjects()
25 {
26     _paragraphs.clear();
27     _lines.clear();
28     _chunks.clear();
29     for (std::vector<Span>::iterator it_span = _spans.begin() ; it_span != _spans.end() ; it_span++)
30         if (it_span->font) it_span->font->Unref();
31     _spans.clear();
32     _characters.clear();
33     _glyphs.clear();
34     _path_fitted = NULL;
35 }
37 void Layout::LineHeight::max(LineHeight const &other)
38 {
39     if (other.ascent > ascent)  ascent  = other.ascent;
40     if (other.descent > descent) descent = other.descent;
41     if (other.leading > leading) leading = other.leading;
42 }
44 void Layout::_getGlyphTransformMatrix(int glyph_index, NRMatrix *matrix) const
45 {
46     Span const &span = _glyphs[glyph_index].span(this);
47     double sin_rotation = sin(_glyphs[glyph_index].rotation);
48     double cos_rotation = cos(_glyphs[glyph_index].rotation);
49     (*matrix)[0] = span.font_size * cos_rotation;
50     (*matrix)[1] = span.font_size * sin_rotation;
51     (*matrix)[2] = span.font_size * sin_rotation;
52     (*matrix)[3] = -span.font_size * cos_rotation;
53     if (span.block_progression == LEFT_TO_RIGHT || span.block_progression == RIGHT_TO_LEFT) {
54         (*matrix)[4] = _lines[_chunks[span.in_chunk].in_line].baseline_y + _glyphs[glyph_index].y;
55         (*matrix)[5] = _chunks[span.in_chunk].left_x + _glyphs[glyph_index].x;
56     } else {
57         (*matrix)[4] = _chunks[span.in_chunk].left_x + _glyphs[glyph_index].x;
58         (*matrix)[5] = _lines[_chunks[span.in_chunk].in_line].baseline_y + _glyphs[glyph_index].y;
59     }
60 }
62 void Layout::show(NRArenaGroup *in_arena, NRRect const *paintbox) const
63 {
64     int glyph_index = 0;
65     for (unsigned span_index = 0 ; span_index < _spans.size() ; span_index++) {
66         if (_input_stream[_spans[span_index].in_input_stream_item]->Type() != TEXT_SOURCE) continue;
67         InputStreamTextSource const *text_source = static_cast<InputStreamTextSource const *>(_input_stream[_spans[span_index].in_input_stream_item]);
68         NRArenaGlyphsGroup *nr_group = NRArenaGlyphsGroup::create(in_arena->arena);
69         nr_arena_item_add_child(in_arena, nr_group, NULL);
70         nr_arena_item_unref(nr_group);
72         nr_arena_glyphs_group_set_style(nr_group, text_source->style);
73         while (glyph_index < (int)_glyphs.size() && _characters[_glyphs[glyph_index].in_character].in_span == span_index) {
74             if (_characters[_glyphs[glyph_index].in_character].in_glyph != -1) {
75                 NRMatrix glyph_matrix;
76                 _getGlyphTransformMatrix(glyph_index, &glyph_matrix);
77                 nr_arena_glyphs_group_add_component(nr_group, _spans[span_index].font, _glyphs[glyph_index].glyph, &glyph_matrix);
78             }
79             glyph_index++;
80         }
81         nr_arena_glyphs_group_set_paintbox(NR_ARENA_GLYPHS_GROUP(nr_group), paintbox);
82     }
83     nr_arena_item_request_update(NR_ARENA_ITEM(in_arena), NR_ARENA_ITEM_STATE_ALL, FALSE);
84 }
86 void Layout::getBoundingBox(NRRect *bounding_box, NR::Matrix const &transform, int start, int length) const
87 {
88     for (unsigned glyph_index = 0 ; glyph_index < _glyphs.size() ; glyph_index++) {
89         if (_characters[_glyphs[glyph_index].in_character].in_glyph == -1) continue;
90         if (start != -1 && _glyphs[glyph_index].in_character < start) continue;
91         if (length != -1) {
92             if (start == -1)
93                 start = 0;
94             if (_glyphs[glyph_index].in_character > start + length) continue;
95         }
96         // this could be faster
97         NRMatrix glyph_matrix;
98         _getGlyphTransformMatrix(glyph_index, &glyph_matrix);
99         NR::Matrix total_transform = glyph_matrix;
100         total_transform *= transform;
101         NR::Rect glyph_rect = _glyphs[glyph_index].span(this).font->BBox(_glyphs[glyph_index].glyph);
102         NR::Point bmi = glyph_rect.min(), bma = glyph_rect.max();
103         NR::Point tlp(bmi[0],bmi[1]), trp(bma[0],bmi[1]), blp(bmi[0],bma[1]), brp(bma[0],bma[1]);
104         tlp *= total_transform;
105         trp *= total_transform;
106         blp *= total_transform;
107         brp *= total_transform;
108         glyph_rect = NR::Rect(tlp,trp);
109         glyph_rect.expandTo(blp);
110         glyph_rect.expandTo(brp);
111         if ( (glyph_rect.min())[0] < bounding_box->x0 ) bounding_box->x0=(glyph_rect.min())[0];
112         if ( (glyph_rect.max())[0] > bounding_box->x1 ) bounding_box->x1=(glyph_rect.max())[0];
113         if ( (glyph_rect.min())[1] < bounding_box->y0 ) bounding_box->y0=(glyph_rect.min())[1];
114         if ( (glyph_rect.max())[1] > bounding_box->y1 ) bounding_box->y1=(glyph_rect.max())[1];
115     }
118 void Layout::print(SPPrintContext *ctx,
119                    NRRect const *pbox, NRRect const *dbox, NRRect const *bbox,
120                    NRMatrix const &ctm) const
122     if (_input_stream.empty()) return;
124     Direction block_progression = _blockProgression();
125     bool text_to_path = ctx->module->textToPath();
126     for (unsigned glyph_index = 0 ; glyph_index < _glyphs.size() ; ) {
127         if (_characters[_glyphs[glyph_index].in_character].in_glyph == -1) {
128             // invisible glyphs
129             unsigned same_character = _glyphs[glyph_index].in_character;
130             while (_glyphs[glyph_index].in_character == same_character)
131                 glyph_index++;
132             continue;
133         }
134         NRMatrix glyph_matrix;
135         Span const &span = _spans[_characters[_glyphs[glyph_index].in_character].in_span];
136         InputStreamTextSource const *text_source = static_cast<InputStreamTextSource const *>(_input_stream[span.in_input_stream_item]);
137         if (text_to_path || _path_fitted) {
138             NRBPath bpath;
139             bpath.path = (NArtBpath*)span.font->ArtBPath(_glyphs[glyph_index].glyph);
140             if (bpath.path) {
141                 NRBPath abp;
142                 _getGlyphTransformMatrix(glyph_index, &glyph_matrix);
143                 abp.path = nr_artpath_affine(bpath.path, glyph_matrix);
144                 if (text_source->style->fill.type != SP_PAINT_TYPE_NONE)
145                     sp_print_fill(ctx, &abp, &ctm, text_source->style, pbox, dbox, bbox);
146                 if (text_source->style->stroke.type != SP_PAINT_TYPE_NONE)
147                     sp_print_stroke(ctx, &abp, &ctm, text_source->style, pbox, dbox, bbox);
148                 nr_free(abp.path);
149             }
150             glyph_index++;
151         } else {
152             NR::Point g_pos(0,0);    // all strings are output at (0,0) because we do the translation using the matrix
153             glyph_matrix = NR::Matrix(NR::scale(1.0, -1.0) * NR::Matrix(NR::rotate(_glyphs[glyph_index].rotation)));
154             if (block_progression == LEFT_TO_RIGHT || block_progression == RIGHT_TO_LEFT) {
155                 glyph_matrix.c[4] = span.line(this).baseline_y + span.baseline_shift;
156                 // since we're outputting character codes, not glyphs, we want the character x
157                 glyph_matrix.c[5] = span.chunk(this).left_x + span.x_start + _characters[_glyphs[glyph_index].in_character].x;
158             } else {
159                 glyph_matrix.c[4] = span.chunk(this).left_x + span.x_start + _characters[_glyphs[glyph_index].in_character].x;
160                 glyph_matrix.c[5] = span.line(this).baseline_y + span.baseline_shift;
161             }
162             Glib::ustring::const_iterator span_iter = span.input_stream_first_character;
163             unsigned char_index = _glyphs[glyph_index].in_character;
164             unsigned original_span = _characters[char_index].in_span;
165             while (char_index && _characters[char_index - 1].in_span == original_span) {
166                 char_index--;
167                 span_iter++;
168             }
170             // try to output as many characters as possible in one go by detecting kerning and stopping when we encounter it
171             Glib::ustring span_string;
172             double char_x = _characters[_glyphs[glyph_index].in_character].x;
173             unsigned this_span_index = _characters[_glyphs[glyph_index].in_character].in_span;
174             do {
175                 span_string += *span_iter;
176                 span_iter++;
178                 unsigned same_character = _glyphs[glyph_index].in_character;
179                 while (glyph_index < _glyphs.size() && _glyphs[glyph_index].in_character == same_character) {
180                     char_x += _glyphs[glyph_index].width;
181                     glyph_index++;
182                 }
183             } while (glyph_index < _glyphs.size()
184                      && _path_fitted == NULL
185                      && _characters[_glyphs[glyph_index].in_character].in_span == this_span_index
186                      && fabs(char_x - _characters[_glyphs[glyph_index].in_character].x) < 1e-5);
187             sp_print_bind(ctx, glyph_matrix, 1.0);
188             sp_print_text(ctx, span_string.c_str(), g_pos, text_source->style);
189             sp_print_release(ctx);
190         }
191     }
194 // these functions are for dumpAsText() only. No need to translate
195 static char const *direction_to_text(Layout::Direction d)
197     switch (d) {
198         case Layout::LEFT_TO_RIGHT: return "ltr";
199         case Layout::RIGHT_TO_LEFT: return "rtl";
200         case Layout::TOP_TO_BOTTOM: return "ttb";
201         case Layout::BOTTOM_TO_TOP: return "btt";
202     }
203     return "???";
206 static char const *style_to_text(PangoStyle s)
208     switch (s) {
209         case PANGO_STYLE_NORMAL: return "upright";
210         case PANGO_STYLE_ITALIC: return "italic";
211         case PANGO_STYLE_OBLIQUE: return "oblique";
212     }
213     return "???";
216 static char const *weight_to_text(PangoWeight w)
218     switch (w) {
219         case PANGO_WEIGHT_ULTRALIGHT: return "ultralight";
220         case PANGO_WEIGHT_LIGHT     : return "light";
221         case PANGO_WEIGHT_SEMIBOLD  : return "semibold";
222         case PANGO_WEIGHT_NORMAL    : return "normalweight";
223         case PANGO_WEIGHT_BOLD      : return "bold";
224         case PANGO_WEIGHT_ULTRABOLD : return "ultrabold";
225         case PANGO_WEIGHT_HEAVY     : return "heavy";
226     }
227     return "???";
230 Glib::ustring Layout::dumpAsText() const
232     Glib::ustring result;
234     for (unsigned span_index = 0 ; span_index < _spans.size() ; span_index++) {
235         char line[256];
236         snprintf(line, sizeof(line), "==== span %d\n", span_index);
237         result += line;
238         snprintf(line, sizeof(line), "  in para %d (direction=%s)\n", _lines[_chunks[_spans[span_index].in_chunk].in_line].in_paragraph,
239                  direction_to_text(_paragraphs[_lines[_chunks[_spans[span_index].in_chunk].in_line].in_paragraph].base_direction));
240         result += line;
241         snprintf(line, sizeof(line), "  in source %d (type=%d, cookie=%p)\n", _spans[span_index].in_input_stream_item,
242                  _input_stream[_spans[span_index].in_input_stream_item]->Type(),
243                  _input_stream[_spans[span_index].in_input_stream_item]->source_cookie);
244         result += line;
245         snprintf(line, sizeof(line), "  in line %d (baseline=%f, shape=%d)\n", _chunks[_spans[span_index].in_chunk].in_line,
246                  _lines[_chunks[_spans[span_index].in_chunk].in_line].baseline_y,
247                  _lines[_chunks[_spans[span_index].in_chunk].in_line].in_shape);
248         result += line;
249         snprintf(line, sizeof(line), "  in chunk %d (x=%f, baselineshift=%f)\n", _spans[span_index].in_chunk, _chunks[_spans[span_index].in_chunk].left_x, _spans[span_index].baseline_shift);
250         result += line;
251         if (_spans[span_index].font) {
252             snprintf(line, sizeof(line), "    font '%s' %f %s %s\n", pango_font_description_get_family(_spans[span_index].font->descr), _spans[span_index].font_size, style_to_text(pango_font_description_get_style(_spans[span_index].font->descr)), weight_to_text(pango_font_description_get_weight(_spans[span_index].font->descr)));
253             result += line;
254         }
255         snprintf(line, sizeof(line), "    x_start = %f, x_end = %f\n", _spans[span_index].x_start, _spans[span_index].x_end);
256         result += line;
257         snprintf(line, sizeof(line), "    line height: ascent %f, descent %f leading %f\n", _spans[span_index].line_height.ascent, _spans[span_index].line_height.descent, _spans[span_index].line_height.leading);
258         result += line;
259         snprintf(line, sizeof(line), "    direction %s, block-progression %s\n", direction_to_text(_spans[span_index].direction), direction_to_text(_spans[span_index].block_progression));
260         result += line;
261         result += "    ** characters:\n";
262         Glib::ustring::const_iterator iter_char = _spans[span_index].input_stream_first_character;
263         // very inefficent code. what the hell, it's only debug stuff.
264         for (unsigned char_index = 0 ; char_index < _characters.size() ; char_index++) {
265             if (_characters[char_index].in_span != span_index) continue;
266             if (_input_stream[_spans[span_index].in_input_stream_item]->Type() != TEXT_SOURCE) {
267                 snprintf(line, sizeof(line), "      %d: control x=%f flags=%03x glyph=%d\n", char_index, _characters[char_index].x, *(unsigned*)&_characters[char_index].char_attributes, _characters[char_index].in_glyph);
268             } else {
269                 snprintf(line, sizeof(line), "      %d: '%c' x=%f flags=%03x glyph=%d\n", char_index, *iter_char, _characters[char_index].x, *(unsigned*)&_characters[char_index].char_attributes, _characters[char_index].in_glyph);
270                 iter_char++;
271             }
272             result += line;
273         }
274         result += "    ** glyphs:\n";
275         for (unsigned glyph_index = 0 ; glyph_index < _glyphs.size() ; glyph_index++) {
276             if (_characters[_glyphs[glyph_index].in_character].in_span != span_index) continue;
277             snprintf(line, sizeof(line), "      %d: %d (%f,%f) rot=%f cx=%f char=%d\n", glyph_index, _glyphs[glyph_index].glyph, _glyphs[glyph_index].x, _glyphs[glyph_index].y, _glyphs[glyph_index].rotation, _glyphs[glyph_index].width, _glyphs[glyph_index].in_character);
278             result += line;
279         }
280         result += "\n";
281     }
282     result += "EOT\n";
283     return result;
286 void Layout::fitToPathAlign(SVGLength const &startOffset, Path const &path)
288     double offset = 0.0;
290     if (startOffset._set) {
291         if (startOffset.unit == SVGLength::PERCENT)
292             offset = startOffset.computed * const_cast<Path&>(path).Length();
293         else
294             offset = startOffset.computed;
295     }
297     switch (_paragraphs.front().alignment) {
298         case CENTER:
299             offset -= _getChunkWidth(0) * 0.5;
300             break;
301         case RIGHT:
302             offset -= _getChunkWidth(0);
303             break;
304         default:
305             break;
306     }
308     if (_characters.empty()) {
309         int unused = 0;
310         Path::cut_position *point_otp = const_cast<Path&>(path).CurvilignToPosition(1, &offset, unused);
311         if (offset >= 0.0 && point_otp != NULL && point_otp[0].piece >= 0) {
312             NR::Point point;
313             NR::Point tangent;
314             const_cast<Path&>(path).PointAndTangentAt(point_otp[0].piece, point_otp[0].t, point, tangent);
315             _empty_cursor_shape.position = point;
316             _empty_cursor_shape.rotation = atan2(tangent[NR::Y], tangent[NR::X]);
317         }
318     }
320     for (unsigned char_index = 0 ; char_index < _characters.size() ; ) {
321         int next_cluster_glyph_index;
322         unsigned next_cluster_char_index;
323         double character_advance;
324         Span const &span = _characters[char_index].span(this);
326         for (next_cluster_char_index = char_index + 1 ;
327              next_cluster_char_index < _characters.size() && !_characters[next_cluster_char_index].char_attributes.is_cursor_position;
328              next_cluster_char_index++);
330         if (next_cluster_char_index == _characters.size()) {
331             next_cluster_glyph_index = _glyphs.size();
332             character_advance = 0.0;   // arbitrary because we're not going to advance
333         } else {
334             next_cluster_glyph_index = _characters[next_cluster_char_index].in_glyph;
335             character_advance =   (_glyphs[next_cluster_glyph_index].x + _glyphs[next_cluster_glyph_index].chunk(this).left_x)
336                 - (_glyphs[_characters[char_index].in_glyph].x + span.chunk(this).left_x);
337         }
339         double start_offset = offset + span.x_start + _characters[char_index].x;
340         double cluster_width = 0.0;
341         for (int glyph_index = _characters[char_index].in_glyph ; glyph_index < next_cluster_glyph_index ; glyph_index++)
342             cluster_width += _glyphs[glyph_index].width;
343         if (span.direction == RIGHT_TO_LEFT)
344             start_offset -= cluster_width;
345         double end_offset = start_offset + cluster_width;
347         int unused = 0;
348         double midpoint_offset = (start_offset + end_offset) * 0.5;
349         // as far as I know these functions are const, they're just not marked as such
350         Path::cut_position *midpoint_otp = const_cast<Path&>(path).CurvilignToPosition(1, &midpoint_offset, unused);
351         if (midpoint_offset >= 0.0 && midpoint_otp != NULL && midpoint_otp[0].piece >= 0) {
352             NR::Point midpoint;
353             NR::Point tangent;
355             const_cast<Path&>(path).PointAndTangentAt(midpoint_otp[0].piece, midpoint_otp[0].t, midpoint, tangent);
357             if (start_offset >= 0.0 && end_offset >= 0.0) {
358                 Path::cut_position *start_otp = const_cast<Path&>(path).CurvilignToPosition(1, &start_offset, unused);
359                 if (start_otp != NULL && start_otp[0].piece >= 0) {
360                     Path::cut_position *end_otp = const_cast<Path&>(path).CurvilignToPosition(1, &end_offset, unused);
361                     if (end_otp != NULL && end_otp[0].piece >= 0) {
362                         bool on_same_subpath = true;
363                         for (size_t i = 0 ; i < path.pts.size() ; i++) {
364                             if (path.pts[i].piece <= start_otp[0].piece) continue;
365                             if (path.pts[i].piece >= end_otp[0].piece) break;
366                             if (path.pts[i].isMoveTo == polyline_moveto) {
367                                 on_same_subpath = false;
368                                 break;
369                             }
370                         }
371                         if (on_same_subpath) {
372                             // both points were on the same subpath (without this test the angle is very weird)
373                             NR::Point startpoint, endpoint;
374                             const_cast<Path&>(path).PointAt(start_otp[0].piece, start_otp[0].t, startpoint);
375                             const_cast<Path&>(path).PointAt(end_otp[0].piece, end_otp[0].t, endpoint);
376                             if (endpoint != startpoint) {
377                                 tangent = endpoint - startpoint;
378                                 tangent.normalize();
379                             } else {
380                                 tangent = NR::Point (0,0);
381                             }
382                         }
383                         g_free(end_otp);
384                     }
385                     g_free(start_otp);
386                 }
387             }
389             double rotation = atan2(tangent[1], tangent[0]);
390             for (int glyph_index = _characters[char_index].in_glyph ; glyph_index < next_cluster_glyph_index ; glyph_index++) {
391                 double tangent_shift = -cluster_width * 0.5 + _glyphs[glyph_index].x - (_characters[char_index].x + span.x_start);
392                 double normal_shift = _glyphs[glyph_index].y;
393                 if (span.direction == RIGHT_TO_LEFT)
394                     tangent_shift += cluster_width;
395                 _glyphs[glyph_index].x = midpoint[0] - span.chunk(this).left_x + tangent[0] * tangent_shift - tangent[1] * normal_shift;
396                 _glyphs[glyph_index].y = midpoint[1] - _lines.front().baseline_y + tangent[1] * tangent_shift + tangent[0] * normal_shift;
397                 _glyphs[glyph_index].rotation += rotation;
398             }
399         } else {  // outside the bounds of the path: hide the glyphs
400             _characters[char_index].in_glyph = -1;
401         }
402         g_free(midpoint_otp);
404         char_index = next_cluster_char_index;
405     }
407     for (unsigned span_index = 0 ; span_index < _spans.size() ; span_index++) {
408         _spans[span_index].x_start += offset;
409         _spans[span_index].x_end += offset;
410     }
412     _path_fitted = &path;
415 SPCurve *Layout::convertToCurves(iterator const &from_glyph, iterator const &to_glyph) const
417     GSList *cc = NULL;
419     for (int glyph_index = from_glyph._glyph_index ; glyph_index < to_glyph._glyph_index ; glyph_index++) {
420         NRMatrix glyph_matrix;
421         Span const &span = _glyphs[glyph_index].span(this);
422         _getGlyphTransformMatrix(glyph_index, &glyph_matrix);
424         NRBPath bpath;
425         bpath.path = (NArtBpath*)span.font->ArtBPath(_glyphs[glyph_index].glyph);
426         if (bpath.path) {
427             NArtBpath *abp = nr_artpath_affine(bpath.path, glyph_matrix);
428             SPCurve *c = sp_curve_new_from_bpath(abp);
429             if (c) cc = g_slist_prepend(cc, c);
430         }
431     }
432     cc = g_slist_reverse(cc);
434     SPCurve *curve;
435     if ( cc ) {
436         curve = sp_curve_concat(cc);
437     } else {
438         curve = sp_curve_new();
439     }
441     while (cc) {
442         /* fixme: This is dangerous, as we are mixing art_alloc and g_new */
443         sp_curve_unref((SPCurve *) cc->data);
444         cc = g_slist_remove(cc, cc->data);
445     }
447     return curve;
450 void Layout::transform(NR::Matrix const &transform)
452     // this is all massively oversimplified
453     // I can't actually think of anybody who'll want to use it at the moment, so it'll stay simple
454     for (unsigned glyph_index = 0 ; glyph_index < _glyphs.size() ; glyph_index++) {
455         NR::Point point(_glyphs[glyph_index].x, _glyphs[glyph_index].y);
456         point *= transform;
457         _glyphs[glyph_index].x = point[0];
458         _glyphs[glyph_index].y = point[1];
459     }
462 }//namespace Text
463 }//namespace Inkscape
466 /*
467   Local Variables:
468   mode:c++
469   c-file-style:"stroustrup"
470   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
471   indent-tabs-mode:nil
472   fill-column:99
473   End:
474 */
475 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :