1 /*
2 * Inkscape::Text::Layout - text layout engine
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 #ifndef __LAYOUT_TNG_H__
12 #define __LAYOUT_TNG_H__
14 #ifdef HAVE_CONFIG_H
15 # include "config.h"
16 #endif
17 #include <libnr/nr-matrix-ops.h>
18 #include <libnr/nr-rotate-ops.h>
19 #include <libnr/nr-rect.h>
20 #include <2geom/d2.h>
21 #include <2geom/matrix.h>
22 #include <glibmm/ustring.h>
23 #include <pango/pango-break.h>
24 #include <algorithm>
25 #include <vector>
26 #include <boost/optional.hpp>
28 #ifdef HAVE_CAIRO_PDF
29 namespace Inkscape {
30 namespace Extension {
31 namespace Internal {
32 class CairoRenderContext;
33 }
34 }
35 }
37 using Inkscape::Extension::Internal::CairoRenderContext;
38 #endif
40 class SPStyle;
41 class Shape;
42 class NRArenaGroup;
43 class SPPrintContext;
44 class SVGLength;
45 class Path;
46 class SPCurve;
47 class font_instance;
48 typedef struct _PangoFontDescription PangoFontDescription;
50 namespace Inkscape {
51 namespace Text {
53 /** \brief Generates the layout for either wrapped or non-wrapped text and stores the result
55 Use this class for all your text output needs. It takes text with formatting
56 markup as input and turns that into the glyphs and their necessary positions.
57 It stores the glyphs internally, but maintains enough information to both
58 retrieve your own rendering information if you wish and to perform visual
59 text editing where the output refers back to where it came from.
61 Usage:
62 -# Construct
63 -# Set the text using appendText() and appendControlCode()
64 -# If you want text wrapping, call appendWrapShape() a few times
65 -# Call calculateFlow()
66 -# You can go several directions from here, but the most interesting
67 things start with creating a Layout::iterator with begin() or end().
69 Terminology, in descending order of size:
70 - Flow: Not often used, but when it is it means all the text
71 - Shape: A Shape object which is used to represent one of the regions inside
72 which to flow the text. Can overlap with...
73 - Paragraph: Err...A paragraph. Contains one or more...
74 - Line: An entire horizontal line with a common baseline. Contains one or
75 more...
76 - Chunk: You only get more than one of these when a shape is sufficiently
77 complex that the text has to flow either side of some obstruction in
78 the middle. A chunk is the base unit for wrapping. Contains one or more...
79 - Span: A convenient subset of a chunk with the same font, style,
80 directionality, block progression and input stream. Fill and outline
81 need not be constant because that's a later rendering stage.
82 - This is where it gets weird because a span will contain one or more
83 elements of both of the following, which can overlap with each other in
84 any way:
85 - Character: a single Unicode codepoint from an input stream. Many arabic
86 characters contain multiple glyphs
87 - Glyph: a rendering primitive for font engines. A ligature glyph will
88 represent multiple characters.
90 Other terminology:
91 - Input stream: An object representing a single call to appendText() or
92 appendControlCode().
93 - Control code: Metadata in the text stream to signify items that occupy
94 real space (unlike style changes) but don't belong in the text string.
95 Paragraph breaks are in this category. See Layout::TextControlCode.
96 - SVG1.1: The W3C Recommendation "Scalable Vector Graphics (SVG) 1.1"
97 http://www.w3.org/TR/SVG11/
98 - 'left', 'down', etc: These terms are generally used to mean what they
99 mean in left-to-right, top-to-bottom text but rotated or reflected for
100 the current directionality. Thus, the 'width' of a ttb line is actually
101 its height, and the (internally stored) y coordinate of a glyph is
102 actually its x coordinate. Confusing to the reader but much simpler in
103 the code. All public methods use real x and y.
105 Comments:
106 - There's a strong emphasis on international support in this class, but
107 that's primarily because once you can display all the insane things
108 required by various languages, simple things like styling text are
109 almost trivial.
110 - There are a few places (appendText() is one) where pointers are held to
111 caller-owned objects and used for quite a long time. This is messy but
112 is safe for our usage scenario and in many cases the cost of copying the
113 objects is quite high.
114 - "Why isn't foo here?": Ask yourself if it's possible to implement foo
115 externally using iterators. However this may not mean that it doesn't
116 belong as a member, though.
117 - I've used floats rather than doubles to store relative distances in some
118 places (internal only) where it would save significant amounts of memory.
119 The SVG spec allows you to do this as long as intermediate calculations
120 are done double. Very very long lines might not finish precisely where
121 you want, but that's to be expected with any typesetting. Also,
122 SVGLength only uses floats.
123 - If you look at the six arrays for holding the output data you'll realise
124 that there's no O(1) way to drill down from a paragraph to find its
125 starting glyph. This was a conscious decision to reduce complexity and
126 to save memory. Drilling down isn't actually that slow because a binary
127 chop will work nicely. Add this to the realisation that most of the
128 times you do this will be in response to user actions and hence you only
129 need to be faster than the user and I think the design makes sense.
130 - There are a massive number of functions acting on Layout::iterator. A
131 large number are trivial and will be inline, but is it really necessary
132 to have all these, especially when some can be implemented by the caller
133 using the others?
134 - The separation of methods between Layout and Layout::iterator is a
135 bit arbitrary, because many methods could go in either. I've used the STL
136 model where the iterator itself can only move around; the base class is
137 required to do anything interesting.
138 - I use Pango internally, not Pangomm. The reason for this is lots of
139 Pangomm methods take Glib::ustrings as input and then output byte offsets
140 within the strings. There's simply no way to use byte offsets with
141 ustrings without some very entertaining reinterpret_cast<>s. The Pangomm
142 docs seem to be lacking quite a lot of things mentioned in the Pango
143 docs, too.
144 */
145 class Layout {
146 public:
147 class iterator;
148 friend class iterator;
149 class Calculator;
150 friend class Calculator;
151 class ScanlineMaker;
152 class InfiniteScanlineMaker;
153 class ShapeScanlineMaker;
155 Layout();
156 virtual ~Layout();
158 /** Used to specify any particular text direction required. Used for
159 both the 'direction' and 'block-progression' CSS attributes. */
160 enum Direction {LEFT_TO_RIGHT, RIGHT_TO_LEFT, TOP_TO_BOTTOM, BOTTOM_TO_TOP};
162 /** Display alignment for shapes. See appendWrapShape(). */
163 enum DisplayAlign {DISPLAY_ALIGN_BEFORE, DISPLAY_ALIGN_CENTER, DISPLAY_ALIGN_AFTER};
165 /** The optional attributes which can be applied to a SVG text or
166 related tag. See appendText(). See SVG1.1 section 10.4 for the
167 definitions of all these members. See sp_svg_length_list_read() for
168 the standard way to make these vectors. It is the responsibility of
169 the caller to deal with the inheritance of these values using its
170 knowledge of the parse tree. */
171 struct OptionalTextTagAttrs {
172 std::vector<SVGLength> x;
173 std::vector<SVGLength> y;
174 std::vector<SVGLength> dx;
175 std::vector<SVGLength> dy;
176 std::vector<SVGLength> rotate;
177 };
179 /** Control codes which can be embedded in the text to be flowed. See
180 appendControlCode(). */
181 enum TextControlCode {
182 PARAGRAPH_BREAK, /// forces the flow to move on to the next line
183 SHAPE_BREAK, /// forces the flow to ignore the remainder of the current shape (from #flow_inside_shapes) and continue at the top of the one after.
184 ARBITRARY_GAP /// inserts an arbitrarily-sized hole in the flow in line with the current text.
185 };
187 /** For expressing paragraph alignment. These values are rotated in the
188 case of vertical text, but are not dependent on whether the paragraph is
189 rtl or ltr, thus LEFT is always either left or top. */
190 enum Alignment {LEFT, CENTER, RIGHT, FULL};
192 /** The CSS spec allows line-height:normal to be whatever the user agent
193 thinks will look good. This is our value, as a multiple of font-size. */
194 static const double LINE_HEIGHT_NORMAL;
196 // ************************** describing the stuff to flow *************************
198 /** \name Input
199 Methods for describing the text you want to flow, its style, and the
200 shapes to flow in to.
201 */
202 //@{
204 /** Empties everything stored in this class and resets it to its
205 original state, like when it was created. All iterators on this
206 object will be invalidated (but can be revalidated using
207 validateIterator(). */
208 void clear();
210 /** Queries whether any calls have been made to appendText() or
211 appendControlCode() since the object was last cleared. */
212 bool inputExists() const
213 {return !_input_stream.empty();}
215 /** adds a new piece of text to the end of the current list of text to
216 be processed. This method can only add text of a consistent style.
217 To add lots of different styles, call it lots of times.
218 \param text The text. \b Note: only a \em pointer is stored. Do not
219 mess with the text until after you have called
220 calculateFlow().
221 \param style The font style. Layout will hold a reference to this
222 object for the duration of its ownership, ie until you
223 call clear() or the class is destroyed. Must not be NULL.
224 \param source_cookie This pointer is treated as opaque by Layout
225 but will be passed through the flowing process intact so
226 that callers can use it to refer to the original object
227 that generated a particular glyph. See Layout::iterator.
228 Implementation detail: currently all callers put an
229 SPString in here.
230 \param optional_attributes A structure containing additional options
231 for this text. See OptionalTextTagAttrs. The values are
232 copied to internal storage before this method returns.
233 \param optional_attributes_offset It is convenient for callers to be
234 able to use the same \a optional_attributes structure for
235 several sequential text fields, in which case the vectors
236 will need to be offset. This parameter causes the <i>n</i>th
237 element of all the vectors to be read as if it were the
238 first.
239 \param text_begin Used for selecting only a substring of \a text
240 to process.
241 \param text_end Used for selecting only a substring of \a text
242 to process.
243 */
244 void appendText(Glib::ustring const &text, SPStyle *style, void *source_cookie, OptionalTextTagAttrs const *optional_attributes, unsigned optional_attributes_offset, Glib::ustring::const_iterator text_begin, Glib::ustring::const_iterator text_end);
245 inline void appendText(Glib::ustring const &text, SPStyle *style, void *source_cookie, OptionalTextTagAttrs const *optional_attributes = NULL, unsigned optional_attributes_offset = 0)
246 {appendText(text, style, source_cookie, optional_attributes, optional_attributes_offset, text.begin(), text.end());}
248 /** Control codes are metadata in the text stream to signify items
249 that occupy real space (unlike style changes) but don't belong in the
250 text string. See TextControlCode for the types available.
252 A control code \em cannot be the first item in the input stream. Use
253 appendText() with an empty string to set up the paragraph properties.
254 \param code A member of the TextFlowControlCode enumeration.
255 \param width The width in pixels that this item occupies.
256 \param ascent The number of pixels above the text baseline that this
257 control code occupies.
258 \param descent The number of pixels below the text baseline that this
259 control code occupies.
260 \param source_cookie This pointer is treated as opaque by Layout
261 but will be passed through the flowing process intact so
262 that callers can use it to refer to the original object
263 that generated a particular area. See Layout::iterator.
264 Implementation detail: currently all callers put an
265 SPObject in here.
266 Note that for some control codes (eg tab) the values of the \a width,
267 \a ascender and \a descender are implied by the surrounding text (and
268 in the case of tabs, the values set in tab_stops) so the values you pass
269 here are ignored.
270 */
271 void appendControlCode(TextControlCode code, void *source_cookie, double width = 0.0, double ascent = 0.0, double descent = 0.0);
273 /** Stores another shape inside which to flow the text. If this method
274 is never called then no automatic wrapping is done and lines will
275 continue to infinity if necessary. Text can be flowed inside multiple
276 shapes in sequence, like with frames in a DTP package. If the text flows
277 past the end of the last shape all remaining text is ignored.
279 \param shape The Shape to use next in the flow. The storage for this
280 is managed by the caller, and need only be valid for
281 the duration of the call to calculateFlow().
282 \param display_align The vertical alignment of the text within this
283 shape. See XSL1.0 section 7.13.4. The behaviour of
284 settings other than DISPLAY_ALIGN_BEFORE when using
285 non-rectangular shapes is undefined.
286 */
287 void appendWrapShape(Shape const *shape, DisplayAlign display_align = DISPLAY_ALIGN_BEFORE);
289 //@}
291 // ************************** doing the actual flowing *************************
293 /** \name Processing
294 The method to do the actual work of converting text into glyphs.
295 */
296 //@{
298 /** Takes all the stuff you set with the members above here and creates
299 a load of glyphs for use with the members below here. All iterators on
300 this object will be invalidated (but can be fixed with validateIterator().
301 The implementation just creates a new Layout::Calculator and calls its
302 Calculator::Calculate() method, so if you want more details on the
303 internals, go there.
304 \return false on failure.
305 */
306 bool calculateFlow();
308 //@}
310 // ************************** operating on the output glyphs *************************
312 /** \name Output
313 Methods for reading and interpreting the output glyphs. See also
314 Layout::iterator.
315 */
316 //@{
318 /** Returns true if there are some glyphs in this object, ie whether
319 computeFlow() has been called on a non-empty input since the object was
320 created or the last call to clear(). */
321 inline bool outputExists() const
322 {return !_characters.empty();}
324 /** Adds all the output glyphs to \a in_arena using the given \a paintbox.
325 \param in_arena The arena to add the glyphs group to
326 \param paintbox The current rendering tile
327 */
328 void show(NRArenaGroup *in_arena, NRRect const *paintbox) const;
330 /** Calculates the smallest rectangle completely enclosing all the
331 glyphs.
332 \param bounding_box Where to store the box
333 \param transform The transform to be applied to the entire object
334 prior to calculating its bounds.
335 */
336 void getBoundingBox(NRRect *bounding_box, Geom::Matrix const &transform, int start = -1, int length = -1) const;
338 /** Sends all the glyphs to the given print context.
339 \param ctx I have
340 \param pbox no idea
341 \param dbox what these
342 \param bbox parameters
343 \param ctm do yet
344 */
345 void print(SPPrintContext *ctx, NRRect const *pbox, NRRect const *dbox, NRRect const *bbox, Geom::Matrix const &ctm) const;
347 #ifdef HAVE_CAIRO_PDF
348 /** Renders all the glyphs to the given Cairo rendering context.
349 \param ctx The Cairo rendering context to be used
350 */
351 void showGlyphs(CairoRenderContext *ctx) const;
352 #endif
354 /** debug and unit test method. Creates a textual representation of the
355 contents of this object. The output is designed to be both human-readable
356 and comprehensible when diffed with a known-good dump. */
357 Glib::ustring dumpAsText() const;
359 /** Moves all the glyphs in the structure so that the baseline of all
360 the characters sits neatly along the path specified. If the text has
361 more than one line the results are undefined. The 'align' means to
362 use the SVG align method as documented in SVG1.1 section 10.13.2.
363 NB: njh has suggested that it would be cool if we could flow from
364 shape to path and back again. This is possible, so this method will be
365 removed at some point.
366 A pointer to \a path is retained by the class for use by the cursor
367 positioning functions. */
368 void fitToPathAlign(SVGLength const &startOffset, Path const &path);
370 /** Convert the specified range of characters into their bezier
371 outlines.
372 */
373 SPCurve* convertToCurves(iterator const &from_glyph, iterator const &to_glyph) const;
374 inline SPCurve* convertToCurves() const;
376 /** Apply the given transform to all the output presently stored in
377 this object. This only transforms the glyph positions, The glyphs
378 themselves will not be transformed. */
379 void transform(Geom::Matrix const &transform);
381 //@}
383 // **********
385 /** \name Output (Iterators)
386 Methods for operating with the Layout::iterator class. The method
387 names ending with 'Index' return 0-based offsets of the number of
388 items since the beginning of the flow.
389 */
390 //@{
392 /** Returns an iterator pointing at the first glyph of the flowed output.
393 The first glyph is also the first character, line, paragraph, etc. */
394 inline iterator begin() const;
396 /** Returns an iterator pointing just past the end of the last glyph,
397 which is also just past the end of the last chunk, span, etc, etc. */
398 inline iterator end() const;
400 /** Returns an iterator pointing at the given character index. This
401 index should be related to the result from a prior call to
402 iteratorToCharIndex(). */
403 inline iterator charIndexToIterator(int char_index) const;
405 /** Returns the character index from the start of the flow represented
406 by the given iterator. This number isn't very useful, except for when
407 editing text it will stay valid across calls to computeFlow() and will
408 change in predictable ways when characters are added and removed. It's
409 also useful when transitioning old code. */
410 inline int iteratorToCharIndex(iterator const &it) const;
412 /** Checks the validity of the given iterator over the current layout.
413 If it points to a position out of the bounds for this layout it will
414 be corrected to the nearest valid position. If you pass an iterator
415 belonging to a different layout it will be converted to one for this
416 layout. */
417 inline void validateIterator(iterator *it) const;
419 /** Returns an iterator pointing to the cursor position for a mouse
420 click at the given coordinates. */
421 iterator getNearestCursorPositionTo(double x, double y) const;
422 inline iterator getNearestCursorPositionTo(Geom::Point const &point) const;
424 /** Returns an iterator pointing to the letter whose bounding box contains
425 the given coordinates. end() if the point is not over any letter. The
426 iterator will \em not point at the specific glyph within the character. */
427 iterator getLetterAt(double x, double y) const;
428 inline iterator getLetterAt(Geom::Point &point) const;
430 /** Returns an iterator pointing to the character in the output which
431 was created from the given input. If the character at the given byte
432 offset was removed (soft hyphens, for example) the next character after
433 it is returned. If no input was added with the given cookie, end() is
434 returned. If more than one input has the same cookie, the first will
435 be used regardless of the value of \a text_iterator. If
436 \a text_iterator is out of bounds, the first or last character belonging
437 to the given input will be returned accordingly. */
438 iterator sourceToIterator(void *source_cookie, Glib::ustring::const_iterator text_iterator) const;
440 /** Returns an iterator pointing to the first character in the output
441 which was created from the given source. If \a source_cookie is invalid,
442 end() is returned. If more than one input has the same cookie, the
443 first one will be used. */
444 iterator sourceToIterator(void *source_cookie) const;
446 // many functions acting on iterators, most of which are obvious
447 // also most of them don't check that \a it != end(). Be careful.
449 /** Returns the bounding box of the given glyph, and its rotation.
450 The centre of rotation is the horizontal centre of the box at the
451 text baseline. */
452 Geom::OptRect glyphBoundingBox(iterator const &it, double *rotation) const;
454 /** Returns the zero-based line number of the character pointed to by
455 \a it. */
456 inline unsigned lineIndex(iterator const &it) const;
458 /** Returns the zero-based number of the shape which contains the
459 character pointed to by \a it. */
460 inline unsigned shapeIndex(iterator const &it) const;
462 /** Returns true if the character at \a it is a whitespace, as defined
463 by Pango. This is not meant to be used for picking out words from the
464 output, use iterator::nextStartOfWord() and friends instead. */
465 inline bool isWhitespace(iterator const &it) const;
467 /** Returns the unicode character code of the character pointed to by
468 \a it. If \a it == end() the result is undefined. */
469 inline int characterAt(iterator const &it) const;
471 /** Discovers where the character pointed to by \a it came from, by
472 retrieving the cookie that was passed to the call to appendText() or
473 appendControlCode() which generated that output. If \a it == end()
474 then NULL is returned as the cookie. If the character was generated
475 from a call to appendText() then the optional \a text_iterator
476 parameter is set to point to the actual character, otherwise
477 \a text_iterator is unaltered. */
478 void getSourceOfCharacter(iterator const &it, void **source_cookie, Glib::ustring::iterator *text_iterator = NULL) const;
480 /** For latin text, the left side of the character, on the baseline */
481 Geom::Point characterAnchorPoint(iterator const &it) const;
483 /** This is that value to apply to the x,y attributes of tspan role=line
484 elements, and hence it takes alignment into account. */
485 Geom::Point chunkAnchorPoint(iterator const &it) const;
487 /** Returns the box extents (not ink extents) of the given character.
488 The centre of rotation is at the horizontal centre of the box on the
489 text baseline. */
490 Geom::Rect characterBoundingBox(iterator const &it, double *rotation = NULL) const;
492 /** Basically uses characterBoundingBox() on all the characters from
493 \a start to \a end and returns the union of these boxes. The return value
494 is a list of zero or more quadrilaterals specified by a group of four
495 points for each, thus size() is always a multiple of four. */
496 std::vector<Geom::Point> createSelectionShape(iterator const &it_start, iterator const &it_end, Geom::Matrix const &transform) const;
498 /** Returns true if \a it points to a character which is a valid cursor
499 position, as defined by Pango. */
500 inline bool isCursorPosition(iterator const &it) const;
502 /** Gets the ideal cursor shape for a given iterator. The result is
503 undefined if \a it is not at a valid cursor position.
504 \param it The location in the output
505 \param position The pixel location of the centre of the 'bottom' of
506 the cursor.
507 \param height The height in pixels of the surrounding text
508 \param rotation The angle to draw from \a position. Radians, zero up,
509 increasing clockwise.
510 */
511 void queryCursorShape(iterator const &it, Geom::Point &position, double &height, double &rotation) const;
513 /** Returns true if \a it points to a character which is a the start of
514 a word, as defined by Pango. */
515 inline bool isStartOfWord(iterator const &it) const;
517 /** Returns true if \a it points to a character which is a the end of
518 a word, as defined by Pango. */
519 inline bool isEndOfWord(iterator const &it) const;
521 /** Returns true if \a it points to a character which is a the start of
522 a sentence, as defined by Pango. */
523 inline bool isStartOfSentence(iterator const &it) const;
525 /** Returns true if \a it points to a character which is a the end of
526 a sentence, as defined by Pango. */
527 inline bool isEndOfSentence(iterator const &it) const;
529 /** Returns the zero-based number of the paragraph containing the
530 character pointed to by \a it. */
531 inline unsigned paragraphIndex(iterator const &it) const;
533 /** Returns the actual alignment used for the paragraph containing
534 the character pointed to by \a it. This means that the CSS 'start'
535 and 'end' are correctly translated into LEFT or RIGHT according to
536 the paragraph's directionality. For vertical text, LEFT is top
537 alignment and RIGHT is bottom. */
538 inline Alignment paragraphAlignment(iterator const &it) const;
540 /** Returns kerning information which could cause the current output
541 to be exactly reproduced if the letter and word spacings were zero and
542 full justification was not used. The x and y arrays are not used, but
543 they are cleared. The dx applied to the first character in a chunk
544 will always be zero. If the region between \a from and \a to crosses
545 a line break then the results may be surprising, and are undefined.
546 Trailing zeros on the returned arrays will be trimmed. */
547 void simulateLayoutUsingKerning(iterator const &from, iterator const &to, OptionalTextTagAttrs *result) const;
549 //@}
551 /// it's useful for this to be public so that ScanlineMaker can use it
552 struct LineHeight {
553 double ascent;
554 double descent;
555 double leading;
556 inline double total() const {return ascent + descent + leading;}
557 inline void setZero() {ascent = descent = leading = 0.0;}
558 inline LineHeight& operator*=(double x) {ascent *= x; descent *= x; leading *= x; return *this;}
559 void max(LineHeight const &other); /// makes this object contain the largest of all three members between this object and other
560 };
562 /// see _enum_converter()
563 struct EnumConversionItem {
564 int input, output;
565 };
567 private:
568 /** Erases all the stuff set by the owner as input, ie #_input_stream
569 and #_input_wrap_shapes. */
570 void _clearInputObjects();
572 /** Erases all the stuff output by computeFlow(). Glyphs and things. */
573 void _clearOutputObjects();
575 static const gunichar UNICODE_SOFT_HYPHEN;
577 // ******************* input flow
579 enum InputStreamItemType {TEXT_SOURCE, CONTROL_CODE};
581 class InputStreamItem {
582 public:
583 virtual ~InputStreamItem() {}
584 virtual InputStreamItemType Type() =0;
585 void *source_cookie;
586 };
588 /** Represents a text item in the input stream. See #_input_stream.
589 Most of the members are copies of the values passed to appendText(). */
590 class InputStreamTextSource : public InputStreamItem {
591 public:
592 virtual InputStreamItemType Type() {return TEXT_SOURCE;}
593 virtual ~InputStreamTextSource();
594 Glib::ustring const *text; /// owned by the caller
595 Glib::ustring::const_iterator text_begin, text_end;
596 int text_length; /// in characters, from text_start to text_end only
597 SPStyle *style;
598 /** These vectors can (often will) be shorter than the text
599 in this source, but never longer. */
600 std::vector<SVGLength> x;
601 std::vector<SVGLength> y;
602 std::vector<SVGLength> dx;
603 std::vector<SVGLength> dy;
604 std::vector<SVGLength> rotate;
606 // a few functions for some of the more complicated style accesses
607 float styleComputeFontSize() const;
608 /// The return value must be freed with pango_font_description_free()
609 PangoFontDescription *styleGetFontDescription() const;
610 font_instance *styleGetFontInstance() const;
611 Direction styleGetBlockProgression() const;
612 Alignment styleGetAlignment(Direction para_direction, bool try_text_align) const;
613 };
615 /** Represents a control code item in the input stream. See
616 #_input_streams. All the members are copies of the values passed to
617 appendControlCode(). */
618 class InputStreamControlCode : public InputStreamItem {
619 public:
620 virtual InputStreamItemType Type() {return CONTROL_CODE;}
621 TextControlCode code;
622 double ascent;
623 double descent;
624 double width;
625 };
627 /** This is our internal storage for all the stuff passed to the
628 appendText() and appendControlCode() functions. */
629 std::vector<InputStreamItem*> _input_stream;
631 /** The parameters to appendText() are allowed to be a little bit
632 complex. This copies them to be the right length and starting at zero.
633 We also don't want to write five bits of identical code just with
634 different variable names. */
635 static void _copyInputVector(std::vector<SVGLength> const &input_vector, unsigned input_offset, std::vector<SVGLength> *output_vector, size_t max_length);
637 /** There are a few cases where we have different sets of enums meaning
638 the same thing, eg Pango font styles vs. SPStyle font styles. These need
639 converting. */
640 static int _enum_converter(int input, EnumConversionItem const *conversion_table, unsigned conversion_table_size);
642 /** The overall block-progression of the whole flow. */
643 inline Direction _blockProgression() const
644 {return static_cast<InputStreamTextSource*>(_input_stream.front())->styleGetBlockProgression();}
646 /** so that LEFT_TO_RIGHT == RIGHT_TO_LEFT but != TOP_TO_BOTTOM */
647 static bool _directions_are_orthogonal(Direction d1, Direction d2);
649 /** If the output is empty callers still want to be able to call
650 queryCursorShape() and get a valid answer so, while #_input_wrap_shapes
651 can still be considered valid, we need to precompute the cursor shape
652 for this case. */
653 void _calculateCursorShapeForEmpty();
655 struct CursorShape {
656 Geom::Point position;
657 double height;
658 double rotation;
659 } _empty_cursor_shape;
661 // ******************* input shapes
663 struct InputWrapShape {
664 Shape const *shape; /// as passed to Layout::appendWrapShape()
665 DisplayAlign display_align; /// as passed to Layout::appendWrapShape()
666 };
667 std::vector<InputWrapShape> _input_wrap_shapes;
669 // ******************* output
671 /** as passed to fitToPathAlign() */
672 Path const *_path_fitted;
674 struct Glyph;
675 struct Character;
676 struct Span;
677 struct Chunk;
678 struct Line;
679 struct Paragraph;
681 struct Glyph {
682 int glyph;
683 unsigned in_character;
684 float x; /// relative to the start of the chunk
685 float y; /// relative to the current line's baseline
686 float rotation; /// absolute, modulo any object transforms, which we don't know about
687 float width;
688 inline Span const & span(Layout const *l) const {return l->_spans[l->_characters[in_character].in_span];}
689 inline Chunk const & chunk(Layout const *l) const {return l->_chunks[l->_spans[l->_characters[in_character].in_span].in_chunk];}
690 inline Line const & line(Layout const *l) const {return l->_lines[l->_chunks[l->_spans[l->_characters[in_character].in_span].in_chunk].in_line];}
691 };
692 struct Character {
693 unsigned in_span;
694 float x; /// relative to the start of the *span* (so we can do block-progression)
695 PangoLogAttr char_attributes;
696 int in_glyph; /// will be -1 if this character has no visual representation
697 inline Span const & span(Layout const *l) const {return l->_spans[in_span];}
698 inline Chunk const & chunk(Layout const *l) const {return l->_chunks[l->_spans[in_span].in_chunk];}
699 inline Line const & line(Layout const *l) const {return l->_lines[l->_chunks[l->_spans[in_span].in_chunk].in_line];}
700 inline Paragraph const & paragraph(Layout const *l) const {return l->_paragraphs[l->_lines[l->_chunks[l->_spans[in_span].in_chunk].in_line].in_paragraph];}
701 // to get the advance width of a character, subtract the x values if it's in the middle of a span, or use span.x_end if it's at the end
702 };
703 struct Span {
704 unsigned in_chunk;
705 font_instance *font;
706 float font_size;
707 float x_start; /// relative to the start of the chunk
708 float x_end; /// relative to the start of the chunk
709 LineHeight line_height;
710 double baseline_shift; /// relative to the line's baseline
711 Direction direction; /// See CSS3 section 3.2. Either rtl or ltr
712 Direction block_progression; /// See CSS3 section 3.2. The direction in which lines go.
713 unsigned in_input_stream_item;
714 Glib::ustring::const_iterator input_stream_first_character;
715 inline Chunk const & chunk(Layout const *l) const {return l->_chunks[in_chunk];}
716 inline Line const & line(Layout const *l) const {return l->_lines[l->_chunks[in_chunk].in_line];}
717 inline Paragraph const & paragraph(Layout const *l) const {return l->_paragraphs[l->_lines[l->_chunks[in_chunk].in_line].in_paragraph];}
718 };
719 struct Chunk {
720 unsigned in_line;
721 double left_x;
722 };
723 struct Line {
724 unsigned in_paragraph;
725 double baseline_y;
726 unsigned in_shape;
727 };
728 struct Paragraph {
729 Direction base_direction; /// can be overridden by child Span objects
730 Alignment alignment;
731 };
732 std::vector<Paragraph> _paragraphs;
733 std::vector<Line> _lines;
734 std::vector<Chunk> _chunks;
735 std::vector<Span> _spans;
736 std::vector<Character> _characters;
737 std::vector<Glyph> _glyphs;
739 /** gets the overall matrix that transforms the given glyph from local
740 space to world space. */
741 void _getGlyphTransformMatrix(int glyph_index, Geom::Matrix *matrix) const;
743 // loads of functions to drill down the object tree, all of them
744 // annoyingly similar and all of them requiring predicate functors.
745 // I'll be buggered if I can find a way to make it work with
746 // functions or with a templated functor, so macros it is.
747 #define EMIT_PREDICATE(name, object_type, index_generator) \
748 class name { \
749 Layout const * const _flow; \
750 public: \
751 inline name(Layout const *flow) : _flow(flow) {} \
752 inline bool operator()(object_type const &object, unsigned index) \
753 {return index_generator < index;} \
754 }
755 // end of macro
756 EMIT_PREDICATE(PredicateLineToSpan, Span, _flow->_chunks[object.in_chunk].in_line);
757 EMIT_PREDICATE(PredicateLineToCharacter, Character, _flow->_chunks[_flow->_spans[object.in_span].in_chunk].in_line);
758 EMIT_PREDICATE(PredicateSpanToCharacter, Character, object.in_span);
759 EMIT_PREDICATE(PredicateSourceToCharacter, Character, _flow->_spans[object.in_span].in_input_stream_item);
761 inline unsigned _lineToSpan(unsigned line_index) const
762 {return std::lower_bound(_spans.begin(), _spans.end(), line_index, PredicateLineToSpan(this)) - _spans.begin();}
763 inline unsigned _lineToCharacter(unsigned line_index) const
764 {return std::lower_bound(_characters.begin(), _characters.end(), line_index, PredicateLineToCharacter(this)) - _characters.begin();}
765 inline unsigned _spanToCharacter(unsigned span_index) const
766 {return std::lower_bound(_characters.begin(), _characters.end(), span_index, PredicateSpanToCharacter(this)) - _characters.begin();}
767 inline unsigned _sourceToCharacter(unsigned source_index) const
768 {return std::lower_bound(_characters.begin(), _characters.end(), source_index, PredicateSourceToCharacter(this)) - _characters.begin();}
770 /** given an x coordinate and a line number, returns an iterator
771 pointing to the closest cursor position on that line to the
772 coordinate. */
773 iterator _cursorXOnLineToIterator(unsigned line_index, double local_x) const;
775 /** calculates the width of a chunk, which is the largest x
776 coordinate (start or end) of the spans contained within it. */
777 double _getChunkWidth(unsigned chunk_index) const;
778 };
780 /** \brief Holds a position within the glyph output of Layout.
782 Used to access the output of a Layout, query information and generally
783 move around in it. See Layout for a glossary of the names of functions.
785 I'm not going to document all the methods because most of their names make
786 their function self-evident.
788 A lot of the functions would do the same thing in a naive implementation
789 for latin-only text, for example nextCharacter(), nextCursorPosition() and
790 cursorRight(). Generally it's fairly obvious which one you should use in a
791 given situation, but sometimes you might need to put some thought in to it.
793 All the methods return false if the requested action would have caused the
794 current position to move out of bounds. In this case the position is moved
795 to either begin() or end(), depending on which direction you were going.
797 Note that some characters do not have a glyph representation (eg line
798 breaks), so if you try using prev/nextGlyph() from one of these you're
799 heading for a crash.
800 */
801 class Layout::iterator {
802 public:
803 friend class Layout;
804 // this is just so you can create uninitialised iterators - don't actually try to use one
805 iterator() : _parent_layout(NULL) {}
806 // no copy constructor required, the default does what we want
807 bool operator== (iterator const &other) const
808 {return _glyph_index == other._glyph_index && _char_index == other._char_index;}
809 bool operator!= (iterator const &other) const
810 {return _glyph_index != other._glyph_index || _char_index != other._char_index;}
812 /* mustn't compare _glyph_index in these operators because for characters
813 that don't have glyphs (line breaks, elided soft hyphens, etc), the glyph
814 index is -1 which makes them not well-ordered. To be honest, interating by
815 glyphs is not very useful and should be avoided. */
816 bool operator< (iterator const &other) const
817 {return _char_index < other._char_index;}
818 bool operator<= (iterator const &other) const
819 {return _char_index <= other._char_index;}
820 bool operator> (iterator const &other) const
821 {return _char_index > other._char_index;}
822 bool operator>= (iterator const &other) const
823 {return _char_index >= other._char_index;}
825 /* **** visual-oriented methods **** */
827 //glyphs
828 inline bool prevGlyph();
829 inline bool nextGlyph();
831 //span
832 bool prevStartOfSpan();
833 bool thisStartOfSpan();
834 bool nextStartOfSpan();
836 //chunk
837 bool prevStartOfChunk();
838 bool thisStartOfChunk();
839 bool nextStartOfChunk();
841 //line
842 bool prevStartOfLine();
843 bool thisStartOfLine();
844 bool nextStartOfLine();
845 bool thisEndOfLine();
847 //shape
848 bool prevStartOfShape();
849 bool thisStartOfShape();
850 bool nextStartOfShape();
852 /* **** text-oriented methods **** */
854 //characters
855 inline bool nextCharacter();
856 inline bool prevCharacter();
858 bool nextCursorPosition();
859 bool prevCursorPosition();
860 bool nextLineCursor(int n = 1);
861 bool prevLineCursor(int n = 1);
863 //words
864 bool nextStartOfWord();
865 bool prevStartOfWord();
866 bool nextEndOfWord();
867 bool prevEndOfWord();
869 //sentences
870 bool nextStartOfSentence();
871 bool prevStartOfSentence();
872 bool nextEndOfSentence();
873 bool prevEndOfSentence();
875 //paragraphs
876 bool prevStartOfParagraph();
877 bool thisStartOfParagraph();
878 bool nextStartOfParagraph();
879 //no endOfPara methods because that's just the previous char
881 //sources
882 bool prevStartOfSource();
883 bool thisStartOfSource();
884 bool nextStartOfSource();
886 //logical cursor movement
887 bool cursorUp(int n = 1);
888 bool cursorDown(int n = 1);
889 bool cursorLeft();
890 bool cursorRight();
892 //logical cursor movement (by word or paragraph)
893 bool cursorUpWithControl();
894 bool cursorDownWithControl();
895 bool cursorLeftWithControl();
896 bool cursorRightWithControl();
898 private:
899 Layout const *_parent_layout;
900 int _glyph_index; /// index into Layout::glyphs, or -1
901 unsigned _char_index; /// index into Layout::character
902 bool _cursor_moving_vertically;
903 /** for cursor up/down movement we must maintain the x position where
904 we started so the cursor doesn't 'drift' left or right with the repeated
905 quantization to character boundaries. */
906 double _x_coordinate;
908 inline iterator(Layout const *p, unsigned c, int g)
909 : _parent_layout(p), _glyph_index(g), _char_index(c), _cursor_moving_vertically(false), _x_coordinate(0.0) {}
910 inline iterator(Layout const *p, unsigned c)
911 : _parent_layout(p), _glyph_index(p->_characters[c].in_glyph), _char_index(c), _cursor_moving_vertically(false), _x_coordinate(0.0) {}
912 // no dtor required
913 void beginCursorUpDown(); /// stores the current x coordinate so that the cursor won't drift. See #_x_coordinate
915 /** moves forward or backwards one cursor position according to the
916 directionality of the current paragraph, but ignoring block progression.
917 Helper for the cursor*() functions. */
918 bool _cursorLeftOrRightLocalX(Direction direction);
920 /** moves forward or backwards by until the next character with
921 is_word_start according to the directionality of the current paragraph,
922 but ignoring block progression. Helper for the cursor*WithControl()
923 functions. */
924 bool _cursorLeftOrRightLocalXByWord(Direction direction);
925 };
927 // ************************** inline methods
929 inline SPCurve* Layout::convertToCurves() const
930 {return convertToCurves(begin(), end());}
932 inline Layout::iterator Layout::begin() const
933 {return iterator(this, 0, 0);}
935 inline Layout::iterator Layout::end() const
936 {return iterator(this, _characters.size(), _glyphs.size());}
938 inline Layout::iterator Layout::charIndexToIterator(int char_index) const
939 {
940 if (char_index < 0) return begin();
941 if (char_index >= (int)_characters.size()) return end();
942 return iterator(this, char_index);
943 }
945 inline int Layout::iteratorToCharIndex(Layout::iterator const &it) const
946 {return it._char_index;}
948 inline void Layout::validateIterator(Layout::iterator *it) const
949 {
950 it->_parent_layout = this;
951 if (it->_char_index >= _characters.size()) {
952 it->_char_index = _characters.size();
953 it->_glyph_index = _glyphs.size();
954 } else
955 it->_glyph_index = _characters[it->_char_index].in_glyph;
956 }
958 inline Layout::iterator Layout::getNearestCursorPositionTo(Geom::Point const &point) const
959 {return getNearestCursorPositionTo(point[0], point[1]);}
961 inline Layout::iterator Layout::getLetterAt(Geom::Point &point) const
962 {return getLetterAt(point[0], point[1]);}
964 inline unsigned Layout::lineIndex(iterator const &it) const
965 {return it._char_index == _characters.size() ? _lines.size() - 1 : _characters[it._char_index].chunk(this).in_line;}
967 inline unsigned Layout::shapeIndex(iterator const &it) const
968 {return it._char_index == _characters.size() ? _input_wrap_shapes.size() - 1 : _characters[it._char_index].line(this).in_shape;}
970 inline bool Layout::isWhitespace(iterator const &it) const
971 {return it._char_index == _characters.size() || _characters[it._char_index].char_attributes.is_white;}
973 inline int Layout::characterAt(iterator const &it) const
974 {
975 void *unused;
976 Glib::ustring::iterator text_iter;
977 getSourceOfCharacter(it, &unused, &text_iter);
978 return *text_iter;
979 }
981 inline bool Layout::isCursorPosition(iterator const &it) const
982 {return it._char_index == _characters.size() || _characters[it._char_index].char_attributes.is_cursor_position;}
984 inline bool Layout::isStartOfWord(iterator const &it) const
985 {return it._char_index != _characters.size() && _characters[it._char_index].char_attributes.is_word_start;}
987 inline bool Layout::isEndOfWord(iterator const &it) const
988 {return it._char_index == _characters.size() || _characters[it._char_index].char_attributes.is_word_end;}
990 inline bool Layout::isStartOfSentence(iterator const &it) const
991 {return it._char_index != _characters.size() && _characters[it._char_index].char_attributes.is_sentence_start;}
993 inline bool Layout::isEndOfSentence(iterator const &it) const
994 {return it._char_index == _characters.size() || _characters[it._char_index].char_attributes.is_sentence_end;}
996 inline unsigned Layout::paragraphIndex(iterator const &it) const
997 {return it._char_index == _characters.size() ? _paragraphs.size() - 1 : _characters[it._char_index].line(this).in_paragraph;}
999 inline Layout::Alignment Layout::paragraphAlignment(iterator const &it) const
1000 {return _paragraphs[paragraphIndex(it)].alignment;}
1002 inline bool Layout::iterator::nextGlyph()
1003 {
1004 _cursor_moving_vertically = false;
1005 if (_glyph_index >= (int)_parent_layout->_glyphs.size() - 1) {
1006 if (_glyph_index == (int)_parent_layout->_glyphs.size()) return false;
1007 _char_index = _parent_layout->_characters.size();
1008 _glyph_index = _parent_layout->_glyphs.size();
1009 }
1010 else _char_index = _parent_layout->_glyphs[++_glyph_index].in_character;
1011 return true;
1012 }
1014 inline bool Layout::iterator::prevGlyph()
1015 {
1016 _cursor_moving_vertically = false;
1017 if (_glyph_index == 0) return false;
1018 _char_index = _parent_layout->_glyphs[--_glyph_index].in_character;
1019 return true;
1020 }
1022 inline bool Layout::iterator::nextCharacter()
1023 {
1024 _cursor_moving_vertically = false;
1025 if (_char_index + 1 >= _parent_layout->_characters.size()) {
1026 if (_char_index == _parent_layout->_characters.size()) return false;
1027 _char_index = _parent_layout->_characters.size();
1028 _glyph_index = _parent_layout->_glyphs.size();
1029 }
1030 else _glyph_index = _parent_layout->_characters[++_char_index].in_glyph;
1031 return true;
1032 }
1034 inline bool Layout::iterator::prevCharacter()
1035 {
1036 _cursor_moving_vertically = false;
1037 if (_char_index == 0) return false;
1038 _glyph_index = _parent_layout->_characters[--_char_index].in_glyph;
1039 return true;
1040 }
1042 }//namespace Text
1043 }//namespace Inkscape
1045 #endif
1048 /*
1049 Local Variables:
1050 mode:c++
1051 c-file-style:"stroustrup"
1052 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1053 indent-tabs-mode:nil
1054 fill-column:99
1055 End:
1056 */
1057 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :