1 /****************************************************************************
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtGui module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #ifndef QTEXTENGINE_P_H
43 #define QTEXTENGINE_P_H
49 // This file is not part of the Qt API. It exists for the convenience
50 // of other Qt classes. This header file may change from version to
51 // version without notice, or even be removed.
56 #include "QtCore/qglobal.h"
57 #include "QtCore/qstring.h"
58 #include "QtCore/qvarlengtharray.h"
59 #include "QtCore/qnamespace.h"
60 #include "QtGui/qtextlayout.h"
61 #include "private/qtextformat_p.h"
62 #include "private/qfont_p.h"
63 #include "QtCore/qvector.h"
64 #include "QtGui/qpaintengine.h"
65 #include "QtGui/qtextobject.h"
66 #include "QtGui/qtextoption.h"
67 #include "QtGui/qtextcursor.h"
68 #include "QtCore/qset.h"
69 #include "QtCore/qdebug.h"
70 #ifndef QT_BUILD_COMPAT_LIB
71 #include "private/qtextdocument_p.h"
74 #include "private/qharfbuzz_copy_p.h"
76 #include "private/qfixed_p.h"
88 class QAbstractTextDocumentLayout;
91 // this uses the same coordinate system as Qt, but a different one to freetype.
92 // * y is usually negative, and is equal to the ascent.
93 // * negative yoff means the following stuff is drawn higher up.
94 // the characters bounding rect is given by QRect(x,y,width,height), its advance by
96 struct Q_GUI_EXPORT glyph_metrics_t
98 inline glyph_metrics_t()
99 : x(100000), y(100000) {}
100 inline glyph_metrics_t(QFixed _x, QFixed _y, QFixed _width, QFixed _height, QFixed _xoff, QFixed _yoff)
115 glyph_metrics_t transformed(const QTransform &xform) const;
116 inline bool isValid() const {return x != 100000 && y != 100000;}
118 Q_DECLARE_TYPEINFO(glyph_metrics_t, Q_PRIMITIVE_TYPE);
120 struct Q_AUTOTEST_EXPORT QScriptAnalysis
127 LineOrParagraphSeparator = 4,
129 SpaceTabOrObject = Space,
134 unsigned short script : 7;
135 unsigned short bidiLevel : 6; // Unicode Bidi algorithm embedding level (0-61)
136 unsigned short flags : 3;
137 inline bool operator == (const QScriptAnalysis &other) const {
138 return script == other.script && bidiLevel == other.bidiLevel && flags == other.flags;
141 Q_DECLARE_TYPEINFO(QScriptAnalysis, Q_PRIMITIVE_TYPE);
143 struct QGlyphJustification
145 inline QGlyphJustification()
146 : type(0), nKashidas(0), space_18d6(0)
149 enum JustificationType {
156 uint nKashidas : 6; // more do not make sense...
157 uint space_18d6 : 24;
159 Q_DECLARE_TYPEINFO(QGlyphJustification, Q_PRIMITIVE_TYPE);
161 struct QGlyphLayoutInstance
166 QGlyphJustification justification;
167 HB_GlyphAttributes attributes;
172 // init to 0 not needed, done when shaping
173 QFixedPoint *offsets; // 8 bytes per element
174 HB_Glyph *glyphs; // 4 bytes per element
175 QFixed *advances_x; // 4 bytes per element
176 QFixed *advances_y; // 4 bytes per element
177 QGlyphJustification *justifications; // 4 bytes per element
178 HB_GlyphAttributes *attributes; // 2 bytes per element
182 inline QGlyphLayout() : numGlyphs(0) {}
184 inline explicit QGlyphLayout(char *address, int totalGlyphs)
186 offsets = reinterpret_cast<QFixedPoint *>(address);
187 int offset = totalGlyphs * sizeof(HB_FixedPoint);
188 glyphs = reinterpret_cast<HB_Glyph *>(address + offset);
189 offset += totalGlyphs * sizeof(HB_Glyph);
190 advances_x = reinterpret_cast<QFixed *>(address + offset);
191 offset += totalGlyphs * sizeof(QFixed);
192 advances_y = reinterpret_cast<QFixed *>(address + offset);
193 offset += totalGlyphs * sizeof(QFixed);
194 justifications = reinterpret_cast<QGlyphJustification *>(address + offset);
195 offset += totalGlyphs * sizeof(QGlyphJustification);
196 attributes = reinterpret_cast<HB_GlyphAttributes *>(address + offset);
197 numGlyphs = totalGlyphs;
200 inline QGlyphLayout mid(int position, int n = -1) const {
201 QGlyphLayout copy = *this;
202 copy.glyphs += position;
203 copy.advances_x += position;
204 copy.advances_y += position;
205 copy.offsets += position;
206 copy.justifications += position;
207 copy.attributes += position;
209 copy.numGlyphs -= position;
215 static inline int spaceNeededForGlyphLayout(int totalGlyphs) {
216 return totalGlyphs * (sizeof(HB_Glyph) + sizeof(HB_GlyphAttributes)
217 + sizeof(QFixed) + sizeof(QFixed) + sizeof(QFixedPoint)
218 + sizeof(QGlyphJustification));
221 inline QFixed effectiveAdvance(int item) const
222 { return (advances_x[item] + QFixed::fromFixed(justifications[item].space_18d6)) * !attributes[item].dontPrint; }
224 inline QGlyphLayoutInstance instance(int position) const {
225 QGlyphLayoutInstance g;
226 g.offset.x = offsets[position].x;
227 g.offset.y = offsets[position].y;
228 g.glyph = glyphs[position];
229 g.advance.x = advances_x[position];
230 g.advance.y = advances_y[position];
231 g.justification = justifications[position];
232 g.attributes = attributes[position];
236 inline void setInstance(int position, const QGlyphLayoutInstance &g) {
237 offsets[position].x = g.offset.x;
238 offsets[position].y = g.offset.y;
239 glyphs[position] = g.glyph;
240 advances_x[position] = g.advance.x;
241 advances_y[position] = g.advance.y;
242 justifications[position] = g.justification;
243 attributes[position] = g.attributes;
246 inline void clear(int first = 0, int last = -1) {
249 if (first == 0 && last == numGlyphs
250 && reinterpret_cast<char *>(offsets + numGlyphs) == reinterpret_cast<char *>(glyphs)) {
251 memset(offsets, 0, spaceNeededForGlyphLayout(numGlyphs));
253 const int num = last - first;
254 memset(offsets + first, 0, num * sizeof(QFixedPoint));
255 memset(glyphs + first, 0, num * sizeof(HB_Glyph));
256 memset(advances_x + first, 0, num * sizeof(QFixed));
257 memset(advances_y + first, 0, num * sizeof(QFixed));
258 memset(justifications + first, 0, num * sizeof(QGlyphJustification));
259 memset(attributes + first, 0, num * sizeof(HB_GlyphAttributes));
263 inline char *data() {
264 return reinterpret_cast<char *>(offsets);
267 void grow(char *address, int totalGlyphs);
270 class QVarLengthGlyphLayoutArray : private QVarLengthArray<void *>, public QGlyphLayout
273 typedef QVarLengthArray<void *> Array;
275 QVarLengthGlyphLayoutArray(int totalGlyphs)
276 : Array(spaceNeededForGlyphLayout(totalGlyphs) / sizeof(void *) + 1)
277 , QGlyphLayout(reinterpret_cast<char *>(Array::data()), totalGlyphs)
279 memset(Array::data(), 0, Array::size() * sizeof(void *));
282 void resize(int totalGlyphs)
284 Array::resize(spaceNeededForGlyphLayout(totalGlyphs) / sizeof(void *) + 1);
286 *((QGlyphLayout *)this) = QGlyphLayout(reinterpret_cast<char *>(Array::data()), totalGlyphs);
287 memset(Array::data(), 0, Array::size() * sizeof(void *));
291 template <int N> struct QGlyphLayoutArray : public QGlyphLayout
295 : QGlyphLayout(reinterpret_cast<char *>(buffer), N)
297 memset(buffer, 0, sizeof(buffer));
301 void *buffer[(N * (sizeof(HB_Glyph) + sizeof(HB_GlyphAttributes)
302 + sizeof(QFixed) + sizeof(QFixed) + sizeof(QFixedPoint)
303 + sizeof(QGlyphJustification)))
304 / sizeof(void *) + 1];
308 /// Internal QTextItem
309 class QTextItemInt : public QTextItem
312 inline QTextItemInt()
313 : justified(false), underlineStyle(QTextCharFormat::NoUnderline), num_chars(0), chars(0),
314 logClusters(0), f(0), fontEngine(0)
316 QTextItemInt(const QScriptItem &si, QFont *font, const QTextCharFormat &format = QTextCharFormat());
317 QTextItemInt(const QGlyphLayout &g, QFont *font, const QChar *chars, int numChars, QFontEngine *fe,
318 const QTextCharFormat &format = QTextCharFormat());
320 /// copy the structure items, adjusting the glyphs arrays to the right subarrays.
321 /// the width of the returned QTextItemInt is not adjusted, for speed reasons
322 QTextItemInt midItem(QFontEngine *fontEngine, int firstGlyphIndex, int numGlyphs) const;
323 void initWithScriptItem(const QScriptItem &si);
331 QTextCharFormat::UnderlineStyle underlineStyle;
332 const QTextCharFormat charFormat;
335 const unsigned short *logClusters;
339 QFontEngine *fontEngine;
342 inline bool qIsControlChar(ushort uc)
344 return uc >= 0x200b && uc <= 0x206f
345 && (uc <= 0x200f /* ZW Space, ZWNJ, ZWJ, LRM and RLM */
346 || (uc >= 0x2028 && uc <= 0x202f /* LS, PS, LRE, RLE, PDF, LRO, RLO, NNBSP */)
347 || uc >= 0x206a /* ISS, ASS, IAFS, AFS, NADS, NODS */);
350 struct Q_AUTOTEST_EXPORT QScriptItem
354 num_glyphs(0), descent(-1), ascent(-1), leading(-1), width(-1),
355 glyph_data_offset(0) {}
356 inline QScriptItem(int p, const QScriptAnalysis &a)
357 : position(p), analysis(a),
358 num_glyphs(0), descent(-1), ascent(-1), leading(-1), width(-1),
359 glyph_data_offset(0) {}
362 QScriptAnalysis analysis;
363 unsigned short num_glyphs;
368 int glyph_data_offset;
369 QFixed height() const { return ascent + descent + 1; }
373 Q_DECLARE_TYPEINFO(QScriptItem, Q_MOVABLE_TYPE);
375 typedef QVector<QScriptItem> QScriptItemArray;
377 struct Q_AUTOTEST_EXPORT QScriptLine
379 // created and filled in QTextLine::layout_helper
381 : from(0), trailingSpaces(0), length(0),
382 justified(0), gridfitted(0),
383 hasTrailingSpaces(0), leadingIncluded(0) {}
393 unsigned short trailingSpaces;
394 signed int length : 28;
395 mutable uint justified : 1;
396 mutable uint gridfitted : 1;
397 uint hasTrailingSpaces : 1;
398 uint leadingIncluded : 1;
399 QFixed height() const { return (ascent + descent).ceil() + 1
400 + (leadingIncluded? qMax(QFixed(),leading) : QFixed()); }
401 QFixed base() const { return ascent
402 + (leadingIncluded ? qMax(QFixed(),leading) : QFixed()); }
403 void setDefaultHeight(QTextEngine *eng);
404 void operator+=(const QScriptLine &other);
406 Q_DECLARE_TYPEINFO(QScriptLine, Q_PRIMITIVE_TYPE);
409 inline void QScriptLine::operator+=(const QScriptLine &other)
411 leading= qMax(leading + ascent, other.leading + other.ascent) - qMax(ascent, other.ascent);
412 descent = qMax(descent, other.descent);
413 ascent = qMax(ascent, other.ascent);
414 textWidth += other.textWidth;
415 length += other.length;
418 typedef QVector<QScriptLine> QScriptLineArray;
421 class QTextFormatCollection;
423 class Q_GUI_EXPORT QTextEngine {
430 struct Q_GUI_EXPORT LayoutData {
431 LayoutData(const QString &str, void **stack_memory, int mem_size);
434 mutable QScriptItemArray items;
436 int available_glyphs;
438 unsigned short *logClustersPtr;
439 QGlyphLayout glyphLayout;
442 uint layoutState : 2;
443 uint memory_on_stack : 1;
444 uint haveCharAttributes : 1;
446 bool reallocate(int totalGlyphs);
449 QTextEngine(LayoutData *data);
451 QTextEngine(const QString &str, const QFont &f);
458 // keep in sync with QAbstractFontEngine::TextShapingFlag!!
460 RightToLeft = 0x0001,
461 DesignMetrics = 0x0002,
462 GlyphIndicesOnly = 0x0004
464 Q_DECLARE_FLAGS(ShaperFlags, ShaperFlag)
467 void clearLineData();
469 void validate() const;
470 void itemize() const;
472 bool isRightToLeft() const;
473 static void bidiReorder(int numRuns, const quint8 *levels, int *visualOrder);
475 const HB_CharAttributes *attributes() const;
477 void shape(int item) const;
479 void justify(const QScriptLine &si);
480 QFixed alignLine(const QScriptLine &line);
482 QFixed width(int charFrom, int numChars) const;
483 glyph_metrics_t boundingBox(int from, int len) const;
484 glyph_metrics_t tightBoundingBox(int from, int len) const;
486 int length(int item) const {
487 const QScriptItem &si = layoutData->items[item];
488 int from = si.position;
490 return (item < layoutData->items.size() ? layoutData->items[item].position : layoutData->string.length()) - from;
492 int length(const QScriptItem *si) const {
494 if (si + 1 < layoutData->items.constData()+ layoutData->items.size())
495 end = (si+1)->position;
497 end = layoutData->string.length();
498 return end - si->position;
501 QFontEngine *fontEngine(const QScriptItem &si, QFixed *ascent = 0, QFixed *descent = 0, QFixed *leading = 0) const;
502 QFont font(const QScriptItem &si) const;
503 inline QFont font() const { return fnt; }
506 * Returns a pointer to an array of log clusters, offset at the script item.
507 * Each item in the array is a unsigned short. For each character in the original string there is an entry in the table
508 * so there is a one to one correlation in indexes between the original text and the index in the logcluster.
509 * The value of each item is the position in the glyphs array. Multiple similar pointers in the logclusters array imply
510 * that one glyph is used for more than one character.
513 inline unsigned short *logClusters(const QScriptItem *si) const
514 { return layoutData->logClustersPtr+si->position; }
516 * Returns an array of QGlyphLayout items, offset at the script item.
517 * Each item in the array matches one glyph in the text, storing the advance, position etc.
518 * The returned item's length equals to the number of available glyphs. This may be more
519 * than what was actually shaped.
522 inline QGlyphLayout availableGlyphs(const QScriptItem *si) const {
523 return layoutData->glyphLayout.mid(si->glyph_data_offset);
526 * Returns an array of QGlyphLayout items, offset at the script item.
527 * Each item in the array matches one glyph in the text, storing the advance, position etc.
528 * The returned item's length equals to the number of shaped glyphs.
531 inline QGlyphLayout shapedGlyphs(const QScriptItem *si) const {
532 return layoutData->glyphLayout.mid(si->glyph_data_offset, si->num_glyphs);
535 inline bool ensureSpace(int nGlyphs) const {
536 if (layoutData->glyphLayout.numGlyphs - layoutData->used < nGlyphs)
537 return layoutData->reallocate((((layoutData->used + nGlyphs)*3/2 + 15) >> 4) << 4);
543 int findItem(int strPos) const;
544 inline QTextFormatCollection *formats() const {
545 #ifdef QT_BUILD_COMPAT_LIB
546 return 0; // Compat should never reference this symbol
548 return block.docHandle()->formatCollection();
551 QTextCharFormat format(const QScriptItem *si) const;
552 inline QAbstractTextDocumentLayout *docLayout() const {
553 #ifdef QT_BUILD_COMPAT_LIB
554 return 0; // Compat should never reference this symbol
556 return block.docHandle()->document()->documentLayout();
559 int formatIndex(const QScriptItem *si) const;
561 /// returns the width of tab at index (in the tabs array) with the tab-start at position x
562 QFixed calculateTabWidth(int index, QFixed x) const;
564 mutable QScriptLineArray lines;
566 struct FontEngineCache {
568 mutable QFontEngine *prevFontEngine;
569 mutable QFontEngine *prevScaledFontEngine;
570 mutable int prevScript;
571 mutable int prevPosition;
572 mutable int prevLength;
573 inline void reset() {
575 prevScaledFontEngine = 0;
581 mutable FontEngineCache feCache;
593 uint cacheGlyphs : 1;
594 uint stackEngine : 1;
595 uint forceJustification : 1;
596 uint visualMovement : 1;
598 int *underlinePositions;
600 mutable LayoutData *layoutData;
602 inline bool hasFormats() const { return (block.docHandle() || specialData); }
603 inline bool visualCursorMovement() const
605 return (visualMovement ||
606 (block.docHandle() ? block.docHandle()->defaultCursorMoveStyle == Qt::VisualMoveStyle : false));
612 QList<QTextLayout::FormatRange> addFormats;
613 QVector<int> addFormatIndices;
614 QVector<int> resolvedFormatIndices;
616 SpecialData *specialData;
618 bool atWordSeparator(int position) const;
619 bool atSpace(int position) const;
620 void indexAdditionalFormats();
622 QString elidedText(Qt::TextElideMode mode, const QFixed &width, int flags = 0) const;
624 void shapeLine(const QScriptLine &line);
625 QFixed leadingSpaceWidth(const QScriptLine &line);
627 QFixed offsetInLigature(const QScriptItem *si, int pos, int max, int glyph_pos);
628 int positionInLigature(const QScriptItem *si, int end, QFixed x, QFixed edge, int glyph_pos, bool cursorOnCharacter);
629 int previousLogicalPosition(int oldPos) const;
630 int nextLogicalPosition(int oldPos) const;
631 int lineNumberForTextPosition(int pos);
632 int positionAfterVisualMovement(int oldPos, QTextCursor::MoveOperation op);
633 void insertionPointsForLine(int lineNum, QVector<int> &insertionPoints);
636 void setBoundary(int strPos) const;
637 void addRequiredBoundaries() const;
638 void shapeText(int item) const;
639 void shapeTextWithHarfbuzz(int item) const;
640 #if defined(Q_WS_WINCE)
641 void shapeTextWithCE(int item) const;
643 #if defined(Q_WS_MAC)
644 void shapeTextMac(int item) const;
646 void splitItem(int item, int pos) const;
648 void resolveAdditionalFormats() const;
649 int endOfLine(int lineNum);
650 int beginningOfLine(int lineNum);
651 int getClusterLength(unsigned short *logClusters, const HB_CharAttributes *attributes, int from, int to, int glyph_pos, int *start);
654 class Q_GUI_EXPORT QStackTextEngine : public QTextEngine {
656 enum { MemSize = 256*40/sizeof(void *) };
657 QStackTextEngine(const QString &string, const QFont &f);
658 LayoutData _layoutData;
659 void *_memory[MemSize];
662 struct QTextLineItemIterator
664 QTextLineItemIterator(QTextEngine *eng, int lineNum, const QPointF &pos = QPointF(),
665 const QTextLayout::FormatRange *_selection = 0);
667 inline bool atEnd() const { return logicalItem >= nItems - 1; }
668 inline bool atBeginning() const { return logicalItem <= 0; }
671 bool getSelectionBounds(QFixed *selectionX, QFixed *selectionWidth) const;
672 inline bool isOutsideSelection() const {
674 return !getSelectionBounds(&tmp1, &tmp2);
681 const QScriptLine &line;
700 QVarLengthArray<int> visualOrder;
701 QVarLengthArray<uchar> levels;
703 const QTextLayout::FormatRange *selection;
706 Q_DECLARE_OPERATORS_FOR_FLAGS(QTextEngine::ShaperFlags)
710 #endif // QTEXTENGINE_P_H