Fix uses of qRound on non-floating-point types.
[profile/ivi/qtbase.git] / src / gui / text / qfontmetrics.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of the QtGui module of the Qt Toolkit.
8 **
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.
17 **
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.
21 **
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.
29 **
30 ** Other Usage
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.
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qfont.h"
43 #include "qpaintdevice.h"
44 #include "qfontmetrics.h"
45
46 #include "qfont_p.h"
47 #include "qfontengine_p.h"
48 #include <private/qunicodetables_p.h>
49
50 #include <math.h>
51
52 #ifdef Q_WS_X11
53 #include "qx11info_x11.h"
54 #endif
55
56 QT_BEGIN_NAMESPACE
57
58 #ifdef Q_WS_X11
59 extern const QX11Info *qt_x11Info(const QPaintDevice *pd);
60 #endif
61
62 extern void qt_format_text(const QFont& font, const QRectF &_r,
63                            int tf, const QString &text, QRectF *brect,
64                            int tabStops, int *tabArray, int tabArrayLen,
65                            QPainter *painter);
66
67 /*****************************************************************************
68   QFontMetrics member functions
69  *****************************************************************************/
70
71 /*!
72     \class QFontMetrics
73     \reentrant
74
75     \brief The QFontMetrics class provides font metrics information.
76
77     \ingroup painting
78     \ingroup shared
79
80     QFontMetrics functions calculate the size of characters and
81     strings for a given font. There are three ways you can create a
82     QFontMetrics object:
83
84     \list 1
85     \o Calling the QFontMetrics constructor with a QFont creates a
86     font metrics object for a screen-compatible font, i.e. the font
87     cannot be a printer font. If the font is changed
88     later, the font metrics object is \e not updated.
89
90     (Note: If you use a printer font the values returned may be
91     inaccurate. Printer fonts are not always accessible so the nearest
92     screen font is used if a printer font is supplied.)
93
94     \o QWidget::fontMetrics() returns the font metrics for a widget's
95     font. This is equivalent to QFontMetrics(widget->font()). If the
96     widget's font is changed later, the font metrics object is \e not
97     updated.
98
99     \o QPainter::fontMetrics() returns the font metrics for a
100     painter's current font. If the painter's font is changed later, the
101     font metrics object is \e not updated.
102     \endlist
103
104     Once created, the object provides functions to access the
105     individual metrics of the font, its characters, and for strings
106     rendered in the font.
107
108     There are several functions that operate on the font: ascent(),
109     descent(), height(), leading() and lineSpacing() return the basic
110     size properties of the font. The underlinePos(), overlinePos(),
111     strikeOutPos() and lineWidth() functions, return the properties of
112     the line that underlines, overlines or strikes out the
113     characters. These functions are all fast.
114
115     There are also some functions that operate on the set of glyphs in
116     the font: minLeftBearing(), minRightBearing() and maxWidth().
117     These are by necessity slow, and we recommend avoiding them if
118     possible.
119
120     For each character, you can get its width(), leftBearing() and
121     rightBearing() and find out whether it is in the font using
122     inFont(). You can also treat the character as a string, and use
123     the string functions on it.
124
125     The string functions include width(), to return the width of a
126     string in pixels (or points, for a printer), boundingRect(), to
127     return a rectangle large enough to contain the rendered string,
128     and size(), to return the size of that rectangle.
129
130     Example:
131     \snippet doc/src/snippets/code/src_gui_text_qfontmetrics.cpp 0
132
133     \sa QFont, QFontInfo, QFontDatabase, QFontComboBox, {Character Map Example}
134 */
135
136 /*!
137     \fn QRect QFontMetrics::boundingRect(int x, int y, int width, int height,
138         int flags, const QString &text, int tabStops, int *tabArray) const
139     \overload
140
141     Returns the bounding rectangle for the given \a text within the
142     rectangle specified by the \a x and \a y coordinates, \a width, and
143     \a height.
144
145     If Qt::TextExpandTabs is set in \a flags and \a tabArray is
146     non-null, it specifies a 0-terminated sequence of pixel-positions
147     for tabs; otherwise, if \a tabStops is non-zero, it is used as the
148     tab spacing (in pixels).
149 */
150
151 /*!
152     Constructs a font metrics object for \a font.
153
154     The font metrics will be compatible with the paintdevice used to
155     create \a font.
156
157     The font metrics object holds the information for the font that is
158     passed in the constructor at the time it is created, and is not
159     updated if the font's attributes are changed later.
160
161     Use QFontMetrics(const QFont &, QPaintDevice *) to get the font
162     metrics that are compatible with a certain paint device.
163 */
164 QFontMetrics::QFontMetrics(const QFont &font)
165     : d(font.d.data())
166 {
167 }
168
169 /*!
170     Constructs a font metrics object for \a font and \a paintdevice.
171
172     The font metrics will be compatible with the paintdevice passed.
173     If the \a paintdevice is 0, the metrics will be screen-compatible,
174     ie. the metrics you get if you use the font for drawing text on a
175     \link QWidget widgets\endlink or \link QPixmap pixmaps\endlink,
176     not on a QPicture or QPrinter.
177
178     The font metrics object holds the information for the font that is
179     passed in the constructor at the time it is created, and is not
180     updated if the font's attributes are changed later.
181 */
182 QFontMetrics::QFontMetrics(const QFont &font, QPaintDevice *paintdevice)
183 {
184     int dpi = paintdevice ? paintdevice->logicalDpiY() : qt_defaultDpi();
185 #ifdef Q_WS_X11
186     const QX11Info *info = qt_x11Info(paintdevice);
187     int screen = info ? info->screen() : 0;
188 #else
189     const int screen = 0;
190 #endif
191     if (font.d->dpi != dpi || font.d->screen != screen ) {
192         d = new QFontPrivate(*font.d);
193         d->dpi = dpi;
194         d->screen = screen;
195     } else {
196         d = font.d.data();
197     }
198
199 }
200
201 /*!
202     Constructs a copy of \a fm.
203 */
204 QFontMetrics::QFontMetrics(const QFontMetrics &fm)
205     : d(fm.d.data())
206 {
207 }
208
209 /*!
210     Destroys the font metrics object and frees all allocated
211     resources.
212 */
213 QFontMetrics::~QFontMetrics()
214 {
215 }
216
217 /*!
218     Assigns the font metrics \a fm.
219 */
220 QFontMetrics &QFontMetrics::operator=(const QFontMetrics &fm)
221 {
222     d = fm.d.data();
223     return *this;
224 }
225
226 /*!
227     \overload
228     Returns true if \a other is equal to this object; otherwise
229     returns false.
230
231     Two font metrics are considered equal if they were constructed
232     from the same QFont and the paint devices they were constructed
233     for are considered compatible.
234
235     \sa operator!=()
236 */
237 bool QFontMetrics::operator ==(const QFontMetrics &other) const
238 {
239     return d == other.d;
240 }
241
242 /*!
243     Returns true if \a other is equal to this object; otherwise
244     returns false.
245
246     Two font metrics are considered equal if they were constructed
247     from the same QFont and the paint devices they were constructed
248     for are considered compatible.
249
250     \sa operator!=()
251 */
252 bool QFontMetrics::operator ==(const QFontMetrics &other)
253 {
254     return d == other.d;
255 }
256
257 /*!
258     \fn bool QFontMetrics::operator!=(const QFontMetrics &other)
259
260     Returns true if \a other is not equal to this object; otherwise returns false.
261
262     Two font metrics are considered equal if they were constructed
263     from the same QFont and the paint devices they were constructed
264     for are considered compatible.
265
266     \sa operator==()
267 */
268
269 /*!
270     \fn bool QFontMetrics::operator !=(const QFontMetrics &other) const
271
272     Returns true if \a other is not equal to this object; otherwise returns false.
273
274     Two font metrics are considered equal if they were constructed
275     from the same QFont and the paint devices they were constructed
276     for are considered compatible.
277
278     \sa operator==()
279 */
280
281 /*!
282     Returns the ascent of the font.
283
284     The ascent of a font is the distance from the baseline to the
285     highest position characters extend to. In practice, some font
286     designers break this rule, e.g. when they put more than one accent
287     on top of a character, or to accommodate an unusual character in
288     an exotic language, so it is possible (though rare) that this
289     value will be too small.
290
291     \sa descent()
292 */
293 int QFontMetrics::ascent() const
294 {
295     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
296     Q_ASSERT(engine != 0);
297     return qRound(engine->ascent());
298 }
299
300
301 /*!
302     Returns the descent of the font.
303
304     The descent is the distance from the base line to the lowest point
305     characters extend to. In practice, some font designers break this rule,
306     e.g. to accommodate an unusual character in an exotic language, so
307     it is possible (though rare) that this value will be too small.
308
309     \sa ascent()
310 */
311 int QFontMetrics::descent() const
312 {
313     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
314     Q_ASSERT(engine != 0);
315     return qRound(engine->descent());
316 }
317
318 /*!
319     Returns the height of the font.
320
321     This is always equal to ascent()+descent()+1 (the 1 is for the
322     base line).
323
324     \sa leading(), lineSpacing()
325 */
326 int QFontMetrics::height() const
327 {
328     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
329     Q_ASSERT(engine != 0);
330     return qRound(engine->ascent()) + qRound(engine->descent()) + 1;
331 }
332
333 /*!
334     Returns the leading of the font.
335
336     This is the natural inter-line spacing.
337
338     \sa height(), lineSpacing()
339 */
340 int QFontMetrics::leading() const
341 {
342     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
343     Q_ASSERT(engine != 0);
344     return qRound(engine->leading());
345 }
346
347 /*!
348     Returns the distance from one base line to the next.
349
350     This value is always equal to leading()+height().
351
352     \sa height(), leading()
353 */
354 int QFontMetrics::lineSpacing() const
355 {
356     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
357     Q_ASSERT(engine != 0);
358     return qRound(engine->leading()) + qRound(engine->ascent()) + qRound(engine->descent()) + 1;
359 }
360
361 /*!
362     Returns the minimum left bearing of the font.
363
364     This is the smallest leftBearing(char) of all characters in the
365     font.
366
367     Note that this function can be very slow if the font is large.
368
369     \sa minRightBearing(), leftBearing()
370 */
371 int QFontMetrics::minLeftBearing() const
372 {
373     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
374     Q_ASSERT(engine != 0);
375     return qRound(engine->minLeftBearing());
376 }
377
378 /*!
379     Returns the minimum right bearing of the font.
380
381     This is the smallest rightBearing(char) of all characters in the
382     font.
383
384     Note that this function can be very slow if the font is large.
385
386     \sa minLeftBearing(), rightBearing()
387 */
388 int QFontMetrics::minRightBearing() const
389 {
390     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
391     Q_ASSERT(engine != 0);
392     return qRound(engine->minRightBearing());
393 }
394
395 /*!
396     Returns the width of the widest character in the font.
397 */
398 int QFontMetrics::maxWidth() const
399 {
400     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
401     Q_ASSERT(engine != 0);
402     return qRound(engine->maxCharWidth());
403 }
404
405 /*!
406     Returns the 'x' height of the font. This is often but not always
407     the same as the height of the character 'x'.
408 */
409 int QFontMetrics::xHeight() const
410 {
411     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
412     Q_ASSERT(engine != 0);
413     if (d->capital == QFont::SmallCaps)
414         return qRound(d->smallCapsFontPrivate()->engineForScript(QUnicodeTables::Common)->ascent());
415     return qRound(engine->xHeight());
416 }
417
418 /*!
419     \since 4.2
420
421     Returns the average width of glyphs in the font.
422 */
423 int QFontMetrics::averageCharWidth() const
424 {
425     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
426     Q_ASSERT(engine != 0);
427     return qRound(engine->averageCharWidth());
428 }
429
430 /*!
431     Returns true if character \a ch is a valid character in the font;
432     otherwise returns false.
433 */
434 bool QFontMetrics::inFont(QChar ch) const
435 {
436     const int script = QUnicodeTables::script(ch);
437     QFontEngine *engine = d->engineForScript(script);
438     Q_ASSERT(engine != 0);
439     if (engine->type() == QFontEngine::Box)
440         return false;
441     return engine->canRender(&ch, 1);
442 }
443
444 /*!
445    Returns true if the character encoded in UCS-4/UTF-32 is a valid
446    character in the font; otherwise returns false.
447 */
448 bool QFontMetrics::inFontUcs4(uint ucs4) const
449 {
450     const int script = QUnicodeTables::script(ucs4);
451     QFontEngine *engine = d->engineForScript(script);
452     Q_ASSERT(engine != 0);
453     if (engine->type() == QFontEngine::Box)
454         return false;
455     QString utf16 = QString::fromUcs4(&ucs4, 1);
456     return engine->canRender(utf16.data(), utf16.length());
457 }
458
459 /*!
460     Returns the left bearing of character \a ch in the font.
461
462     The left bearing is the right-ward distance of the left-most pixel
463     of the character from the logical origin of the character. This
464     value is negative if the pixels of the character extend to the
465     left of the logical origin.
466
467     See width(QChar) for a graphical description of this metric.
468
469     \sa rightBearing(), minLeftBearing(), width()
470 */
471 int QFontMetrics::leftBearing(QChar ch) const
472 {
473     const int script = QUnicodeTables::script(ch);
474     QFontEngine *engine;
475     if (d->capital == QFont::SmallCaps && ch.isLower())
476         engine = d->smallCapsFontPrivate()->engineForScript(script);
477     else
478         engine = d->engineForScript(script);
479     Q_ASSERT(engine != 0);
480     if (engine->type() == QFontEngine::Box)
481         return 0;
482
483     d->alterCharForCapitalization(ch);
484
485     QGlyphLayoutArray<10> glyphs;
486     int nglyphs = 9;
487     engine->stringToCMap(&ch, 1, &glyphs, &nglyphs, 0);
488     // ### can nglyphs != 1 happen at all? Not currently I think
489     qreal lb;
490     engine->getGlyphBearings(glyphs.glyphs[0], &lb);
491     return qRound(lb);
492 }
493
494 /*!
495     Returns the right bearing of character \a ch in the font.
496
497     The right bearing is the left-ward distance of the right-most
498     pixel of the character from the logical origin of a subsequent
499     character. This value is negative if the pixels of the character
500     extend to the right of the width() of the character.
501
502     See width() for a graphical description of this metric.
503
504     \sa leftBearing(), minRightBearing(), width()
505 */
506 int QFontMetrics::rightBearing(QChar ch) const
507 {
508     const int script = QUnicodeTables::script(ch);
509     QFontEngine *engine;
510     if (d->capital == QFont::SmallCaps && ch.isLower())
511         engine = d->smallCapsFontPrivate()->engineForScript(script);
512     else
513         engine = d->engineForScript(script);
514     Q_ASSERT(engine != 0);
515     if (engine->type() == QFontEngine::Box)
516         return 0;
517
518     d->alterCharForCapitalization(ch);
519
520     QGlyphLayoutArray<10> glyphs;
521     int nglyphs = 9;
522     engine->stringToCMap(&ch, 1, &glyphs, &nglyphs, 0);
523     // ### can nglyphs != 1 happen at all? Not currently I think
524     qreal rb;
525     engine->getGlyphBearings(glyphs.glyphs[0], 0, &rb);
526     return qRound(rb);
527 }
528
529 /*!
530     Returns the width in pixels of the first \a len characters of \a
531     text. If \a len is negative (the default), the entire string is
532     used.
533
534     Note that this value is \e not equal to boundingRect().width();
535     boundingRect() returns a rectangle describing the pixels this
536     string will cover whereas width() returns the distance to where
537     the next string should be drawn.
538
539     \sa boundingRect()
540 */
541 int QFontMetrics::width(const QString &text, int len) const
542 {
543     return width(text, len, 0);
544 }
545
546 /*!
547     \internal
548 */
549 int QFontMetrics::width(const QString &text, int len, int flags) const
550 {
551     int pos = text.indexOf(QLatin1Char('\x9c'));
552     if (pos != -1) {
553         len = (len < 0) ? pos : qMin(pos, len);
554     } else if (len < 0) {
555         len = text.length();
556     }
557     if (len == 0)
558         return 0;
559
560     if (flags & Qt::TextBypassShaping) {
561         // Skip harfbuzz complex shaping, only use advances
562         int numGlyphs = len;
563         QVarLengthGlyphLayoutArray glyphs(numGlyphs);
564         QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
565         if (!engine->stringToCMap(text.data(), len, &glyphs, &numGlyphs, 0)) {
566             glyphs.resize(numGlyphs);
567             if (!engine->stringToCMap(text.data(), len, &glyphs, &numGlyphs, 0))
568                 Q_ASSERT_X(false, Q_FUNC_INFO, "stringToCMap shouldn't fail twice");
569         }
570
571         QFixed width;
572         for (int i = 0; i < numGlyphs; ++i)
573             width += glyphs.advances_x[i];
574         return qRound(width);
575     }
576
577     QStackTextEngine layout(text, d.data());
578     layout.ignoreBidi = true;
579     return qRound(layout.width(0, len));
580 }
581
582 /*!
583     \overload
584
585     \img bearings.png Bearings
586
587     Returns the logical width of character \a ch in pixels. This is a
588     distance appropriate for drawing a subsequent character after \a
589     ch.
590
591     Some of the metrics are described in the image to the right. The
592     central dark rectangles cover the logical width() of each
593     character. The outer pale rectangles cover the leftBearing() and
594     rightBearing() of each character. Notice that the bearings of "f"
595     in this particular font are both negative, while the bearings of
596     "o" are both positive.
597
598     \warning This function will produce incorrect results for Arabic
599     characters or non-spacing marks in the middle of a string, as the
600     glyph shaping and positioning of marks that happens when
601     processing strings cannot be taken into account. When implementing
602     an interactive text control, use QTextLayout instead.
603
604     \sa boundingRect()
605 */
606 int QFontMetrics::width(QChar ch) const
607 {
608     if (QChar::category(ch.unicode()) == QChar::Mark_NonSpacing)
609         return 0;
610
611     const int script = QUnicodeTables::script(ch);
612     QFontEngine *engine;
613     if (d->capital == QFont::SmallCaps && ch.isLower())
614         engine = d->smallCapsFontPrivate()->engineForScript(script);
615     else
616         engine = d->engineForScript(script);
617     Q_ASSERT(engine != 0);
618
619     d->alterCharForCapitalization(ch);
620
621     QGlyphLayoutArray<8> glyphs;
622     int nglyphs = 7;
623     engine->stringToCMap(&ch, 1, &glyphs, &nglyphs, 0);
624     return qRound(glyphs.advances_x[0]);
625 }
626
627 /*! \obsolete
628
629     Returns the width of the character at position \a pos in the
630     string \a text.
631
632     The whole string is needed, as the glyph drawn may change
633     depending on the context (the letter before and after the current
634     one) for some languages (e.g. Arabic).
635
636     This function also takes non spacing marks and ligatures into
637     account.
638 */
639 int QFontMetrics::charWidth(const QString &text, int pos) const
640 {
641     if (pos < 0 || pos > (int)text.length())
642         return 0;
643
644     QChar ch = text.unicode()[pos];
645     const int script = QUnicodeTables::script(ch);
646     int width;
647
648     if (script != QUnicodeTables::Common) {
649         // complex script shaping. Have to do some hard work
650         int from = qMax(0, pos - 8);
651         int to = qMin(text.length(), pos + 8);
652         QString cstr = QString::fromRawData(text.unicode() + from, to - from);
653         QStackTextEngine layout(cstr, d.data());
654         layout.ignoreBidi = true;
655         layout.itemize();
656         width = qRound(layout.width(pos-from, 1));
657     } else if (QChar::category(ch.unicode()) == QChar::Mark_NonSpacing) {
658         width = 0;
659     } else {
660         QFontEngine *engine;
661         if (d->capital == QFont::SmallCaps && ch.isLower())
662             engine = d->smallCapsFontPrivate()->engineForScript(script);
663         else
664             engine = d->engineForScript(script);
665         Q_ASSERT(engine != 0);
666
667         d->alterCharForCapitalization(ch);
668
669         QGlyphLayoutArray<8> glyphs;
670         int nglyphs = 7;
671         engine->stringToCMap(&ch, 1, &glyphs, &nglyphs, 0);
672         width = qRound(glyphs.advances_x[0]);
673     }
674     return width;
675 }
676
677 /*!
678     Returns the bounding rectangle of the characters in the string
679     specified by \a text. The bounding rectangle always covers at least
680     the set of pixels the text would cover if drawn at (0, 0).
681
682     Note that the bounding rectangle may extend to the left of (0, 0),
683     e.g. for italicized fonts, and that the width of the returned
684     rectangle might be different than what the width() method returns.
685
686     If you want to know the advance width of the string (to layout
687     a set of strings next to each other), use width() instead.
688
689     Newline characters are processed as normal characters, \e not as
690     linebreaks.
691
692     The height of the bounding rectangle is at least as large as the
693     value returned by height().
694
695     \sa width(), height(), QPainter::boundingRect(), tightBoundingRect()
696 */
697 QRect QFontMetrics::boundingRect(const QString &text) const
698 {
699     if (text.length() == 0)
700         return QRect();
701
702     QStackTextEngine layout(text, d.data());
703     layout.ignoreBidi = true;
704     layout.itemize();
705     glyph_metrics_t gm = layout.boundingBox(0, text.length());
706     return QRect(qRound(gm.x), qRound(gm.y), qRound(gm.width), qRound(gm.height));
707 }
708
709 /*!
710     Returns the rectangle that is covered by ink if character \a ch
711     were to be drawn at the origin of the coordinate system.
712
713     Note that the bounding rectangle may extend to the left of (0, 0)
714     (e.g., for italicized fonts), and that the text output may cover \e
715     all pixels in the bounding rectangle. For a space character the rectangle
716     will usually be empty.
717
718     Note that the rectangle usually extends both above and below the
719     base line.
720
721     \warning The width of the returned rectangle is not the advance width
722     of the character. Use boundingRect(const QString &) or width() instead.
723
724     \sa width()
725 */
726 QRect QFontMetrics::boundingRect(QChar ch) const
727 {
728     const int script = QUnicodeTables::script(ch);
729     QFontEngine *engine;
730     if (d->capital == QFont::SmallCaps && ch.isLower())
731         engine = d->smallCapsFontPrivate()->engineForScript(script);
732     else
733         engine = d->engineForScript(script);
734     Q_ASSERT(engine != 0);
735
736     d->alterCharForCapitalization(ch);
737
738     QGlyphLayoutArray<10> glyphs;
739     int nglyphs = 9;
740     engine->stringToCMap(&ch, 1, &glyphs, &nglyphs, 0);
741     glyph_metrics_t gm = engine->boundingBox(glyphs.glyphs[0]);
742     return QRect(qRound(gm.x), qRound(gm.y), qRound(gm.width), qRound(gm.height));
743 }
744
745 /*!
746     \overload
747
748     Returns the bounding rectangle of the characters in the string
749     specified by \a text, which is the set of pixels the text would
750     cover if drawn at (0, 0). The drawing, and hence the bounding
751     rectangle, is constrained to the rectangle \a rect.
752
753     The \a flags argument is the bitwise OR of the following flags:
754     \list
755     \o Qt::AlignLeft aligns to the left border, except for
756           Arabic and Hebrew where it aligns to the right.
757     \o Qt::AlignRight aligns to the right border, except for
758           Arabic and Hebrew where it aligns to the left.
759     \o Qt::AlignJustify produces justified text.
760     \o Qt::AlignHCenter aligns horizontally centered.
761     \o Qt::AlignTop aligns to the top border.
762     \o Qt::AlignBottom aligns to the bottom border.
763     \o Qt::AlignVCenter aligns vertically centered
764     \o Qt::AlignCenter (== \c{Qt::AlignHCenter | Qt::AlignVCenter})
765     \o Qt::TextSingleLine ignores newline characters in the text.
766     \o Qt::TextExpandTabs expands tabs (see below)
767     \o Qt::TextShowMnemonic interprets "&x" as \underline{x}; i.e., underlined.
768     \o Qt::TextWordWrap breaks the text to fit the rectangle.
769     \endlist
770
771     Qt::Horizontal alignment defaults to Qt::AlignLeft and vertical
772     alignment defaults to Qt::AlignTop.
773
774     If several of the horizontal or several of the vertical alignment
775     flags are set, the resulting alignment is undefined.
776
777     If Qt::TextExpandTabs is set in \a flags, then: if \a tabArray is
778     non-null, it specifies a 0-terminated sequence of pixel-positions
779     for tabs; otherwise if \a tabStops is non-zero, it is used as the
780     tab spacing (in pixels).
781
782     Note that the bounding rectangle may extend to the left of (0, 0),
783     e.g. for italicized fonts, and that the text output may cover \e
784     all pixels in the bounding rectangle.
785
786     Newline characters are processed as linebreaks.
787
788     Despite the different actual character heights, the heights of the
789     bounding rectangles of "Yes" and "yes" are the same.
790
791     The bounding rectangle returned by this function is somewhat larger
792     than that calculated by the simpler boundingRect() function. This
793     function uses the \link minLeftBearing() maximum left \endlink and
794     \link minRightBearing() right \endlink font bearings as is
795     necessary for multi-line text to align correctly. Also,
796     fontHeight() and lineSpacing() are used to calculate the height,
797     rather than individual character heights.
798
799     \sa width(), QPainter::boundingRect(), Qt::Alignment
800 */
801 QRect QFontMetrics::boundingRect(const QRect &rect, int flags, const QString &text, int tabStops,
802                                  int *tabArray) const
803 {
804     int tabArrayLen = 0;
805     if (tabArray)
806         while (tabArray[tabArrayLen])
807             tabArrayLen++;
808
809     QRectF rb;
810     QRectF rr(rect);
811     qt_format_text(QFont(d.data()), rr, flags | Qt::TextDontPrint, text, &rb, tabStops, tabArray,
812                    tabArrayLen, 0);
813
814     return rb.toAlignedRect();
815 }
816
817 /*!
818     Returns the size in pixels of \a text.
819
820     The \a flags argument is the bitwise OR of the following flags:
821     \list
822     \o Qt::TextSingleLine ignores newline characters.
823     \o Qt::TextExpandTabs expands tabs (see below)
824     \o Qt::TextShowMnemonic interprets "&x" as \underline{x}; i.e., underlined.
825     \o Qt::TextWordBreak breaks the text to fit the rectangle.
826     \endlist
827
828     If Qt::TextExpandTabs is set in \a flags, then: if \a tabArray is
829     non-null, it specifies a 0-terminated sequence of pixel-positions
830     for tabs; otherwise if \a tabStops is non-zero, it is used as the
831     tab spacing (in pixels).
832
833     Newline characters are processed as linebreaks.
834
835     Despite the different actual character heights, the heights of the
836     bounding rectangles of "Yes" and "yes" are the same.
837
838     \sa boundingRect()
839 */
840 QSize QFontMetrics::size(int flags, const QString &text, int tabStops, int *tabArray) const
841 {
842     return boundingRect(QRect(0,0,0,0), flags | Qt::TextLongestVariant, text, tabStops, tabArray).size();
843 }
844
845 /*!
846   \since 4.3
847
848     Returns a tight bounding rectangle around the characters in the
849     string specified by \a text. The bounding rectangle always covers
850     at least the set of pixels the text would cover if drawn at (0,
851     0).
852
853     Note that the bounding rectangle may extend to the left of (0, 0),
854     e.g. for italicized fonts, and that the width of the returned
855     rectangle might be different than what the width() method returns.
856
857     If you want to know the advance width of the string (to layout
858     a set of strings next to each other), use width() instead.
859
860     Newline characters are processed as normal characters, \e not as
861     linebreaks.
862
863     \warning Calling this method is very slow on Windows.
864
865     \sa width(), height(), boundingRect()
866 */
867 QRect QFontMetrics::tightBoundingRect(const QString &text) const
868 {
869     if (text.length() == 0)
870         return QRect();
871
872     QStackTextEngine layout(text, d.data());
873     layout.ignoreBidi = true;
874     layout.itemize();
875     glyph_metrics_t gm = layout.tightBoundingBox(0, text.length());
876     return QRect(qRound(gm.x), qRound(gm.y), qRound(gm.width), qRound(gm.height));
877 }
878
879
880 /*!
881     \since 4.2
882
883     If the string \a text is wider than \a width, returns an elided
884     version of the string (i.e., a string with "..." in it).
885     Otherwise, returns the original string.
886
887     The \a mode parameter specifies whether the text is elided on the
888     left (e.g., "...tech"), in the middle (e.g., "Tr...ch"), or on
889     the right (e.g., "Trol...").
890
891     The \a width is specified in pixels, not characters.
892
893     The \a flags argument is optional and currently only supports
894     Qt::TextShowMnemonic as value.
895
896     The elide mark will follow the \l{Qt::LayoutDirection}{layout
897     direction}; it will be on the right side of the text for
898     right-to-left layouts, and on the left side for right-to-left
899     layouts. Note that this behavior is independent of the text
900     language.
901 */
902 QString QFontMetrics::elidedText(const QString &text, Qt::TextElideMode mode, int width, int flags) const
903 {
904     QString _text = text;
905     if (!(flags & Qt::TextLongestVariant)) {
906         int posA = 0;
907         int posB = _text.indexOf(QLatin1Char('\x9c'));
908         while (posB >= 0) {
909             QString portion = _text.mid(posA, posB - posA);
910             if (size(flags, portion).width() <= width)
911                 return portion;
912             posA = posB + 1;
913             posB = _text.indexOf(QLatin1Char('\x9c'), posA);
914         }
915         _text = _text.mid(posA);
916     }
917     QStackTextEngine engine(_text, QFont(d.data()));
918     return engine.elidedText(mode, width, flags);
919 }
920
921 /*!
922     Returns the distance from the base line to where an underscore
923     should be drawn.
924
925     \sa overlinePos(), strikeOutPos(), lineWidth()
926 */
927 int QFontMetrics::underlinePos() const
928 {
929     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
930     Q_ASSERT(engine != 0);
931     return qRound(engine->underlinePosition());
932 }
933
934 /*!
935     Returns the distance from the base line to where an overline
936     should be drawn.
937
938     \sa underlinePos(), strikeOutPos(), lineWidth()
939 */
940 int QFontMetrics::overlinePos() const
941 {
942     return ascent() + 1;
943 }
944
945 /*!
946     Returns the distance from the base line to where the strikeout
947     line should be drawn.
948
949     \sa underlinePos(), overlinePos(), lineWidth()
950 */
951 int QFontMetrics::strikeOutPos() const
952 {
953     int pos = ascent() / 3;
954     return pos > 0 ? pos : 1;
955 }
956
957 /*!
958     Returns the width of the underline and strikeout lines, adjusted
959     for the point size of the font.
960
961     \sa underlinePos(), overlinePos(), strikeOutPos()
962 */
963 int QFontMetrics::lineWidth() const
964 {
965     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
966     Q_ASSERT(engine != 0);
967     return qRound(engine->lineThickness());
968 }
969
970
971
972
973 /*****************************************************************************
974   QFontMetricsF member functions
975  *****************************************************************************/
976
977 /*!
978     \class QFontMetricsF
979     \reentrant
980
981     \brief The QFontMetricsF class provides font metrics information.
982
983     \ingroup painting
984     \ingroup shared
985
986     QFontMetricsF functions calculate the size of characters and
987     strings for a given font. You can construct a QFontMetricsF object
988     with an existing QFont to obtain metrics for that font. If the
989     font is changed later, the font metrics object is \e not updated.
990
991     Once created, the object provides functions to access the
992     individual metrics of the font, its characters, and for strings
993     rendered in the font.
994
995     There are several functions that operate on the font: ascent(),
996     descent(), height(), leading() and lineSpacing() return the basic
997     size properties of the font. The underlinePos(), overlinePos(),
998     strikeOutPos() and lineWidth() functions, return the properties of
999     the line that underlines, overlines or strikes out the
1000     characters. These functions are all fast.
1001
1002     There are also some functions that operate on the set of glyphs in
1003     the font: minLeftBearing(), minRightBearing() and maxWidth().
1004     These are by necessity slow, and we recommend avoiding them if
1005     possible.
1006
1007     For each character, you can get its width(), leftBearing() and
1008     rightBearing() and find out whether it is in the font using
1009     inFont(). You can also treat the character as a string, and use
1010     the string functions on it.
1011
1012     The string functions include width(), to return the width of a
1013     string in pixels (or points, for a printer), boundingRect(), to
1014     return a rectangle large enough to contain the rendered string,
1015     and size(), to return the size of that rectangle.
1016
1017     Example:
1018     \snippet doc/src/snippets/code/src_gui_text_qfontmetrics.cpp 1
1019
1020     \sa QFont QFontInfo QFontDatabase
1021 */
1022
1023 /*!
1024     \since 4.2
1025
1026     Constructs a font metrics object with floating point precision
1027     from the given \a fontMetrics object.
1028 */
1029 QFontMetricsF::QFontMetricsF(const QFontMetrics &fontMetrics)
1030     : d(fontMetrics.d.data())
1031 {
1032 }
1033
1034 /*!
1035     \since 4.2
1036
1037     Assigns \a other to this object.
1038 */
1039 QFontMetricsF &QFontMetricsF::operator=(const QFontMetrics &other)
1040 {
1041     d = other.d.data();
1042     return *this;
1043 }
1044
1045 /*!
1046     Constructs a font metrics object for \a font.
1047
1048     The font metrics will be compatible with the paintdevice used to
1049     create \a font.
1050
1051     The font metrics object holds the information for the font that is
1052     passed in the constructor at the time it is created, and is not
1053     updated if the font's attributes are changed later.
1054
1055     Use QFontMetricsF(const QFont &, QPaintDevice *) to get the font
1056     metrics that are compatible with a certain paint device.
1057 */
1058 QFontMetricsF::QFontMetricsF(const QFont &font)
1059     : d(font.d.data())
1060 {
1061 }
1062
1063 /*!
1064     Constructs a font metrics object for \a font and \a paintdevice.
1065
1066     The font metrics will be compatible with the paintdevice passed.
1067     If the \a paintdevice is 0, the metrics will be screen-compatible,
1068     ie. the metrics you get if you use the font for drawing text on a
1069     \link QWidget widgets\endlink or \link QPixmap pixmaps\endlink,
1070     not on a QPicture or QPrinter.
1071
1072     The font metrics object holds the information for the font that is
1073     passed in the constructor at the time it is created, and is not
1074     updated if the font's attributes are changed later.
1075 */
1076 QFontMetricsF::QFontMetricsF(const QFont &font, QPaintDevice *paintdevice)
1077 {
1078     int dpi = paintdevice ? paintdevice->logicalDpiY() : qt_defaultDpi();
1079 #ifdef Q_WS_X11
1080     const QX11Info *info = qt_x11Info(paintdevice);
1081     int screen = info ? info->screen() : 0;
1082 #else
1083     const int screen = 0;
1084 #endif
1085     if (font.d->dpi != dpi || font.d->screen != screen ) {
1086         d = new QFontPrivate(*font.d);
1087         d->dpi = dpi;
1088         d->screen = screen;
1089     } else {
1090         d = font.d.data();
1091     }
1092
1093 }
1094
1095 /*!
1096     Constructs a copy of \a fm.
1097 */
1098 QFontMetricsF::QFontMetricsF(const QFontMetricsF &fm)
1099     : d(fm.d.data())
1100 {
1101 }
1102
1103 /*!
1104     Destroys the font metrics object and frees all allocated
1105     resources.
1106 */
1107 QFontMetricsF::~QFontMetricsF()
1108 {
1109 }
1110
1111 /*!
1112     Assigns the font metrics \a fm to this font metrics object.
1113 */
1114 QFontMetricsF &QFontMetricsF::operator=(const QFontMetricsF &fm)
1115 {
1116     d = fm.d.data();
1117     return *this;
1118 }
1119
1120 /*!
1121   \overload
1122   Returns true if the font metrics are equal to the \a other font
1123   metrics; otherwise returns false.
1124
1125   Two font metrics are considered equal if they were constructed from the
1126   same QFont and the paint devices they were constructed for are
1127   considered to be compatible.
1128 */
1129 bool QFontMetricsF::operator ==(const QFontMetricsF &other) const
1130 {
1131     return d == other.d;
1132 }
1133
1134 /*!
1135   Returns true if the font metrics are equal to the \a other font
1136   metrics; otherwise returns false.
1137
1138   Two font metrics are considered equal if they were constructed from the
1139   same QFont and the paint devices they were constructed for are
1140   considered to be compatible.
1141 */
1142 bool QFontMetricsF::operator ==(const QFontMetricsF &other)
1143 {
1144     return d == other.d;
1145 }
1146
1147 /*!
1148     \fn bool QFontMetricsF::operator!=(const QFontMetricsF &other)
1149
1150     Returns true if the font metrics are not equal to the \a other font
1151     metrics; otherwise returns false.
1152
1153     \sa operator==()
1154 */
1155
1156 /*!
1157     \fn bool QFontMetricsF::operator !=(const QFontMetricsF &other) const
1158     \overload
1159
1160     Returns true if the font metrics are not equal to the \a other font
1161     metrics; otherwise returns false.
1162
1163     \sa operator==()
1164 */
1165
1166 /*!
1167     Returns the ascent of the font.
1168
1169     The ascent of a font is the distance from the baseline to the
1170     highest position characters extend to. In practice, some font
1171     designers break this rule, e.g. when they put more than one accent
1172     on top of a character, or to accommodate an unusual character in
1173     an exotic language, so it is possible (though rare) that this
1174     value will be too small.
1175
1176     \sa descent()
1177 */
1178 qreal QFontMetricsF::ascent() const
1179 {
1180     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
1181     Q_ASSERT(engine != 0);
1182     return engine->ascent().toReal();
1183 }
1184
1185
1186 /*!
1187     Returns the descent of the font.
1188
1189     The descent is the distance from the base line to the lowest point
1190     characters extend to. (Note that this is different from X, which
1191     adds 1 pixel.) In practice, some font designers break this rule,
1192     e.g. to accommodate an unusual character in an exotic language, so
1193     it is possible (though rare) that this value will be too small.
1194
1195     \sa ascent()
1196 */
1197 qreal QFontMetricsF::descent() const
1198 {
1199     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
1200     Q_ASSERT(engine != 0);
1201     return engine->descent().toReal();
1202 }
1203
1204 /*!
1205     Returns the height of the font.
1206
1207     This is always equal to ascent()+descent()+1 (the 1 is for the
1208     base line).
1209
1210     \sa leading(), lineSpacing()
1211 */
1212 qreal QFontMetricsF::height() const
1213 {
1214     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
1215     Q_ASSERT(engine != 0);
1216
1217     return (engine->ascent() + engine->descent() + 1).toReal();
1218 }
1219
1220 /*!
1221     Returns the leading of the font.
1222
1223     This is the natural inter-line spacing.
1224
1225     \sa height(), lineSpacing()
1226 */
1227 qreal QFontMetricsF::leading() const
1228 {
1229     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
1230     Q_ASSERT(engine != 0);
1231     return engine->leading().toReal();
1232 }
1233
1234 /*!
1235     Returns the distance from one base line to the next.
1236
1237     This value is always equal to leading()+height().
1238
1239     \sa height(), leading()
1240 */
1241 qreal QFontMetricsF::lineSpacing() const
1242 {
1243     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
1244     Q_ASSERT(engine != 0);
1245     return (engine->leading() + engine->ascent() + engine->descent() + 1).toReal();
1246 }
1247
1248 /*!
1249     Returns the minimum left bearing of the font.
1250
1251     This is the smallest leftBearing(char) of all characters in the
1252     font.
1253
1254     Note that this function can be very slow if the font is large.
1255
1256     \sa minRightBearing(), leftBearing()
1257 */
1258 qreal QFontMetricsF::minLeftBearing() const
1259 {
1260     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
1261     Q_ASSERT(engine != 0);
1262     return engine->minLeftBearing();
1263 }
1264
1265 /*!
1266     Returns the minimum right bearing of the font.
1267
1268     This is the smallest rightBearing(char) of all characters in the
1269     font.
1270
1271     Note that this function can be very slow if the font is large.
1272
1273     \sa minLeftBearing(), rightBearing()
1274 */
1275 qreal QFontMetricsF::minRightBearing() const
1276 {
1277     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
1278     Q_ASSERT(engine != 0);
1279     return engine->minRightBearing();
1280 }
1281
1282 /*!
1283     Returns the width of the widest character in the font.
1284 */
1285 qreal QFontMetricsF::maxWidth() const
1286 {
1287     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
1288     Q_ASSERT(engine != 0);
1289     return engine->maxCharWidth();
1290 }
1291
1292 /*!
1293     Returns the 'x' height of the font. This is often but not always
1294     the same as the height of the character 'x'.
1295 */
1296 qreal QFontMetricsF::xHeight() const
1297 {
1298     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
1299     Q_ASSERT(engine != 0);
1300     if (d->capital == QFont::SmallCaps)
1301         return d->smallCapsFontPrivate()->engineForScript(QUnicodeTables::Common)->ascent().toReal();
1302     return engine->xHeight().toReal();
1303 }
1304
1305 /*!
1306     \since 4.2
1307
1308     Returns the average width of glyphs in the font.
1309 */
1310 qreal QFontMetricsF::averageCharWidth() const
1311 {
1312     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
1313     Q_ASSERT(engine != 0);
1314     return engine->averageCharWidth().toReal();
1315 }
1316
1317 /*!
1318     Returns true if character \a ch is a valid character in the font;
1319     otherwise returns false.
1320 */
1321 bool QFontMetricsF::inFont(QChar ch) const
1322 {
1323     const int script = QUnicodeTables::script(ch);
1324     QFontEngine *engine = d->engineForScript(script);
1325     Q_ASSERT(engine != 0);
1326     if (engine->type() == QFontEngine::Box)
1327         return false;
1328     return engine->canRender(&ch, 1);
1329 }
1330
1331 /*!
1332     \fn bool QFontMetricsF::inFontUcs4(uint ch) const
1333
1334     Returns true if the character given by \a ch, encoded in UCS-4/UTF-32,
1335     is a valid character in the font; otherwise returns false.
1336 */
1337 bool QFontMetricsF::inFontUcs4(uint ucs4) const
1338 {
1339     const int script = QUnicodeTables::script(ucs4);
1340     QFontEngine *engine = d->engineForScript(script);
1341     Q_ASSERT(engine != 0);
1342     if (engine->type() == QFontEngine::Box)
1343         return false;
1344     QString utf16 = QString::fromUcs4(&ucs4, 1);
1345     return engine->canRender(utf16.data(), utf16.length());
1346 }
1347
1348 /*!
1349     Returns the left bearing of character \a ch in the font.
1350
1351     The left bearing is the right-ward distance of the left-most pixel
1352     of the character from the logical origin of the character. This
1353     value is negative if the pixels of the character extend to the
1354     left of the logical origin.
1355
1356     See width(QChar) for a graphical description of this metric.
1357
1358     \sa rightBearing(), minLeftBearing(), width()
1359 */
1360 qreal QFontMetricsF::leftBearing(QChar ch) const
1361 {
1362     const int script = QUnicodeTables::script(ch);
1363     QFontEngine *engine;
1364     if (d->capital == QFont::SmallCaps && ch.isLower())
1365         engine = d->smallCapsFontPrivate()->engineForScript(script);
1366     else
1367         engine = d->engineForScript(script);
1368     Q_ASSERT(engine != 0);
1369     if (engine->type() == QFontEngine::Box)
1370         return 0;
1371
1372     d->alterCharForCapitalization(ch);
1373
1374     QGlyphLayoutArray<10> glyphs;
1375     int nglyphs = 9;
1376     engine->stringToCMap(&ch, 1, &glyphs, &nglyphs, 0);
1377     // ### can nglyphs != 1 happen at all? Not currently I think
1378     qreal lb;
1379     engine->getGlyphBearings(glyphs.glyphs[0], &lb);
1380     return lb;
1381 }
1382
1383 /*!
1384     Returns the right bearing of character \a ch in the font.
1385
1386     The right bearing is the left-ward distance of the right-most
1387     pixel of the character from the logical origin of a subsequent
1388     character. This value is negative if the pixels of the character
1389     extend to the right of the width() of the character.
1390
1391     See width() for a graphical description of this metric.
1392
1393     \sa leftBearing(), minRightBearing(), width()
1394 */
1395 qreal QFontMetricsF::rightBearing(QChar ch) const
1396 {
1397     const int script = QUnicodeTables::script(ch);
1398     QFontEngine *engine;
1399     if (d->capital == QFont::SmallCaps && ch.isLower())
1400         engine = d->smallCapsFontPrivate()->engineForScript(script);
1401     else
1402         engine = d->engineForScript(script);
1403     Q_ASSERT(engine != 0);
1404     if (engine->type() == QFontEngine::Box)
1405         return 0;
1406
1407     d->alterCharForCapitalization(ch);
1408
1409     QGlyphLayoutArray<10> glyphs;
1410     int nglyphs = 9;
1411     engine->stringToCMap(&ch, 1, &glyphs, &nglyphs, 0);
1412     // ### can nglyphs != 1 happen at all? Not currently I think
1413     qreal rb;
1414     engine->getGlyphBearings(glyphs.glyphs[0], 0, &rb);
1415     return rb;
1416
1417 }
1418
1419 /*!
1420     Returns the width in pixels of the characters in the given \a text.
1421
1422     Note that this value is \e not equal to the width returned by
1423     boundingRect().width() because boundingRect() returns a rectangle
1424     describing the pixels this string will cover whereas width()
1425     returns the distance to where the next string should be drawn.
1426
1427     \sa boundingRect()
1428 */
1429 qreal QFontMetricsF::width(const QString &text) const
1430 {
1431     int pos = text.indexOf(QLatin1Char('\x9c'));
1432     int len = (pos != -1) ? pos : text.length();
1433
1434     QStackTextEngine layout(text, d.data());
1435     layout.ignoreBidi = true;
1436     layout.itemize();
1437     return layout.width(0, len).toReal();
1438 }
1439
1440 /*!
1441     \overload
1442
1443     \img bearings.png Bearings
1444
1445     Returns the logical width of character \a ch in pixels. This is a
1446     distance appropriate for drawing a subsequent character after \a
1447     ch.
1448
1449     Some of the metrics are described in the image to the right. The
1450     central dark rectangles cover the logical width() of each
1451     character. The outer pale rectangles cover the leftBearing() and
1452     rightBearing() of each character. Notice that the bearings of "f"
1453     in this particular font are both negative, while the bearings of
1454     "o" are both positive.
1455
1456     \warning This function will produce incorrect results for Arabic
1457     characters or non-spacing marks in the middle of a string, as the
1458     glyph shaping and positioning of marks that happens when
1459     processing strings cannot be taken into account. When implementing
1460     an interactive text control, use QTextLayout instead.
1461
1462     \sa boundingRect()
1463 */
1464 qreal QFontMetricsF::width(QChar ch) const
1465 {
1466     if (QChar::category(ch.unicode()) == QChar::Mark_NonSpacing)
1467         return 0.;
1468
1469     const int script = QUnicodeTables::script(ch);
1470     QFontEngine *engine;
1471     if (d->capital == QFont::SmallCaps && ch.isLower())
1472         engine = d->smallCapsFontPrivate()->engineForScript(script);
1473     else
1474         engine = d->engineForScript(script);
1475     Q_ASSERT(engine != 0);
1476
1477     d->alterCharForCapitalization(ch);
1478
1479     QGlyphLayoutArray<8> glyphs;
1480     int nglyphs = 7;
1481     engine->stringToCMap(&ch, 1, &glyphs, &nglyphs, 0);
1482     return glyphs.advances_x[0].toReal();
1483 }
1484
1485 /*!
1486     Returns the bounding rectangle of the characters in the string
1487     specified by \a text. The bounding rectangle always covers at least
1488     the set of pixels the text would cover if drawn at (0, 0).
1489
1490     Note that the bounding rectangle may extend to the left of (0, 0),
1491     e.g. for italicized fonts, and that the width of the returned
1492     rectangle might be different than what the width() method returns.
1493
1494     If you want to know the advance width of the string (to layout
1495     a set of strings next to each other), use width() instead.
1496
1497     Newline characters are processed as normal characters, \e not as
1498     linebreaks.
1499
1500     The height of the bounding rectangle is at least as large as the
1501     value returned height().
1502
1503     \sa width(), height(), QPainter::boundingRect()
1504 */
1505 QRectF QFontMetricsF::boundingRect(const QString &text) const
1506 {
1507     int len = text.length();
1508     if (len == 0)
1509         return QRectF();
1510
1511     QStackTextEngine layout(text, d.data());
1512     layout.ignoreBidi = true;
1513     layout.itemize();
1514     glyph_metrics_t gm = layout.boundingBox(0, len);
1515     return QRectF(gm.x.toReal(), gm.y.toReal(),
1516                   gm.width.toReal(), gm.height.toReal());
1517 }
1518
1519 /*!
1520     Returns the bounding rectangle of the character \a ch relative to
1521     the left-most point on the base line.
1522
1523     Note that the bounding rectangle may extend to the left of (0, 0),
1524     e.g. for italicized fonts, and that the text output may cover \e
1525     all pixels in the bounding rectangle.
1526
1527     Note that the rectangle usually extends both above and below the
1528     base line.
1529
1530     \sa width()
1531 */
1532 QRectF QFontMetricsF::boundingRect(QChar ch) const
1533 {
1534     const int script = QUnicodeTables::script(ch);
1535     QFontEngine *engine;
1536     if (d->capital == QFont::SmallCaps && ch.isLower())
1537         engine = d->smallCapsFontPrivate()->engineForScript(script);
1538     else
1539         engine = d->engineForScript(script);
1540     Q_ASSERT(engine != 0);
1541
1542     d->alterCharForCapitalization(ch);
1543
1544     QGlyphLayoutArray<10> glyphs;
1545     int nglyphs = 9;
1546     engine->stringToCMap(&ch, 1, &glyphs, &nglyphs, 0);
1547     glyph_metrics_t gm = engine->boundingBox(glyphs.glyphs[0]);
1548     return QRectF(gm.x.toReal(), gm.y.toReal(), gm.width.toReal(), gm.height.toReal());
1549 }
1550
1551 /*!
1552     \overload
1553
1554     Returns the bounding rectangle of the characters in the given \a text.
1555     This is the set of pixels the text would cover if drawn when constrained
1556     to the bounding rectangle specified by \a rect.
1557
1558     The \a flags argument is the bitwise OR of the following flags:
1559     \list
1560     \o Qt::AlignLeft aligns to the left border, except for
1561           Arabic and Hebrew where it aligns to the right.
1562     \o Qt::AlignRight aligns to the right border, except for
1563           Arabic and Hebrew where it aligns to the left.
1564     \o Qt::AlignJustify produces justified text.
1565     \o Qt::AlignHCenter aligns horizontally centered.
1566     \o Qt::AlignTop aligns to the top border.
1567     \o Qt::AlignBottom aligns to the bottom border.
1568     \o Qt::AlignVCenter aligns vertically centered
1569     \o Qt::AlignCenter (== \c{Qt::AlignHCenter | Qt::AlignVCenter})
1570     \o Qt::TextSingleLine ignores newline characters in the text.
1571     \o Qt::TextExpandTabs expands tabs (see below)
1572     \o Qt::TextShowMnemonic interprets "&x" as \underline{x}; i.e., underlined.
1573     \o Qt::TextWordWrap breaks the text to fit the rectangle.
1574     \endlist
1575
1576     Qt::Horizontal alignment defaults to Qt::AlignLeft and vertical
1577     alignment defaults to Qt::AlignTop.
1578
1579     If several of the horizontal or several of the vertical alignment
1580     flags are set, the resulting alignment is undefined.
1581
1582     These flags are defined in \l{Qt::AlignmentFlag}.
1583
1584     If Qt::TextExpandTabs is set in \a flags, the following behavior is
1585     used to interpret tab characters in the text:
1586     \list
1587     \o If \a tabArray is non-null, it specifies a 0-terminated sequence of
1588        pixel-positions for tabs in the text.
1589     \o If \a tabStops is non-zero, it is used as the tab spacing (in pixels).
1590     \endlist
1591
1592     Note that the bounding rectangle may extend to the left of (0, 0),
1593     e.g. for italicized fonts.
1594
1595     Newline characters are processed as line breaks.
1596
1597     Despite the different actual character heights, the heights of the
1598     bounding rectangles of "Yes" and "yes" are the same.
1599
1600     The bounding rectangle returned by this function is somewhat larger
1601     than that calculated by the simpler boundingRect() function. This
1602     function uses the \link minLeftBearing() maximum left \endlink and
1603     \link minRightBearing() right \endlink font bearings as is
1604     necessary for multi-line text to align correctly. Also,
1605     fontHeight() and lineSpacing() are used to calculate the height,
1606     rather than individual character heights.
1607
1608     \sa width(), QPainter::boundingRect(), Qt::Alignment
1609 */
1610 QRectF QFontMetricsF::boundingRect(const QRectF &rect, int flags, const QString& text,
1611                                    int tabStops, int *tabArray) const
1612 {
1613     int tabArrayLen = 0;
1614     if (tabArray)
1615         while (tabArray[tabArrayLen])
1616             tabArrayLen++;
1617
1618     QRectF rb;
1619     qt_format_text(QFont(d.data()), rect, flags | Qt::TextDontPrint, text, &rb, tabStops, tabArray,
1620                    tabArrayLen, 0);
1621     return rb;
1622 }
1623
1624 /*!
1625     Returns the size in pixels of the characters in the given \a text.
1626
1627     The \a flags argument is the bitwise OR of the following flags:
1628     \list
1629     \o Qt::TextSingleLine ignores newline characters.
1630     \o Qt::TextExpandTabs expands tabs (see below)
1631     \o Qt::TextShowMnemonic interprets "&x" as \underline{x}; i.e., underlined.
1632     \o Qt::TextWordBreak breaks the text to fit the rectangle.
1633     \endlist
1634
1635     These flags are defined in \l{Qt::TextFlags}.
1636
1637     If Qt::TextExpandTabs is set in \a flags, the following behavior is
1638     used to interpret tab characters in the text:
1639     \list
1640     \o If \a tabArray is non-null, it specifies a 0-terminated sequence of
1641        pixel-positions for tabs in the text.
1642     \o If \a tabStops is non-zero, it is used as the tab spacing (in pixels).
1643     \endlist
1644
1645     Newline characters are processed as line breaks.
1646
1647     Note: Despite the different actual character heights, the heights of the
1648     bounding rectangles of "Yes" and "yes" are the same.
1649
1650     \sa boundingRect()
1651 */
1652 QSizeF QFontMetricsF::size(int flags, const QString &text, int tabStops, int *tabArray) const
1653 {
1654     return boundingRect(QRectF(), flags | Qt::TextLongestVariant, text, tabStops, tabArray).size();
1655 }
1656
1657 /*!
1658   \since 4.3
1659
1660     Returns a tight bounding rectangle around the characters in the
1661     string specified by \a text. The bounding rectangle always covers
1662     at least the set of pixels the text would cover if drawn at (0,
1663     0).
1664
1665     Note that the bounding rectangle may extend to the left of (0, 0),
1666     e.g. for italicized fonts, and that the width of the returned
1667     rectangle might be different than what the width() method returns.
1668
1669     If you want to know the advance width of the string (to layout
1670     a set of strings next to each other), use width() instead.
1671
1672     Newline characters are processed as normal characters, \e not as
1673     linebreaks.
1674
1675     \warning Calling this method is very slow on Windows.
1676
1677     \sa width(), height(), boundingRect()
1678 */
1679 QRectF QFontMetricsF::tightBoundingRect(const QString &text) const
1680 {
1681     if (text.length() == 0)
1682         return QRect();
1683
1684     QStackTextEngine layout(text, d.data());
1685     layout.ignoreBidi = true;
1686     layout.itemize();
1687     glyph_metrics_t gm = layout.tightBoundingBox(0, text.length());
1688     return QRectF(gm.x.toReal(), gm.y.toReal(), gm.width.toReal(), gm.height.toReal());
1689 }
1690
1691 /*!
1692     \since 4.2
1693
1694     If the string \a text is wider than \a width, returns an elided
1695     version of the string (i.e., a string with "..." in it).
1696     Otherwise, returns the original string.
1697
1698     The \a mode parameter specifies whether the text is elided on the
1699     left (e.g., "...tech"), in the middle (e.g., "Tr...ch"), or on
1700     the right (e.g., "Trol...").
1701
1702     The \a width is specified in pixels, not characters.
1703
1704     The \a flags argument is optional and currently only supports
1705     Qt::TextShowMnemonic as value.
1706 */
1707 QString QFontMetricsF::elidedText(const QString &text, Qt::TextElideMode mode, qreal width, int flags) const
1708 {
1709     QString _text = text;
1710     if (!(flags & Qt::TextLongestVariant)) {
1711         int posA = 0;
1712         int posB = _text.indexOf(QLatin1Char('\x9c'));
1713         while (posB >= 0) {
1714             QString portion = _text.mid(posA, posB - posA);
1715             if (size(flags, portion).width() <= width)
1716                 return portion;
1717             posA = posB + 1;
1718             posB = _text.indexOf(QLatin1Char('\x9c'), posA);
1719         }
1720         _text = _text.mid(posA);
1721     }
1722     QStackTextEngine engine(_text, QFont(d.data()));
1723     return engine.elidedText(mode, QFixed::fromReal(width), flags);
1724 }
1725
1726 /*!
1727     Returns the distance from the base line to where an underscore
1728     should be drawn.
1729
1730     \sa overlinePos(), strikeOutPos(), lineWidth()
1731 */
1732 qreal QFontMetricsF::underlinePos() const
1733 {
1734     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
1735     Q_ASSERT(engine != 0);
1736     return engine->underlinePosition().toReal();
1737 }
1738
1739 /*!
1740     Returns the distance from the base line to where an overline
1741     should be drawn.
1742
1743     \sa underlinePos(), strikeOutPos(), lineWidth()
1744 */
1745 qreal QFontMetricsF::overlinePos() const
1746 {
1747     return ascent() + 1;
1748 }
1749
1750 /*!
1751     Returns the distance from the base line to where the strikeout
1752     line should be drawn.
1753
1754     \sa underlinePos(), overlinePos(), lineWidth()
1755 */
1756 qreal QFontMetricsF::strikeOutPos() const
1757 {
1758     return ascent() / 3.;
1759 }
1760
1761 /*!
1762     Returns the width of the underline and strikeout lines, adjusted
1763     for the point size of the font.
1764
1765     \sa underlinePos(), overlinePos(), strikeOutPos()
1766 */
1767 qreal QFontMetricsF::lineWidth() const
1768 {
1769     QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
1770     Q_ASSERT(engine != 0);
1771     return engine->lineThickness().toReal();
1772 }
1773
1774 /*!
1775     \fn QSize QFontMetrics::size(int flags, const QString &text, int len,
1776                                  int tabStops, int *tabArray) const
1777     \compat
1778
1779     Use the size() function in combination with QString::left()
1780     instead.
1781
1782     \oldcode
1783         QSize size = size(flags, str, len, tabstops, tabarray);
1784     \newcode
1785         QSize size = size(flags, str.left(len), tabstops, tabarray);
1786     \endcode
1787 */
1788
1789 /*!
1790     \fn QRect QFontMetrics::boundingRect(int x, int y, int w, int h, int flags,
1791         const QString& text, int len, int tabStops, int *tabArray) const
1792     \compat
1793
1794     Use the boundingRect() function in combination with
1795     QString::left() and a QRect constructor instead.
1796
1797     \oldcode
1798         QRect rect = boundingRect(x, y, w, h , flags, text, len,
1799                                   tabStops, tabArray);
1800     \newcode
1801         QRect rect = boundingRect(QRect(x, y, w, h), flags, text.left(len),
1802                                   tabstops, tabarray);
1803     \endcode
1804
1805 */
1806
1807 /*!
1808     \fn QRect QFontMetrics::boundingRect(const QString &text, int len) const
1809     \compat
1810
1811     Use the boundingRect() function in combination with
1812     QString::left() instead.
1813
1814     \oldcode
1815         QRect rect = boundingRect(text, len);
1816     \newcode
1817         QRect rect = boundingRect(text.left(len));
1818     \endcode
1819 */
1820
1821 QT_END_NAMESPACE