summaryrefslogtreecommitdiffstats
path: root/src/gui/text
diff options
context:
space:
mode:
Diffstat (limited to 'src/gui/text')
-rw-r--r--src/gui/text/qcssparser.cpp47
-rw-r--r--src/gui/text/qcssparser_p.h3
-rw-r--r--src/gui/text/qfont.cpp26
-rw-r--r--src/gui/text/qfont.h6
-rw-r--r--src/gui/text/qfont_mac.cpp1
-rw-r--r--src/gui/text/qfont_p.h5
-rw-r--r--src/gui/text/qfont_qpa.cpp114
-rw-r--r--src/gui/text/qfontdatabase.cpp76
-rw-r--r--src/gui/text/qfontdatabase.h3
-rw-r--r--src/gui/text/qfontdatabase_mac.cpp120
-rw-r--r--src/gui/text/qfontdatabase_qpa.cpp390
-rw-r--r--src/gui/text/qfontdatabase_qws.cpp10
-rw-r--r--src/gui/text/qfontdatabase_x11.cpp30
-rw-r--r--src/gui/text/qfontengine.cpp57
-rw-r--r--src/gui/text/qfontengine_coretext.mm733
-rw-r--r--src/gui/text/qfontengine_coretext_p.h136
-rw-r--r--src/gui/text/qfontengine_ft.cpp47
-rw-r--r--src/gui/text/qfontengine_ft_p.h27
-rw-r--r--src/gui/text/qfontengine_mac.mm702
-rw-r--r--src/gui/text/qfontengine_mac_p.h167
-rw-r--r--src/gui/text/qfontengine_p.h237
-rw-r--r--src/gui/text/qfontengine_qpa.cpp691
-rw-r--r--src/gui/text/qfontengine_qpa_p.h262
-rw-r--r--src/gui/text/qfontengine_s60.cpp7
-rw-r--r--src/gui/text/qfontengine_win.cpp2
-rw-r--r--src/gui/text/qfontengine_win_p.h2
-rw-r--r--src/gui/text/qfontengine_x11.cpp2
-rw-r--r--src/gui/text/qfontengineglyphcache_p.h2
-rw-r--r--src/gui/text/qfontmetrics.cpp32
-rw-r--r--src/gui/text/qfontmetrics.h11
-rw-r--r--src/gui/text/qglyphs.cpp240
-rw-r--r--src/gui/text/qglyphs.h96
-rw-r--r--src/gui/text/qglyphs_p.h84
-rw-r--r--src/gui/text/qpfutil.cpp2
-rw-r--r--src/gui/text/qplatformfontdatabase_qpa.cpp290
-rw-r--r--src/gui/text/qplatformfontdatabase_qpa.h108
-rw-r--r--src/gui/text/qtextcontrol.cpp5
-rw-r--r--src/gui/text/qtextcursor.h1
-rw-r--r--src/gui/text/qtextdocument.cpp36
-rw-r--r--src/gui/text/qtextdocumentfragment.cpp4
-rw-r--r--src/gui/text/qtextdocumentlayout.cpp38
-rw-r--r--src/gui/text/qtextengine.cpp89
-rw-r--r--src/gui/text/qtextengine_mac.cpp3
-rw-r--r--src/gui/text/qtextengine_p.h23
-rw-r--r--src/gui/text/qtextformat.cpp111
-rw-r--r--src/gui/text/qtextformat.h51
-rw-r--r--src/gui/text/qtexthtmlparser.cpp20
-rw-r--r--src/gui/text/qtexthtmlparser_p.h2
-rw-r--r--src/gui/text/qtextlayout.cpp464
-rw-r--r--src/gui/text/qtextlayout.h6
-rw-r--r--src/gui/text/qtextlist.cpp14
-rw-r--r--src/gui/text/qtextobject.cpp29
-rw-r--r--src/gui/text/qtextobject.h3
-rw-r--r--src/gui/text/qtextodfwriter.cpp10
-rw-r--r--src/gui/text/text.pri36
55 files changed, 4446 insertions, 1267 deletions
diff --git a/src/gui/text/qcssparser.cpp b/src/gui/text/qcssparser.cpp
index 5aac5ea6c6..54ca7cc802 100644
--- a/src/gui/text/qcssparser.cpp
+++ b/src/gui/text/qcssparser.cpp
@@ -68,6 +68,8 @@ static const QCssKnownValue properties[NumProperties - 1] = {
{ "-qt-background-role", QtBackgroundRole },
{ "-qt-block-indent", QtBlockIndent },
{ "-qt-list-indent", QtListIndent },
+ { "-qt-list-number-prefix", QtListNumberPrefix },
+ { "-qt-list-number-suffix", QtListNumberSuffix },
{ "-qt-paragraph-type", QtParagraphType },
{ "-qt-style-features", QtStyleFeatures },
{ "-qt-table-type", QtTableType },
@@ -120,6 +122,7 @@ static const QCssKnownValue properties[NumProperties - 1] = {
{ "image", QtImage },
{ "image-position", QtImageAlignment },
{ "left", Left },
+ { "line-height", LineHeight },
{ "list-style", ListStyle },
{ "list-style-type", ListStyleType },
{ "margin" , Margin },
@@ -403,7 +406,7 @@ int ValueExtractor::lengthValue(const Declaration &decl)
if (decl.d->values.count() < 1)
return 0;
LengthData data = lengthValue(decl.d->values.at(0));
- decl.d->parsed = qVariantFromValue<LengthData>(data);
+ decl.d->parsed = QVariant::fromValue<LengthData>(data);
return lengthValueFromData(data,f);
}
@@ -435,7 +438,7 @@ void ValueExtractor::lengthValues(const Declaration &decl, int *m)
QList<QVariant> v;
for (i = 0; i < 4; i++) {
- v += qVariantFromValue<LengthData>(datas[i]);
+ v += QVariant::fromValue<LengthData>(datas[i]);
m[i] = lengthValueFromData(datas[i], f);
}
decl.d->parsed = v;
@@ -541,7 +544,7 @@ QSize ValueExtractor::sizeValue(const Declaration &decl)
else
x[1] = x[0];
QList<QVariant> v;
- v << qVariantFromValue<LengthData>(x[0]) << qVariantFromValue<LengthData>(x[1]);
+ v << QVariant::fromValue<LengthData>(x[0]) << qVariantFromValue<LengthData>(x[1]);
decl.d->parsed = v;
return QSize(lengthValueFromData(x[0], f), lengthValueFromData(x[1], f));
}
@@ -916,7 +919,7 @@ void ValueExtractor::borderValue(const Declaration &decl, int *width, QCss::Bord
data.width = lengthValue(decl.d->values.at(i));
*width = lengthValueFromData(data.width, f);
if (++i >= decl.d->values.count()) {
- decl.d->parsed = qVariantFromValue<BorderData>(data);
+ decl.d->parsed = QVariant::fromValue<BorderData>(data);
return;
}
}
@@ -925,7 +928,7 @@ void ValueExtractor::borderValue(const Declaration &decl, int *width, QCss::Bord
if (data.style != BorderStyle_Unknown) {
*style = data.style;
if (++i >= decl.d->values.count()) {
- decl.d->parsed = qVariantFromValue<BorderData>(data);
+ decl.d->parsed = QVariant::fromValue<BorderData>(data);
return;
}
} else {
@@ -935,7 +938,7 @@ void ValueExtractor::borderValue(const Declaration &decl, int *width, QCss::Bord
data.color = parseBrushValue(decl.d->values.at(i), pal);
*color = brushFromData(data.color, pal);
if (data.color.type != BrushData::DependsOnThePalette)
- decl.d->parsed = qVariantFromValue<BorderData>(data);
+ decl.d->parsed = QVariant::fromValue<BorderData>(data);
}
static void parseShorthandBackgroundProperty(const QVector<Value> &values, BrushData *brush, QString *image, Repeat *repeat, Qt::Alignment *alignment, const QPalette &pal)
@@ -1032,16 +1035,8 @@ bool ValueExtractor::extractBackground(QBrush *brush, QString *image, Repeat *re
parseShorthandBackgroundProperty(decl.d->values, &brushData, image, repeat, alignment, pal);
*brush = brushFromData(brushData, pal);
if (brushData.type != BrushData::DependsOnThePalette) {
-#if defined Q_CC_MSVC && _MSC_VER <= 1300
- BackgroundData data;
- data.brush = brushData;
- data.image = *image;
- data.repeat = *repeat;
- data.alignment = *alignment;
-#else
BackgroundData data = { brushData, *image, *repeat, *alignment };
-#endif
- decl.d->parsed = qVariantFromValue<BackgroundData>(data);
+ decl.d->parsed = QVariant::fromValue<BackgroundData>(data);
}
}
break;
@@ -1319,10 +1314,10 @@ QColor Declaration::colorValue(const QPalette &pal) const
ColorData color = parseColorValue(d->values.at(0));
if(color.type == ColorData::Role) {
- d->parsed = qVariantFromValue<int>(color.role);
+ d->parsed = QVariant::fromValue<int>(color.role);
return pal.color((QPalette::ColorRole)(color.role));
} else {
- d->parsed = qVariantFromValue<QColor>(color.color);
+ d->parsed = QVariant::fromValue<QColor>(color.color);
return color.color;
}
}
@@ -1342,11 +1337,11 @@ QBrush Declaration::brushValue(const QPalette &pal) const
BrushData data = parseBrushValue(d->values.at(0), pal);
if(data.type == BrushData::Role) {
- d->parsed = qVariantFromValue<int>(data.role);
+ d->parsed = QVariant::fromValue<int>(data.role);
return pal.color((QPalette::ColorRole)(data.role));
} else {
if (data.type != BrushData::DependsOnThePalette)
- d->parsed = qVariantFromValue<QBrush>(data.brush);
+ d->parsed = QVariant::fromValue<QBrush>(data.brush);
return data.brush;
}
}
@@ -1376,11 +1371,11 @@ void Declaration::brushValues(QBrush *c, const QPalette &pal) const
continue;
BrushData data = parseBrushValue(d->values.at(i), pal);
if(data.type == BrushData::Role) {
- v += qVariantFromValue<int>(data.role);
+ v += QVariant::fromValue<int>(data.role);
c[i] = pal.color((QPalette::ColorRole)(data.role));
} else {
if (data.type != BrushData::DependsOnThePalette) {
- v += qVariantFromValue<QBrush>(data.brush);
+ v += QVariant::fromValue<QBrush>(data.brush);
} else {
v += QVariant();
}
@@ -1453,7 +1448,7 @@ QSize Declaration::sizeValue() const
else
x[1] = x[0];
QSize size(x[0], x[1]);
- d->parsed = qVariantFromValue<QSize>(size);
+ d->parsed = QVariant::fromValue<QSize>(size);
return size;
}
@@ -1475,7 +1470,7 @@ QRect Declaration::rectValue() const
if (args.count() != 4)
return QRect();
QRect rect(args[0].toInt(), args[1].toInt(), args[2].toInt(), args[3].toInt());
- d->parsed = qVariantFromValue<QRect>(rect);
+ d->parsed = QVariant::fromValue<QRect>(rect);
return rect;
}
@@ -1496,10 +1491,10 @@ void Declaration::colorValues(QColor *c, const QPalette &pal) const
for (i = 0; i < qMin(d->values.count(), 4); i++) {
ColorData color = parseColorValue(d->values.at(i));
if(color.type == ColorData::Role) {
- v += qVariantFromValue<int>(color.role);
+ v += QVariant::fromValue<int>(color.role);
c[i] = pal.color((QPalette::ColorRole)(color.role));
} else {
- v += qVariantFromValue<QColor>(color.color);
+ v += QVariant::fromValue<QColor>(color.color);
c[i] = color.color;
}
}
@@ -1691,7 +1686,7 @@ QIcon Declaration::iconValue() const
i++;
}
- d->parsed = qVariantFromValue<QIcon>(icon);
+ d->parsed = QVariant::fromValue<QIcon>(icon);
return icon;
}
diff --git a/src/gui/text/qcssparser_p.h b/src/gui/text/qcssparser_p.h
index cb2cfd3c1d..79c46b3664 100644
--- a/src/gui/text/qcssparser_p.h
+++ b/src/gui/text/qcssparser_p.h
@@ -178,6 +178,9 @@ enum Property {
OutlineBottomRightRadius,
FontVariant,
TextTransform,
+ QtListNumberPrefix,
+ QtListNumberSuffix,
+ LineHeight,
NumProperties
};
diff --git a/src/gui/text/qfont.cpp b/src/gui/text/qfont.cpp
index 24d8fafe65..084b7ac988 100644
--- a/src/gui/text/qfont.cpp
+++ b/src/gui/text/qfont.cpp
@@ -75,6 +75,10 @@
#ifdef Q_OS_SYMBIAN
#include <private/qt_s60_p.h>
#endif
+#ifdef Q_WS_QPA
+#include <QtGui/qplatformscreen_qpa.h>
+#include <QtGui/private/qapplication_p.h>
+#endif
#include <QMutexLocker>
@@ -172,6 +176,17 @@ Q_GUI_EXPORT int qt_defaultDpiX()
if (!subScreens.isEmpty())
screen = subScreens.at(0);
dpi = qRound(screen->width() / (screen->physicalWidth() / qreal(25.4)));
+#elif defined(Q_WS_QPA)
+ QPlatformIntegration *pi = QApplicationPrivate::platformIntegration();
+ if (pi) {
+ QPlatformScreen *screen = QApplicationPrivate::platformIntegration()->screens().at(0);
+ const QSize screenSize = screen->geometry().size();
+ const QSize physicalSize = screen->physicalSize();
+ dpi = qRound(screenSize.width() / (physicalSize.width() / qreal(25.4)));
+ } else {
+ //PI has not been initialised, or it is being initialised. Give a default dpi
+ dpi = 100;
+ }
#elif defined(Q_OS_SYMBIAN)
dpi = S60->defaultDpiX;
#endif // Q_WS_X11
@@ -200,6 +215,17 @@ Q_GUI_EXPORT int qt_defaultDpiY()
if (!subScreens.isEmpty())
screen = subScreens.at(0);
dpi = qRound(screen->height() / (screen->physicalHeight() / qreal(25.4)));
+#elif defined(Q_WS_QPA)
+ QPlatformIntegration *pi = QApplicationPrivate::platformIntegration();
+ if (pi) {
+ QPlatformScreen *screen = QApplicationPrivate::platformIntegration()->screens().at(0);
+ const QSize screenSize = screen->geometry().size();
+ const QSize physicalSize = screen->physicalSize();
+ dpi = qRound(screenSize.height() / (physicalSize.height() / qreal(25.4)));
+ } else {
+ //PI has not been initialised, or it is being initialised. Give a default dpi
+ dpi = 100;
+ }
#elif defined(Q_OS_SYMBIAN)
dpi = S60->defaultDpiY;
#endif // Q_WS_X11
diff --git a/src/gui/text/qfont.h b/src/gui/text/qfont.h
index 178394bd82..e7e8a40483 100644
--- a/src/gui/text/qfont.h
+++ b/src/gui/text/qfont.h
@@ -226,7 +226,10 @@ public:
bool operator<(const QFont &) const;
operator QVariant() const;
bool isCopyOf(const QFont &) const;
-
+#ifdef Q_COMPILER_RVALUE_REFS
+ inline QFont &operator=(QFont &&other)
+ { qSwap(d, other.d); return *this; }
+#endif
#ifdef Q_WS_WIN
HFONT handle() const;
@@ -315,6 +318,7 @@ private:
friend class QPainterReplayer;
friend class QPaintBufferEngine;
friend class QCommandLinkButtonPrivate;
+ friend class QFontEngine;
#ifndef QT_NO_DATASTREAM
friend Q_GUI_EXPORT QDataStream &operator<<(QDataStream &, const QFont &);
diff --git a/src/gui/text/qfont_mac.cpp b/src/gui/text/qfont_mac.cpp
index b2e5f6e981..daf68c03ea 100644
--- a/src/gui/text/qfont_mac.cpp
+++ b/src/gui/text/qfont_mac.cpp
@@ -42,6 +42,7 @@
#include "qfont.h"
#include "qfont_p.h"
#include "qfontengine_p.h"
+#include "qfontengine_mac_p.h"
#include "qfontinfo.h"
#include "qfontmetrics.h"
#include "qpaintdevice.h"
diff --git a/src/gui/text/qfont_p.h b/src/gui/text/qfont_p.h
index bb69aa10ed..0a3f76daef 100644
--- a/src/gui/text/qfont_p.h
+++ b/src/gui/text/qfont_p.h
@@ -192,6 +192,11 @@ public:
QFont smallCapsFont() const { return QFont(smallCapsFontPrivate()); }
QFontPrivate *smallCapsFontPrivate() const;
+ static QFontPrivate *get(const QFont &font)
+ {
+ return font.d.data();
+ }
+
void resolve(uint mask, const QFontPrivate *other);
private:
QFontPrivate &operator=(const QFontPrivate &) { return *this; }
diff --git a/src/gui/text/qfont_qpa.cpp b/src/gui/text/qfont_qpa.cpp
new file mode 100644
index 0000000000..5fed18bc5e
--- /dev/null
+++ b/src/gui/text/qfont_qpa.cpp
@@ -0,0 +1,114 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <QtGui/private/qapplication_p.h>
+#include <QtGui/QPlatformFontDatabase>
+
+QT_BEGIN_NAMESPACE
+
+void QFont::initialize()
+{
+ QApplicationPrivate::platformIntegration()->fontDatabase()->populateFontDatabase();
+}
+
+void QFont::cleanup()
+{
+ QFontCache::cleanup();
+}
+
+
+/*****************************************************************************
+ QFont member functions
+ *****************************************************************************/
+
+Qt::HANDLE QFont::handle() const
+{
+ return 0;
+}
+
+QString QFont::rawName() const
+{
+ return QLatin1String("unknown");
+}
+
+void QFont::setRawName(const QString &)
+{
+}
+
+QString QFont::defaultFamily() const
+{
+ QString familyName;
+ switch(d->request.styleHint) {
+ case QFont::Times:
+ familyName = QString::fromLatin1("times");
+ case QFont::Courier:
+ case QFont::Monospace:
+ familyName = QString::fromLatin1("monospace");
+ case QFont::Decorative:
+ familyName = QString::fromLatin1("old english");
+ case QFont::Helvetica:
+ case QFont::System:
+ default:
+ familyName = QString::fromLatin1("helvetica");
+ }
+
+ QStringList list = QApplicationPrivate::platformIntegration()->fontDatabase()->fallbacksForFamily(familyName,QFont::StyleNormal,QUnicodeTables::Common);
+ if (list.size()) {
+ familyName = list.at(0);
+ }
+ return familyName;
+}
+
+QString QFont::lastResortFamily() const
+{
+ return QString::fromLatin1("helvetica");
+}
+
+QString QFont::lastResortFont() const
+{
+ qFatal("QFont::lastResortFont: Cannot find any reasonable font");
+ // Shut compiler up
+ return QString();
+}
+
+
+QT_END_NAMESPACE
+
diff --git a/src/gui/text/qfontdatabase.cpp b/src/gui/text/qfontdatabase.cpp
index 5cecf08bef..20c72dde6b 100644
--- a/src/gui/text/qfontdatabase.cpp
+++ b/src/gui/text/qfontdatabase.cpp
@@ -50,13 +50,19 @@
#include "private/qunicodetables_p.h"
#include "qfontengine_p.h"
+#ifdef Q_WS_QPA
+#include <QtGui/private/qapplication_p.h>
+#include <QtGui/qplatformfontdatabase_qpa.h>
+#include "qabstractfileengine.h"
+#endif
+
#ifdef Q_WS_X11
#include <locale.h>
#endif
#include <stdlib.h>
#include <limits.h>
-#if (defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN)) && !defined(QT_NO_FREETYPE)
+#if (defined(Q_WS_QWS)|| defined(Q_OS_SYMBIAN)) && !defined(QT_NO_FREETYPE)
# include <ft2build.h>
# include FT_TRUETYPE_TABLES_H
#endif
@@ -75,10 +81,6 @@
# define FM_DEBUG if (false) qDebug
#endif
-#if defined(Q_CC_MSVC) && !defined(Q_CC_MSVC_NET)
-# define for if(0){}else for
-#endif
-
QT_BEGIN_NAMESPACE
#define SMOOTH_SCALABLE 0xffff
@@ -143,7 +145,7 @@ struct QtFontEncoding
uchar pitch : 8;
};
-struct QtFontSize
+struct QtFontSize
{
#ifdef Q_WS_X11
QtFontEncoding *encodings;
@@ -151,10 +153,14 @@ struct QtFontSize
uint yres = 0, uint avgwidth = 0, bool add = false);
unsigned short count : 16;
#endif // Q_WS_X11
+
#if defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN)
QByteArray fileName;
int fileIndex;
-#endif // defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN)
+#endif // defined(Q_WS_QWS) || defined(Q_WS_QPA) || defined(Q_OS_SYMBIAN)
+#if defined(Q_WS_QPA)
+ void *handle;
+#endif
unsigned short pixelSize : 16;
};
@@ -230,7 +236,7 @@ struct QtFontStyle
delete [] weightName;
delete [] setwidthName;
#endif
-#if defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN)
+#if defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_WS_QPA) || defined(Q_OS_SYMBIAN)
while (count) {
// bitfield count-- in while condition does not work correctly in mwccsym2
count--;
@@ -240,6 +246,12 @@ struct QtFontStyle
#if defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN)
pixelSizes[count].fileName.~QByteArray();
#endif
+#if defined (Q_WS_QPA)
+ QPlatformIntegration *integration = QApplicationPrivate::platformIntegration();
+ if (integration) { //on shut down there will be some that we don't release.
+ integration->fontDatabase()->releaseHandle(pixelSizes[count].handle);
+ }
+#endif
}
#endif
free(pixelSizes);
@@ -255,7 +267,7 @@ struct QtFontStyle
const char *weightName;
const char *setwidthName;
#endif // Q_WS_X11
-#if defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN)
+#if defined(Q_WS_QWS) || defined(Q_WS_QPA) || defined(Q_OS_SYMBIAN)
bool antialiased;
#endif
@@ -305,6 +317,9 @@ QtFontSize *QtFontStyle::pixelSize(unsigned short size, bool add)
new (&pixelSizes[count].fileName) QByteArray;
pixelSizes[count].fileIndex = 0;
#endif
+#if defined(Q_WS_QPA)
+ pixelSizes[count].handle = 0;
+#endif
return pixelSizes + (count++);
}
@@ -361,7 +376,7 @@ QtFontStyle *QtFontFoundry::style(const QtFontStyle::Key &key, bool create)
}
-struct QtFontFamily
+struct QtFontFamily
{
enum WritingSystemStatus {
Unknown = 0,
@@ -387,9 +402,12 @@ struct QtFontFamily
fixedPitchComputed(false),
#endif
name(n), count(0), foundries(0)
-#if defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN) && !defined(QT_NO_FREETYPE)
+#if defined(Q_WS_QWS) || defined(Q_WS_QPA) || defined(Q_OS_SYMBIAN) && !defined(QT_NO_FREETYPE)
, bogusWritingSystems(false)
#endif
+#if defined(Q_WS_QPA)
+ , askedForFallback(false)
+#endif
{
memset(writingSystems, 0, sizeof(writingSystems));
}
@@ -427,10 +445,13 @@ struct QtFontFamily
int count;
QtFontFoundry **foundries;
-#if defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN) && !defined(QT_NO_FREETYPE)
+#if defined(Q_WS_QWS) || defined(Q_WS_QPA) || defined(Q_OS_SYMBIAN) && !defined(QT_NO_FREETYPE)
bool bogusWritingSystems;
QStringList fallbackFamilies;
#endif
+#if defined (Q_WS_QPA)
+ bool askedForFallback;
+#endif
unsigned char writingSystems[QFontDatabase::WritingSystemsCount];
QtFontFoundry *foundry(const QString &f, bool = false);
@@ -475,6 +496,7 @@ QtFontFoundry *QtFontFamily::foundry(const QString &f, bool create)
// ### copied to tools/makeqpf/qpf2.cpp
#if (defined(Q_WS_QWS) && !defined(QT_NO_FREETYPE)) || defined(Q_WS_WIN) || defined(Q_OS_SYMBIAN) || (defined(Q_WS_MAC) && !defined(QT_MAC_USE_COCOA))
+
// see the Unicode subset bitfields in the MSDN docs
static int requiredUnicodeBits[QFontDatabase::WritingSystemsCount][2] = {
// Any,
@@ -642,6 +664,9 @@ public:
}
int count;
+#if defined(Q_WS_X11) && !defined(QT_NO_FONTCONFIG)
+ QString systemLang;
+#endif
QtFontFamily **families;
struct ApplicationFont {
@@ -667,7 +692,7 @@ public:
bool loadFromCache(const QString &fontPath);
void addQPF2File(const QByteArray &file);
#endif // Q_WS_QWS
-#if defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN) && !defined(QT_NO_FREETYPE)
+#if defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN) && !defined(QT_NO_FREETYPE)
void addFont(const QString &familyname, const char *foundryname, int weight,
bool italic, int pixelSize, const QByteArray &file, int fileIndex,
bool antialiased,
@@ -678,10 +703,12 @@ public:
#endif
#if defined(Q_WS_QWS)
QDataStream *stream;
- QStringList fallbackFamilies;
#elif defined(Q_OS_SYMBIAN) && defined(QT_NO_FREETYPE)
const QSymbianFontDatabaseExtras *symbianExtras;
#endif
+#if defined(Q_WS_QWS) || defined(Q_WS_QPA)
+ QStringList fallbackFamilies;
+#endif
};
void QFontDatabasePrivate::invalidate()
@@ -730,7 +757,7 @@ QtFontFamily *QFontDatabasePrivate::family(const QString &f, bool create)
return families[pos];
}
-#if defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN) && !defined(QT_NO_FREETYPE)
+#if defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN) && !defined(QT_NO_FREETYPE)
void QFontDatabasePrivate::addFont(const QString &familyname, const char *foundryname, int weight, bool italic, int pixelSize,
const QByteArray &file, int fileIndex, bool antialiased,
const QList<QFontDatabase::WritingSystem> &writingSystems)
@@ -963,7 +990,7 @@ static void match(int script, const QFontDef &request,
const QString &family_name, const QString &foundry_name, int force_encoding_id,
QtFontDesc *desc, const QList<int> &blacklistedFamilies = QList<int>(), bool forceXLFD=false);
-#if defined(Q_WS_X11) || defined(Q_WS_QWS)
+#if defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_WS_QPA)
static void initFontDef(const QtFontDesc &desc, const QFontDef &request, QFontDef *fontDef)
{
fontDef->family = desc.family->name;
@@ -992,7 +1019,7 @@ static void initFontDef(const QtFontDesc &desc, const QFontDef &request, QFontDe
#endif
#endif
-#if defined(Q_WS_X11) || defined(Q_WS_WIN) || defined(Q_OS_SYMBIAN)
+#if defined(Q_WS_X11) || defined(Q_WS_WIN) || defined(Q_OS_SYMBIAN) || defined(Q_WS_QPA)
static void getEngineData(const QFontPrivate *d, const QFontCache::Key &key)
{
// look for the requested font in the engine data cache
@@ -1053,6 +1080,8 @@ QT_BEGIN_INCLUDE_NAMESPACE
# include "qfontdatabase_win.cpp"
#elif defined(Q_WS_QWS)
# include "qfontdatabase_qws.cpp"
+#elif defined(Q_WS_QPA)
+# include "qfontdatabase_qpa.cpp"
#elif defined(Q_OS_SYMBIAN)
# include "qfontdatabase_s60.cpp"
#endif
@@ -1338,6 +1367,7 @@ static void match(int script, const QFontDef &request,
styleKey.stretch = request.stretch;
char pitch = request.ignorePitch ? '*' : request.fixedPitch ? 'm' : 'p';
+
FM_DEBUG("QFontDatabase::match\n"
" request:\n"
" family: %s [%s], script: %d\n"
@@ -2427,10 +2457,12 @@ QString QFontDatabase::writingSystemSample(WritingSystem writingSystem)
sample += QChar(0x4f8b);
break;
case Japanese:
- sample += QChar(0x3050);
- sample += QChar(0x3060);
- sample += QChar(0x30b0);
- sample += QChar(0x30c0);
+ sample += QChar(0x30b5);
+ sample += QChar(0x30f3);
+ sample += QChar(0x30d7);
+ sample += QChar(0x30eb);
+ sample += QChar(0x3067);
+ sample += QChar(0x3059);
break;
case Korean:
sample += QChar(0xac00);
@@ -2483,7 +2515,7 @@ void QFontDatabase::createDatabase()
{ initializeDb(); }
// used from qfontengine_ft.cpp
-QByteArray qt_fontdata_from_index(int index)
+Q_GUI_EXPORT QByteArray qt_fontdata_from_index(int index)
{
QMutexLocker locker(fontDatabaseMutex());
return privateDb()->applicationFonts.value(index).data;
diff --git a/src/gui/text/qfontdatabase.h b/src/gui/text/qfontdatabase.h
index 69a24843dd..3e9483b097 100644
--- a/src/gui/text/qfontdatabase.h
+++ b/src/gui/text/qfontdatabase.h
@@ -152,7 +152,7 @@ public:
private:
static void createDatabase();
static void parseFontName(const QString &name, QString &foundry, QString &family);
-#if defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN)
+#if defined(Q_WS_QWS) || defined(Q_WS_QPA) || defined(Q_OS_SYMBIAN)
static QFontEngine *findFont(int script, const QFontPrivate *fp, const QFontDef &request);
#endif
static void load(const QFontPrivate *d, int script);
@@ -167,6 +167,7 @@ private:
friend class QFontEngineMultiXLFD;
friend class QFontEngineMultiQWS;
friend class QFontEngineMultiS60;
+ friend class QFontEngineMultiQPA;
QFontDatabasePrivate *d;
};
diff --git a/src/gui/text/qfontdatabase_mac.cpp b/src/gui/text/qfontdatabase_mac.cpp
index 6dfec28b02..ad2c1b2ea6 100644
--- a/src/gui/text/qfontdatabase_mac.cpp
+++ b/src/gui/text/qfontdatabase_mac.cpp
@@ -45,6 +45,8 @@
#include <qabstractfileengine.h>
#include <stdlib.h>
#include <qendian.h>
+#include <private/qfontengine_coretext_p.h>
+#include <private/qfontengine_mac_p.h>
QT_BEGIN_NAMESPACE
@@ -293,8 +295,12 @@ void QFontDatabase::load(const QFontPrivate *d, int script)
// previous versions
family_list << QApplication::font().defaultFamily();
+#if defined(QT_MAC_USE_COCOA)
+ QCFString fontName = NULL, familyName = NULL;
+#else
ATSFontFamilyRef familyRef = 0;
ATSFontRef fontRef = 0;
+#endif
QMutexLocker locker(fontDatabaseMutex());
QFontDatabasePrivate *db = privateDb();
@@ -304,26 +310,20 @@ void QFontDatabase::load(const QFontPrivate *d, int script)
for (int k = 0; k < db->count; ++k) {
if (db->families[k]->name.compare(family_list.at(i), Qt::CaseInsensitive) == 0) {
QByteArray family_name = db->families[k]->name.toUtf8();
+#if defined(QT_MAC_USE_COCOA)
+ QCFType<CTFontRef> ctFont = CTFontCreateWithName(QCFString(db->families[k]->name), 12, NULL);
+ if (ctFont) {
+ fontName = CTFontCopyFullName(ctFont);
+ familyName = CTFontCopyFamilyName(ctFont);
+ goto FamilyFound;
+ }
+#else
familyRef = ATSFontFamilyFindFromName(QCFString(db->families[k]->name), kATSOptionFlagsDefault);
if (familyRef) {
fontRef = ATSFontFindFromName(QCFString(db->families[k]->name), kATSOptionFlagsDefault);
goto FamilyFound;
- } else {
-#if defined(QT_MAC_USE_COCOA)
- // ATS and CT disagrees on what the family name should be,
- // use CT to look up the font if ATS fails.
- QCFString familyName = QString::fromAscii(family_name);
- QCFType<CTFontRef> CTfontRef = CTFontCreateWithName(familyName, 12, NULL);
- QCFType<CTFontDescriptorRef> fontDescriptor = CTFontCopyFontDescriptor(CTfontRef);
- QCFString displayName = (CFStringRef)CTFontDescriptorCopyAttribute(fontDescriptor, kCTFontDisplayNameAttribute);
-
- familyRef = ATSFontFamilyFindFromName(displayName, kATSOptionFlagsDefault);
- if (familyRef) {
- fontRef = ATSFontFindFromName(displayName, kATSOptionFlagsDefault);
- goto FamilyFound;
- }
-#endif
}
+#endif
}
}
}
@@ -331,92 +331,18 @@ FamilyFound:
//fill in the engine's font definition
QFontDef fontDef = d->request; //copy..
if(fontDef.pointSize < 0)
- fontDef.pointSize = qt_mac_pointsize(fontDef, d->dpi);
+ fontDef.pointSize = qt_mac_pointsize(fontDef, d->dpi);
else
- fontDef.pixelSize = qt_mac_pixelsize(fontDef, d->dpi);
-#if 0
- ItemCount name_count;
- if(ATSUCountFontNames(fontID, &name_count) == noErr && name_count) {
- ItemCount actualName_size;
- if(ATSUGetIndFontName(fontID, 0, 0, 0, &actualName_size, 0, 0, 0, 0) == noErr && actualName_size) {
- QByteArray actualName(actualName_size);
- if(ATSUGetIndFontName(fontID, 0, actualName_size, actualName.data(), &actualName_size, 0, 0, 0, 0) == noErr && actualName_size)
- fontDef.family = QString::fromUtf8(actualName);
- }
- }
-#else
- {
- QCFString actualName;
- if(ATSFontFamilyGetName(familyRef, kATSOptionFlagsDefault, &actualName) == noErr)
- fontDef.family = actualName;
- }
-#endif
+ fontDef.pixelSize = qt_mac_pixelsize(fontDef, d->dpi);
#ifdef QT_MAC_USE_COCOA
- QFontEngine *engine = new QCoreTextFontEngineMulti(familyRef, fontRef, fontDef, d->kerning);
-#elif 1
- QFontEngine *engine = new QFontEngineMacMulti(familyRef, fontRef, fontDef, d->kerning);
+ fontDef.family = familyName;
+ QFontEngine *engine = new QCoreTextFontEngineMulti(fontName, fontDef, d->kerning);
#else
- ATSFontFamilyRef atsFamily = familyRef;
- ATSFontFamilyRef atsFontRef = fontRef;
-
- FMFont fontID;
- FMFontFamily fmFamily;
- FMFontStyle fntStyle = 0;
- fmFamily = FMGetFontFamilyFromATSFontFamilyRef(atsFamily);
- if (fmFamily == kInvalidFontFamily) {
- // Use the ATSFont then...
- fontID = FMGetFontFromATSFontRef(atsFontRef);
- } else {
- if (fontDef.weight >= QFont::Bold)
- fntStyle |= ::bold;
- if (fontDef.style != QFont::StyleNormal)
- fntStyle |= ::italic;
-
- FMFontStyle intrinsicStyle;
- FMFont fnt = 0;
- if (FMGetFontFromFontFamilyInstance(fmFamily, fntStyle, &fnt, &intrinsicStyle) == noErr)
- fontID = FMGetATSFontRefFromFont(fnt);
- }
-
- OSStatus status;
-
- const int maxAttributeCount = 5;
- ATSUAttributeTag tags[maxAttributeCount + 1];
- ByteCount sizes[maxAttributeCount + 1];
- ATSUAttributeValuePtr values[maxAttributeCount + 1];
- int attributeCount = 0;
-
- Fixed size = FixRatio(fontDef.pixelSize, 1);
- tags[attributeCount] = kATSUSizeTag;
- sizes[attributeCount] = sizeof(size);
- values[attributeCount] = &size;
- ++attributeCount;
-
- tags[attributeCount] = kATSUFontTag;
- sizes[attributeCount] = sizeof(fontID);
- values[attributeCount] = &fontID;
- ++attributeCount;
-
- CGAffineTransform transform = CGAffineTransformIdentity;
- if (fontDef.stretch != 100) {
- transform = CGAffineTransformMakeScale(float(fontDef.stretch) / float(100), 1);
- tags[attributeCount] = kATSUFontMatrixTag;
- sizes[attributeCount] = sizeof(transform);
- values[attributeCount] = &transform;
- ++attributeCount;
- }
-
- ATSUStyle style;
- status = ATSUCreateStyle(&style);
- Q_ASSERT(status == noErr);
-
- Q_ASSERT(attributeCount < maxAttributeCount + 1);
- status = ATSUSetAttributes(style, attributeCount, tags, sizes, values);
- Q_ASSERT(status == noErr);
-
- QFontEngine *engine = new QFontEngineMac(style, fontID, fontDef, /*multiEngine*/ 0);
- ATSUDisposeStyle(style);
+ QCFString actualName;
+ if (ATSFontFamilyGetName(familyRef, kATSOptionFlagsDefault, &actualName) == noErr)
+ fontDef.family = actualName;
+ QFontEngine *engine = new QFontEngineMacMulti(familyRef, fontRef, fontDef, d->kerning);
#endif
d->engineData->engine = engine;
engine->ref.ref(); //a ref for the engineData->engine
diff --git a/src/gui/text/qfontdatabase_qpa.cpp b/src/gui/text/qfontdatabase_qpa.cpp
new file mode 100644
index 0000000000..e54093ce2e
--- /dev/null
+++ b/src/gui/text/qfontdatabase_qpa.cpp
@@ -0,0 +1,390 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qlibraryinfo.h"
+#include <QtCore/qsettings.h>
+
+#include "qfontengine_qpa_p.h"
+#include "qplatformdefs.h"
+
+#include <QtGui/private/qapplication_p.h>
+#include <QtGui/qplatformfontdatabase_qpa.h>
+
+#include <QtCore/qmath.h>
+
+QT_BEGIN_NAMESPACE
+
+Q_GUI_EXPORT void qt_registerFont(const QString &familyName, const QString &foundryname, int weight,
+ QFont::Style style, int stretch, bool antialiased, bool scalable, int pixelSize,
+ const QSupportedWritingSystems &writingSystems, void *handle)
+{
+ QFontDatabasePrivate *d = privateDb();
+ // qDebug() << "Adding font" << familyname << weight << italic << pixelSize << file << fileIndex << antialiased;
+ QtFontStyle::Key styleKey;
+ styleKey.style = style;
+ styleKey.weight = weight;
+ styleKey.stretch = stretch;
+ QtFontFamily *f = d->family(familyName, true);
+
+ for (int i = 0; i < QFontDatabase::WritingSystemsCount; ++i) {
+ if (writingSystems.supported(QFontDatabase::WritingSystem(i))) {
+ f->writingSystems[i] = QtFontFamily::Supported;
+ } else {
+ f->writingSystems[i] = QtFontFamily::Unsupported;
+ }
+ }
+
+ QtFontFoundry *foundry = f->foundry(foundryname, true);
+ QtFontStyle *fontStyle = foundry->style(styleKey, true);
+ fontStyle->smoothScalable = scalable;
+ fontStyle->antialiased = antialiased;
+ QtFontSize *size = fontStyle->pixelSize(pixelSize?pixelSize:SMOOTH_SCALABLE, true);
+ size->handle = handle;
+}
+
+static QStringList fallbackFamilies(const QString &family, const QFont::Style &style, const QUnicodeTables::Script &script)
+{
+ QStringList retList = QApplicationPrivate::platformIntegration()->fontDatabase()->fallbacksForFamily(family,style,script);
+ QFontDatabasePrivate *db = privateDb();
+
+ QStringList::iterator i;
+ for (i = retList.begin(); i != retList.end(); ++i) {
+ bool contains = false;
+ for (int j = 0; j < db->count; j++) {
+ QtFontFamily *qtFamily = db->families[j];
+ if (!(i->compare(qtFamily->name,Qt::CaseInsensitive))) {
+ contains = true;
+ break;
+ }
+ }
+ if (!contains) {
+ i = retList.erase(i);
+ i--;
+ }
+ }
+ return retList;
+}
+
+static void initializeDb()
+{
+ static int initialized = false;
+
+ if (!initialized) {
+ //init by asking for the platformfontdb for the first time :)
+ QApplicationPrivate::platformIntegration()->fontDatabase()->populateFontDatabase();
+ initialized = true;
+ }
+}
+
+#ifndef QT_NO_SETTINGS
+// called from qapplication_qws.cpp
+void qt_applyFontDatabaseSettings(const QSettings &settings)
+{
+ initializeDb();
+ QFontDatabasePrivate *db = privateDb();
+ for (int i = 0; i < db->count; ++i) {
+ QtFontFamily *family = db->families[i];
+ if (settings.contains(family->name))
+ family->fallbackFamilies = settings.value(family->name).toStringList();
+ }
+
+ if (settings.contains(QLatin1String("Global Fallbacks")))
+ db->fallbackFamilies = settings.value(QLatin1String("Global Fallbacks")).toStringList();
+}
+#endif // QT_NO_SETTINGS
+
+static inline void load(const QString & = QString(), int = -1)
+{
+ initializeDb();
+}
+
+static
+QFontEngine *loadSingleEngine(int script,
+ const QFontDef &request,
+ QtFontFoundry *foundry,
+ QtFontStyle *style, QtFontSize *size)
+{
+ Q_UNUSED(foundry);
+
+ Q_ASSERT(size);
+ int pixelSize = size->pixelSize;
+ if (!pixelSize || (style->smoothScalable && pixelSize == SMOOTH_SCALABLE))
+ pixelSize = request.pixelSize;
+
+ QFontDef def = request;
+ def.pixelSize = pixelSize;
+
+ QFontCache::Key key(def,script);
+ QFontEngine *engine = QFontCache::instance()->findEngine(key);
+ if (!engine) {
+ QPlatformFontDatabase *pfdb = QApplicationPrivate::platformIntegration()->fontDatabase();
+ engine = pfdb->fontEngine(def,QUnicodeTables::Script(script),size->handle);
+ if (engine) {
+ QFontCache::Key key(def,script);
+ QFontCache::instance()->instance()->insertEngine(key,engine);
+ }
+ }
+ return engine;
+}
+
+static
+QFontEngine *loadEngine(int script, const QFontDef &request,
+ QtFontFamily *family, QtFontFoundry *foundry,
+ QtFontStyle *style, QtFontSize *size)
+{
+
+ QFontEngine *engine = loadSingleEngine(script, request, foundry, style, size);
+ //make sure that the db has all fallback families
+ if (engine
+ && !(request.styleStrategy & QFont::NoFontMerging) && !engine->symbol ) {
+
+ if (family && !family->askedForFallback) {
+ family->fallbackFamilies = fallbackFamilies(family->name,QFont::Style(style->key.style),QUnicodeTables::Script(script));
+
+ family->askedForFallback = true;
+ }
+
+ QStringList fallbacks = privateDb()->fallbackFamilies;
+ if (family && !family->fallbackFamilies.isEmpty())
+ fallbacks = family->fallbackFamilies;
+
+ engine = new QFontEngineMultiQPA(engine, script, fallbacks);
+ }
+
+ return engine;
+}
+
+static void registerFont(QFontDatabasePrivate::ApplicationFont *fnt)
+{
+ QFontDatabasePrivate *db = privateDb();
+
+ fnt->families = QApplicationPrivate::platformIntegration()->fontDatabase()->addApplicationFont(fnt->data,fnt->fileName);
+
+ db->reregisterAppFonts = true;
+}
+
+bool QFontDatabase::removeApplicationFont(int handle)
+{
+ QMutexLocker locker(fontDatabaseMutex());
+
+ QFontDatabasePrivate *db = privateDb();
+ if (handle < 0 || handle >= db->applicationFonts.count())
+ return false;
+
+ db->applicationFonts[handle] = QFontDatabasePrivate::ApplicationFont();
+
+ db->reregisterAppFonts = true;
+ db->invalidate();
+ return true;
+}
+
+bool QFontDatabase::removeAllApplicationFonts()
+{
+ QMutexLocker locker(fontDatabaseMutex());
+
+ QFontDatabasePrivate *db = privateDb();
+ if (db->applicationFonts.isEmpty())
+ return false;
+
+ db->applicationFonts.clear();
+ db->invalidate();
+ return true;
+}
+
+bool QFontDatabase::supportsThreadedFontRendering()
+{
+ return true;
+}
+
+/*!
+ \internal
+*/
+QFontEngine *
+QFontDatabase::findFont(int script, const QFontPrivate *fp,
+ const QFontDef &request)
+{
+ QMutexLocker locker(fontDatabaseMutex());
+
+ const int force_encoding_id = -1;
+
+ if (!privateDb()->count)
+ initializeDb();
+
+ QFontEngine *engine;
+ QFontCache::Key key(request, script);
+ engine = QFontCache::instance()->findEngine(key);
+ if (engine) {
+ qDebug() << "Cache hit level 1";
+ return engine;
+ }
+
+ QString family_name, foundry_name;
+
+ parseFontName(request.family, foundry_name, family_name);
+
+ if (qt_enable_test_font && request.family == QLatin1String("__Qt__Box__Engine__")) {
+ engine =new QTestFontEngine(request.pixelSize);
+ engine->fontDef = request;
+ }
+
+ QtFontDesc desc;
+ match(script, request, family_name, foundry_name, force_encoding_id, &desc);
+ if (desc.family != 0 && desc.foundry != 0 && desc.style != 0) {
+ engine = loadEngine(script, request, desc.family, desc.foundry, desc.style, desc.size);
+ } else {
+ FM_DEBUG(" NO MATCH FOUND\n");
+ }
+
+ if (engine) {
+ initFontDef(desc, request, &engine->fontDef);
+
+ if (fp) {
+ QFontDef def = request;
+ if (def.family.isEmpty()) {
+ def.family = fp->request.family;
+ def.family = def.family.left(def.family.indexOf(QLatin1Char(',')));
+ }
+ }
+ }
+
+ if (!engine) {
+ if (!request.family.isEmpty()) {
+ QStringList fallbacks = fallbackFamilies(request.family,QFont::Style(request.style),QUnicodeTables::Script(script));
+ for (int i = 0; i < fallbacks.size(); i++) {
+ QFontDef def = request;
+ def.family = fallbacks.at(i);
+ QFontCache::Key key(def,script);
+ engine = QFontCache::instance()->findEngine(key);
+ if (!engine) {
+ QtFontDesc desc;
+ match(script, def, def.family, QLatin1String(""), 0, &desc);
+ if (desc.family == 0 && desc.foundry == 0 && desc.style == 0) {
+ continue;
+ }
+ engine = loadEngine(script, def, desc.family, desc.foundry, desc.style, desc.size);
+ if (engine) {
+ initFontDef(desc, def, &engine->fontDef);
+ break;
+ }
+ }
+ }
+ }
+
+ if (!engine)
+ engine = new QFontEngineBox(request.pixelSize);
+
+ FM_DEBUG("returning box engine");
+ }
+
+ if (fp && fp->dpi > 0) {
+ engine->fontDef.pointSize = qreal(double((engine->fontDef.pixelSize * 72) / fp->dpi));
+ } else {
+ engine->fontDef.pointSize = request.pointSize;
+ }
+
+ return engine;
+}
+
+void QFontDatabase::load(const QFontPrivate *d, int script)
+{
+ QFontDef req = d->request;
+
+ if (req.pixelSize == -1) {
+ req.pixelSize = floor(((req.pointSize * d->dpi) / 72) * 100 + 0.5) / 100;
+ req.pixelSize = qRound(req.pixelSize);
+ }
+ if (req.pointSize < 0)
+ req.pointSize = req.pixelSize*72.0/d->dpi;
+ if (req.weight == 0)
+ req.weight = QFont::Normal;
+ if (req.stretch == 0)
+ req.stretch = 100;
+
+ QFontCache::Key key(req, script);
+
+ if (!d->engineData)
+ getEngineData(d, key);
+
+ // the cached engineData could have already loaded the engine we want
+ if (d->engineData->engines[script])
+ return;
+
+ QFontEngine *fe = QFontCache::instance()->findEngine(key);
+
+ // list of families to try
+ QStringList family_list;
+
+ if (!req.family.isEmpty()) {
+ family_list = familyList(req);
+
+ // add the default family
+ QString defaultFamily = QApplication::font().family();
+ if (! family_list.contains(defaultFamily))
+ family_list << defaultFamily;
+
+ }
+
+ // null family means find the first font matching the specified script
+ family_list << QString();
+
+ QStringList::ConstIterator it = family_list.constBegin(), end = family_list.constEnd();
+ for (; !fe && it != end; ++it) {
+ req.family = *it;
+
+ fe = QFontDatabase::findFont(script, d, req);
+ if (fe && (fe->type()==QFontEngine::Box) && !req.family.isEmpty())
+ fe = 0;
+ }
+
+ if (fe->symbol || (d->request.styleStrategy & QFont::NoFontMerging)) {
+ for (int i = 0; i < QUnicodeTables::ScriptCount; ++i) {
+ if (!d->engineData->engines[i]) {
+ d->engineData->engines[i] = fe;
+ fe->ref.ref();
+ }
+ }
+ } else {
+ d->engineData->engines[script] = fe;
+ fe->ref.ref();
+ }
+}
+
+QT_END_NAMESPACE
diff --git a/src/gui/text/qfontdatabase_qws.cpp b/src/gui/text/qfontdatabase_qws.cpp
index a0126f12ec..d076de05d3 100644
--- a/src/gui/text/qfontdatabase_qws.cpp
+++ b/src/gui/text/qfontdatabase_qws.cpp
@@ -40,8 +40,10 @@
****************************************************************************/
#include "qdir.h"
+#if defined(Q_WS_QWS)
#include "qscreen_qws.h" //so we can check for rotation
#include "qwindowsystem_qws.h"
+#endif
#include "qlibraryinfo.h"
#include "qabstractfileengine.h"
#include <QtCore/qsettings.h>
@@ -153,7 +155,11 @@ extern QString qws_fontCacheDir();
#ifndef QT_FONTS_ARE_RESOURCES
bool QFontDatabasePrivate::loadFromCache(const QString &fontPath)
{
+#ifdef Q_WS_QWS
const bool weAreTheServer = QWSServer::instance();
+#else
+ const bool weAreTheServer = true; // assume single-process
+#endif
QString fontDirFile = fontPath + QLatin1String("/fontdir");
@@ -382,12 +388,14 @@ static void initializeDb()
}
#endif
+#ifndef QT_NO_QWS_QPF2
QDir dir(fontpath, QLatin1String("*.qpf2"));
for (int i = 0; i < int(dir.count()); ++i) {
const QByteArray file = QFile::encodeName(dir.absoluteFilePath(dir[i]));
//qDebug() << "looking at" << file;
db->addQPF2File(file);
}
+#endif
#endif //QT_FONTS_ARE_RESOURCES
@@ -688,6 +696,7 @@ QFontEngine *loadEngine(int script, const QFontPrivate *fp,
{
QScopedPointer<QFontEngine> engine(loadSingleEngine(script, fp, request, family, foundry,
style, size));
+#ifndef QT_NO_QWS_QPF
if (!engine.isNull()
&& script == QUnicodeTables::Common
&& !(request.styleStrategy & QFont::NoFontMerging) && !engine->symbol) {
@@ -701,6 +710,7 @@ QFontEngine *loadEngine(int script, const QFontPrivate *fp,
engine.take();
engine.reset(fe);
}
+#endif
return engine.take();
}
diff --git a/src/gui/text/qfontdatabase_x11.cpp b/src/gui/text/qfontdatabase_x11.cpp
index a4a5665720..2186058e9f 100644
--- a/src/gui/text/qfontdatabase_x11.cpp
+++ b/src/gui/text/qfontdatabase_x11.cpp
@@ -1018,6 +1018,13 @@ static void loadFontConfig()
QFontDatabasePrivate *db = privateDb();
FcFontSet *fonts;
+ FcPattern *pattern = FcPatternCreate();
+ FcDefaultSubstitute(pattern);
+ FcChar8 *lang = 0;
+ if (FcPatternGetString(pattern, FC_LANG, 0, &lang) == FcResultMatch)
+ db->systemLang = QString::fromUtf8((const char *) lang);
+ FcPatternDestroy(pattern);
+
QString familyName;
FcChar8 *value = 0;
int weight_value;
@@ -1455,6 +1462,7 @@ void qt_addPatternProps(FcPattern *pattern, int screen, int script, const QFontD
weight_value = FC_WEIGHT_DEMIBOLD;
else if (request.weight < (QFont::Bold + QFont::Black) / 2)
weight_value = FC_WEIGHT_BOLD;
+ FcPatternDel(pattern, FC_WEIGHT);
FcPatternAddInteger(pattern, FC_WEIGHT, weight_value);
int slant_value = FC_SLANT_ROMAN;
@@ -1462,20 +1470,25 @@ void qt_addPatternProps(FcPattern *pattern, int screen, int script, const QFontD
slant_value = FC_SLANT_ITALIC;
else if (request.style == QFont::StyleOblique)
slant_value = FC_SLANT_OBLIQUE;
+ FcPatternDel(pattern, FC_SLANT);
FcPatternAddInteger(pattern, FC_SLANT, slant_value);
double size_value = qMax(qreal(1.), request.pixelSize);
+ FcPatternDel(pattern, FC_PIXEL_SIZE);
FcPatternAddDouble(pattern, FC_PIXEL_SIZE, size_value);
int stretch = request.stretch;
if (!stretch)
stretch = 100;
+ FcPatternDel(pattern, FC_WIDTH);
FcPatternAddInteger(pattern, FC_WIDTH, stretch);
if (X11->display && QX11Info::appDepth(screen) <= 8) {
+ FcPatternDel(pattern, FC_ANTIALIAS);
// can't do antialiasing on 8bpp
FcPatternAddBool(pattern, FC_ANTIALIAS, false);
} else if (request.styleStrategy & (QFont::PreferAntialias|QFont::NoAntialias)) {
+ FcPatternDel(pattern, FC_ANTIALIAS);
FcPatternAddBool(pattern, FC_ANTIALIAS,
!(request.styleStrategy & QFont::NoAntialias));
}
@@ -1484,6 +1497,7 @@ void qt_addPatternProps(FcPattern *pattern, int screen, int script, const QFontD
Q_ASSERT(script < QUnicodeTables::ScriptCount);
FcLangSet *ls = FcLangSetCreate();
FcLangSetAdd(ls, (const FcChar8*)specialLanguages[script]);
+ FcPatternDel(pattern, FC_LANG);
FcPatternAddLangSet(pattern, FC_LANG, ls);
FcLangSetDestroy(ls);
}
@@ -2030,6 +2044,7 @@ static void registerFont(QFontDatabasePrivate::ApplicationFont *fnt)
int count = 0;
QStringList families;
+ QFontDatabasePrivate *db = privateDb();
FcPattern *pattern = 0;
do {
@@ -2041,8 +2056,19 @@ static void registerFont(QFontDatabasePrivate::ApplicationFont *fnt)
FcPatternDel(pattern, FC_FILE);
FcPatternAddString(pattern, FC_FILE, (const FcChar8 *)fnt->fileName.toUtf8().constData());
- FcChar8 *fam = 0;
- if (FcPatternGetString(pattern, FC_FAMILY, 0, &fam) == FcResultMatch) {
+ FcChar8 *fam = 0, *familylang = 0;
+ int i, n = 0;
+ for (i = 0; ; i++) {
+ if (FcPatternGetString(pattern, FC_FAMILYLANG, i, &familylang) != FcResultMatch)
+ break;
+ QString familyLang = QString::fromUtf8((const char *) familylang);
+ if (familyLang.compare(db->systemLang, Qt::CaseInsensitive) == 0) {
+ n = i;
+ break;
+ }
+ }
+
+ if (FcPatternGetString(pattern, FC_FAMILY, n, &fam) == FcResultMatch) {
QString family = QString::fromUtf8(reinterpret_cast<const char *>(fam));
families << family;
}
diff --git a/src/gui/text/qfontengine.cpp b/src/gui/text/qfontengine.cpp
index 44346d1e38..3adf4ebc13 100644
--- a/src/gui/text/qfontengine.cpp
+++ b/src/gui/text/qfontengine.cpp
@@ -184,10 +184,6 @@ QFontEngine::QFontEngine()
QFontEngine::~QFontEngine()
{
- for (QLinkedList<GlyphCacheEntry>::const_iterator it = m_glyphCaches.constBegin(),
- end = m_glyphCaches.constEnd(); it != end; ++it) {
- delete it->cache;
- }
m_glyphCaches.clear();
qHBFreeFace(hbFace);
}
@@ -241,6 +237,24 @@ glyph_metrics_t QFontEngine::boundingBox(glyph_t glyph, const QTransform &matrix
return metrics;
}
+QFont QFontEngine::createExplicitFont() const
+{
+ return createExplicitFontWithName(fontDef.family);
+}
+
+QFont QFontEngine::createExplicitFontWithName(const QString &familyName) const
+{
+ QFont font(familyName);
+ font.setStyleStrategy(QFont::NoFontMerging);
+ font.setWeight(fontDef.weight);
+ font.setItalic(fontDef.style == QFont::StyleItalic);
+ if (fontDef.pointSize < 0)
+ font.setPixelSize(fontDef.pixelSize);
+ else
+ font.setPointSizeF(fontDef.pointSize);
+ return font;
+}
+
QFixed QFontEngine::xHeight() const
{
QGlyphLayoutArray<8> glyphs;
@@ -480,7 +494,7 @@ static void collectSingleContour(qreal x0, qreal y0, uint *grid, int x, int y, i
path->closeSubpath();
}
-void qt_addBitmapToPath(qreal x0, qreal y0, const uchar *image_data, int bpl, int w, int h, QPainterPath *path)
+Q_GUI_EXPORT void qt_addBitmapToPath(qreal x0, qreal y0, const uchar *image_data, int bpl, int w, int h, QPainterPath *path)
{
uint *grid = new uint[(w+1)*(h+1)];
// set up edges
@@ -591,6 +605,12 @@ void QFontEngine::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int n
addBitmapFontToPath(x, y, g, path, flags);
}
+QImage QFontEngine::alphaMapForGlyph(glyph_t glyph, QFixed /*subPixelPosition*/)
+{
+ // For font engines don't support subpixel positioning
+ return alphaMapForGlyph(glyph);
+}
+
QImage QFontEngine::alphaMapForGlyph(glyph_t glyph, const QTransform &t)
{
QImage i = alphaMapForGlyph(glyph);
@@ -601,7 +621,20 @@ QImage QFontEngine::alphaMapForGlyph(glyph_t glyph, const QTransform &t)
return i;
}
-QImage QFontEngine::alphaRGBMapForGlyph(glyph_t glyph, int /* margin */, const QTransform &t)
+QImage QFontEngine::alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition, const QTransform &t)
+{
+ if (! supportsSubPixelPositions())
+ return alphaMapForGlyph(glyph, t);
+
+ QImage i = alphaMapForGlyph(glyph, subPixelPosition);
+ if (t.type() > QTransform::TxTranslate)
+ i = i.transformed(t).convertToFormat(QImage::Format_Indexed8);
+ Q_ASSERT(i.depth() <= 8); // To verify that transformed didn't change the format...
+
+ return i;
+}
+
+QImage QFontEngine::alphaRGBMapForGlyph(glyph_t glyph, QFixed /*subPixelPosition*/, int /* margin */, const QTransform &t)
{
QImage alphaMask = alphaMapForGlyph(glyph, t);
QImage rgbMask(alphaMask.width(), alphaMask.height(), QImage::Format_RGB32);
@@ -711,14 +744,16 @@ void QFontEngine::setGlyphCache(void *key, QFontEngineGlyphCache *data)
{
Q_ASSERT(data);
- GlyphCacheEntry entry = { key, data };
+ GlyphCacheEntry entry;
+ entry.context = key;
+ entry.cache = data;
if (m_glyphCaches.contains(entry))
return;
// Limit the glyph caches to 4. This covers all 90 degree rotations and limits
// memory use when there is continuous or random rotation
if (m_glyphCaches.size() == 4)
- delete m_glyphCaches.takeLast().cache;
+ m_glyphCaches.removeLast();
m_glyphCaches.push_front(entry);
@@ -727,7 +762,7 @@ void QFontEngine::setGlyphCache(void *key, QFontEngineGlyphCache *data)
QFontEngineGlyphCache *QFontEngine::glyphCache(void *key, QFontEngineGlyphCache::Type type, const QTransform &transform) const
{
for (QLinkedList<GlyphCacheEntry>::const_iterator it = m_glyphCaches.constBegin(), end = m_glyphCaches.constEnd(); it != end; ++it) {
- QFontEngineGlyphCache *c = it->cache;
+ QFontEngineGlyphCache *c = it->cache.data();
if (key == it->context
&& type == c->cacheType()
&& qtransform_equals_no_translate(c->m_transform, transform)) {
@@ -737,7 +772,7 @@ QFontEngineGlyphCache *QFontEngine::glyphCache(void *key, QFontEngineGlyphCache:
return 0;
}
-#if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN)
+#if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_WS_QPA) || defined(Q_OS_SYMBIAN)
static inline QFixed kerning(int left, int right, const QFontEngine::KernPair *pairs, int numPairs)
{
uint left_right = (left << 16) + right;
@@ -1181,7 +1216,7 @@ glyph_metrics_t QFontEngineBox::boundingBox(const QGlyphLayout &glyphs)
return overall;
}
-#if defined(Q_WS_QWS)
+#if defined(Q_WS_QWS) || defined(Q_WS_QPA)
void QFontEngineBox::draw(QPaintEngine *p, qreal x, qreal y, const QTextItemInt &ti)
{
if (!ti.glyphs.numGlyphs)
diff --git a/src/gui/text/qfontengine_coretext.mm b/src/gui/text/qfontengine_coretext.mm
new file mode 100644
index 0000000000..2ae60b15f4
--- /dev/null
+++ b/src/gui/text/qfontengine_coretext.mm
@@ -0,0 +1,733 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qfontengine_coretext_p.h"
+
+#include <QtCore/qendian.h>
+#include <QtCore/qsettings.h>
+
+#include <private/qimage_p.h>
+
+#if !defined(Q_WS_MAC) || (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
+
+QT_BEGIN_NAMESPACE
+
+static float SYNTHETIC_ITALIC_SKEW = tanf(14 * acosf(0) / 90);
+
+QCoreTextFontEngineMulti::QCoreTextFontEngineMulti(const QCFString &name, const QFontDef &fontDef, bool kerning)
+ : QFontEngineMulti(0)
+{
+ this->fontDef = fontDef;
+ CTFontSymbolicTraits symbolicTraits = 0;
+ if (fontDef.weight >= QFont::Bold)
+ symbolicTraits |= kCTFontBoldTrait;
+ switch (fontDef.style) {
+ case QFont::StyleNormal:
+ break;
+ case QFont::StyleItalic:
+ case QFont::StyleOblique:
+ symbolicTraits |= kCTFontItalicTrait;
+ break;
+ }
+
+ transform = CGAffineTransformIdentity;
+ if (fontDef.stretch != 100) {
+ transform = CGAffineTransformMakeScale(float(fontDef.stretch) / float(100), 1);
+ }
+
+ QCFType<CTFontDescriptorRef> descriptor = CTFontDescriptorCreateWithNameAndSize(name, fontDef.pixelSize);
+ QCFType<CTFontRef> baseFont = CTFontCreateWithFontDescriptor(descriptor, fontDef.pixelSize, &transform);
+ ctfont = CTFontCreateCopyWithSymbolicTraits(baseFont, fontDef.pixelSize, &transform, symbolicTraits, symbolicTraits);
+
+ // CTFontCreateCopyWithSymbolicTraits returns NULL if we ask for a trait that does
+ // not exist for the given font. (for example italic)
+ if (ctfont == 0) {
+ ctfont = baseFont;
+ CFRetain(ctfont);
+ }
+
+ attributeDict = CFDictionaryCreateMutable(0, 2,
+ &kCFTypeDictionaryKeyCallBacks,
+ &kCFTypeDictionaryValueCallBacks);
+ CFDictionaryAddValue(attributeDict, NSFontAttributeName, ctfont);
+ if (!kerning) {
+ float zero = 0.0;
+ QCFType<CFNumberRef> noKern = CFNumberCreate(kCFAllocatorDefault, kCFNumberFloatType, &zero);
+ CFDictionaryAddValue(attributeDict, kCTKernAttributeName, noKern);
+ }
+
+ QCoreTextFontEngine *fe = new QCoreTextFontEngine(ctfont, fontDef, this);
+ fe->ref.ref();
+ engines.append(fe);
+
+}
+
+QCoreTextFontEngineMulti::~QCoreTextFontEngineMulti()
+{
+ CFRelease(ctfont);
+}
+
+uint QCoreTextFontEngineMulti::fontIndexForFont(CTFontRef id) const
+{
+ for (int i = 0; i < engines.count(); ++i) {
+ if (CFEqual(engineAt(i)->ctfont, id))
+ return i;
+ }
+
+ QCoreTextFontEngineMulti *that = const_cast<QCoreTextFontEngineMulti *>(this);
+ QCoreTextFontEngine *fe = new QCoreTextFontEngine(id, fontDef, that);
+ fe->ref.ref();
+ that->engines.append(fe);
+ return engines.count() - 1;
+}
+
+bool QCoreTextFontEngineMulti::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags,
+ unsigned short *logClusters, const HB_CharAttributes *) const
+{
+ QCFType<CFStringRef> cfstring = CFStringCreateWithCharactersNoCopy(0,
+ reinterpret_cast<const UniChar *>(str),
+ len, kCFAllocatorNull);
+ QCFType<CFAttributedStringRef> attributedString = CFAttributedStringCreate(0, cfstring, attributeDict);
+ QCFType<CTTypesetterRef> typeSetter = CTTypesetterCreateWithAttributedString(attributedString);
+ CFRange range = {0, 0};
+ QCFType<CTLineRef> line = CTTypesetterCreateLine(typeSetter, range);
+ CFArrayRef array = CTLineGetGlyphRuns(line);
+ uint arraySize = CFArrayGetCount(array);
+ glyph_t *outGlyphs = glyphs->glyphs;
+ HB_GlyphAttributes *outAttributes = glyphs->attributes;
+ QFixed *outAdvances_x = glyphs->advances_x;
+ QFixed *outAdvances_y = glyphs->advances_y;
+ glyph_t *initialGlyph = outGlyphs;
+
+ if (arraySize == 0) {
+ // CoreText failed to shape the text we gave it, so we assume one glyph
+ // per character and build a list of invalid glyphs with zero advance
+ *nglyphs = len;
+ for (int i = 0; i < len; ++i) {
+ outGlyphs[i] = 0;
+ if (logClusters)
+ logClusters[i] = i;
+ outAdvances_x[i] = QFixed();
+ outAdvances_y[i] = QFixed();
+ outAttributes[i].clusterStart = true;
+ }
+ return true;
+ }
+
+ const bool rtl = (CTRunGetStatus(static_cast<CTRunRef>(CFArrayGetValueAtIndex(array, 0))) & kCTRunStatusRightToLeft);
+
+ bool outOBounds = false;
+ for (uint i = 0; i < arraySize; ++i) {
+ CTRunRef run = static_cast<CTRunRef>(CFArrayGetValueAtIndex(array, rtl ? (arraySize - 1 - i) : i));
+ CFIndex glyphCount = CTRunGetGlyphCount(run);
+ if (glyphCount == 0)
+ continue;
+
+ Q_ASSERT((CTRunGetStatus(run) & kCTRunStatusRightToLeft) == rtl);
+ CFRange stringRange = CTRunGetStringRange(run);
+ UniChar endGlyph = CFStringGetCharacterAtIndex(cfstring, stringRange.location + stringRange.length - 1);
+ bool endWithPDF = QChar::direction(endGlyph) == QChar::DirPDF;
+ if (endWithPDF)
+ glyphCount++;
+
+ if (!outOBounds && outGlyphs + glyphCount - initialGlyph > *nglyphs) {
+ outOBounds = true;
+ }
+ if (!outOBounds) {
+ CFDictionaryRef runAttribs = CTRunGetAttributes(run);
+ //NSLog(@"Dictionary %@", runAttribs);
+ if (!runAttribs)
+ runAttribs = attributeDict;
+ CTFontRef runFont = static_cast<CTFontRef>(CFDictionaryGetValue(runAttribs, NSFontAttributeName));
+ const uint fontIndex = (fontIndexForFont(runFont) << 24);
+ //NSLog(@"Run Font Name = %@", CTFontCopyFamilyName(runFont));
+ if (endWithPDF)
+ glyphCount--;
+
+ QVarLengthArray<CGGlyph, 512> cgglyphs(0);
+ const CGGlyph *tmpGlyphs = CTRunGetGlyphsPtr(run);
+ if (!tmpGlyphs) {
+ cgglyphs.resize(glyphCount);
+ CTRunGetGlyphs(run, range, cgglyphs.data());
+ tmpGlyphs = cgglyphs.constData();
+ }
+ QVarLengthArray<CGPoint, 512> cgpoints(0);
+ const CGPoint *tmpPoints = CTRunGetPositionsPtr(run);
+ if (!tmpPoints) {
+ cgpoints.resize(glyphCount);
+ CTRunGetPositions(run, range, cgpoints.data());
+ tmpPoints = cgpoints.constData();
+ }
+
+ const int rtlOffset = rtl ? (glyphCount - 1) : 0;
+ const int rtlSign = rtl ? -1 : 1;
+
+ if (logClusters) {
+ CFRange stringRange = CTRunGetStringRange(run);
+ QVarLengthArray<CFIndex, 512> stringIndices(0);
+ const CFIndex *tmpIndices = CTRunGetStringIndicesPtr(run);
+ if (!tmpIndices) {
+ stringIndices.resize(glyphCount);
+ CTRunGetStringIndices(run, range, stringIndices.data());
+ tmpIndices = stringIndices.constData();
+ }
+
+ const int firstGlyphIndex = outGlyphs - initialGlyph;
+ outAttributes[0].clusterStart = true;
+
+ CFIndex k = 0;
+ CFIndex i = 0;
+ for (i = stringRange.location;
+ (i < stringRange.location + stringRange.length) && (k < glyphCount); ++i) {
+ if (tmpIndices[k * rtlSign + rtlOffset] == i || i == stringRange.location) {
+ logClusters[i] = k + firstGlyphIndex;
+ outAttributes[k].clusterStart = true;
+ ++k;
+ } else {
+ logClusters[i] = k + firstGlyphIndex - 1;
+ }
+ }
+ // in case of a ligature at the end, fill the remaining logcluster entries
+ for (;i < stringRange.location + stringRange.length; i++) {
+ logClusters[i] = k + firstGlyphIndex - 1;
+ }
+ }
+ for (CFIndex i = 0; i < glyphCount - 1; ++i) {
+ int idx = rtlOffset + rtlSign * i;
+ outGlyphs[idx] = tmpGlyphs[i] | fontIndex;
+ outAdvances_x[idx] = QFixed::fromReal(tmpPoints[i + 1].x - tmpPoints[i].x);
+ outAdvances_y[idx] = QFixed::fromReal(tmpPoints[i + 1].y - tmpPoints[i].y);
+
+ if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) {
+ outAdvances_x[idx] = outAdvances_x[idx].round();
+ outAdvances_y[idx] = outAdvances_y[idx].round();
+ }
+ }
+ CGSize lastGlyphAdvance;
+ CTFontGetAdvancesForGlyphs(runFont, kCTFontHorizontalOrientation, tmpGlyphs + glyphCount - 1, &lastGlyphAdvance, 1);
+
+ outGlyphs[rtl ? 0 : (glyphCount - 1)] = tmpGlyphs[glyphCount - 1] | fontIndex;
+ outAdvances_x[rtl ? 0 : (glyphCount - 1)] =
+ (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
+ ? QFixed::fromReal(lastGlyphAdvance.width).round()
+ : QFixed::fromReal(lastGlyphAdvance.width);
+
+ if (endWithPDF) {
+ logClusters[stringRange.location + stringRange.length - 1] = glyphCount;
+ outGlyphs[glyphCount] = 0xFFFF;
+ outAdvances_x[glyphCount] = 0;
+ outAdvances_y[glyphCount] = 0;
+ outAttributes[glyphCount].clusterStart = true;
+ outAttributes[glyphCount].dontPrint = true;
+ glyphCount++;
+ }
+ }
+ outGlyphs += glyphCount;
+ outAttributes += glyphCount;
+ outAdvances_x += glyphCount;
+ outAdvances_y += glyphCount;
+ }
+ *nglyphs = (outGlyphs - initialGlyph);
+ return !outOBounds;
+}
+
+bool QCoreTextFontEngineMulti::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs,
+ int *nglyphs, QTextEngine::ShaperFlags flags) const
+{
+ *nglyphs = len;
+ QCFType<CFStringRef> cfstring;
+
+ QVarLengthArray<CGGlyph> cgGlyphs(len);
+ CTFontGetGlyphsForCharacters(ctfont, (const UniChar*)str, cgGlyphs.data(), len);
+
+ for (int i = 0; i < len; ++i) {
+ if (cgGlyphs[i]) {
+ glyphs->glyphs[i] = cgGlyphs[i];
+ } else {
+ if (!cfstring)
+ cfstring = CFStringCreateWithCharactersNoCopy(0, reinterpret_cast<const UniChar *>(str), len, kCFAllocatorNull);
+ QCFType<CTFontRef> substituteFont = CTFontCreateForString(ctfont, cfstring, CFRangeMake(i, 1));
+ CGGlyph substituteGlyph = 0;
+ CTFontGetGlyphsForCharacters(substituteFont, (const UniChar*)str + i, &substituteGlyph, 1);
+ if (substituteGlyph) {
+ const uint fontIndex = (fontIndexForFont(substituteFont) << 24);
+ glyphs->glyphs[i] = substituteGlyph | fontIndex;
+ if (!(flags & QTextEngine::GlyphIndicesOnly)) {
+ CGSize advance;
+ CTFontGetAdvancesForGlyphs(substituteFont, kCTFontHorizontalOrientation, &substituteGlyph, &advance, 1);
+ glyphs->advances_x[i] = QFixed::fromReal(advance.width);
+ glyphs->advances_y[i] = QFixed::fromReal(advance.height);
+ }
+ }
+ }
+ }
+
+ if (flags & QTextEngine::GlyphIndicesOnly)
+ return true;
+
+ QVarLengthArray<CGSize> advances(len);
+ CTFontGetAdvancesForGlyphs(ctfont, kCTFontHorizontalOrientation, cgGlyphs.data(), advances.data(), len);
+
+ for (int i = 0; i < len; ++i) {
+ if (glyphs->glyphs[i] & 0xff000000)
+ continue;
+ glyphs->advances_x[i] = QFixed::fromReal(advances[i].width);
+ glyphs->advances_y[i] = QFixed::fromReal(advances[i].height);
+ }
+
+ if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) {
+ for (int i = 0; i < len; ++i) {
+ glyphs->advances_x[i] = glyphs->advances_x[i].round();
+ glyphs->advances_y[i] = glyphs->advances_y[i].round();
+ }
+ }
+
+ return true;
+}
+
+void QCoreTextFontEngineMulti::recalcAdvances(int , QGlyphLayout *, QTextEngine::ShaperFlags) const
+{
+}
+void QCoreTextFontEngineMulti::doKerning(int , QGlyphLayout *, QTextEngine::ShaperFlags) const
+{
+}
+
+void QCoreTextFontEngineMulti::loadEngine(int)
+{
+ // Do nothing
+ Q_ASSERT(false);
+}
+
+
+
+QCoreTextFontEngine::QCoreTextFontEngine(CTFontRef font, const QFontDef &def,
+ QCoreTextFontEngineMulti *multiEngine)
+{
+ fontDef = def;
+ parentEngine = multiEngine;
+ synthesisFlags = 0;
+ ctfont = font;
+ CFRetain(ctfont);
+ cgFont = CTFontCopyGraphicsFont(ctfont, NULL);
+ CTFontSymbolicTraits traits = CTFontGetSymbolicTraits(ctfont);
+ if (fontDef.weight >= QFont::Bold && !(traits & kCTFontBoldTrait)) {
+ synthesisFlags |= SynthesizedBold;
+ }
+
+ if (fontDef.style != QFont::StyleNormal && !(traits & kCTFontItalicTrait)) {
+ synthesisFlags |= SynthesizedItalic;
+ }
+ transform = CGAffineTransformIdentity;
+ if (fontDef.stretch != 100) {
+ transform = CGAffineTransformMakeScale(float(fontDef.stretch) / float(100), 1);
+ }
+ QByteArray os2Table = getSfntTable(MAKE_TAG('O', 'S', '/', '2'));
+ if (os2Table.size() >= 10)
+ fsType = qFromBigEndian<quint16>(reinterpret_cast<const uchar *>(os2Table.constData() + 8));
+
+ QSettings appleSettings(QLatin1String("apple.com"));
+ QVariant appleValue = appleSettings.value(QLatin1String("AppleAntiAliasingThreshold"));
+ if (appleValue.isValid())
+ antialiasing_threshold = appleValue.toInt();
+ else
+ antialiasing_threshold = -1;
+}
+
+QCoreTextFontEngine::~QCoreTextFontEngine()
+{
+ CFRelease(cgFont);
+ CFRelease(ctfont);
+}
+
+bool QCoreTextFontEngine::stringToCMap(const QChar *, int, QGlyphLayout *, int *, QTextEngine::ShaperFlags) const
+{
+ return false;
+}
+
+glyph_metrics_t QCoreTextFontEngine::boundingBox(const QGlyphLayout &glyphs)
+{
+ QFixed w;
+ bool round = fontDef.styleStrategy & QFont::ForceIntegerMetrics;
+
+ for (int i = 0; i < glyphs.numGlyphs; ++i) {
+ w += round ? glyphs.effectiveAdvance(i).round()
+ : glyphs.effectiveAdvance(i);
+ }
+ return glyph_metrics_t(0, -(ascent()), w - lastRightBearing(glyphs, round), ascent()+descent(), w, 0);
+}
+glyph_metrics_t QCoreTextFontEngine::boundingBox(glyph_t glyph)
+{
+ glyph_metrics_t ret;
+ CGGlyph g = glyph;
+ CGRect rect = CTFontGetBoundingRectsForGlyphs(ctfont, kCTFontHorizontalOrientation, &g, 0, 1);
+ if (synthesisFlags & QFontEngine::SynthesizedItalic) {
+ rect.size.width += rect.size.height * SYNTHETIC_ITALIC_SKEW;
+ }
+ ret.width = QFixed::fromReal(rect.size.width);
+ ret.height = QFixed::fromReal(rect.size.height);
+ ret.x = QFixed::fromReal(rect.origin.x);
+ ret.y = -QFixed::fromReal(rect.origin.y) - ret.height;
+ CGSize advances[1];
+ CTFontGetAdvancesForGlyphs(ctfont, kCTFontHorizontalOrientation, &g, advances, 1);
+ ret.xoff = QFixed::fromReal(advances[0].width);
+ ret.yoff = QFixed::fromReal(advances[0].height);
+
+ if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) {
+ ret.xoff = ret.xoff.round();
+ ret.yoff = ret.yoff.round();
+ }
+
+ return ret;
+}
+
+QFixed QCoreTextFontEngine::ascent() const
+{
+ return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
+ ? QFixed::fromReal(CTFontGetAscent(ctfont)).round()
+ : QFixed::fromReal(CTFontGetAscent(ctfont));
+}
+QFixed QCoreTextFontEngine::descent() const
+{
+ QFixed d = QFixed::fromReal(CTFontGetDescent(ctfont));
+ if (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
+ d = d.round();
+
+ // subtract a pixel to even out the historical +1 in QFontMetrics::height().
+ // Fix in Qt 5.
+ return d - 1;
+}
+QFixed QCoreTextFontEngine::leading() const
+{
+ return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
+ ? QFixed::fromReal(CTFontGetLeading(ctfont)).round()
+ : QFixed::fromReal(CTFontGetLeading(ctfont));
+}
+QFixed QCoreTextFontEngine::xHeight() const
+{
+ return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
+ ? QFixed::fromReal(CTFontGetXHeight(ctfont)).round()
+ : QFixed::fromReal(CTFontGetXHeight(ctfont));
+}
+QFixed QCoreTextFontEngine::averageCharWidth() const
+{
+ // ### Need to implement properly and get the information from the OS/2 Table.
+ return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
+ ? QFontEngine::averageCharWidth().round()
+ : QFontEngine::averageCharWidth();
+}
+
+qreal QCoreTextFontEngine::maxCharWidth() const
+{
+ // ### Max Help!
+ return 0;
+
+}
+qreal QCoreTextFontEngine::minLeftBearing() const
+{
+ // ### Min Help!
+ return 0;
+
+}
+qreal QCoreTextFontEngine::minRightBearing() const
+{
+ // ### Max Help! (even thought it's right)
+ return 0;
+
+}
+
+void QCoreTextFontEngine::draw(CGContextRef ctx, qreal x, qreal y, const QTextItemInt &ti, int paintDeviceHeight)
+{
+ QVarLengthArray<QFixedPoint> positions;
+ QVarLengthArray<glyph_t> glyphs;
+ QTransform matrix;
+ matrix.translate(x, y);
+ getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
+ if (glyphs.size() == 0)
+ return;
+
+ CGContextSetFontSize(ctx, fontDef.pixelSize);
+
+ CGAffineTransform oldTextMatrix = CGContextGetTextMatrix(ctx);
+
+ CGAffineTransform cgMatrix = CGAffineTransformMake(1, 0, 0, -1, 0, -paintDeviceHeight);
+
+ CGAffineTransformConcat(cgMatrix, oldTextMatrix);
+
+ if (synthesisFlags & QFontEngine::SynthesizedItalic)
+ cgMatrix = CGAffineTransformConcat(cgMatrix, CGAffineTransformMake(1, 0, -SYNTHETIC_ITALIC_SKEW, 1, 0, 0));
+
+ cgMatrix = CGAffineTransformConcat(cgMatrix, transform);
+
+ CGContextSetTextMatrix(ctx, cgMatrix);
+
+ CGContextSetTextDrawingMode(ctx, kCGTextFill);
+
+
+ QVarLengthArray<CGSize> advances(glyphs.size());
+ QVarLengthArray<CGGlyph> cgGlyphs(glyphs.size());
+
+ for (int i = 0; i < glyphs.size() - 1; ++i) {
+ advances[i].width = (positions[i + 1].x - positions[i].x).toReal();
+ advances[i].height = (positions[i + 1].y - positions[i].y).toReal();
+ cgGlyphs[i] = glyphs[i];
+ }
+ advances[glyphs.size() - 1].width = 0;
+ advances[glyphs.size() - 1].height = 0;
+ cgGlyphs[glyphs.size() - 1] = glyphs[glyphs.size() - 1];
+
+ CGContextSetFont(ctx, cgFont);
+ //NSLog(@"Font inDraw %@ ctfont %@", CGFontCopyFullName(cgFont), CTFontCopyFamilyName(ctfont));
+
+ CGContextSetTextPosition(ctx, positions[0].x.toReal(), positions[0].y.toReal());
+
+ CGContextShowGlyphsWithAdvances(ctx, cgGlyphs.data(), advances.data(), glyphs.size());
+
+ if (synthesisFlags & QFontEngine::SynthesizedBold) {
+ CGContextSetTextPosition(ctx, positions[0].x.toReal() + 0.5 * lineThickness().toReal(),
+ positions[0].y.toReal());
+
+ CGContextShowGlyphsWithAdvances(ctx, cgGlyphs.data(), advances.data(), glyphs.size());
+ }
+
+ CGContextSetTextMatrix(ctx, oldTextMatrix);
+}
+
+struct ConvertPathInfo
+{
+ ConvertPathInfo(QPainterPath *newPath, const QPointF &newPos) : path(newPath), pos(newPos) {}
+ QPainterPath *path;
+ QPointF pos;
+};
+
+static void convertCGPathToQPainterPath(void *info, const CGPathElement *element)
+{
+ ConvertPathInfo *myInfo = static_cast<ConvertPathInfo *>(info);
+ switch(element->type) {
+ case kCGPathElementMoveToPoint:
+ myInfo->path->moveTo(element->points[0].x + myInfo->pos.x(),
+ element->points[0].y + myInfo->pos.y());
+ break;
+ case kCGPathElementAddLineToPoint:
+ myInfo->path->lineTo(element->points[0].x + myInfo->pos.x(),
+ element->points[0].y + myInfo->pos.y());
+ break;
+ case kCGPathElementAddQuadCurveToPoint:
+ myInfo->path->quadTo(element->points[0].x + myInfo->pos.x(),
+ element->points[0].y + myInfo->pos.y(),
+ element->points[1].x + myInfo->pos.x(),
+ element->points[1].y + myInfo->pos.y());
+ break;
+ case kCGPathElementAddCurveToPoint:
+ myInfo->path->cubicTo(element->points[0].x + myInfo->pos.x(),
+ element->points[0].y + myInfo->pos.y(),
+ element->points[1].x + myInfo->pos.x(),
+ element->points[1].y + myInfo->pos.y(),
+ element->points[2].x + myInfo->pos.x(),
+ element->points[2].y + myInfo->pos.y());
+ break;
+ case kCGPathElementCloseSubpath:
+ myInfo->path->closeSubpath();
+ break;
+ default:
+ qDebug() << "Unhandled path transform type: " << element->type;
+ }
+
+}
+
+void QCoreTextFontEngine::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nGlyphs,
+ QPainterPath *path, QTextItem::RenderFlags)
+{
+ CGAffineTransform cgMatrix = CGAffineTransformIdentity;
+ cgMatrix = CGAffineTransformScale(cgMatrix, 1, -1);
+
+ if (synthesisFlags & QFontEngine::SynthesizedItalic)
+ cgMatrix = CGAffineTransformConcat(cgMatrix, CGAffineTransformMake(1, 0, -SYNTHETIC_ITALIC_SKEW, 1, 0, 0));
+
+ for (int i = 0; i < nGlyphs; ++i) {
+ QCFType<CGPathRef> cgpath = CTFontCreatePathForGlyph(ctfont, glyphs[i], &cgMatrix);
+ ConvertPathInfo info(path, positions[i].toPointF());
+ CGPathApply(cgpath, &info, convertCGPathToQPainterPath);
+ }
+}
+
+QFont QCoreTextFontEngine::createExplicitFont() const
+{
+ QString familyName = QCFString::toQString(CTFontCopyFamilyName(ctfont));
+ return createExplicitFontWithName(familyName);
+}
+
+QImage QCoreTextFontEngine::imageForGlyph(glyph_t glyph, QFixed subPixelPosition, int /*margin*/, bool aa)
+{
+ const glyph_metrics_t br = boundingBox(glyph);
+ QImage im(qRound(br.width)+2, qRound(br.height)+2, QImage::Format_RGB32);
+ im.fill(0);
+
+ CGColorSpaceRef colorspace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
+ uint cgflags = kCGImageAlphaNoneSkipFirst;
+#ifdef kCGBitmapByteOrder32Host //only needed because CGImage.h added symbols in the minor version
+ cgflags |= kCGBitmapByteOrder32Host;
+#endif
+ CGContextRef ctx = CGBitmapContextCreate(im.bits(), im.width(), im.height(),
+ 8, im.bytesPerLine(), colorspace,
+ cgflags);
+ CGContextSetFontSize(ctx, fontDef.pixelSize);
+ CGContextSetShouldAntialias(ctx, aa ||
+ (fontDef.pointSize > antialiasing_threshold
+ && !(fontDef.styleStrategy & QFont::NoAntialias)));
+ CGContextSetShouldSmoothFonts(ctx, aa);
+ CGAffineTransform oldTextMatrix = CGContextGetTextMatrix(ctx);
+ CGAffineTransform cgMatrix = CGAffineTransformMake(1, 0, 0, 1, 0, 0);
+
+ CGAffineTransformConcat(cgMatrix, oldTextMatrix);
+
+ if (synthesisFlags & QFontEngine::SynthesizedItalic)
+ cgMatrix = CGAffineTransformConcat(cgMatrix, CGAffineTransformMake(1, 0, SYNTHETIC_ITALIC_SKEW, 1, 0, 0));
+
+ cgMatrix = CGAffineTransformConcat(cgMatrix, transform);
+
+ CGContextSetTextMatrix(ctx, cgMatrix);
+ CGContextSetRGBFillColor(ctx, 1, 1, 1, 1);
+ CGContextSetTextDrawingMode(ctx, kCGTextFill);
+
+ CGContextSetFont(ctx, cgFont);
+
+ qreal pos_x = -br.x.toReal() + subPixelPosition.toReal();
+ qreal pos_y = im.height() + br.y.toReal() - 1;
+ CGContextSetTextPosition(ctx, pos_x, pos_y);
+
+ CGSize advance;
+ advance.width = 0;
+ advance.height = 0;
+ CGGlyph cgGlyph = glyph;
+ CGContextShowGlyphsWithAdvances(ctx, &cgGlyph, &advance, 1);
+
+ if (synthesisFlags & QFontEngine::SynthesizedBold) {
+ CGContextSetTextPosition(ctx, pos_x + 0.5 * lineThickness().toReal(), pos_y);
+ CGContextShowGlyphsWithAdvances(ctx, &cgGlyph, &advance, 1);
+ }
+
+ CGContextRelease(ctx);
+
+ return im;
+}
+
+QImage QCoreTextFontEngine::alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition)
+{
+ QImage im = imageForGlyph(glyph, subPixelPosition, 0, false);
+
+ QImage indexed(im.width(), im.height(), QImage::Format_Indexed8);
+ QVector<QRgb> colors(256);
+ for (int i=0; i<256; ++i)
+ colors[i] = qRgba(0, 0, 0, i);
+ indexed.setColorTable(colors);
+
+ for (int y=0; y<im.height(); ++y) {
+ uint *src = (uint*) im.scanLine(y);
+ uchar *dst = indexed.scanLine(y);
+ for (int x=0; x<im.width(); ++x) {
+ *dst = qGray(*src);
+ ++dst;
+ ++src;
+ }
+ }
+
+ return indexed;
+}
+
+QImage QCoreTextFontEngine::alphaRGBMapForGlyph(glyph_t glyph, QFixed subPixelPosition, int margin, const QTransform &x)
+{
+ if (x.type() >= QTransform::TxScale)
+ return QFontEngine::alphaRGBMapForGlyph(glyph, subPixelPosition, margin, x);
+
+ QImage im = imageForGlyph(glyph, subPixelPosition, margin, true);
+ qGamma_correct_back_to_linear_cs(&im);
+ return im;
+}
+
+void QCoreTextFontEngine::recalcAdvances(int numGlyphs, QGlyphLayout *glyphs, QTextEngine::ShaperFlags flags) const
+{
+ Q_ASSERT(false);
+ Q_UNUSED(numGlyphs);
+ Q_UNUSED(glyphs);
+ Q_UNUSED(flags);
+}
+
+QFontEngine::FaceId QCoreTextFontEngine::faceId() const
+{
+ return QFontEngine::FaceId();
+}
+
+bool QCoreTextFontEngine::canRender(const QChar *string, int len)
+{
+ QCFType<CTFontRef> retFont = CTFontCreateForString(ctfont,
+ QCFType<CFStringRef>(CFStringCreateWithCharactersNoCopy(0,
+ reinterpret_cast<const UniChar *>(string),
+ len, kCFAllocatorNull)),
+ CFRangeMake(0, len));
+ return retFont != 0;
+ return false;
+}
+
+ bool QCoreTextFontEngine::getSfntTableData(uint tag, uchar *buffer, uint *length) const
+ {
+ QCFType<CFDataRef> table = CTFontCopyTable(ctfont, tag, 0);
+ if (!table || !length)
+ return false;
+ CFIndex tableLength = CFDataGetLength(table);
+ int availableLength = *length;
+ *length = tableLength;
+ if (buffer) {
+ if (tableLength > availableLength)
+ return false;
+ CFDataGetBytes(table, CFRangeMake(0, tableLength), buffer);
+ }
+ return true;
+ }
+
+void QCoreTextFontEngine::getUnscaledGlyph(glyph_t, QPainterPath *, glyph_metrics_t *)
+{
+ // ###
+}
+
+QT_END_NAMESPACE
+
+#endif// !defined(Q_WS_MAC) || (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
+
diff --git a/src/gui/text/qfontengine_coretext_p.h b/src/gui/text/qfontengine_coretext_p.h
new file mode 100644
index 0000000000..b4450fa304
--- /dev/null
+++ b/src/gui/text/qfontengine_coretext_p.h
@@ -0,0 +1,136 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QFONTENGINE_CORETEXT_P_H
+#define QFONTENGINE_CORETEXT_P_H
+
+#include <private/qfontengine_p.h>
+
+#if !defined(Q_WS_MAC) || (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
+
+class QCoreTextFontEngineMulti;
+class QCoreTextFontEngine : public QFontEngine
+{
+public:
+ QCoreTextFontEngine(CTFontRef font, const QFontDef &def,
+ QCoreTextFontEngineMulti *multiEngine = 0);
+ ~QCoreTextFontEngine();
+ virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const;
+ virtual void recalcAdvances(int , QGlyphLayout *, QTextEngine::ShaperFlags) const;
+
+ virtual glyph_metrics_t boundingBox(const QGlyphLayout &glyphs);
+ virtual glyph_metrics_t boundingBox(glyph_t glyph);
+
+ virtual QFixed ascent() const;
+ virtual QFixed descent() const;
+ virtual QFixed leading() const;
+ virtual QFixed xHeight() const;
+ virtual qreal maxCharWidth() const;
+ virtual QFixed averageCharWidth() const;
+
+ virtual void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int numGlyphs,
+ QPainterPath *path, QTextItem::RenderFlags);
+
+ virtual const char *name() const { return "QCoreTextFontEngine"; }
+
+ virtual bool canRender(const QChar *string, int len);
+
+ virtual int synthesized() const { return synthesisFlags; }
+ virtual bool supportsSubPixelPositions() const { return true; }
+
+ virtual Type type() const { return QFontEngine::Mac; }
+
+ void draw(CGContextRef ctx, qreal x, qreal y, const QTextItemInt &ti, int paintDeviceHeight);
+
+ virtual FaceId faceId() const;
+ virtual bool getSfntTableData(uint /*tag*/, uchar * /*buffer*/, uint * /*length*/) const;
+ virtual void getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics);
+ virtual QImage alphaMapForGlyph(glyph_t, QFixed subPixelPosition);
+ virtual QImage alphaRGBMapForGlyph(glyph_t, QFixed subPixelPosition, int margin, const QTransform &t);
+ virtual qreal minRightBearing() const;
+ virtual qreal minLeftBearing() const;
+ virtual QFont createExplicitFont() const;
+
+private:
+ QImage imageForGlyph(glyph_t glyph, QFixed subPixelPosition, int margin, bool colorful);
+ CTFontRef ctfont;
+ CGFontRef cgFont;
+ QCoreTextFontEngineMulti *parentEngine;
+ int synthesisFlags;
+ CGAffineTransform transform;
+ friend class QCoreTextFontEngineMulti;
+ int antialiasing_threshold;
+};
+
+class QCoreTextFontEngineMulti : public QFontEngineMulti
+{
+public:
+ QCoreTextFontEngineMulti(const QCFString &name, const QFontDef &fontDef, bool kerning);
+ ~QCoreTextFontEngineMulti();
+
+ virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs,
+ QTextEngine::ShaperFlags flags) const;
+ bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs,
+ QTextEngine::ShaperFlags flags,
+ unsigned short *logClusters, const HB_CharAttributes *charAttributes) const;
+
+
+ virtual void recalcAdvances(int , QGlyphLayout *, QTextEngine::ShaperFlags) const;
+ virtual void doKerning(int , QGlyphLayout *, QTextEngine::ShaperFlags) const;
+
+ virtual const char *name() const { return "CoreText"; }
+protected:
+ virtual void loadEngine(int at);
+
+private:
+ inline const QCoreTextFontEngine *engineAt(int i) const
+ { return static_cast<const QCoreTextFontEngine *>(engines.at(i)); }
+
+ uint fontIndexForFont(CTFontRef id) const;
+ CTFontRef ctfont;
+ mutable QCFType<CFMutableDictionaryRef> attributeDict;
+ CGAffineTransform transform;
+ friend class QFontDialogPrivate;
+};
+
+#endif// !defined(Q_WS_MAC) || (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
+
+#endif // QFONTENGINE_CORETEXT_P_H
diff --git a/src/gui/text/qfontengine_ft.cpp b/src/gui/text/qfontengine_ft.cpp
index e89b508601..f5e9e1ca9a 100644
--- a/src/gui/text/qfontengine_ft.cpp
+++ b/src/gui/text/qfontengine_ft.cpp
@@ -723,7 +723,7 @@ bool QFontEngineFT::init(FaceId faceId, bool antialias, GlyphFormat format)
metrics = face->size->metrics;
-#if defined(Q_WS_QWS)
+#if defined(Q_WS_QWS) || defined(Q_WS_QPA)
/*
TrueType fonts with embedded bitmaps may have a bitmap font specific
ascent/descent in the EBLC table. There is no direct public API
@@ -755,16 +755,42 @@ bool QFontEngineFT::init(FaceId faceId, bool antialias, GlyphFormat format)
return true;
}
-QFontEngineFT::Glyph *QFontEngineFT::loadGlyphMetrics(QGlyphSet *set, uint glyph) const
+void QFontEngineFT::setDefaultHintStyle(HintStyle style)
+{
+ default_hint_style = style;
+}
+
+QFontEngineFT::Glyph *QFontEngineFT::loadGlyphMetrics(QGlyphSet *set, uint glyph, GlyphFormat format) const
{
Glyph *g = set->getGlyph(glyph);
- if (g)
+ if (g && g->format == format)
return g;
int load_flags = FT_LOAD_DEFAULT | default_load_flags;
+ int load_target = default_hint_style == HintLight
+ ? FT_LOAD_TARGET_LIGHT
+ : FT_LOAD_TARGET_NORMAL;
+
+ if (format == Format_Mono) {
+ load_target = FT_LOAD_TARGET_MONO;
+ } else if (format == Format_A32) {
+ if (subpixelType == QFontEngineFT::Subpixel_RGB || subpixelType == QFontEngineFT::Subpixel_BGR) {
+ if (default_hint_style == HintFull)
+ load_target = FT_LOAD_TARGET_LCD;
+ } else if (subpixelType == QFontEngineFT::Subpixel_VRGB || subpixelType == QFontEngineFT::Subpixel_VBGR) {
+ if (default_hint_style == HintFull)
+ load_target = FT_LOAD_TARGET_LCD_V;
+ }
+ }
+
if (set->outline_drawing)
load_flags = FT_LOAD_NO_BITMAP;
+ if (default_hint_style == HintNone)
+ load_flags |= FT_LOAD_NO_HINTING;
+ else
+ load_flags |= load_target;
+
// apply our matrix to this, but note that the metrics will not be affected by this.
FT_Face face = lockFace();
FT_Matrix matrix = this->matrix;
@@ -1758,6 +1784,11 @@ glyph_metrics_t QFontEngineFT::boundingBox(glyph_t glyph)
glyph_metrics_t QFontEngineFT::boundingBox(glyph_t glyph, const QTransform &matrix)
{
+ return alphaMapBoundingBox(glyph, matrix, QFontEngine::Format_None);
+}
+
+glyph_metrics_t QFontEngineFT::alphaMapBoundingBox(glyph_t glyph, const QTransform &matrix, QFontEngine::GlyphFormat format)
+{
FT_Face face = 0;
glyph_metrics_t overall;
QGlyphSet *glyphSet = 0;
@@ -1801,9 +1832,9 @@ glyph_metrics_t QFontEngineFT::boundingBox(glyph_t glyph, const QTransform &matr
glyphSet = &defaultGlyphSet;
}
Glyph * g = glyphSet->getGlyph(glyph);
- if (!g) {
+ if (!g || g->format != format) {
face = lockFace();
- g = loadGlyphMetrics(glyphSet, glyph);
+ g = loadGlyphMetrics(glyphSet, glyph, format);
}
if (g) {
@@ -1865,10 +1896,10 @@ QImage QFontEngineFT::alphaMapForGlyph(glyph_t g)
return img;
}
-QImage QFontEngineFT::alphaRGBMapForGlyph(glyph_t g, int margin, const QTransform &t)
+QImage QFontEngineFT::alphaRGBMapForGlyph(glyph_t g, QFixed subPixelPosition, int margin, const QTransform &t)
{
if (t.type() > QTransform::TxTranslate)
- return QFontEngine::alphaRGBMapForGlyph(g, margin, t);
+ return QFontEngine::alphaRGBMapForGlyph(g, subPixelPosition, margin, t);
lockFace();
@@ -1877,7 +1908,7 @@ QImage QFontEngineFT::alphaRGBMapForGlyph(glyph_t g, int margin, const QTransfor
Glyph *glyph = defaultGlyphSet.outline_drawing ? 0 : loadGlyph(g, glyph_format);
if (!glyph) {
unlockFace();
- return QFontEngine::alphaRGBMapForGlyph(g, margin, t);
+ return QFontEngine::alphaRGBMapForGlyph(g, subPixelPosition, margin, t);
}
QImage img(glyph->width, glyph->height, QImage::Format_RGB32);
diff --git a/src/gui/text/qfontengine_ft_p.h b/src/gui/text/qfontengine_ft_p.h
index 93a6d16aaf..abdbd2099b 100644
--- a/src/gui/text/qfontengine_ft_p.h
+++ b/src/gui/text/qfontengine_ft_p.h
@@ -130,13 +130,6 @@ private:
class Q_GUI_EXPORT QFontEngineFT : public QFontEngine
{
public:
- enum GlyphFormat {
- Format_None,
- Format_Render = Format_None,
- Format_Mono,
- Format_A8,
- Format_A32
- };
/* we don't cache glyphs that are too large anyway, so we can make this struct rather small */
struct Glyph {
@@ -241,7 +234,9 @@ private:
virtual void recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags flags) const;
virtual QImage alphaMapForGlyph(glyph_t);
- virtual QImage alphaRGBMapForGlyph(glyph_t, int margin, const QTransform &t);
+ virtual QImage alphaRGBMapForGlyph(glyph_t, QFixed subPixelPosition, int margin, const QTransform &t);
+ virtual glyph_metrics_t alphaMapBoundingBox(glyph_t glyph, const QTransform &matrix,
+ QFontEngine::GlyphFormat format);
virtual void removeGlyphFromCache(glyph_t glyph);
virtual int glyphCount() const;
@@ -282,6 +277,14 @@ private:
virtual HB_Error getPointInOutline(HB_Glyph glyph, int flags, hb_uint32 point, HB_Fixed *xpos, HB_Fixed *ypos, hb_uint32 *nPoints);
+ enum HintStyle {
+ HintNone,
+ HintLight,
+ HintMedium,
+ HintFull
+ };
+
+ void setDefaultHintStyle(HintStyle style);
protected:
void freeGlyphSets();
@@ -293,12 +296,6 @@ protected:
QFreetypeFace *freetype;
int default_load_flags;
- enum HintStyle {
- HintNone,
- HintLight,
- HintMedium,
- HintFull
- };
HintStyle default_hint_style;
@@ -311,7 +308,7 @@ protected:
bool embeddedbitmap;
private:
- QFontEngineFT::Glyph *loadGlyphMetrics(QGlyphSet *set, uint glyph) const;
+ QFontEngineFT::Glyph *loadGlyphMetrics(QGlyphSet *set, uint glyph, GlyphFormat format) const;
GlyphFormat defaultFormat;
FT_Matrix matrix;
diff --git a/src/gui/text/qfontengine_mac.mm b/src/gui/text/qfontengine_mac.mm
index 1c21f91bce..7751bbe62f 100644
--- a/src/gui/text/qfontengine_mac.mm
+++ b/src/gui/text/qfontengine_mac.mm
@@ -39,6 +39,8 @@
**
****************************************************************************/
+#include "qfontengine_mac_p.h"
+
#include <private/qapplication_p.h>
#include <private/qfontengine_p.h>
#include <private/qpainter_p.h>
@@ -53,6 +55,7 @@
#include <qdebug.h>
#include <qendian.h>
#include <qmath.h>
+#include <private/qimage_p.h>
#include <ApplicationServices/ApplicationServices.h>
#include <AppKit/AppKit.h>
@@ -119,679 +122,6 @@ OSStatus QMacFontPath::closePath(void *data)
}
-
-void qmacfontengine_gamma_correct(QImage *image)
-{
- extern uchar qt_pow_rgb_gamma[256];
-
- // gamma correct the pixels back to linear color space...
- int h = image->height();
- int w = image->width();
-
- for (int y=0; y<h; ++y) {
- uint *pixels = (uint *) image->scanLine(y);
- for (int x=0; x<w; ++x) {
- uint p = pixels[x];
- uint r = qt_pow_rgb_gamma[qRed(p)];
- uint g = qt_pow_rgb_gamma[qGreen(p)];
- uint b = qt_pow_rgb_gamma[qBlue(p)];
- pixels[x] = (r << 16) | (g << 8) | b | 0xff000000;
- }
- }
-}
-
-
-#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
-QCoreTextFontEngineMulti::QCoreTextFontEngineMulti(const ATSFontFamilyRef &, const ATSFontRef &atsFontRef, const QFontDef &fontDef, bool kerning)
- : QFontEngineMulti(0)
-{
- this->fontDef = fontDef;
- CTFontSymbolicTraits symbolicTraits = 0;
- if (fontDef.weight >= QFont::Bold)
- symbolicTraits |= kCTFontBoldTrait;
- switch (fontDef.style) {
- case QFont::StyleNormal:
- break;
- case QFont::StyleItalic:
- case QFont::StyleOblique:
- symbolicTraits |= kCTFontItalicTrait;
- break;
- }
-
- QCFString name;
- ATSFontGetName(atsFontRef, kATSOptionFlagsDefault, &name);
-
- transform = CGAffineTransformIdentity;
- if (fontDef.stretch != 100) {
- transform = CGAffineTransformMakeScale(float(fontDef.stretch) / float(100), 1);
- }
-
- QCFType<CTFontDescriptorRef> descriptor = CTFontDescriptorCreateWithNameAndSize(name, fontDef.pixelSize);
- QCFType<CTFontRef> baseFont = CTFontCreateWithFontDescriptor(descriptor, fontDef.pixelSize, &transform);
- ctfont = CTFontCreateCopyWithSymbolicTraits(baseFont, fontDef.pixelSize, &transform, symbolicTraits, symbolicTraits);
-
- // CTFontCreateCopyWithSymbolicTraits returns NULL if we ask for a trait that does
- // not exist for the given font. (for example italic)
- if (ctfont == 0) {
- ctfont = baseFont;
- CFRetain(ctfont);
- }
-
- attributeDict = CFDictionaryCreateMutable(0, 2,
- &kCFTypeDictionaryKeyCallBacks,
- &kCFTypeDictionaryValueCallBacks);
- CFDictionaryAddValue(attributeDict, NSFontAttributeName, ctfont);
- if (!kerning) {
- float zero = 0.0;
- QCFType<CFNumberRef> noKern = CFNumberCreate(kCFAllocatorDefault, kCFNumberFloatType, &zero);
- CFDictionaryAddValue(attributeDict, kCTKernAttributeName, noKern);
- }
-
- QCoreTextFontEngine *fe = new QCoreTextFontEngine(ctfont, fontDef, this);
- fe->ref.ref();
- engines.append(fe);
-
-}
-
-QCoreTextFontEngineMulti::~QCoreTextFontEngineMulti()
-{
- CFRelease(ctfont);
-}
-
-uint QCoreTextFontEngineMulti::fontIndexForFont(CTFontRef id) const
-{
- for (int i = 0; i < engines.count(); ++i) {
- if (CFEqual(engineAt(i)->ctfont, id))
- return i;
- }
-
- QCoreTextFontEngineMulti *that = const_cast<QCoreTextFontEngineMulti *>(this);
- QCoreTextFontEngine *fe = new QCoreTextFontEngine(id, fontDef, that);
- fe->ref.ref();
- that->engines.append(fe);
- return engines.count() - 1;
-}
-
-bool QCoreTextFontEngineMulti::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags,
- unsigned short *logClusters, const HB_CharAttributes *) const
-{
- QCFType<CFStringRef> cfstring = CFStringCreateWithCharactersNoCopy(0,
- reinterpret_cast<const UniChar *>(str),
- len, kCFAllocatorNull);
- QCFType<CFAttributedStringRef> attributedString = CFAttributedStringCreate(0, cfstring, attributeDict);
- QCFType<CTTypesetterRef> typeSetter = CTTypesetterCreateWithAttributedString(attributedString);
- CFRange range = {0, 0};
- QCFType<CTLineRef> line = CTTypesetterCreateLine(typeSetter, range);
- CFArrayRef array = CTLineGetGlyphRuns(line);
- uint arraySize = CFArrayGetCount(array);
- glyph_t *outGlyphs = glyphs->glyphs;
- HB_GlyphAttributes *outAttributes = glyphs->attributes;
- QFixed *outAdvances_x = glyphs->advances_x;
- QFixed *outAdvances_y = glyphs->advances_y;
- glyph_t *initialGlyph = outGlyphs;
-
- if (arraySize == 0) {
- // CoreText failed to shape the text we gave it, so we assume one glyph
- // per character and build a list of invalid glyphs with zero advance
- *nglyphs = len;
- for (int i = 0; i < len; ++i) {
- outGlyphs[i] = 0;
- if (logClusters)
- logClusters[i] = i;
- outAdvances_x[i] = QFixed();
- outAdvances_y[i] = QFixed();
- outAttributes[i].clusterStart = true;
- }
- return true;
- }
-
- const bool rtl = (CTRunGetStatus(static_cast<CTRunRef>(CFArrayGetValueAtIndex(array, 0))) & kCTRunStatusRightToLeft);
-
- bool outOBounds = false;
- for (uint i = 0; i < arraySize; ++i) {
- CTRunRef run = static_cast<CTRunRef>(CFArrayGetValueAtIndex(array, rtl ? (arraySize - 1 - i) : i));
- CFIndex glyphCount = CTRunGetGlyphCount(run);
- if (glyphCount == 0)
- continue;
-
- Q_ASSERT((CTRunGetStatus(run) & kCTRunStatusRightToLeft) == rtl);
-
- if (!outOBounds && outGlyphs + glyphCount - initialGlyph > *nglyphs) {
- outOBounds = true;
- }
- if (!outOBounds) {
- CFDictionaryRef runAttribs = CTRunGetAttributes(run);
- //NSLog(@"Dictionary %@", runAttribs);
- if (!runAttribs)
- runAttribs = attributeDict;
- CTFontRef runFont = static_cast<CTFontRef>(CFDictionaryGetValue(runAttribs, NSFontAttributeName));
- const uint fontIndex = (fontIndexForFont(runFont) << 24);
- //NSLog(@"Run Font Name = %@", CTFontCopyFamilyName(runFont));
- QVarLengthArray<CGGlyph, 512> cgglyphs(0);
- const CGGlyph *tmpGlyphs = CTRunGetGlyphsPtr(run);
- if (!tmpGlyphs) {
- cgglyphs.resize(glyphCount);
- CTRunGetGlyphs(run, range, cgglyphs.data());
- tmpGlyphs = cgglyphs.constData();
- }
- QVarLengthArray<CGPoint, 512> cgpoints(0);
- const CGPoint *tmpPoints = CTRunGetPositionsPtr(run);
- if (!tmpPoints) {
- cgpoints.resize(glyphCount);
- CTRunGetPositions(run, range, cgpoints.data());
- tmpPoints = cgpoints.constData();
- }
-
- const int rtlOffset = rtl ? (glyphCount - 1) : 0;
- const int rtlSign = rtl ? -1 : 1;
-
- if (logClusters) {
- CFRange stringRange = CTRunGetStringRange(run);
- QVarLengthArray<CFIndex, 512> stringIndices(0);
- const CFIndex *tmpIndices = CTRunGetStringIndicesPtr(run);
- if (!tmpIndices) {
- stringIndices.resize(glyphCount);
- CTRunGetStringIndices(run, range, stringIndices.data());
- tmpIndices = stringIndices.constData();
- }
-
- const int firstGlyphIndex = outGlyphs - initialGlyph;
- outAttributes[0].clusterStart = true;
-
- CFIndex k = 0;
- CFIndex i = 0;
- for (i = stringRange.location;
- (i < stringRange.location + stringRange.length) && (k < glyphCount); ++i) {
- if (tmpIndices[k * rtlSign + rtlOffset] == i || i == stringRange.location) {
- logClusters[i] = k + firstGlyphIndex;
- outAttributes[k].clusterStart = true;
- ++k;
- } else {
- logClusters[i] = k + firstGlyphIndex - 1;
- }
- }
- // in case of a ligature at the end, fill the remaining logcluster entries
- for (;i < stringRange.location + stringRange.length; i++) {
- logClusters[i] = k + firstGlyphIndex - 1;
- }
- }
- for (CFIndex i = 0; i < glyphCount - 1; ++i) {
- int idx = rtlOffset + rtlSign * i;
- outGlyphs[idx] = tmpGlyphs[i] | fontIndex;
- outAdvances_x[idx] = QFixed::fromReal(tmpPoints[i + 1].x - tmpPoints[i].x);
- outAdvances_y[idx] = QFixed::fromReal(tmpPoints[i + 1].y - tmpPoints[i].y);
-
- if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) {
- outAdvances_x[idx] = outAdvances_x[idx].round();
- outAdvances_y[idx] = outAdvances_y[idx].round();
- }
- }
- CGSize lastGlyphAdvance;
- CTFontGetAdvancesForGlyphs(runFont, kCTFontHorizontalOrientation, tmpGlyphs + glyphCount - 1, &lastGlyphAdvance, 1);
-
- outGlyphs[rtl ? 0 : (glyphCount - 1)] = tmpGlyphs[glyphCount - 1] | fontIndex;
- outAdvances_x[rtl ? 0 : (glyphCount - 1)] =
- (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
- ? QFixed::fromReal(lastGlyphAdvance.width).round()
- : QFixed::fromReal(lastGlyphAdvance.width);
- }
- outGlyphs += glyphCount;
- outAttributes += glyphCount;
- outAdvances_x += glyphCount;
- outAdvances_y += glyphCount;
- }
- *nglyphs = (outGlyphs - initialGlyph);
- return !outOBounds;
-}
-
-bool QCoreTextFontEngineMulti::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs,
- int *nglyphs, QTextEngine::ShaperFlags flags) const
-{
- *nglyphs = len;
- QCFType<CFStringRef> cfstring;
-
- QVarLengthArray<CGGlyph> cgGlyphs(len);
- CTFontGetGlyphsForCharacters(ctfont, (const UniChar*)str, cgGlyphs.data(), len);
-
- for (int i = 0; i < len; ++i) {
- if (cgGlyphs[i]) {
- glyphs->glyphs[i] = cgGlyphs[i];
- } else {
- if (!cfstring)
- cfstring = CFStringCreateWithCharactersNoCopy(0, reinterpret_cast<const UniChar *>(str), len, kCFAllocatorNull);
- QCFType<CTFontRef> substituteFont = CTFontCreateForString(ctfont, cfstring, CFRangeMake(i, 1));
- CGGlyph substituteGlyph = 0;
- CTFontGetGlyphsForCharacters(substituteFont, (const UniChar*)str + i, &substituteGlyph, 1);
- if (substituteGlyph) {
- const uint fontIndex = (fontIndexForFont(substituteFont) << 24);
- glyphs->glyphs[i] = substituteGlyph | fontIndex;
- if (!(flags & QTextEngine::GlyphIndicesOnly)) {
- CGSize advance;
- CTFontGetAdvancesForGlyphs(substituteFont, kCTFontHorizontalOrientation, &substituteGlyph, &advance, 1);
- glyphs->advances_x[i] = QFixed::fromReal(advance.width);
- glyphs->advances_y[i] = QFixed::fromReal(advance.height);
- }
- }
- }
- }
-
- if (flags & QTextEngine::GlyphIndicesOnly)
- return true;
-
- QVarLengthArray<CGSize> advances(len);
- CTFontGetAdvancesForGlyphs(ctfont, kCTFontHorizontalOrientation, cgGlyphs.data(), advances.data(), len);
-
- for (int i = 0; i < len; ++i) {
- if (glyphs->glyphs[i] & 0xff000000)
- continue;
- glyphs->advances_x[i] = QFixed::fromReal(advances[i].width);
- glyphs->advances_y[i] = QFixed::fromReal(advances[i].height);
- }
-
- if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) {
- for (int i = 0; i < len; ++i) {
- glyphs->advances_x[i] = glyphs->advances_x[i].round();
- glyphs->advances_y[i] = glyphs->advances_y[i].round();
- }
- }
-
- return true;
-}
-
-void QCoreTextFontEngineMulti::recalcAdvances(int , QGlyphLayout *, QTextEngine::ShaperFlags) const
-{
-}
-void QCoreTextFontEngineMulti::doKerning(int , QGlyphLayout *, QTextEngine::ShaperFlags) const
-{
-}
-
-void QCoreTextFontEngineMulti::loadEngine(int)
-{
- // Do nothing
- Q_ASSERT(false);
-}
-
-
-
-QCoreTextFontEngine::QCoreTextFontEngine(CTFontRef font, const QFontDef &def,
- QCoreTextFontEngineMulti *multiEngine)
-{
- fontDef = def;
- parentEngine = multiEngine;
- synthesisFlags = 0;
- ctfont = font;
- CFRetain(ctfont);
- ATSFontRef atsfont = CTFontGetPlatformFont(ctfont, 0);
- cgFont = CGFontCreateWithPlatformFont(&atsfont);
- CTFontSymbolicTraits traits = CTFontGetSymbolicTraits(ctfont);
- if (fontDef.weight >= QFont::Bold && !(traits & kCTFontBoldTrait)) {
- synthesisFlags |= SynthesizedBold;
- }
-
- if (fontDef.style != QFont::StyleNormal && !(traits & kCTFontItalicTrait)) {
- synthesisFlags |= SynthesizedItalic;
- }
- transform = CGAffineTransformIdentity;
- if (fontDef.stretch != 100) {
- transform = CGAffineTransformMakeScale(float(fontDef.stretch) / float(100), 1);
- }
- QByteArray os2Table = getSfntTable(MAKE_TAG('O', 'S', '/', '2'));
- if (os2Table.size() >= 10)
- fsType = qFromBigEndian<quint16>(reinterpret_cast<const uchar *>(os2Table.constData() + 8));
-}
-
-QCoreTextFontEngine::~QCoreTextFontEngine()
-{
- CFRelease(ctfont);
- CFRelease(cgFont);
-}
-
-bool QCoreTextFontEngine::stringToCMap(const QChar *, int, QGlyphLayout *, int *, QTextEngine::ShaperFlags) const
-{
- return false;
-}
-
-glyph_metrics_t QCoreTextFontEngine::boundingBox(const QGlyphLayout &glyphs)
-{
- QFixed w;
- bool round = fontDef.styleStrategy & QFont::ForceIntegerMetrics;
-
- for (int i = 0; i < glyphs.numGlyphs; ++i) {
- w += round ? glyphs.effectiveAdvance(i).round()
- : glyphs.effectiveAdvance(i);
- }
- return glyph_metrics_t(0, -(ascent()), w - lastRightBearing(glyphs, round), ascent()+descent(), w, 0);
-}
-glyph_metrics_t QCoreTextFontEngine::boundingBox(glyph_t glyph)
-{
- glyph_metrics_t ret;
- CGGlyph g = glyph;
- CGRect rect = CTFontGetBoundingRectsForGlyphs(ctfont, kCTFontHorizontalOrientation, &g, 0, 1);
- ret.width = QFixed::fromReal(rect.size.width);
- ret.height = QFixed::fromReal(rect.size.height);
- ret.x = QFixed::fromReal(rect.origin.x);
- ret.y = -QFixed::fromReal(rect.origin.y) - ret.height;
- CGSize advances[1];
- CTFontGetAdvancesForGlyphs(ctfont, kCTFontHorizontalOrientation, &g, advances, 1);
- ret.xoff = QFixed::fromReal(advances[0].width);
- ret.yoff = QFixed::fromReal(advances[0].height);
-
- if (fontDef.styleStrategy & QFont::ForceIntegerMetrics) {
- ret.xoff = ret.xoff.round();
- ret.yoff = ret.yoff.round();
- }
-
- return ret;
-}
-
-QFixed QCoreTextFontEngine::ascent() const
-{
- return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
- ? QFixed::fromReal(CTFontGetAscent(ctfont)).round()
- : QFixed::fromReal(CTFontGetAscent(ctfont));
-}
-QFixed QCoreTextFontEngine::descent() const
-{
- QFixed d = QFixed::fromReal(CTFontGetDescent(ctfont));
- if (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
- d = d.round();
-
- // subtract a pixel to even out the historical +1 in QFontMetrics::height().
- // Fix in Qt 5.
- return d - 1;
-}
-QFixed QCoreTextFontEngine::leading() const
-{
- return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
- ? QFixed::fromReal(CTFontGetLeading(ctfont)).round()
- : QFixed::fromReal(CTFontGetLeading(ctfont));
-}
-QFixed QCoreTextFontEngine::xHeight() const
-{
- return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
- ? QFixed::fromReal(CTFontGetXHeight(ctfont)).round()
- : QFixed::fromReal(CTFontGetXHeight(ctfont));
-}
-QFixed QCoreTextFontEngine::averageCharWidth() const
-{
- // ### Need to implement properly and get the information from the OS/2 Table.
- return (fontDef.styleStrategy & QFont::ForceIntegerMetrics)
- ? QFontEngine::averageCharWidth().round()
- : QFontEngine::averageCharWidth();
-}
-
-qreal QCoreTextFontEngine::maxCharWidth() const
-{
- // ### Max Help!
- return 0;
-
-}
-qreal QCoreTextFontEngine::minLeftBearing() const
-{
- // ### Min Help!
- return 0;
-
-}
-qreal QCoreTextFontEngine::minRightBearing() const
-{
- // ### Max Help! (even thought it's right)
- return 0;
-
-}
-
-void QCoreTextFontEngine::draw(CGContextRef ctx, qreal x, qreal y, const QTextItemInt &ti, int paintDeviceHeight)
-{
- QVarLengthArray<QFixedPoint> positions;
- QVarLengthArray<glyph_t> glyphs;
- QTransform matrix;
- matrix.translate(x, y);
- getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions);
- if (glyphs.size() == 0)
- return;
-
- CGContextSetFontSize(ctx, fontDef.pixelSize);
-
- CGAffineTransform oldTextMatrix = CGContextGetTextMatrix(ctx);
-
- CGAffineTransform cgMatrix = CGAffineTransformMake(1, 0, 0, -1, 0, -paintDeviceHeight);
-
- CGAffineTransformConcat(cgMatrix, oldTextMatrix);
-
- if (synthesisFlags & QFontEngine::SynthesizedItalic)
- cgMatrix = CGAffineTransformConcat(cgMatrix, CGAffineTransformMake(1, 0, -tanf(14 * acosf(0) / 90), 1, 0, 0));
-
- cgMatrix = CGAffineTransformConcat(cgMatrix, transform);
-
- CGContextSetTextMatrix(ctx, cgMatrix);
-
- CGContextSetTextDrawingMode(ctx, kCGTextFill);
-
-
- QVarLengthArray<CGSize> advances(glyphs.size());
- QVarLengthArray<CGGlyph> cgGlyphs(glyphs.size());
-
- for (int i = 0; i < glyphs.size() - 1; ++i) {
- advances[i].width = (positions[i + 1].x - positions[i].x).toReal();
- advances[i].height = (positions[i + 1].y - positions[i].y).toReal();
- cgGlyphs[i] = glyphs[i];
- }
- advances[glyphs.size() - 1].width = 0;
- advances[glyphs.size() - 1].height = 0;
- cgGlyphs[glyphs.size() - 1] = glyphs[glyphs.size() - 1];
-
- CGContextSetFont(ctx, cgFont);
- //NSLog(@"Font inDraw %@ ctfont %@", CGFontCopyFullName(cgFont), CTFontCopyFamilyName(ctfont));
-
- CGContextSetTextPosition(ctx, positions[0].x.toReal(), positions[0].y.toReal());
-
- CGContextShowGlyphsWithAdvances(ctx, cgGlyphs.data(), advances.data(), glyphs.size());
-
- if (synthesisFlags & QFontEngine::SynthesizedBold) {
- CGContextSetTextPosition(ctx, positions[0].x.toReal() + 0.5 * lineThickness().toReal(),
- positions[0].y.toReal());
-
- CGContextShowGlyphsWithAdvances(ctx, cgGlyphs.data(), advances.data(), glyphs.size());
- }
-
- CGContextSetTextMatrix(ctx, oldTextMatrix);
-}
-
-struct ConvertPathInfo
-{
- ConvertPathInfo(QPainterPath *newPath, const QPointF &newPos) : path(newPath), pos(newPos) {}
- QPainterPath *path;
- QPointF pos;
-};
-
-static void convertCGPathToQPainterPath(void *info, const CGPathElement *element)
-{
- ConvertPathInfo *myInfo = static_cast<ConvertPathInfo *>(info);
- switch(element->type) {
- case kCGPathElementMoveToPoint:
- myInfo->path->moveTo(element->points[0].x + myInfo->pos.x(),
- element->points[0].y + myInfo->pos.y());
- break;
- case kCGPathElementAddLineToPoint:
- myInfo->path->lineTo(element->points[0].x + myInfo->pos.x(),
- element->points[0].y + myInfo->pos.y());
- break;
- case kCGPathElementAddQuadCurveToPoint:
- myInfo->path->quadTo(element->points[0].x + myInfo->pos.x(),
- element->points[0].y + myInfo->pos.y(),
- element->points[1].x + myInfo->pos.x(),
- element->points[1].y + myInfo->pos.y());
- break;
- case kCGPathElementAddCurveToPoint:
- myInfo->path->cubicTo(element->points[0].x + myInfo->pos.x(),
- element->points[0].y + myInfo->pos.y(),
- element->points[1].x + myInfo->pos.x(),
- element->points[1].y + myInfo->pos.y(),
- element->points[2].x + myInfo->pos.x(),
- element->points[2].y + myInfo->pos.y());
- break;
- case kCGPathElementCloseSubpath:
- myInfo->path->closeSubpath();
- break;
- default:
- qDebug() << "Unhandled path transform type: " << element->type;
- }
-
-}
-
-void QCoreTextFontEngine::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nGlyphs,
- QPainterPath *path, QTextItem::RenderFlags)
-{
-
- CGAffineTransform cgMatrix = CGAffineTransformIdentity;
- cgMatrix = CGAffineTransformScale(cgMatrix, 1, -1);
-
- if (synthesisFlags & QFontEngine::SynthesizedItalic)
- cgMatrix = CGAffineTransformConcat(cgMatrix, CGAffineTransformMake(1, 0, -tanf(14 * acosf(0) / 90), 1, 0, 0));
-
-
- for (int i = 0; i < nGlyphs; ++i) {
- QCFType<CGPathRef> cgpath = CTFontCreatePathForGlyph(ctfont, glyphs[i], &cgMatrix);
- ConvertPathInfo info(path, positions[i].toPointF());
- CGPathApply(cgpath, &info, convertCGPathToQPainterPath);
- }
-}
-
-QImage QCoreTextFontEngine::imageForGlyph(glyph_t glyph, int margin, bool aa)
-{
- const glyph_metrics_t br = boundingBox(glyph);
- QImage im(qRound(br.width)+2, qRound(br.height)+2, QImage::Format_RGB32);
- im.fill(0);
-
- CGColorSpaceRef colorspace = QCoreGraphicsPaintEngine::macGenericColorSpace();
- uint cgflags = kCGImageAlphaNoneSkipFirst;
-#ifdef kCGBitmapByteOrder32Host //only needed because CGImage.h added symbols in the minor version
- cgflags |= kCGBitmapByteOrder32Host;
-#endif
- CGContextRef ctx = CGBitmapContextCreate(im.bits(), im.width(), im.height(),
- 8, im.bytesPerLine(), colorspace,
- cgflags);
- CGContextSetFontSize(ctx, fontDef.pixelSize);
- CGContextSetShouldAntialias(ctx, aa ||
- (fontDef.pointSize > qt_antialiasing_threshold
- && !(fontDef.styleStrategy & QFont::NoAntialias)));
- CGContextSetShouldSmoothFonts(ctx, aa);
- CGAffineTransform oldTextMatrix = CGContextGetTextMatrix(ctx);
- CGAffineTransform cgMatrix = CGAffineTransformMake(1, 0, 0, 1, 0, 0);
-
- CGAffineTransformConcat(cgMatrix, oldTextMatrix);
-
- if (synthesisFlags & QFontEngine::SynthesizedItalic)
- cgMatrix = CGAffineTransformConcat(cgMatrix, CGAffineTransformMake(1, 0, tanf(14 * acosf(0) / 90), 1, 0, 0));
-
- cgMatrix = CGAffineTransformConcat(cgMatrix, transform);
-
- CGContextSetTextMatrix(ctx, cgMatrix);
- CGContextSetRGBFillColor(ctx, 1, 1, 1, 1);
- CGContextSetTextDrawingMode(ctx, kCGTextFill);
-
- ATSFontRef atsfont = CTFontGetPlatformFont(ctfont, 0);
- QCFType<CGFontRef> cgFont = CGFontCreateWithPlatformFont(&atsfont);
- CGContextSetFont(ctx, cgFont);
-
- qreal pos_x = -br.x.toReal()+1, pos_y = im.height()+br.y.toReal();
- CGContextSetTextPosition(ctx, pos_x, pos_y);
-
- CGSize advance;
- advance.width = 0;
- advance.height = 0;
- CGGlyph cgGlyph = glyph;
- CGContextShowGlyphsWithAdvances(ctx, &cgGlyph, &advance, 1);
-
- if (synthesisFlags & QFontEngine::SynthesizedBold) {
- CGContextSetTextPosition(ctx, pos_x + 0.5 * lineThickness().toReal(), pos_y);
- CGContextShowGlyphsWithAdvances(ctx, &cgGlyph, &advance, 1);
- }
-
- CGContextRelease(ctx);
-
- return im;
-}
-
-QImage QCoreTextFontEngine::alphaMapForGlyph(glyph_t glyph)
-{
- QImage im = imageForGlyph(glyph, 0, false);
-
- QImage indexed(im.width(), im.height(), QImage::Format_Indexed8);
- QVector<QRgb> colors(256);
- for (int i=0; i<256; ++i)
- colors[i] = qRgba(0, 0, 0, i);
- indexed.setColorTable(colors);
-
- for (int y=0; y<im.height(); ++y) {
- uint *src = (uint*) im.scanLine(y);
- uchar *dst = indexed.scanLine(y);
- for (int x=0; x<im.width(); ++x) {
- *dst = qGray(*src);
- ++dst;
- ++src;
- }
- }
-
- return indexed;
-}
-
-QImage QCoreTextFontEngine::alphaRGBMapForGlyph(glyph_t glyph, int margin, const QTransform &x)
-{
- if (x.type() >= QTransform::TxScale)
- return QFontEngine::alphaRGBMapForGlyph(glyph, margin, x);
-
- QImage im = imageForGlyph(glyph, margin, true);
- qmacfontengine_gamma_correct(&im);
- return im;
-}
-
-void QCoreTextFontEngine::recalcAdvances(int numGlyphs, QGlyphLayout *glyphs, QTextEngine::ShaperFlags flags) const
-{
- Q_ASSERT(false);
- Q_UNUSED(numGlyphs);
- Q_UNUSED(glyphs);
- Q_UNUSED(flags);
-}
-
-QFontEngine::FaceId QCoreTextFontEngine::faceId() const
-{
- return QFontEngine::FaceId();
-}
-
-bool QCoreTextFontEngine::canRender(const QChar *string, int len)
-{
- QCFType<CTFontRef> retFont = CTFontCreateForString(ctfont,
- QCFType<CFStringRef>(CFStringCreateWithCharactersNoCopy(0,
- reinterpret_cast<const UniChar *>(string),
- len, kCFAllocatorNull)),
- CFRangeMake(0, len));
- return retFont != 0;
- return false;
-}
-
- bool QCoreTextFontEngine::getSfntTableData(uint tag, uchar *buffer, uint *length) const
- {
- QCFType<CFDataRef> table = CTFontCopyTable(ctfont, tag, 0);
- if (!table || !length)
- return false;
- CFIndex tableLength = CFDataGetLength(table);
- int availableLength = *length;
- *length = tableLength;
- if (buffer) {
- if (tableLength > availableLength)
- return false;
- CFDataGetBytes(table, CFRangeMake(0, tableLength), buffer);
- }
- return true;
- }
-
-void QCoreTextFontEngine::getUnscaledGlyph(glyph_t, QPainterPath *, glyph_metrics_t *)
-{
- // ###
-}
-
-#endif // MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
-
#ifndef QT_MAC_USE_COCOA
QFontEngineMacMulti::QFontEngineMacMulti(const ATSFontFamilyRef &atsFamily, const ATSFontRef &atsFontRef, const QFontDef &fontDef, bool kerning)
: QFontEngineMulti(0)
@@ -1419,6 +749,7 @@ static inline unsigned int getChar(const QChar *str, int &i, const int len)
return uc;
}
+// Not used directly for shaping, only used to calculate m_averageCharWidth
bool QFontEngineMac::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const
{
if (!cmap) {
@@ -1591,6 +922,27 @@ static void addGlyphsToPathHelper(ATSUStyle style, glyph_t *glyphs, QFixedPoint
DisposeATSCubicClosePathUPP(closePath);
}
+QFont QFontEngineMac::createExplicitFont() const
+{
+ FMFont fmFont = FMGetFontFromATSFontRef(fontID);
+
+ FMFontFamily fmFamily;
+ FMFontStyle fmStyle;
+ QString familyName;
+ if (!FMGetFontFamilyInstanceFromFont(fmFont, &fmFamily, &fmStyle)) {
+ ATSFontFamilyRef familyRef = FMGetATSFontFamilyRefFromFontFamily(fmFamily);
+ QCFString cfFamilyName;;
+ ATSFontFamilyGetName(familyRef, kATSOptionFlagsDefault, &cfFamilyName);
+ familyName = cfFamilyName;
+ } else {
+ QCFString cfFontName;
+ ATSFontGetName(fontID, kATSOptionFlagsDefault, &cfFontName);
+ familyName = cfFontName;
+ }
+
+ return createExplicitFontWithName(familyName);
+}
+
void QFontEngineMac::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int numGlyphs, QPainterPath *path,
QTextItem::RenderFlags)
{
@@ -1677,7 +1029,7 @@ QImage QFontEngineMac::alphaMapForGlyph(glyph_t glyph)
return indexed;
}
-QImage QFontEngineMac::alphaRGBMapForGlyph(glyph_t glyph, int margin, const QTransform &t)
+QImage QFontEngineMac::alphaRGBMapForGlyph(glyph_t glyph, QFixed, int margin, const QTransform &t)
{
QImage im = imageForGlyph(glyph, margin, true);
@@ -1685,7 +1037,7 @@ QImage QFontEngineMac::alphaRGBMapForGlyph(glyph_t glyph, int margin, const QTra
im = im.transformed(t);
}
- qmacfontengine_gamma_correct(&im);
+ qGamma_correct_back_to_linear_cs(&im);
return im;
}
diff --git a/src/gui/text/qfontengine_mac_p.h b/src/gui/text/qfontengine_mac_p.h
new file mode 100644
index 0000000000..5577c765a6
--- /dev/null
+++ b/src/gui/text/qfontengine_mac_p.h
@@ -0,0 +1,167 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QFONTENGINE_MAC_P_H
+#define QFONTENGINE_MAC_P_H
+
+#include <private/qfontengine_p.h>
+
+#ifndef QT_MAC_USE_COCOA
+class QFontEngineMacMulti;
+class QFontEngineMac : public QFontEngine
+{
+ friend class QFontEngineMacMulti;
+public:
+ QFontEngineMac(ATSUStyle baseStyle, ATSUFontID fontID, const QFontDef &def, QFontEngineMacMulti *multiEngine = 0);
+ virtual ~QFontEngineMac();
+
+ virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *numGlyphs, QTextEngine::ShaperFlags flags) const;
+ virtual void recalcAdvances(QGlyphLayout *, QTextEngine::ShaperFlags) const;
+
+ virtual glyph_metrics_t boundingBox(const QGlyphLayout &glyphs);
+ virtual glyph_metrics_t boundingBox(glyph_t glyph);
+
+ virtual QFixed ascent() const;
+ virtual QFixed descent() const;
+ virtual QFixed leading() const;
+ virtual QFixed xHeight() const;
+ virtual qreal maxCharWidth() const;
+ virtual QFixed averageCharWidth() const;
+
+ virtual QFont createExplicitFont() const;
+
+ virtual void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int numGlyphs,
+ QPainterPath *path, QTextItem::RenderFlags);
+
+ virtual const char *name() const { return "QFontEngineMac"; }
+
+ virtual bool canRender(const QChar *string, int len);
+
+ virtual int synthesized() const { return synthesisFlags; }
+
+ virtual Type type() const { return QFontEngine::Mac; }
+
+ void draw(CGContextRef ctx, qreal x, qreal y, const QTextItemInt &ti, int paintDeviceHeight);
+
+ virtual FaceId faceId() const;
+ virtual QByteArray getSfntTable(uint tag) const;
+ virtual Properties properties() const;
+ virtual void getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics);
+ virtual QImage alphaMapForGlyph(glyph_t);
+ virtual QImage alphaRGBMapForGlyph(glyph_t, QFixed subPixelPosition, int margin, const QTransform &t);
+
+private:
+ QImage imageForGlyph(glyph_t glyph, int margin, bool colorful);
+
+ ATSUFontID fontID;
+ QCFType<CGFontRef> cgFont;
+ ATSUStyle style;
+ int synthesisFlags;
+ mutable QGlyphLayout kashidaGlyph;
+ QFontEngineMacMulti *multiEngine;
+ mutable const unsigned char *cmap;
+ mutable bool symbolCMap;
+ mutable QByteArray cmapTable;
+ CGAffineTransform transform;
+ QFixed m_ascent;
+ QFixed m_descent;
+ QFixed m_leading;
+ qreal m_maxCharWidth;
+ QFixed m_xHeight;
+ QFixed m_averageCharWidth;
+};
+
+class QFontEngineMacMulti : public QFontEngineMulti
+{
+ friend class QFontEngineMac;
+public:
+ // internal
+ struct ShaperItem
+ {
+ inline ShaperItem() : string(0), from(0), length(0),
+ log_clusters(0), charAttributes(0) {}
+
+ const QChar *string;
+ int from;
+ int length;
+ QGlyphLayout glyphs;
+ unsigned short *log_clusters;
+ const HB_CharAttributes *charAttributes;
+ QTextEngine::ShaperFlags flags;
+ };
+
+ QFontEngineMacMulti(const ATSFontFamilyRef &atsFamily, const ATSFontRef &atsFontRef, const QFontDef &fontDef, bool kerning);
+ virtual ~QFontEngineMacMulti();
+
+ virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const;
+ bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags,
+ unsigned short *logClusters, const HB_CharAttributes *charAttributes) const;
+
+ virtual void recalcAdvances(QGlyphLayout *, QTextEngine::ShaperFlags) const;
+ virtual void doKerning(QGlyphLayout *, QTextEngine::ShaperFlags) const;
+
+ virtual const char *name() const { return "ATSUI"; }
+
+ virtual bool canRender(const QChar *string, int len);
+
+ inline ATSUFontID macFontID() const { return fontID; }
+
+protected:
+ virtual void loadEngine(int at);
+
+private:
+ inline const QFontEngineMac *engineAt(int i) const
+ { return static_cast<const QFontEngineMac *>(engines.at(i)); }
+
+ bool stringToCMapInternal(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags, ShaperItem *item) const;
+
+ int fontIndexForFontID(ATSUFontID id) const;
+
+ ATSUFontID fontID;
+ uint kerning : 1;
+
+ mutable ATSUTextLayout textLayout;
+ mutable ATSUStyle style;
+ CGAffineTransform transform;
+};
+#endif //!QT_MAC_USE_COCOA
+
+#endif // QFONTENGINE_MAC_P_H
diff --git a/src/gui/text/qfontengine_p.h b/src/gui/text/qfontengine_p.h
index ea2d925f5a..bbb242bda9 100644
--- a/src/gui/text/qfontengine_p.h
+++ b/src/gui/text/qfontengine_p.h
@@ -120,6 +120,14 @@ public:
TestFontEngine = 0x1000
};
+ enum GlyphFormat {
+ Format_None,
+ Format_Render = Format_None,
+ Format_Mono,
+ Format_A8,
+ Format_A32
+ };
+
QFontEngine();
virtual ~QFontEngine();
@@ -155,6 +163,7 @@ public:
SynthesizedStretch = 0x4
};
virtual int synthesized() const { return 0; }
+ virtual bool supportsSubPixelPositions() const { return false; }
virtual QFixed emSquareSize() const { return ascent(); }
@@ -168,11 +177,15 @@ public:
virtual void recalcAdvances(QGlyphLayout *, QTextEngine::ShaperFlags) const {}
virtual void doKerning(QGlyphLayout *, QTextEngine::ShaperFlags) const;
-#if !defined(Q_WS_X11) && !defined(Q_WS_WIN) && !defined(Q_WS_MAC) && !defined(Q_OS_SYMBIAN)
+#if !defined(Q_WS_X11) && !defined(Q_WS_WIN) && !defined(Q_WS_MAC) && !defined(Q_OS_SYMBIAN) && !defined(Q_WS_QPA)
virtual void draw(QPaintEngine *p, qreal x, qreal y, const QTextItemInt &si) = 0;
#endif
virtual void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs,
QPainterPath *path, QTextItem::RenderFlags flags);
+
+ /* Creates a QFont object to represent this particular QFontEngine */
+ virtual QFont createExplicitFont() const;
+
void getGlyphPositions(const QGlyphLayout &glyphs, const QTransform &matrix, QTextItem::RenderFlags flags,
QVarLengthArray<glyph_t> &glyphs_out, QVarLengthArray<QFixedPoint> &positions);
@@ -183,8 +196,15 @@ public:
* Returns an image indexed_8 with index values ranging from 0=fully transparent to 255=opaque
*/
virtual QImage alphaMapForGlyph(glyph_t);
+ virtual QImage alphaMapForGlyph(glyph_t glyph, QFixed subPixelPosition);
virtual QImage alphaMapForGlyph(glyph_t, const QTransform &t);
- virtual QImage alphaRGBMapForGlyph(glyph_t, int margin, const QTransform &t);
+ virtual QImage alphaMapForGlyph(glyph_t, QFixed subPixelPosition, const QTransform &t);
+ virtual QImage alphaRGBMapForGlyph(glyph_t, QFixed subPixelPosition, int margin, const QTransform &t);
+
+ virtual glyph_metrics_t alphaMapBoundingBox(glyph_t glyph, const QTransform &matrix, GlyphFormat /*format*/)
+ {
+ return boundingBox(glyph, matrix);
+ }
virtual void removeGlyphFromCache(glyph_t);
@@ -237,7 +257,7 @@ public:
bool symbol;
mutable HB_FontRec hbFont;
mutable HB_Face hbFace;
-#if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN)
+#if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_WS_QPA) || defined(Q_OS_SYMBIAN)
struct KernPair {
uint left_right;
QFixed adjust;
@@ -254,13 +274,14 @@ public:
int glyphFormat;
protected:
+ QFont createExplicitFontWithName(const QString &familyName) const;
static const QVector<QRgb> &grayPalette();
QFixed lastRightBearing(const QGlyphLayout &glyphs, bool round = false);
private:
struct GlyphCacheEntry {
void *context;
- QFontEngineGlyphCache *cache;
+ QExplicitlySharedDataPointer<QFontEngineGlyphCache> cache;
bool operator==(const GlyphCacheEntry &other) { return context == other.context && cache == other.cache; }
};
@@ -412,214 +433,6 @@ protected:
QVector<QFontEngine *> engines;
};
-#if defined(Q_WS_MAC)
-
-struct QCharAttributes;
-class QFontEngineMacMulti;
-# if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
-class QCoreTextFontEngineMulti;
-class QCoreTextFontEngine : public QFontEngine
-{
-public:
- QCoreTextFontEngine(CTFontRef font, const QFontDef &def,
- QCoreTextFontEngineMulti *multiEngine = 0);
- ~QCoreTextFontEngine();
- virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const;
- virtual void recalcAdvances(int , QGlyphLayout *, QTextEngine::ShaperFlags) const;
-
- virtual glyph_metrics_t boundingBox(const QGlyphLayout &glyphs);
- virtual glyph_metrics_t boundingBox(glyph_t glyph);
-
- virtual QFixed ascent() const;
- virtual QFixed descent() const;
- virtual QFixed leading() const;
- virtual QFixed xHeight() const;
- virtual qreal maxCharWidth() const;
- virtual QFixed averageCharWidth() const;
-
- virtual void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int numGlyphs,
- QPainterPath *path, QTextItem::RenderFlags);
-
- virtual const char *name() const { return "QCoreTextFontEngine"; }
-
- virtual bool canRender(const QChar *string, int len);
-
- virtual int synthesized() const { return synthesisFlags; }
-
- virtual Type type() const { return QFontEngine::Mac; }
-
- void draw(CGContextRef ctx, qreal x, qreal y, const QTextItemInt &ti, int paintDeviceHeight);
-
- virtual FaceId faceId() const;
- virtual bool getSfntTableData(uint /*tag*/, uchar * /*buffer*/, uint * /*length*/) const;
- virtual void getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics);
- virtual QImage alphaMapForGlyph(glyph_t);
- virtual QImage alphaRGBMapForGlyph(glyph_t, int margin, const QTransform &t);
- virtual qreal minRightBearing() const;
- virtual qreal minLeftBearing() const;
-
-
-private:
- QImage imageForGlyph(glyph_t glyph, int margin, bool colorful);
- CTFontRef ctfont;
- CGFontRef cgFont;
- QCoreTextFontEngineMulti *parentEngine;
- int synthesisFlags;
- CGAffineTransform transform;
- friend class QCoreTextFontEngineMulti;
-};
-
-class QCoreTextFontEngineMulti : public QFontEngineMulti
-{
-public:
- QCoreTextFontEngineMulti(const ATSFontFamilyRef &atsFamily, const ATSFontRef &atsFontRef,
- const QFontDef &fontDef, bool kerning);
- ~QCoreTextFontEngineMulti();
-
- virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs,
- QTextEngine::ShaperFlags flags) const;
- bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs,
- QTextEngine::ShaperFlags flags,
- unsigned short *logClusters, const HB_CharAttributes *charAttributes) const;
-
-
- virtual void recalcAdvances(int , QGlyphLayout *, QTextEngine::ShaperFlags) const;
- virtual void doKerning(int , QGlyphLayout *, QTextEngine::ShaperFlags) const;
-
- virtual const char *name() const { return "CoreText"; }
-protected:
- virtual void loadEngine(int at);
-
-private:
- inline const QCoreTextFontEngine *engineAt(int i) const
- { return static_cast<const QCoreTextFontEngine *>(engines.at(i)); }
-
- uint fontIndexForFont(CTFontRef id) const;
- CTFontRef ctfont;
- mutable QCFType<CFMutableDictionaryRef> attributeDict;
- CGAffineTransform transform;
- friend class QFontDialogPrivate;
-};
-# endif //MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
-
-#ifndef QT_MAC_USE_COCOA
-class QFontEngineMac : public QFontEngine
-{
- friend class QFontEngineMacMulti;
-public:
- QFontEngineMac(ATSUStyle baseStyle, ATSUFontID fontID, const QFontDef &def, QFontEngineMacMulti *multiEngine = 0);
- virtual ~QFontEngineMac();
-
- virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *numGlyphs, QTextEngine::ShaperFlags flags) const;
- virtual void recalcAdvances(QGlyphLayout *, QTextEngine::ShaperFlags) const;
-
- virtual glyph_metrics_t boundingBox(const QGlyphLayout &glyphs);
- virtual glyph_metrics_t boundingBox(glyph_t glyph);
-
- virtual QFixed ascent() const;
- virtual QFixed descent() const;
- virtual QFixed leading() const;
- virtual QFixed xHeight() const;
- virtual qreal maxCharWidth() const;
- virtual QFixed averageCharWidth() const;
-
- virtual void addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int numGlyphs,
- QPainterPath *path, QTextItem::RenderFlags);
-
- virtual const char *name() const { return "QFontEngineMac"; }
-
- virtual bool canRender(const QChar *string, int len);
-
- virtual int synthesized() const { return synthesisFlags; }
-
- virtual Type type() const { return QFontEngine::Mac; }
-
- void draw(CGContextRef ctx, qreal x, qreal y, const QTextItemInt &ti, int paintDeviceHeight);
-
- virtual FaceId faceId() const;
- virtual QByteArray getSfntTable(uint tag) const;
- virtual Properties properties() const;
- virtual void getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics);
- virtual QImage alphaMapForGlyph(glyph_t);
- virtual QImage alphaRGBMapForGlyph(glyph_t, int margin, const QTransform &t);
-
-private:
- QImage imageForGlyph(glyph_t glyph, int margin, bool colorful);
-
- ATSUFontID fontID;
- QCFType<CGFontRef> cgFont;
- ATSUStyle style;
- int synthesisFlags;
- mutable QGlyphLayout kashidaGlyph;
- QFontEngineMacMulti *multiEngine;
- mutable const unsigned char *cmap;
- mutable bool symbolCMap;
- mutable QByteArray cmapTable;
- CGAffineTransform transform;
- QFixed m_ascent;
- QFixed m_descent;
- QFixed m_leading;
- qreal m_maxCharWidth;
- QFixed m_xHeight;
- QFixed m_averageCharWidth;
-};
-
-class QFontEngineMacMulti : public QFontEngineMulti
-{
- friend class QFontEngineMac;
-public:
- // internal
- struct ShaperItem
- {
- inline ShaperItem() : string(0), from(0), length(0),
- log_clusters(0), charAttributes(0) {}
-
- const QChar *string;
- int from;
- int length;
- QGlyphLayout glyphs;
- unsigned short *log_clusters;
- const HB_CharAttributes *charAttributes;
- QTextEngine::ShaperFlags flags;
- };
-
- QFontEngineMacMulti(const ATSFontFamilyRef &atsFamily, const ATSFontRef &atsFontRef, const QFontDef &fontDef, bool kerning);
- virtual ~QFontEngineMacMulti();
-
- virtual bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const;
- bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags,
- unsigned short *logClusters, const HB_CharAttributes *charAttributes) const;
-
- virtual void recalcAdvances(QGlyphLayout *, QTextEngine::ShaperFlags) const;
- virtual void doKerning(QGlyphLayout *, QTextEngine::ShaperFlags) const;
-
- virtual const char *name() const { return "ATSUI"; }
-
- virtual bool canRender(const QChar *string, int len);
-
- inline ATSUFontID macFontID() const { return fontID; }
-
-protected:
- virtual void loadEngine(int at);
-
-private:
- inline const QFontEngineMac *engineAt(int i) const
- { return static_cast<const QFontEngineMac *>(engines.at(i)); }
-
- bool stringToCMapInternal(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags, ShaperItem *item) const;
-
- int fontIndexForFontID(ATSUFontID id) const;
-
- ATSUFontID fontID;
- uint kerning : 1;
-
- mutable ATSUTextLayout textLayout;
- mutable ATSUStyle style;
- CGAffineTransform transform;
-};
-#endif //!QT_MAC_USE_COCOA
-#endif
-
class QTestFontEngine : public QFontEngineBox
{
public:
diff --git a/src/gui/text/qfontengine_qpa.cpp b/src/gui/text/qfontengine_qpa.cpp
new file mode 100644
index 0000000000..cccbc92fc4
--- /dev/null
+++ b/src/gui/text/qfontengine_qpa.cpp
@@ -0,0 +1,691 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qfontengine_qpa_p.h"
+
+#include <QtCore/QFile>
+#include <QtCore/QFileInfo>
+#include <QtCore/QDir>
+#include <QtCore/QBuffer>
+
+#include <QtGui/private/qapplication_p.h>
+#include <QtGui/QPlatformFontDatabase>
+#include <QtGui/private/qpaintengine_raster_p.h>
+
+QT_BEGIN_NAMESPACE
+
+//#define DEBUG_HEADER
+//#define DEBUG_FONTENGINE
+
+static QFontEngineQPA::TagType tagTypes[QFontEngineQPA::NumTags] = {
+ QFontEngineQPA::StringType, // FontName
+ QFontEngineQPA::StringType, // FileName
+ QFontEngineQPA::UInt32Type, // FileIndex
+ QFontEngineQPA::UInt32Type, // FontRevision
+ QFontEngineQPA::StringType, // FreeText
+ QFontEngineQPA::FixedType, // Ascent
+ QFontEngineQPA::FixedType, // Descent
+ QFontEngineQPA::FixedType, // Leading
+ QFontEngineQPA::FixedType, // XHeight
+ QFontEngineQPA::FixedType, // AverageCharWidth
+ QFontEngineQPA::FixedType, // MaxCharWidth
+ QFontEngineQPA::FixedType, // LineThickness
+ QFontEngineQPA::FixedType, // MinLeftBearing
+ QFontEngineQPA::FixedType, // MinRightBearing
+ QFontEngineQPA::FixedType, // UnderlinePosition
+ QFontEngineQPA::UInt8Type, // GlyphFormat
+ QFontEngineQPA::UInt8Type, // PixelSize
+ QFontEngineQPA::UInt8Type, // Weight
+ QFontEngineQPA::UInt8Type, // Style
+ QFontEngineQPA::StringType, // EndOfHeader
+ QFontEngineQPA::BitFieldType// WritingSystems
+};
+
+
+#if defined(DEBUG_HEADER)
+# define DEBUG_VERIFY qDebug
+#else
+# define DEBUG_VERIFY if (0) qDebug
+#endif
+
+#define READ_VERIFY(type, variable) \
+ if (tagPtr + sizeof(type) > endPtr) { \
+ DEBUG_VERIFY() << "read verify failed in line" << __LINE__; \
+ return 0; \
+ } \
+ variable = qFromBigEndian<type>(tagPtr); \
+ DEBUG_VERIFY() << "read value" << variable << "of type " #type; \
+ tagPtr += sizeof(type)
+
+template <typename T>
+T readValue(const uchar *&data)
+{
+ T value = qFromBigEndian<T>(data);
+ data += sizeof(T);
+ return value;
+}
+
+#define VERIFY(condition) \
+ if (!(condition)) { \
+ DEBUG_VERIFY() << "condition " #condition " failed in line" << __LINE__; \
+ return 0; \
+ }
+
+#define VERIFY_TAG(condition) \
+ if (!(condition)) { \
+ DEBUG_VERIFY() << "verifying tag condition " #condition " failed in line" << __LINE__ << "with tag" << tag; \
+ return 0; \
+ }
+
+static inline const uchar *verifyTag(const uchar *tagPtr, const uchar *endPtr)
+{
+ quint16 tag, length;
+ READ_VERIFY(quint16, tag);
+ READ_VERIFY(quint16, length);
+ if (tag == QFontEngineQPA::Tag_EndOfHeader)
+ return endPtr;
+ if (tag < QFontEngineQPA::NumTags) {
+ switch (tagTypes[tag]) {
+ case QFontEngineQPA::BitFieldType:
+ case QFontEngineQPA::StringType:
+ // can't do anything...
+ break;
+ case QFontEngineQPA::UInt32Type:
+ VERIFY_TAG(length == sizeof(quint32));
+ break;
+ case QFontEngineQPA::FixedType:
+ VERIFY_TAG(length == sizeof(quint32));
+ break;
+ case QFontEngineQPA::UInt8Type:
+ VERIFY_TAG(length == sizeof(quint8));
+ break;
+ }
+#if defined(DEBUG_HEADER)
+ if (length == 1)
+ qDebug() << "tag data" << hex << *tagPtr;
+ else if (length == 4)
+ qDebug() << "tag data" << hex << tagPtr[0] << tagPtr[1] << tagPtr[2] << tagPtr[3];
+#endif
+ }
+ return tagPtr + length;
+}
+
+const QFontEngineQPA::Glyph *QFontEngineQPA::findGlyph(glyph_t g) const
+{
+ if (!g || g >= glyphMapEntries)
+ return 0;
+ const quint32 *gmapPtr = reinterpret_cast<const quint32 *>(fontData + glyphMapOffset);
+ quint32 glyphPos = qFromBigEndian<quint32>(gmapPtr[g]);
+ if (glyphPos > glyphDataSize) {
+ if (glyphPos == 0xffffffff)
+ return 0;
+#if defined(DEBUG_FONTENGINE)
+ qDebug() << "glyph" << g << "outside of glyphData, remapping font file";
+#endif
+ if (glyphPos > glyphDataSize)
+ return 0;
+ }
+ return reinterpret_cast<const Glyph *>(fontData + glyphDataOffset + glyphPos);
+}
+
+bool QFontEngineQPA::verifyHeader(const uchar *data, int size)
+{
+ VERIFY(size >= int(sizeof(Header)));
+ const Header *header = reinterpret_cast<const Header *>(data);
+ if (header->magic[0] != 'Q'
+ || header->magic[1] != 'P'
+ || header->magic[2] != 'F'
+ || header->magic[3] != '2')
+ return false;
+
+ VERIFY(header->majorVersion <= CurrentMajorVersion);
+ const quint16 dataSize = qFromBigEndian<quint16>(header->dataSize);
+ VERIFY(size >= int(sizeof(Header)) + dataSize);
+
+ const uchar *tagPtr = data + sizeof(Header);
+ const uchar *tagEndPtr = tagPtr + dataSize;
+ while (tagPtr < tagEndPtr - 3) {
+ tagPtr = verifyTag(tagPtr, tagEndPtr);
+ VERIFY(tagPtr);
+ }
+
+ VERIFY(tagPtr <= tagEndPtr);
+ return true;
+}
+
+QVariant QFontEngineQPA::extractHeaderField(const uchar *data, HeaderTag requestedTag)
+{
+ const Header *header = reinterpret_cast<const Header *>(data);
+ const uchar *tagPtr = data + sizeof(Header);
+ const uchar *endPtr = tagPtr + qFromBigEndian<quint16>(header->dataSize);
+ while (tagPtr < endPtr - 3) {
+ quint16 tag = readValue<quint16>(tagPtr);
+ quint16 length = readValue<quint16>(tagPtr);
+ if (tag == requestedTag) {
+ switch (tagTypes[requestedTag]) {
+ case StringType:
+ return QVariant(QString::fromUtf8(reinterpret_cast<const char *>(tagPtr), length));
+ case UInt32Type:
+ return QVariant(readValue<quint32>(tagPtr));
+ case UInt8Type:
+ return QVariant(uint(*tagPtr));
+ case FixedType:
+ return QVariant(QFixed::fromFixed(readValue<quint32>(tagPtr)).toReal());
+ case BitFieldType:
+ return QVariant(QByteArray(reinterpret_cast<const char *>(tagPtr), length));
+ }
+ return QVariant();
+ } else if (tag == Tag_EndOfHeader) {
+ break;
+ }
+ tagPtr += length;
+ }
+
+ return QVariant();
+}
+
+
+
+static inline unsigned int getChar(const QChar *str, int &i, const int len)
+{
+ unsigned int uc = str[i].unicode();
+ if (uc >= 0xd800 && uc < 0xdc00 && i < len-1) {
+ uint low = str[i+1].unicode();
+ if (low >= 0xdc00 && low < 0xe000) {
+ uc = (uc - 0xd800)*0x400 + (low - 0xdc00) + 0x10000;
+ ++i;
+ }
+ }
+ return uc;
+}
+
+QFontEngineQPA::QFontEngineQPA(const QFontDef &def, const QByteArray &data)
+ : fontData(reinterpret_cast<const uchar *>(data.constData())), dataSize(data.size())
+{
+ fontDef = def;
+ cache_cost = 100;
+ externalCMap = 0;
+ cmapOffset = 0;
+ cmapSize = 0;
+ glyphMapOffset = 0;
+ glyphMapEntries = 0;
+ glyphDataOffset = 0;
+ glyphDataSize = 0;
+ kerning_pairs_loaded = false;
+ readOnly = true;
+
+#if defined(DEBUG_FONTENGINE)
+ qDebug() << "QFontEngineQPA::QFontEngineQPA( fd =" << fd << ", renderingFontEngine =" << renderingFontEngine << ')';
+#endif
+
+ if (!verifyHeader(fontData, dataSize)) {
+#if defined(DEBUG_FONTENGINE)
+ qDebug() << "verifyHeader failed!";
+#endif
+ return;
+ }
+
+ const Header *header = reinterpret_cast<const Header *>(fontData);
+
+ readOnly = (header->lock == 0xffffffff);
+
+ const uchar *imgData = fontData + sizeof(Header) + qFromBigEndian<quint16>(header->dataSize);
+ const uchar *endPtr = fontData + dataSize;
+ while (imgData <= endPtr - 8) {
+ quint16 blockTag = readValue<quint16>(imgData);
+ imgData += 2; // skip padding
+ quint32 blockSize = readValue<quint32>(imgData);
+
+ if (blockTag == CMapBlock) {
+ cmapOffset = imgData - fontData;
+ cmapSize = blockSize;
+ } else if (blockTag == GMapBlock) {
+ glyphMapOffset = imgData - fontData;
+ glyphMapEntries = blockSize / 4;
+ } else if (blockTag == GlyphBlock) {
+ glyphDataOffset = imgData - fontData;
+ glyphDataSize = blockSize;
+ }
+
+ imgData += blockSize;
+ }
+
+ face_id.filename = QFile::encodeName(extractHeaderField(fontData, Tag_FileName).toString());
+ face_id.index = extractHeaderField(fontData, Tag_FileIndex).toInt();
+
+ // get the real cmap
+ if (cmapOffset) {
+ int tableSize = cmapSize;
+ const uchar *cmapPtr = getCMap(fontData + cmapOffset, tableSize, &symbol, &cmapSize);
+ if (cmapPtr)
+ cmapOffset = cmapPtr - fontData;
+ else
+ cmapOffset = 0;
+ } else if (externalCMap) {
+ int tableSize = cmapSize;
+ externalCMap = getCMap(externalCMap, tableSize, &symbol, &cmapSize);
+ }
+
+ // verify all the positions in the glyphMap
+ if (glyphMapOffset) {
+ const quint32 *gmapPtr = reinterpret_cast<const quint32 *>(fontData + glyphMapOffset);
+ for (uint i = 0; i < glyphMapEntries; ++i) {
+ quint32 glyphDataPos = qFromBigEndian<quint32>(gmapPtr[i]);
+ if (glyphDataPos == 0xffffffff)
+ continue;
+ if (glyphDataPos >= glyphDataSize) {
+ // error
+ glyphMapOffset = 0;
+ glyphMapEntries = 0;
+ break;
+ }
+ }
+ }
+
+#if defined(DEBUG_FONTENGINE)
+ if (!isValid())
+ qDebug() << "fontData" << fontData << "dataSize" << dataSize
+ << "externalCMap" << externalCMap << "cmapOffset" << cmapOffset
+ << "glyphMapOffset" << glyphMapOffset << "glyphDataOffset" << glyphDataOffset
+ << "fd" << fd << "glyphDataSize" << glyphDataSize;
+#endif
+}
+
+QFontEngineQPA::~QFontEngineQPA()
+{
+}
+
+bool QFontEngineQPA::getSfntTableData(uint tag, uchar *buffer, uint *length) const
+{
+ Q_UNUSED(tag);
+ Q_UNUSED(buffer);
+ *length = 0;
+ return false;
+}
+
+bool QFontEngineQPA::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const
+{
+ if (*nglyphs < len) {
+ *nglyphs = len;
+ return false;
+ }
+
+#if defined(DEBUG_FONTENGINE)
+ QSet<QChar> seenGlyphs;
+#endif
+
+ const uchar *cmap = externalCMap ? externalCMap : (fontData + cmapOffset);
+
+ bool mirrored = flags & QTextEngine::RightToLeft;
+ int glyph_pos = 0;
+ if (symbol) {
+ for (int i = 0; i < len; ++i) {
+ unsigned int uc = getChar(str, i, len);
+ if (mirrored)
+ uc = QChar::mirroredChar(uc);
+ glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, uc);
+ if(!glyphs->glyphs[glyph_pos] && uc < 0x100)
+ glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, uc + 0xf000);
+ ++glyph_pos;
+ }
+ } else {
+ for (int i = 0; i < len; ++i) {
+ unsigned int uc = getChar(str, i, len);
+ if (mirrored)
+ uc = QChar::mirroredChar(uc);
+ glyphs->glyphs[glyph_pos] = getTrueTypeGlyphIndex(cmap, uc);
+#if 0 && defined(DEBUG_FONTENGINE)
+ QChar c(uc);
+ if (!findGlyph(glyphs[glyph_pos].glyph) && !seenGlyphs.contains(c))
+ qDebug() << "glyph for character" << c << '/' << hex << uc << "is" << dec << glyphs[glyph_pos].glyph;
+
+ seenGlyphs.insert(c);
+#endif
+ ++glyph_pos;
+ }
+ }
+
+ *nglyphs = glyph_pos;
+ glyphs->numGlyphs = glyph_pos;
+ recalcAdvances(glyphs, flags);
+ return true;
+}
+
+void QFontEngineQPA::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags) const
+{
+ for (int i = 0; i < glyphs->numGlyphs; ++i) {
+ const Glyph *g = findGlyph(glyphs->glyphs[i]);
+ if (!g) {
+ glyphs->glyphs[i] = 0;
+ continue;
+ }
+ glyphs->advances_x[i] = g->advance;
+ glyphs->advances_y[i] = 0;
+ }
+}
+
+QImage QFontEngineQPA::alphaMapForGlyph(glyph_t g)
+{
+ const Glyph *glyph = findGlyph(g);
+ if (!glyph)
+ return QImage();
+
+ const uchar *bits = ((const uchar *) glyph) + sizeof(Glyph);
+
+ QImage image(bits,glyph->width, glyph->height, glyph->bytesPerLine, QImage::Format_Indexed8);
+
+ return image;
+}
+
+void QFontEngineQPA::addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs, QPainterPath *path, QTextItem::RenderFlags flags)
+{
+ addBitmapFontToPath(x, y, glyphs, path, flags);
+}
+
+glyph_metrics_t QFontEngineQPA::boundingBox(const QGlyphLayout &glyphs)
+{
+ glyph_metrics_t overall;
+ // initialize with line height, we get the same behaviour on all platforms
+ overall.y = -ascent();
+ overall.height = ascent() + descent() + 1;
+
+ QFixed ymax = 0;
+ QFixed xmax = 0;
+ for (int i = 0; i < glyphs.numGlyphs; i++) {
+ const Glyph *g = findGlyph(glyphs.glyphs[i]);
+ if (!g)
+ continue;
+
+ QFixed x = overall.xoff + glyphs.offsets[i].x + g->x;
+ QFixed y = overall.yoff + glyphs.offsets[i].y + g->y;
+ overall.x = qMin(overall.x, x);
+ overall.y = qMin(overall.y, y);
+ xmax = qMax(xmax, x + g->width);
+ ymax = qMax(ymax, y + g->height);
+ overall.xoff += g->advance;
+ }
+ overall.height = qMax(overall.height, ymax - overall.y);
+ overall.width = xmax - overall.x;
+
+ return overall;
+}
+
+glyph_metrics_t QFontEngineQPA::boundingBox(glyph_t glyph)
+{
+ glyph_metrics_t overall;
+ const Glyph *g = findGlyph(glyph);
+ if (!g)
+ return overall;
+ overall.x = g->x;
+ overall.y = g->y;
+ overall.width = g->width;
+ overall.height = g->height;
+ overall.xoff = g->advance;
+ return overall;
+}
+
+QFixed QFontEngineQPA::ascent() const
+{
+ return QFixed::fromReal(extractHeaderField(fontData, Tag_Ascent).value<qreal>());
+}
+
+QFixed QFontEngineQPA::descent() const
+{
+ return QFixed::fromReal(extractHeaderField(fontData, Tag_Descent).value<qreal>());
+}
+
+QFixed QFontEngineQPA::leading() const
+{
+ return QFixed::fromReal(extractHeaderField(fontData, Tag_Leading).value<qreal>());
+}
+
+qreal QFontEngineQPA::maxCharWidth() const
+{
+ return extractHeaderField(fontData, Tag_MaxCharWidth).value<qreal>();
+}
+
+qreal QFontEngineQPA::minLeftBearing() const
+{
+ return extractHeaderField(fontData, Tag_MinLeftBearing).value<qreal>();
+}
+
+qreal QFontEngineQPA::minRightBearing() const
+{
+ return extractHeaderField(fontData, Tag_MinRightBearing).value<qreal>();
+}
+
+QFixed QFontEngineQPA::underlinePosition() const
+{
+ return QFixed::fromReal(extractHeaderField(fontData, Tag_UnderlinePosition).value<qreal>());
+}
+
+QFixed QFontEngineQPA::lineThickness() const
+{
+ return QFixed::fromReal(extractHeaderField(fontData, Tag_LineThickness).value<qreal>());
+}
+
+QFontEngine::Type QFontEngineQPA::type() const
+{
+ return QFontEngine::QPF2;
+}
+
+bool QFontEngineQPA::canRender(const QChar *string, int len)
+{
+ const uchar *cmap = externalCMap ? externalCMap : (fontData + cmapOffset);
+
+ if (symbol) {
+ for (int i = 0; i < len; ++i) {
+ unsigned int uc = getChar(string, i, len);
+ glyph_t g = getTrueTypeGlyphIndex(cmap, uc);
+ if(!g && uc < 0x100)
+ g = getTrueTypeGlyphIndex(cmap, uc + 0xf000);
+ if (!g)
+ return false;
+ }
+ } else {
+ for (int i = 0; i < len; ++i) {
+ unsigned int uc = getChar(string, i, len);
+ if (!getTrueTypeGlyphIndex(cmap, uc))
+ return false;
+ }
+ }
+ return true;
+}
+
+bool QFontEngineQPA::isValid() const
+{
+ return fontData && dataSize && (cmapOffset || externalCMap)
+ && glyphMapOffset && glyphDataOffset && glyphDataSize > 0;
+}
+
+void QPAGenerator::generate()
+{
+ writeHeader();
+ writeGMap();
+ writeBlock(QFontEngineQPA::GlyphBlock, QByteArray());
+
+ dev->seek(4); // position of header.lock
+ writeUInt32(0);
+}
+
+void QPAGenerator::writeHeader()
+{
+ QFontEngineQPA::Header header;
+
+ header.magic[0] = 'Q';
+ header.magic[1] = 'P';
+ header.magic[2] = 'F';
+ header.magic[3] = '2';
+ header.lock = 1;
+ header.majorVersion = QFontEngineQPA::CurrentMajorVersion;
+ header.minorVersion = QFontEngineQPA::CurrentMinorVersion;
+ header.dataSize = 0;
+ dev->write((const char *)&header, sizeof(header));
+
+ writeTaggedString(QFontEngineQPA::Tag_FontName, fe->fontDef.family.toUtf8());
+
+ QFontEngine::FaceId face = fe->faceId();
+ writeTaggedString(QFontEngineQPA::Tag_FileName, face.filename);
+ writeTaggedUInt32(QFontEngineQPA::Tag_FileIndex, face.index);
+
+ {
+ uchar data[4];
+ uint len = 4;
+ bool ok = fe->getSfntTableData(MAKE_TAG('h', 'e', 'a', 'd'), data, &len);
+ if (ok) {
+ const quint32 revision = qFromBigEndian<quint32>(data);
+ writeTaggedUInt32(QFontEngineQPA::Tag_FontRevision, revision);
+ }
+ }
+
+ writeTaggedQFixed(QFontEngineQPA::Tag_Ascent, fe->ascent());
+ writeTaggedQFixed(QFontEngineQPA::Tag_Descent, fe->descent());
+ writeTaggedQFixed(QFontEngineQPA::Tag_Leading, fe->leading());
+ writeTaggedQFixed(QFontEngineQPA::Tag_XHeight, fe->xHeight());
+ writeTaggedQFixed(QFontEngineQPA::Tag_AverageCharWidth, fe->averageCharWidth());
+ writeTaggedQFixed(QFontEngineQPA::Tag_MaxCharWidth, QFixed::fromReal(fe->maxCharWidth()));
+ writeTaggedQFixed(QFontEngineQPA::Tag_LineThickness, fe->lineThickness());
+ writeTaggedQFixed(QFontEngineQPA::Tag_MinLeftBearing, QFixed::fromReal(fe->minLeftBearing()));
+ writeTaggedQFixed(QFontEngineQPA::Tag_MinRightBearing, QFixed::fromReal(fe->minRightBearing()));
+ writeTaggedQFixed(QFontEngineQPA::Tag_UnderlinePosition, fe->underlinePosition());
+ writeTaggedUInt8(QFontEngineQPA::Tag_PixelSize, fe->fontDef.pixelSize);
+ writeTaggedUInt8(QFontEngineQPA::Tag_Weight, fe->fontDef.weight);
+ writeTaggedUInt8(QFontEngineQPA::Tag_Style, fe->fontDef.style);
+
+ writeTaggedUInt8(QFontEngineQPA::Tag_GlyphFormat, QFontEngineQPA::AlphamapGlyphs);
+
+ writeTaggedString(QFontEngineQPA::Tag_EndOfHeader, QByteArray());
+ align4();
+
+ const quint64 size = dev->pos();
+ header.dataSize = qToBigEndian<quint16>(size - sizeof(header));
+ dev->seek(0);
+ dev->write((const char *)&header, sizeof(header));
+ dev->seek(size);
+}
+
+void QPAGenerator::writeGMap()
+{
+ const quint16 glyphCount = fe->glyphCount();
+
+ writeUInt16(QFontEngineQPA::GMapBlock);
+ writeUInt16(0); // padding
+ writeUInt32(glyphCount * 4);
+
+ QByteArray &buffer = dev->buffer();
+ const int numBytes = glyphCount * sizeof(quint32);
+ qint64 pos = buffer.size();
+ buffer.resize(pos + numBytes);
+ qMemSet(buffer.data() + pos, 0xff, numBytes);
+ dev->seek(pos + numBytes);
+}
+
+void QPAGenerator::writeBlock(QFontEngineQPA::BlockTag tag, const QByteArray &data)
+{
+ writeUInt16(tag);
+ writeUInt16(0); // padding
+ const int padSize = ((data.size() + 3) / 4) * 4 - data.size();
+ writeUInt32(data.size() + padSize);
+ dev->write(data);
+ for (int i = 0; i < padSize; ++i)
+ writeUInt8(0);
+}
+
+void QPAGenerator::writeTaggedString(QFontEngineQPA::HeaderTag tag, const QByteArray &string)
+{
+ writeUInt16(tag);
+ writeUInt16(string.length());
+ dev->write(string);
+}
+
+void QPAGenerator::writeTaggedUInt32(QFontEngineQPA::HeaderTag tag, quint32 value)
+{
+ writeUInt16(tag);
+ writeUInt16(sizeof(value));
+ writeUInt32(value);
+}
+
+void QPAGenerator::writeTaggedUInt8(QFontEngineQPA::HeaderTag tag, quint8 value)
+{
+ writeUInt16(tag);
+ writeUInt16(sizeof(value));
+ writeUInt8(value);
+}
+
+void QPAGenerator::writeTaggedQFixed(QFontEngineQPA::HeaderTag tag, QFixed value)
+{
+ writeUInt16(tag);
+ writeUInt16(sizeof(quint32));
+ writeUInt32(value.value());
+}
+
+
+/*
+ Creates a new multi QPA engine.
+
+ This function takes ownership of the QFontEngine, increasing it's refcount.
+*/
+QFontEngineMultiQPA::QFontEngineMultiQPA(QFontEngine *fe, int _script, const QStringList &fallbacks)
+ : QFontEngineMulti(fallbacks.size() + 1),
+ fallbackFamilies(fallbacks), script(_script)
+{
+ engines[0] = fe;
+ fe->ref.ref();
+ fontDef = engines[0]->fontDef;
+}
+
+void QFontEngineMultiQPA::loadEngine(int at)
+{
+ Q_ASSERT(at < engines.size());
+ Q_ASSERT(engines.at(at) == 0);
+
+ QFontDef request = fontDef;
+ request.styleStrategy |= QFont::NoFontMerging;
+ request.family = fallbackFamilies.at(at-1);
+ engines[at] = QFontDatabase::findFont(script,
+ /*fontprivate*/0,
+ request);
+ Q_ASSERT(engines[at]);
+ engines[at]->ref.ref();
+ engines[at]->fontDef = request;
+}
+
+QT_END_NAMESPACE
diff --git a/src/gui/text/qfontengine_qpa_p.h b/src/gui/text/qfontengine_qpa_p.h
new file mode 100644
index 0000000000..467fca617e
--- /dev/null
+++ b/src/gui/text/qfontengine_qpa_p.h
@@ -0,0 +1,262 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QFONTENGINE_QPA_P_H
+#define QFONTENGINE_QPA_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists purely as an
+// implementation detail. This header file may change from version to
+// version without notice, or even be removed.
+//
+// We mean it.
+//
+#include <QtCore/qconfig.h>
+#include <QtCore/qglobal.h>
+#include <QtCore/qendian.h>
+#include <QtCore/QBuffer>
+
+#include "qfontengine_p.h"
+
+#include <QtCore/QFile>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+class QFontEngine;
+class QFreetypeFace;
+class QBuffer;
+
+class Q_GUI_EXPORT QFontEngineQPA : public QFontEngine
+{
+public:
+ // if you add new tags please make sure to update the tables in
+ // qpfutil.cpp and tools/makeqpf/qpf2.cpp
+ enum HeaderTag {
+ Tag_FontName, // 0 string
+ Tag_FileName, // 1 string
+ Tag_FileIndex, // 2 quint32
+ Tag_FontRevision, // 3 quint32
+ Tag_FreeText, // 4 string
+ Tag_Ascent, // 5 QFixed
+ Tag_Descent, // 6 QFixed
+ Tag_Leading, // 7 QFixed
+ Tag_XHeight, // 8 QFixed
+ Tag_AverageCharWidth, // 9 QFixed
+ Tag_MaxCharWidth, // 10 QFixed
+ Tag_LineThickness, // 11 QFixed
+ Tag_MinLeftBearing, // 12 QFixed
+ Tag_MinRightBearing, // 13 QFixed
+ Tag_UnderlinePosition, // 14 QFixed
+ Tag_GlyphFormat, // 15 quint8
+ Tag_PixelSize, // 16 quint8
+ Tag_Weight, // 17 quint8
+ Tag_Style, // 18 quint8
+ Tag_EndOfHeader, // 19 string
+ Tag_WritingSystems, // 20 bitfield
+
+ NumTags
+ };
+
+ enum TagType {
+ StringType,
+ FixedType,
+ UInt8Type,
+ UInt32Type,
+ BitFieldType
+ };
+
+ struct Tag
+ {
+ quint16 tag;
+ quint16 size;
+ };
+
+ enum GlyphFormat {
+ BitmapGlyphs = 1,
+ AlphamapGlyphs = 8
+ };
+
+ enum {
+ CurrentMajorVersion = 2,
+ CurrentMinorVersion = 0
+ };
+
+ // The CMap is identical to the TrueType CMap table format
+ // The GMap table is a normal array with the total number of
+ // covered glyphs in the TrueType font
+ enum BlockTag {
+ CMapBlock,
+ GMapBlock,
+ GlyphBlock
+ };
+
+ struct Q_PACKED Header
+ {
+ char magic[4]; // 'QPF2'
+ quint32 lock; // values: 0 = unlocked, 0xffffffff = read-only, otherwise qws client id of locking process
+ quint8 majorVersion;
+ quint8 minorVersion;
+ quint16 dataSize;
+ };
+
+ struct Q_PACKED Block
+ {
+ quint16 tag;
+ quint16 pad;
+ quint32 dataSize;
+ };
+
+ struct Q_PACKED Glyph
+ {
+ quint8 width;
+ quint8 height;
+ quint8 bytesPerLine;
+ qint8 x;
+ qint8 y;
+ qint8 advance;
+ };
+
+ QFontEngineQPA(const QFontDef &def, const QByteArray &data);
+ ~QFontEngineQPA();
+
+ FaceId faceId() const { return face_id; }
+ bool getSfntTableData(uint tag, uchar *buffer, uint *length) const;
+
+ bool stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const;
+ void recalcAdvances(QGlyphLayout *, QTextEngine::ShaperFlags) const;
+
+ void addOutlineToPath(qreal x, qreal y, const QGlyphLayout &glyphs, QPainterPath *path, QTextItem::RenderFlags flags);
+ QImage alphaMapForGlyph(glyph_t t);
+
+ glyph_metrics_t boundingBox(const QGlyphLayout &glyphs);
+ glyph_metrics_t boundingBox(glyph_t glyph);
+
+ QFixed ascent() const;
+ QFixed descent() const;
+ QFixed leading() const;
+ qreal maxCharWidth() const;
+ qreal minLeftBearing() const;
+ qreal minRightBearing() const;
+ QFixed underlinePosition() const;
+ QFixed lineThickness() const;
+
+ Type type() const;
+
+ bool canRender(const QChar *string, int len);
+ inline const char *name() const { return "QPF2"; }
+
+ virtual int glyphCount() const { return glyphMapEntries; }
+
+ bool isValid() const;
+
+ const Glyph *findGlyph(glyph_t g) const;
+
+ static bool verifyHeader(const uchar *data, int size);
+ static QVariant extractHeaderField(const uchar *data, HeaderTag tag);
+
+private:
+
+ const uchar *fontData;
+ int dataSize;
+ const uchar *externalCMap;
+ quint32 cmapOffset;
+ int cmapSize;
+ quint32 glyphMapOffset;
+ quint32 glyphMapEntries;
+ quint32 glyphDataOffset;
+ quint32 glyphDataSize;
+ QString internalFileName;
+ QString encodedFileName;
+ bool readOnly;
+
+ FaceId face_id;
+ QByteArray freetypeCMapTable;
+ mutable bool kerning_pairs_loaded;
+};
+
+struct QPAGenerator
+{
+ QPAGenerator(QBuffer *device, QFontEngine *engine)
+ : dev(device), fe(engine) {}
+
+ void generate();
+ void writeHeader();
+ void writeGMap();
+ void writeBlock(QFontEngineQPA::BlockTag tag, const QByteArray &data);
+
+ void writeTaggedString(QFontEngineQPA::HeaderTag tag, const QByteArray &string);
+ void writeTaggedUInt32(QFontEngineQPA::HeaderTag tag, quint32 value);
+ void writeTaggedUInt8(QFontEngineQPA::HeaderTag tag, quint8 value);
+ void writeTaggedQFixed(QFontEngineQPA::HeaderTag tag, QFixed value);
+
+ void writeUInt16(quint16 value) { value = qToBigEndian(value); dev->write((const char *)&value, sizeof(value)); }
+ void writeUInt32(quint32 value) { value = qToBigEndian(value); dev->write((const char *)&value, sizeof(value)); }
+ void writeUInt8(quint8 value) { dev->write((const char *)&value, sizeof(value)); }
+ void writeInt8(qint8 value) { dev->write((const char *)&value, sizeof(value)); }
+
+ void align4() { while (dev->pos() & 3) { dev->putChar('\0'); } }
+
+ QBuffer *dev;
+ QFontEngine *fe;
+};
+
+class QFontEngineMultiQPA : public QFontEngineMulti
+{
+public:
+ QFontEngineMultiQPA(QFontEngine *fe, int script, const QStringList &fallbacks);
+
+ void loadEngine(int at);
+
+private:
+ QStringList fallbackFamilies;
+ int script;
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QFONTENGINE_QPA_P_H
diff --git a/src/gui/text/qfontengine_s60.cpp b/src/gui/text/qfontengine_s60.cpp
index b572cdd049..4317ee6a3c 100644
--- a/src/gui/text/qfontengine_s60.cpp
+++ b/src/gui/text/qfontengine_s60.cpp
@@ -108,7 +108,8 @@ QByteArray QSymbianTypeFaceExtras::getSfntTable(uint tag) const
Q_ASSERT(m_trueTypeExtension->HasTrueTypeTable(tag));
TInt error = KErrNone;
TInt tableByteLength = 0;
- TAny *table = q_check_ptr(m_trueTypeExtension->GetTrueTypeTable(error, tag, &tableByteLength));
+ TAny *table = m_trueTypeExtension->GetTrueTypeTable(error, tag, &tableByteLength);
+ Q_CHECK_PTR(table);
const QByteArray result(static_cast<const char*>(table), tableByteLength);
m_trueTypeExtension->ReleaseTrueTypeTable(table);
return result;
@@ -138,8 +139,8 @@ bool QSymbianTypeFaceExtras::getSfntTableData(uint tag, uchar *buffer, uint *len
TInt error = KErrNone;
TInt tableByteLength;
- TAny *table =
- q_check_ptr(m_trueTypeExtension->GetTrueTypeTable(error, tag, &tableByteLength));
+ TAny *table = m_trueTypeExtension->GetTrueTypeTable(error, tag, &tableByteLength);
+ Q_CHECK_PTR(table);
if (error != KErrNone) {
return false;
diff --git a/src/gui/text/qfontengine_win.cpp b/src/gui/text/qfontengine_win.cpp
index 167e19af64..ecb0384724 100644
--- a/src/gui/text/qfontengine_win.cpp
+++ b/src/gui/text/qfontengine_win.cpp
@@ -1251,7 +1251,7 @@ QImage QFontEngineWin::alphaMapForGlyph(glyph_t glyph, const QTransform &xform)
#define SPI_GETFONTSMOOTHINGCONTRAST 0x200C
#define SPI_SETFONTSMOOTHINGCONTRAST 0x200D
-QImage QFontEngineWin::alphaRGBMapForGlyph(glyph_t glyph, int margin, const QTransform &t)
+QImage QFontEngineWin::alphaRGBMapForGlyph(glyph_t glyph, QFixed, int margin, const QTransform &t)
{
HFONT font = hfont;
diff --git a/src/gui/text/qfontengine_win_p.h b/src/gui/text/qfontengine_win_p.h
index f60a5c3956..22085e8f3d 100644
--- a/src/gui/text/qfontengine_win_p.h
+++ b/src/gui/text/qfontengine_win_p.h
@@ -104,7 +104,7 @@ public:
virtual QImage alphaMapForGlyph(glyph_t t) { return alphaMapForGlyph(t, QTransform()); }
virtual QImage alphaMapForGlyph(glyph_t, const QTransform &xform);
- virtual QImage alphaRGBMapForGlyph(glyph_t t, int margin, const QTransform &xform);
+ virtual QImage alphaRGBMapForGlyph(glyph_t t, QFixed subPixelPosition, int margin, const QTransform &xform);
#ifndef Q_CC_MINGW
virtual void getGlyphBearings(glyph_t glyph, qreal *leftBearing = 0, qreal *rightBearing = 0);
diff --git a/src/gui/text/qfontengine_x11.cpp b/src/gui/text/qfontengine_x11.cpp
index 1b0fbf1f16..d5ec58407d 100644
--- a/src/gui/text/qfontengine_x11.cpp
+++ b/src/gui/text/qfontengine_x11.cpp
@@ -992,7 +992,7 @@ QFontEngineX11FT::QFontEngineX11FT(FcPattern *pattern, const QFontDef &fd, int s
face_id.filename = file_name;
face_id.index = face_index;
- canUploadGlyphsToServer = qApp->thread() == QThread::currentThread();
+ canUploadGlyphsToServer = QApplication::testAttribute(Qt::AA_X11InitThreads) || (qApp->thread() == QThread::currentThread());
subpixelType = Subpixel_None;
if (antialias) {
diff --git a/src/gui/text/qfontengineglyphcache_p.h b/src/gui/text/qfontengineglyphcache_p.h
index f85f4b9842..8f8d93daf9 100644
--- a/src/gui/text/qfontengineglyphcache_p.h
+++ b/src/gui/text/qfontengineglyphcache_p.h
@@ -72,7 +72,7 @@
QT_BEGIN_NAMESPACE
-class QFontEngineGlyphCache
+class QFontEngineGlyphCache: public QSharedData
{
public:
enum Type {
diff --git a/src/gui/text/qfontmetrics.cpp b/src/gui/text/qfontmetrics.cpp
index ca8500bdc3..5cd85fb3ac 100644
--- a/src/gui/text/qfontmetrics.cpp
+++ b/src/gui/text/qfontmetrics.cpp
@@ -443,6 +443,21 @@ bool QFontMetrics::inFont(QChar ch) const
}
/*!
+ Returns true if the character encoded in UCS-4/UTF-32 is a valid
+ character in the font; otherwise returns false.
+*/
+bool QFontMetrics::inFontUcs4(uint ucs4) const
+{
+ const int script = QUnicodeTables::script(ucs4);
+ QFontEngine *engine = d->engineForScript(script);
+ Q_ASSERT(engine != 0);
+ if (engine->type() == QFontEngine::Box)
+ return false;
+ QString utf16 = QString::fromUcs4(&ucs4, 1);
+ return engine->canRender(utf16.data(), utf16.length());
+}
+
+/*!
Returns the left bearing of character \a ch in the font.
The left bearing is the right-ward distance of the left-most pixel
@@ -1315,6 +1330,21 @@ bool QFontMetricsF::inFont(QChar ch) const
}
/*!
+ Returns true if the character encoded in UCS-4/UTF-32 is a valid
+ character in the font; otherwise returns false.
+*/
+bool QFontMetricsF::inFontUcs4(uint ucs4) const
+{
+ const int script = QUnicodeTables::script(ucs4);
+ QFontEngine *engine = d->engineForScript(script);
+ Q_ASSERT(engine != 0);
+ if (engine->type() == QFontEngine::Box)
+ return false;
+ QString utf16 = QString::fromUcs4(&ucs4, 1);
+ return engine->canRender(utf16.data(), utf16.length());
+}
+
+/*!
Returns the left bearing of character \a ch in the font.
The left bearing is the right-ward distance of the left-most pixel
@@ -1779,7 +1809,7 @@ qreal QFontMetricsF::lineWidth() const
Use the boundingRect() function in combination with
QString::left() instead.
-
+
\oldcode
QRect rect = boundingRect(text, len);
\newcode
diff --git a/src/gui/text/qfontmetrics.h b/src/gui/text/qfontmetrics.h
index 71b7abe8b0..5fe8676993 100644
--- a/src/gui/text/qfontmetrics.h
+++ b/src/gui/text/qfontmetrics.h
@@ -71,6 +71,10 @@ public:
~QFontMetrics();
QFontMetrics &operator=(const QFontMetrics &);
+#ifdef Q_COMPILER_RVALUE_REFS
+ inline QFontMetrics &operator=(QFontMetrics &&other)
+ { qSwap(d, other.d); return *this; }
+#endif
int ascent() const;
int descent() const;
@@ -85,6 +89,7 @@ public:
int averageCharWidth() const;
bool inFont(QChar) const;
+ bool inFontUcs4(uint ucs4) const;
int leftBearing(QChar) const;
int rightBearing(QChar) const;
@@ -148,7 +153,10 @@ public:
QFontMetricsF &operator=(const QFontMetricsF &);
QFontMetricsF &operator=(const QFontMetrics &);
-
+#ifdef Q_COMPILER_RVALUE_REFS
+ inline QFontMetricsF &operator=(QFontMetricsF &&other)
+ { qSwap(d, other.d); return *this; }
+#endif
qreal ascent() const;
qreal descent() const;
qreal height() const;
@@ -162,6 +170,7 @@ public:
qreal averageCharWidth() const;
bool inFont(QChar) const;
+ bool inFontUcs4(uint ucs4) const;
qreal leftBearing(QChar) const;
qreal rightBearing(QChar) const;
diff --git a/src/gui/text/qglyphs.cpp b/src/gui/text/qglyphs.cpp
new file mode 100644
index 0000000000..2447752581
--- /dev/null
+++ b/src/gui/text/qglyphs.cpp
@@ -0,0 +1,240 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qglyphs.h"
+#include "qglyphs_p.h"
+
+QT_BEGIN_NAMESPACE
+
+/*!
+ \class QGlyphs
+ \brief the QGlyphs class provides direct access to the internal glyphs in a font
+ \since 4.8
+
+ \ingroup text
+ \mainclass
+
+ When Qt displays a string of text encoded in Unicode, it will first convert the Unicode points
+ into a list of glyph indexes and a list of positions based on one or more fonts. The Unicode
+ representation of the text and the QFont object will in this case serve as a convenient
+ abstraction that hides the details of what actually takes place when displaying the text
+ on-screen. For instance, by the time the text actually reaches the screen, it may be represented
+ by a set of fonts in addition to the one specified by the user, e.g. in case the originally
+ selected font did not support all the writing systems contained in the text.
+
+ Under certain circumstances, it can be useful as an application developer to have more low-level
+ control over which glyphs in a specific font are drawn to the screen. This could for instance
+ be the case in applications that use an external font engine and text shaper together with Qt.
+ QGlyphs provides an interface to the raw data needed to get text on the screen. It
+ contains a list of glyph indexes, a position for each glyph and a font.
+
+ It is the user's responsibility to ensure that the selected font actually contains the
+ provided glyph indexes.
+
+ QTextLayout::glyphs() can be used to convert unicode encoded text into a list of QGlyphs
+ objects, and QPainter::drawGlyphs() can be used to draw the glyphs.
+*/
+
+
+/*!
+ Constructs an empty QGlyphs object.
+*/
+QGlyphs::QGlyphs() : d(new QGlyphsPrivate)
+{
+}
+
+/*!
+ Constructs a QGlyphs object which is a copy of \a other.
+*/
+QGlyphs::QGlyphs(const QGlyphs &other)
+{
+ d = other.d;
+}
+
+/*!
+ Destroys the QGlyphs.
+*/
+QGlyphs::~QGlyphs()
+{
+ // Required for QExplicitlySharedDataPointer
+}
+
+/*!
+ \internal
+*/
+void QGlyphs::detach()
+{
+ if (d->ref != 1)
+ d.detach();
+}
+
+/*!
+ Assigns \a other to this QGlyphs object.
+*/
+QGlyphs &QGlyphs::operator=(const QGlyphs &other)
+{
+ d = other.d;
+ return *this;
+}
+
+/*!
+ Compares \a other to this QGlyphs object. Returns true if the list of glyph indexes,
+ the list of positions and the font are all equal, otherwise returns false.
+*/
+bool QGlyphs::operator==(const QGlyphs &other) const
+{
+ return ((d == other.d)
+ || (d->glyphIndexes == other.d->glyphIndexes
+ && d->glyphPositions == other.d->glyphPositions
+ && d->font == other.d->font));
+}
+
+/*!
+ Compares \a other to this QGlyphs object. Returns true if any of the list of glyph
+ indexes, the list of positions or the font are different, otherwise returns false.
+*/
+bool QGlyphs::operator!=(const QGlyphs &other) const
+{
+ return !(*this == other);
+}
+
+/*!
+ \internal
+
+ Adds together the lists of glyph indexes and positions in \a other and this QGlyphs
+ object and returns the result. The font in the returned QGlyphs will be the same as in
+ this QGlyphs object.
+*/
+QGlyphs QGlyphs::operator+(const QGlyphs &other) const
+{
+ QGlyphs ret(*this);
+ ret += other;
+ return ret;
+}
+
+/*!
+ \internal
+
+ Appends the glyph indexes and positions in \a other to this QGlyphs object and returns
+ a reference to the current object.
+*/
+QGlyphs &QGlyphs::operator+=(const QGlyphs &other)
+{
+ detach();
+
+ d->glyphIndexes += other.d->glyphIndexes;
+ d->glyphPositions += other.d->glyphPositions;
+
+ return *this;
+}
+
+/*!
+ Returns the font selected for this QGlyphs object.
+
+ \sa setFont()
+*/
+QFont QGlyphs::font() const
+{
+ return d->font;
+}
+
+/*!
+ Sets the font in which to look up the glyph indexes to \a font. This must be an explicitly
+ resolvable font which defines glyphs for the specified glyph indexes.
+
+ \sa font(), setGlyphIndexes()
+*/
+void QGlyphs::setFont(const QFont &font)
+{
+ detach();
+ d->font = font;
+}
+
+/*!
+ Returns the glyph indexes for this QGlyphs object.
+
+ \sa setGlyphIndexes(), setPositions()
+*/
+QVector<quint32> QGlyphs::glyphIndexes() const
+{
+ return d->glyphIndexes;
+}
+
+/*!
+ Set the glyph indexes for this QGlyphs object to \a glyphIndexes. The glyph indexes must
+ be valid for the selected font.
+*/
+void QGlyphs::setGlyphIndexes(const QVector<quint32> &glyphIndexes)
+{
+ detach();
+ d->glyphIndexes = glyphIndexes;
+}
+
+/*!
+ Returns the position of the edge of the baseline for each glyph in this set of glyph indexes.
+*/
+QVector<QPointF> QGlyphs::positions() const
+{
+ return d->glyphPositions;
+}
+
+/*!
+ Sets the positions of the edge of the baseline for each glyph in this set of glyph indexes to
+ \a positions.
+*/
+void QGlyphs::setPositions(const QVector<QPointF> &positions)
+{
+ detach();
+ d->glyphPositions = positions;
+}
+
+/*!
+ Clears all data in the QGlyphs object.
+*/
+void QGlyphs::clear()
+{
+ detach();
+ d->glyphPositions = QVector<QPointF>();
+ d->glyphIndexes = QVector<quint32>();
+ d->font = QFont();
+}
+
+QT_END_NAMESPACE
diff --git a/src/gui/text/qglyphs.h b/src/gui/text/qglyphs.h
new file mode 100644
index 0000000000..282ecb47c5
--- /dev/null
+++ b/src/gui/text/qglyphs.h
@@ -0,0 +1,96 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QGLYPHS_H
+#define QGLYPHS_H
+
+#include <QtCore/qsharedpointer.h>
+#include <QtCore/qvector.h>
+#include <QtCore/qpoint.h>
+#include <QtGui/qfont.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Gui)
+
+class QGlyphsPrivate;
+class Q_GUI_EXPORT QGlyphs
+{
+public:
+ QGlyphs();
+ QGlyphs(const QGlyphs &other);
+ ~QGlyphs();
+
+ QFont font() const;
+ void setFont(const QFont &font);
+
+ QVector<quint32> glyphIndexes() const;
+ void setGlyphIndexes(const QVector<quint32> &glyphIndexes);
+
+ QVector<QPointF> positions() const;
+ void setPositions(const QVector<QPointF> &positions);
+
+ void clear();
+
+ QGlyphs &operator=(const QGlyphs &other);
+ bool operator==(const QGlyphs &other) const;
+ bool operator!=(const QGlyphs &other) const;
+
+private:
+ friend class QGlyphsPrivate;
+ friend class QTextLine;
+
+ QGlyphs operator+(const QGlyphs &other) const;
+ QGlyphs &operator+=(const QGlyphs &other);
+
+ void detach();
+ QExplicitlySharedDataPointer<QGlyphsPrivate> d;
+
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+
+#endif // QGLYPHS_H
diff --git a/src/gui/text/qglyphs_p.h b/src/gui/text/qglyphs_p.h
new file mode 100644
index 0000000000..c39f5d0e56
--- /dev/null
+++ b/src/gui/text/qglyphs_p.h
@@ -0,0 +1,84 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QGLYPHS_P_H
+#define QGLYPHS_P_H
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is not part of the Qt API. It exists for the convenience
+// of internal files. This header file may change from version to version
+// without notice, or even be removed.
+//
+// We mean it.
+//
+
+#include <qfont.h>
+#include "qglyphs.h"
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+class QGlyphsPrivate: public QSharedData
+{
+public:
+ QGlyphsPrivate()
+ {
+ }
+
+ QGlyphsPrivate(const QGlyphsPrivate &other)
+ : QSharedData(other), glyphIndexes(other.glyphIndexes), glyphPositions(other.glyphPositions), font(other.font)
+ {
+ }
+
+ QVector<quint32> glyphIndexes;
+ QVector<QPointF> glyphPositions;
+ QFont font;
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QGLYPHS_P_H
diff --git a/src/gui/text/qpfutil.cpp b/src/gui/text/qpfutil.cpp
index 4a0e29f742..734d4c3592 100644
--- a/src/gui/text/qpfutil.cpp
+++ b/src/gui/text/qpfutil.cpp
@@ -39,7 +39,7 @@
**
****************************************************************************/
-static QFontEngineQPF::TagType tagTypes[QFontEngineQPF::NumTags] = {
+static const QFontEngineQPF::TagType tagTypes[QFontEngineQPF::NumTags] = {
QFontEngineQPF::StringType, // FontName
QFontEngineQPF::StringType, // FileName
QFontEngineQPF::UInt32Type, // FileIndex
diff --git a/src/gui/text/qplatformfontdatabase_qpa.cpp b/src/gui/text/qplatformfontdatabase_qpa.cpp
new file mode 100644
index 0000000000..d6dff413c0
--- /dev/null
+++ b/src/gui/text/qplatformfontdatabase_qpa.cpp
@@ -0,0 +1,290 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include "qplatformfontdatabase_qpa.h"
+#include <QtGui/private/qfontengine_p.h>
+#include <QtGui/private/qfontengine_qpa_p.h>
+#include <QtCore/QLibraryInfo>
+#include <QtCore/QDir>
+
+QT_BEGIN_NAMESPACE
+
+extern void qt_registerFont(const QString &familyname, const QString &foundryname, int weight,
+ QFont::Style style, int stretch, bool antialiased,bool scalable, int pixelSize,
+ const QSupportedWritingSystems &writingSystems, void *hanlde);
+
+void QPlatformFontDatabase::registerQPF2Font(const QByteArray &dataArray, void *handle)
+{
+ if (dataArray.size() == 0)
+ return;
+
+ const uchar *data = reinterpret_cast<const uchar *>(dataArray.constData());
+ if (QFontEngineQPA::verifyHeader(data, dataArray.size())) {
+ QString fontName = QFontEngineQPA::extractHeaderField(data, QFontEngineQPA::Tag_FontName).toString();
+ int pixelSize = QFontEngineQPA::extractHeaderField(data, QFontEngineQPA::Tag_PixelSize).toInt();
+ QVariant weight = QFontEngineQPA::extractHeaderField(data, QFontEngineQPA::Tag_Weight);
+ QVariant style = QFontEngineQPA::extractHeaderField(data, QFontEngineQPA::Tag_Style);
+ QByteArray writingSystemBits = QFontEngineQPA::extractHeaderField(data, QFontEngineQPA::Tag_WritingSystems).toByteArray();
+
+ if (!fontName.isEmpty() && pixelSize) {
+ QFont::Weight fontWeight = QFont::Normal;
+ if (weight.type() == QVariant::Int || weight.type() == QVariant::UInt)
+ fontWeight = QFont::Weight(weight.toInt());
+
+ QFont::Style fontStyle = static_cast<QFont::Style>(style.toInt());
+
+ QSupportedWritingSystems writingSystems;
+ for (int i = 0; i < writingSystemBits.count(); ++i) {
+ uchar currentByte = writingSystemBits.at(i);
+ for (int j = 0; j < 8; ++j) {
+ if (currentByte & 1)
+ writingSystems.setSupported(QFontDatabase::WritingSystem(i * 8 + j));
+ currentByte >>= 1;
+ }
+ }
+ QFont::Stretch stretch = QFont::Unstretched;
+ registerFont(fontName,QString(),fontWeight,fontStyle,stretch,true,false,pixelSize,writingSystems,handle);
+ }
+ } else {
+ qDebug() << "header verification of QPF2 font failed. maybe it is corrupt?";
+ }
+}
+
+void QPlatformFontDatabase::registerFont(const QString &familyname, const QString &foundryname, QFont::Weight weight,
+ QFont::Style style, QFont::Stretch stretch, bool antialiased, bool scalable, int pixelSize,
+ const QSupportedWritingSystems &writingSystems, void *usrPtr)
+{
+ if (scalable)
+ pixelSize = 0;
+ qt_registerFont(familyname,foundryname,weight,style,stretch,antialiased,scalable,pixelSize,writingSystems,usrPtr);
+}
+
+class QWritingSystemsPrivate
+{
+public:
+ QWritingSystemsPrivate()
+ : ref(1)
+ , vector(QFontDatabase::WritingSystemsCount,false)
+ {
+ }
+
+ QWritingSystemsPrivate(const QWritingSystemsPrivate *other)
+ : ref(1)
+ , vector(other->vector)
+ {
+ }
+
+ QAtomicInt ref;
+ QVector<bool> vector;
+};
+
+QSupportedWritingSystems::QSupportedWritingSystems()
+{
+ d = new QWritingSystemsPrivate;
+}
+
+QSupportedWritingSystems::QSupportedWritingSystems(const QSupportedWritingSystems &other)
+{
+ d = other.d;
+ d->ref.ref();
+}
+
+QSupportedWritingSystems &QSupportedWritingSystems::operator=(const QSupportedWritingSystems &other)
+{
+ if (d != other.d) {
+ other.d->ref.ref();
+ if (!d->ref.deref())
+ delete d;
+ d = other.d;
+ }
+ return *this;
+}
+
+QSupportedWritingSystems::~QSupportedWritingSystems()
+{
+ if (!d->ref.deref())
+ delete d;
+}
+
+void QSupportedWritingSystems::detach()
+{
+ if (d->ref != 1) {
+ QWritingSystemsPrivate *newd = new QWritingSystemsPrivate(d);
+ if (!d->ref.deref())
+ delete d;
+ d = newd;
+ }
+}
+
+void QSupportedWritingSystems::setSupported(QFontDatabase::WritingSystem writingSystem, bool support)
+{
+ detach();
+ d->vector[writingSystem] = support;
+}
+
+bool QSupportedWritingSystems::supported(QFontDatabase::WritingSystem writingSystem) const
+{
+ return d->vector.at(writingSystem);
+}
+
+/*!
+ \class QSupportedWritingSystems
+ \brief The QSupportedWritingSystems class is used when registering fonts with the internal Qt
+ fontdatabase
+ \ingroup painting
+
+ Its to provide an easy to use interface for indicating what writing systems a specific font
+ supports.
+
+*/
+
+/*!
+ This function is called once at startup by Qts internal fontdatabase. Reimplement this function
+ in a subclass for a convenient place to initialise the internal fontdatabase.
+
+ The default implementation looks in the fontDir() location and registers all qpf2 fonts.
+*/
+void QPlatformFontDatabase::populateFontDatabase()
+{
+ QString fontpath = fontDir();
+
+ if(!QFile::exists(fontpath)) {
+ qFatal("QFontDatabase: Cannot find font directory %s - is Qt installed correctly?",
+ qPrintable(fontpath));
+ }
+
+ QDir dir(fontpath);
+ dir.setNameFilters(QStringList() << QLatin1String("*.qpf2"));
+ dir.refresh();
+ for (int i = 0; i < int(dir.count()); ++i) {
+ const QByteArray fileName = QFile::encodeName(dir.absoluteFilePath(dir[i]));
+ QFile file(QString::fromLocal8Bit(fileName));
+ if (file.open(QFile::ReadOnly)) {
+ const QByteArray fileData = file.readAll();
+ QByteArray *fileDataPtr = new QByteArray(fileData);
+ registerQPF2Font(fileData, fileDataPtr);
+ }
+ }
+}
+
+/*!
+
+*/
+QFontEngine *QPlatformFontDatabase::fontEngine(const QFontDef &fontDef, QUnicodeTables::Script script, void *handle)
+{
+ Q_UNUSED(script);
+ Q_UNUSED(handle);
+ QByteArray *fileDataPtr = static_cast<QByteArray *>(handle);
+ QFontEngineQPA *engine = new QFontEngineQPA(fontDef,*fileDataPtr);
+ qDebug() << fontDef.pixelSize << fontDef.weight << fontDef.style << fontDef.stretch << fontDef.styleHint << fontDef.styleStrategy << fontDef.family << script;
+ return engine;
+}
+
+/*!
+
+*/
+QStringList QPlatformFontDatabase::fallbacksForFamily(const QString family, const QFont::Style &style, const QUnicodeTables::Script &script) const
+{
+ Q_UNUSED(family);
+ Q_UNUSED(style);
+ Q_UNUSED(script);
+ return QStringList();
+}
+
+/*!
+ Adds an application font. Returns a list of family names, or an empty list if the font could
+ not be added
+*/
+QStringList QPlatformFontDatabase::addApplicationFont(const QByteArray &fontData, const QString &fileName)
+{
+ Q_UNUSED(fontData);
+ Q_UNUSED(fileName);
+
+ qWarning("This plugin does not support application fonts");
+ return QStringList();
+}
+
+/*!
+
+*/
+void QPlatformFontDatabase::releaseHandle(void *handle)
+{
+ QByteArray *fileDataPtr = static_cast<QByteArray *>(handle);
+ delete fileDataPtr;
+}
+
+/*!
+
+*/
+QString QPlatformFontDatabase::fontDir() const
+{
+ QString fontpath = QString::fromLocal8Bit(qgetenv("QT_QPA_FONTDIR"));
+ if (fontpath.isEmpty()) {
+#ifndef QT_NO_SETTINGS
+ fontpath = QLibraryInfo::location(QLibraryInfo::LibrariesPath);
+ fontpath += QLatin1String("/fonts");
+#endif
+ }
+
+ return fontpath;
+}
+
+/*!
+ \class QPlatformFontDatabase
+ \brief The QPlatformFontDatabase makes it possible to customize how fonts are picked up, and
+ and how they are rendered
+
+ \ingroup painting
+
+ QPlatformFontDatabase is the superclass which is intended to let platform implementations use
+ native font handling.
+
+ Qt has its internal fontdatabase which it uses to pick up available fonts. To be able
+ to populate this database subclass this class, and reimplement populateFontDatabase().
+
+ Use the function registerFont to populate the internal fontdatabase.
+
+ Sometimes a specified font does not have the required glyphs, then the fallbackForFamily
+ function is called.
+
+ \sa QSupportedWritingSystems
+*/
+QT_END_NAMESPACE
diff --git a/src/gui/text/qplatformfontdatabase_qpa.h b/src/gui/text/qplatformfontdatabase_qpa.h
new file mode 100644
index 0000000000..aa465ab9ca
--- /dev/null
+++ b/src/gui/text/qplatformfontdatabase_qpa.h
@@ -0,0 +1,108 @@
+/****************************************************************************
+**
+** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+** All rights reserved.
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** This file is part of the QtGui module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** No Commercial Usage
+** This file contains pre-release code and may not be distributed.
+** You may use this file in accordance with the terms and conditions
+** contained in the Technology Preview License Agreement accompanying
+** this package.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**
+**
+**
+**
+**
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QPLATFORMFONTDATABASE_QPA_H
+#define QPLATFORMFONTDATABASE_QPA_H
+
+#include <QtCore/qconfig.h>
+#include <QtCore/QString>
+#include <QtCore/QStringList>
+#include <QtCore/QList>
+#include <QtGui/QFontDatabase>
+#include <QtGui/private/qfont_p.h>
+
+QT_BEGIN_HEADER
+
+QT_BEGIN_NAMESPACE
+
+QT_MODULE(Gui)
+
+class QWritingSystemsPrivate;
+
+class Q_GUI_EXPORT QSupportedWritingSystems
+{
+public:
+
+ QSupportedWritingSystems();
+ QSupportedWritingSystems(const QSupportedWritingSystems &other);
+ QSupportedWritingSystems &operator=(const QSupportedWritingSystems &other);
+ ~QSupportedWritingSystems();
+
+ void setSupported(QFontDatabase::WritingSystem, bool supported = true);
+ bool supported(QFontDatabase::WritingSystem) const;
+
+private:
+ void detach();
+
+ QWritingSystemsPrivate *d;
+
+ friend Q_GUI_EXPORT bool operator==(const QSupportedWritingSystems &, const QSupportedWritingSystems &);
+ friend Q_GUI_EXPORT bool operator!=(const QSupportedWritingSystems &, const QSupportedWritingSystems &);
+};
+
+Q_GUI_EXPORT bool operator==(const QSupportedWritingSystems &, const QSupportedWritingSystems &);
+Q_GUI_EXPORT bool operator!=(const QSupportedWritingSystems &, const QSupportedWritingSystems &);
+
+class QFontRequestPrivate;
+
+class Q_GUI_EXPORT QPlatformFontDatabase
+{
+public:
+ virtual void populateFontDatabase();
+ virtual QFontEngine *fontEngine(const QFontDef &fontDef, QUnicodeTables::Script script, void *handle);
+ virtual QStringList fallbacksForFamily(const QString family, const QFont::Style &style, const QUnicodeTables::Script &script) const;
+ virtual QStringList addApplicationFont(const QByteArray &fontData, const QString &fileName);
+ virtual void releaseHandle(void *handle);
+
+ virtual QString fontDir() const;
+
+ //callback
+ static void registerQPF2Font(const QByteArray &dataArray, void *handle);
+ static void registerFont(const QString &familyname, const QString &foundryname, QFont::Weight weight,
+ QFont::Style style, QFont::Stretch stretch, bool antialiased, bool scalable, int pixelSize,
+ const QSupportedWritingSystems &writingSystems, void *handle);
+};
+
+QT_END_NAMESPACE
+
+QT_END_HEADER
+
+#endif // QPLATFORMFONTDATABASE_QPA_H
diff --git a/src/gui/text/qtextcontrol.cpp b/src/gui/text/qtextcontrol.cpp
index 58bfbc6461..89ca6bf8c1 100644
--- a/src/gui/text/qtextcontrol.cpp
+++ b/src/gui/text/qtextcontrol.cpp
@@ -64,6 +64,7 @@
#include "qgraphicssceneevent.h"
#include "qprinter.h"
#include "qtextdocumentwriter.h"
+#include "private/qtextcursor_p.h"
#include <qtextformat.h>
#include <qdatetime.h>
@@ -1904,6 +1905,8 @@ void QTextControlPrivate::inputMethodEvent(QInputMethodEvent *e)
}
layout->setAdditionalFormats(overrides);
cursor.endEditBlock();
+ if (cursor.d)
+ cursor.d->setX();
}
QVariant QTextControl::inputMethodQuery(Qt::InputMethodQuery property) const
@@ -2894,7 +2897,7 @@ QAbstractTextDocumentLayout::PaintContext QTextControl::getPaintContext(QWidget
if (widget)
style = widget->style();
style->styleHint(QStyle::SH_TextControl_FocusIndicatorTextCharFormat, &opt, widget, &ret);
- selection.format = qVariantValue<QTextFormat>(ret.variant).toCharFormat();
+ selection.format = qvariant_cast<QTextFormat>(ret.variant).toCharFormat();
} else {
QPalette::ColorGroup cg = d->hasFocus ? QPalette::Active : QPalette::Inactive;
selection.format.setBackground(ctx.palette.brush(cg, QPalette::Highlight));
diff --git a/src/gui/text/qtextcursor.h b/src/gui/text/qtextcursor.h
index dc55e0ee85..4eaeb41ee9 100644
--- a/src/gui/text/qtextcursor.h
+++ b/src/gui/text/qtextcursor.h
@@ -230,6 +230,7 @@ private:
QSharedDataPointer<QTextCursorPrivate> d;
friend class QTextDocumentFragmentPrivate;
friend class QTextCopyHelper;
+ friend class QTextControlPrivate;
};
QT_END_NAMESPACE
diff --git a/src/gui/text/qtextdocument.cpp b/src/gui/text/qtextdocument.cpp
index 673ae4648c..be67279cb4 100644
--- a/src/gui/text/qtextdocument.cpp
+++ b/src/gui/text/qtextdocument.cpp
@@ -1985,6 +1985,8 @@ QVariant QTextDocument::loadResource(int type, const QUrl &name)
if (fi.exists()) {
resourceUrl =
QUrl::fromLocalFile(fi.absolutePath() + QDir::separator()).resolved(name);
+ } else if (currentURL.isEmpty()) {
+ resourceUrl.setScheme(QLatin1String("file"));
}
}
@@ -2602,14 +2604,40 @@ void QTextHtmlExporter::emitBlock(const QTextBlock &block)
default: html += QLatin1String("<ul"); // ### should not happen
}
- html += QLatin1String(" style=\"margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px;");
+ QString styleString = QString::fromLatin1("margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px;");
if (format.hasProperty(QTextFormat::ListIndent)) {
- html += QLatin1String(" -qt-list-indent: ");
- html += QString::number(format.indent());
- html += QLatin1Char(';');
+ styleString += QLatin1String(" -qt-list-indent: ");
+ styleString += QString::number(format.indent());
+ styleString += QLatin1Char(';');
+ }
+
+ if (format.hasProperty(QTextFormat::ListNumberPrefix)) {
+ QString numberPrefix = format.numberPrefix();
+ numberPrefix.replace(QLatin1Char('"'), QLatin1String("\\22"));
+ numberPrefix.replace(QLatin1Char('\''), QLatin1String("\\27")); // FIXME: There's a problem in the CSS parser the prevents this from being correctly restored
+ styleString += QLatin1String(" -qt-list-number-prefix: ");
+ styleString += QLatin1Char('\'');
+ styleString += numberPrefix;
+ styleString += QLatin1Char('\'');
+ styleString += QLatin1Char(';');
}
+ if (format.hasProperty(QTextFormat::ListNumberSuffix)) {
+ if (format.numberSuffix() != QLatin1String(".")) { // this is our default
+ QString numberSuffix = format.numberSuffix();
+ numberSuffix.replace(QLatin1Char('"'), QLatin1String("\\22"));
+ numberSuffix.replace(QLatin1Char('\''), QLatin1String("\\27")); // see above
+ styleString += QLatin1String(" -qt-list-number-suffix: ");
+ styleString += QLatin1Char('\'');
+ styleString += numberSuffix;
+ styleString += QLatin1Char('\'');
+ styleString += QLatin1Char(';');
+ }
+ }
+
+ html += QLatin1String(" style=\"");
+ html += styleString;
html += QLatin1String("\">");
}
diff --git a/src/gui/text/qtextdocumentfragment.cpp b/src/gui/text/qtextdocumentfragment.cpp
index b4bd8583b0..7890b38067 100644
--- a/src/gui/text/qtextdocumentfragment.cpp
+++ b/src/gui/text/qtextdocumentfragment.cpp
@@ -682,6 +682,10 @@ QTextHtmlImporter::ProcessNodeResult QTextHtmlImporter::processSpecialNodes()
QTextListFormat listFmt;
listFmt.setStyle(style);
+ if (!currentNode->textListNumberPrefix.isNull())
+ listFmt.setNumberPrefix(currentNode->textListNumberPrefix);
+ if (!currentNode->textListNumberSuffix.isNull())
+ listFmt.setNumberSuffix(currentNode->textListNumberSuffix);
++indent;
if (currentNode->hasCssListIndent)
diff --git a/src/gui/text/qtextdocumentlayout.cpp b/src/gui/text/qtextdocumentlayout.cpp
index d721c91d90..157b7bc417 100644
--- a/src/gui/text/qtextdocumentlayout.cpp
+++ b/src/gui/text/qtextdocumentlayout.cpp
@@ -2506,6 +2506,23 @@ void QTextDocumentLayoutPrivate::layoutFlow(QTextFrame::Iterator it, QTextLayout
fd->currentLayoutStruct = 0;
}
+static inline void getLineHeightParams(const QTextBlockFormat &blockFormat, const QTextLine &line, qreal scaling,
+ QFixed *lineAdjustment, QFixed *lineBreakHeight, QFixed *lineHeight)
+{
+ *lineHeight = QFixed::fromReal(blockFormat.lineHeight(line.height(), scaling));
+ if (blockFormat.lineHeightType() == QTextBlockFormat::FixedHeight || blockFormat.lineHeightType() == QTextBlockFormat::MinimumHeight) {
+ *lineBreakHeight = *lineHeight;
+ if (blockFormat.lineHeightType() == QTextBlockFormat::FixedHeight)
+ *lineAdjustment = QFixed::fromReal(line.ascent() + qMax(line.leading(), qreal(0.0))) - ((*lineHeight * 4) / 5);
+ else
+ *lineAdjustment = QFixed::fromReal(line.height()) - *lineHeight;
+ }
+ else {
+ *lineBreakHeight = QFixed::fromReal(line.height());
+ *lineAdjustment = 0;
+ }
+}
+
void QTextDocumentLayoutPrivate::layoutBlock(const QTextBlock &bl, int blockPosition, const QTextBlockFormat &blockFormat,
QTextLayoutStruct *layoutStruct, int layoutFrom, int layoutTo, const QTextBlockFormat *previousBlockFormat)
{
@@ -2639,8 +2656,12 @@ void QTextDocumentLayoutPrivate::layoutBlock(const QTextBlock &bl, int blockPosi
}
- QFixed lineHeight = QFixed::fromReal(line.height());
- if (layoutStruct->pageHeight > 0 && layoutStruct->absoluteY() + lineHeight > layoutStruct->pageBottom) {
+ QFixed lineBreakHeight, lineHeight, lineAdjustment;
+ qreal scaling = (q->paintDevice() && q->paintDevice()->logicalDpiY() != qt_defaultDpi()) ?
+ qreal(q->paintDevice()->logicalDpiY()) / qreal(qt_defaultDpi()) : 1;
+ getLineHeightParams(blockFormat, line, scaling, &lineAdjustment, &lineBreakHeight, &lineHeight);
+
+ if (layoutStruct->pageHeight > 0 && layoutStruct->absoluteY() + lineBreakHeight > layoutStruct->pageBottom) {
layoutStruct->newPage();
floatMargins(layoutStruct->y, layoutStruct, &left, &right);
@@ -2652,7 +2673,7 @@ void QTextDocumentLayoutPrivate::layoutBlock(const QTextBlock &bl, int blockPosi
right -= text_indent;
}
- line.setPosition(QPointF((left - layoutStruct->x_left).toReal(), (layoutStruct->y - cy).toReal()));
+ line.setPosition(QPointF((left - layoutStruct->x_left).toReal(), (layoutStruct->y - cy - lineAdjustment).toReal()));
layoutStruct->y += lineHeight;
layoutStruct->contentsWidth
= qMax<QFixed>(layoutStruct->contentsWidth, QFixed::fromReal(line.x() + line.naturalTextWidth()) + totalRightMargin);
@@ -2672,11 +2693,16 @@ void QTextDocumentLayoutPrivate::layoutBlock(const QTextBlock &bl, int blockPosi
QTextLine line = tl->lineAt(i);
layoutStruct->contentsWidth
= qMax(layoutStruct->contentsWidth, QFixed::fromReal(line.x() + tl->lineAt(i).naturalTextWidth()) + totalRightMargin);
- const QFixed lineHeight = QFixed::fromReal(line.height());
+
+ QFixed lineBreakHeight, lineHeight, lineAdjustment;
+ qreal scaling = (q->paintDevice() && q->paintDevice()->logicalDpiY() != qt_defaultDpi()) ?
+ qreal(q->paintDevice()->logicalDpiY()) / qreal(qt_defaultDpi()) : 1;
+ getLineHeightParams(blockFormat, line, scaling, &lineAdjustment, &lineBreakHeight, &lineHeight);
+
if (layoutStruct->pageHeight != QFIXED_MAX) {
- if (layoutStruct->absoluteY() + lineHeight > layoutStruct->pageBottom)
+ if (layoutStruct->absoluteY() + lineBreakHeight > layoutStruct->pageBottom)
layoutStruct->newPage();
- line.setPosition(QPointF(line.position().x(), layoutStruct->y.toReal() - tl->position().y()));
+ line.setPosition(QPointF(line.position().x(), (layoutStruct->y - lineAdjustment).toReal() - tl->position().y()));
}
layoutStruct->y += lineHeight;
}
diff --git a/src/gui/text/qtextengine.cpp b/src/gui/text/qtextengine.cpp
index b511b5a237..415fa4b71f 100644
--- a/src/gui/text/qtextengine.cpp
+++ b/src/gui/text/qtextengine.cpp
@@ -612,7 +612,7 @@ static bool bidiItemize(QTextEngine *engine, QScriptAnalysis *analysis, QBidiCon
} else {
eor = current;
}
- dir = QChar::DirON; status.eor = QChar::DirAN;
+ dir = QChar::DirAN; status.eor = QChar::DirAN;
break;
case QChar::DirCS:
if(status.eor == QChar::DirAN) {
@@ -1233,6 +1233,8 @@ void QTextEngine::shapeTextWithHarfbuzz(int item) const
shaper_item.num_glyphs -= itemBoundaries[k + 1];
}
shaper_item.initialGlyphCount = shaper_item.num_glyphs;
+ if (shaper_item.num_glyphs < shaper_item.item.length)
+ shaper_item.num_glyphs = shaper_item.item.length;
QFontEngine *actualFontEngine = font;
uint engineIdx = 0;
@@ -1257,7 +1259,8 @@ void QTextEngine::shapeTextWithHarfbuzz(int item) const
}
const QGlyphLayout g = availableGlyphs(&si).mid(glyph_pos);
- moveGlyphData(g.mid(shaper_item.num_glyphs), g.mid(shaper_item.initialGlyphCount), remaining_glyphs);
+ if (shaper_item.num_glyphs > shaper_item.item.length)
+ moveGlyphData(g.mid(shaper_item.num_glyphs), g.mid(shaper_item.initialGlyphCount), remaining_glyphs);
shaper_item.glyphs = g.glyphs;
shaper_item.attributes = g.attributes;
@@ -1389,6 +1392,7 @@ void QTextEngine::invalidate()
maxWidth = 0;
if (specialData)
specialData->resolvedFormatIndices.clear();
+ feCache.reset();
}
void QTextEngine::clearLineData()
@@ -1780,6 +1784,13 @@ QFont QTextEngine::font(const QScriptItem &si) const
return font;
}
+QTextEngine::FontEngineCache::FontEngineCache()
+{
+ reset();
+}
+
+//we cache the previous results of this function, as calling it numerous times with the same effective
+//input is common (and hard to cache at a higher level)
QFontEngine *QTextEngine::fontEngine(const QScriptItem &si, QFixed *ascent, QFixed *descent, QFixed *leading) const
{
QFontEngine *engine = 0;
@@ -1788,28 +1799,47 @@ QFontEngine *QTextEngine::fontEngine(const QScriptItem &si, QFixed *ascent, QFix
QFont font = fnt;
if (hasFormats()) {
- QTextCharFormat f = format(&si);
- font = f.font();
-
- if (block.docHandle() && block.docHandle()->layout()) {
- // Make sure we get the right dpi on printers
- QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
- if (pdev)
- font = QFont(font, pdev);
+ if (feCache.prevFontEngine && feCache.prevPosition == si.position && feCache.prevLength == length(&si) && feCache.prevScript == script) {
+ engine = feCache.prevFontEngine;
+ scaledEngine = feCache.prevScaledFontEngine;
} else {
- font = font.resolve(fnt);
- }
- engine = font.d->engineForScript(script);
- QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
- if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
- if (font.pointSize() != -1)
- font.setPointSize((font.pointSize() * 2) / 3);
- else
- font.setPixelSize((font.pixelSize() * 2) / 3);
- scaledEngine = font.d->engineForScript(script);
+ QTextCharFormat f = format(&si);
+ font = f.font();
+
+ if (block.docHandle() && block.docHandle()->layout()) {
+ // Make sure we get the right dpi on printers
+ QPaintDevice *pdev = block.docHandle()->layout()->paintDevice();
+ if (pdev)
+ font = QFont(font, pdev);
+ } else {
+ font = font.resolve(fnt);
+ }
+ engine = font.d->engineForScript(script);
+ QTextCharFormat::VerticalAlignment valign = f.verticalAlignment();
+ if (valign == QTextCharFormat::AlignSuperScript || valign == QTextCharFormat::AlignSubScript) {
+ if (font.pointSize() != -1)
+ font.setPointSize((font.pointSize() * 2) / 3);
+ else
+ font.setPixelSize((font.pixelSize() * 2) / 3);
+ scaledEngine = font.d->engineForScript(script);
+ }
+ feCache.prevFontEngine = engine;
+ feCache.prevScaledFontEngine = scaledEngine;
+ feCache.prevScript = script;
+ feCache.prevPosition = si.position;
+ feCache.prevLength = length(&si);
}
} else {
- engine = font.d->engineForScript(script);
+ if (feCache.prevFontEngine && feCache.prevScript == script && feCache.prevPosition == -1)
+ engine = feCache.prevFontEngine;
+ else {
+ engine = font.d->engineForScript(script);
+ feCache.prevFontEngine = engine;
+ feCache.prevScript = script;
+ feCache.prevPosition = -1;
+ feCache.prevLength = -1;
+ feCache.prevScaledFontEngine = 0;
+ }
}
if (si.analysis.flags == QScriptAnalysis::SmallCaps) {
@@ -2353,30 +2383,29 @@ QString QTextEngine::elidedText(Qt::TextElideMode mode, const QFixed &width, int
if (flags & Qt::TextShowMnemonic) {
itemize();
+ HB_CharAttributes *attributes = const_cast<HB_CharAttributes *>(this->attributes());
+ if (!attributes)
+ return QString();
for (int i = 0; i < layoutData->items.size(); ++i) {
QScriptItem &si = layoutData->items[i];
if (!si.num_glyphs)
shape(i);
- HB_CharAttributes *attributes = const_cast<HB_CharAttributes *>(this->attributes());
- if (!attributes)
- return QString();
-
unsigned short *logClusters = this->logClusters(&si);
QGlyphLayout glyphs = shapedGlyphs(&si);
const int end = si.position + length(&si);
- for (int i = si.position; i < end - 1; ++i)
+ for (int i = si.position; i < end - 1; ++i) {
if (layoutData->string.at(i) == QLatin1Char('&')) {
const int gp = logClusters[i - si.position];
glyphs.attributes[gp].dontPrint = true;
attributes[i + 1].charStop = false;
attributes[i + 1].whiteSpace = false;
attributes[i + 1].lineBreakType = HB_NoBreak;
- if (i < end - 1
- && layoutData->string.at(i + 1) == QLatin1Char('&'))
+ if (layoutData->string.at(i + 1) == QLatin1Char('&'))
++i;
}
+ }
}
}
@@ -2438,7 +2467,7 @@ QString QTextEngine::elidedText(Qt::TextElideMode mode, const QFixed &width, int
if (mode == Qt::ElideRight) {
QFixed currentWidth;
- int pos = 0;
+ int pos;
int nextBreak = 0;
do {
@@ -2458,7 +2487,7 @@ QString QTextEngine::elidedText(Qt::TextElideMode mode, const QFixed &width, int
return layoutData->string.left(pos) + ellipsisText;
} else if (mode == Qt::ElideLeft) {
QFixed currentWidth;
- int pos = layoutData->string.length();
+ int pos;
int nextBreak = layoutData->string.length();
do {
diff --git a/src/gui/text/qtextengine_mac.cpp b/src/gui/text/qtextengine_mac.cpp
index ce42241fc8..c0a1e647da 100644
--- a/src/gui/text/qtextengine_mac.cpp
+++ b/src/gui/text/qtextengine_mac.cpp
@@ -41,6 +41,9 @@
#include "qtextengine_p.h"
+#include <private/qfontengine_coretext_p.h>
+#include <private/qfontengine_mac_p.h>
+
QT_BEGIN_NAMESPACE
// set the glyph attributes heuristically. Assumes a 1 to 1 relationship between chars and glyphs
diff --git a/src/gui/text/qtextengine_p.h b/src/gui/text/qtextengine_p.h
index 34723ab1b7..50d1ff8e65 100644
--- a/src/gui/text/qtextengine_p.h
+++ b/src/gui/text/qtextengine_p.h
@@ -128,7 +128,7 @@ struct Q_AUTOTEST_EXPORT QScriptAnalysis
TabOrObject = Tab,
Object = 7
};
- unsigned short script : 8;
+ unsigned short script : 7;
unsigned short bidiLevel : 6; // Unicode Bidi algorithm embedding level (0-61)
unsigned short flags : 3;
inline bool operator == (const QScriptAnalysis &other) const {
@@ -385,7 +385,7 @@ struct Q_AUTOTEST_EXPORT QScriptLine
QFixed textWidth;
QFixed textAdvance;
int from;
- signed int length : 29;
+ signed int length : 28;
mutable uint justified : 1;
mutable uint gridfitted : 1;
uint hasTrailingSpaces : 1;
@@ -435,7 +435,7 @@ public:
uint hasBidi : 1;
uint layoutState : 2;
uint memory_on_stack : 1;
- bool haveCharAttributes;
+ uint haveCharAttributes : 1;
QString string;
bool reallocate(int totalGlyphs);
};
@@ -556,6 +556,23 @@ public:
mutable QScriptLineArray lines;
+ struct FontEngineCache {
+ FontEngineCache();
+ mutable QFontEngine *prevFontEngine;
+ mutable QFontEngine *prevScaledFontEngine;
+ mutable int prevScript;
+ mutable int prevPosition;
+ mutable int prevLength;
+ inline void reset() {
+ prevFontEngine = 0;
+ prevScaledFontEngine = 0;
+ prevScript = -1;
+ prevPosition = -1;
+ prevLength = -1;
+ }
+ };
+ mutable FontEngineCache feCache;
+
QString text;
QFont fnt;
QTextBlock block;
diff --git a/src/gui/text/qtextformat.cpp b/src/gui/text/qtextformat.cpp
index c009ce7849..c9af4014d8 100644
--- a/src/gui/text/qtextformat.cpp
+++ b/src/gui/text/qtextformat.cpp
@@ -541,6 +541,8 @@ Q_GUI_EXPORT QDataStream &operator>>(QDataStream &stream, QTextFormat &fmt)
\value TabPositions Specifies the tab positions. The tab positions are structs of QTextOption::Tab which are stored in
a QList (internally, in a QList<QVariant>).
\value BlockIndent
+ \value LineHeight
+ \value LineHeightType
\value BlockNonBreakableLines
\value BlockTrailingHorizontalRulerWidth The width of a horizontal ruler element.
@@ -933,7 +935,7 @@ qreal QTextFormat::doubleProperty(int propertyId) const
const QVariant prop = d->property(propertyId);
if (prop.userType() != QVariant::Double && prop.userType() != QMetaType::Float)
return 0.;
- return qVariantValue<qreal>(prop);
+ return qvariant_cast<qreal>(prop);
}
/*!
@@ -1856,6 +1858,10 @@ QFont QTextCharFormat::font() const
indentation is set with setIndent(), the indentation of the first
line with setTextIndent().
+ Line spacing is set with setLineHeight() and retrieved via lineHeight()
+ and lineHeightType(). The types of line spacing available are in the
+ LineHeightTypes enum.
+
Line breaking can be enabled and disabled with setNonBreakableLines().
The brush used to paint the paragraph's background
@@ -1872,6 +1878,22 @@ QFont QTextCharFormat::font() const
*/
/*!
+ \since 4.8
+ \enum QTextBlockFormat::LineHeightTypes
+
+ This enum describes the various types of line spacing support paragraphs can have.
+
+ \value SingleHeight This is the default line height: single spacing.
+ \value ProportionalHeight This sets the spacing proportional to the line (in percentage).
+ For example, set to 200 for double spacing.
+ \value FixedHeight This sets the line height to a fixed line height (in pixels).
+ \value MinimumHeight This sets the minimum line height (in pixels).
+ \value LineDistanceHeight This adds the specified height between lines (in pixels).
+
+ \sa lineHeight(), lineHeightType(), setLineHeight()
+*/
+
+/*!
\fn QTextBlockFormat::QTextBlockFormat()
Constructs a new QTextBlockFormat.
@@ -1903,7 +1925,7 @@ void QTextBlockFormat::setTabPositions(const QList<QTextOption::Tab> &tabs)
QList<QTextOption::Tab>::ConstIterator iter = tabs.constBegin();
while (iter != tabs.constEnd()) {
QVariant v;
- qVariantSetValue<QTextOption::Tab>(v, *iter);
+ v.setValue<QTextOption::Tab>(*iter);
list.append(v);
++iter;
}
@@ -1925,7 +1947,7 @@ QList<QTextOption::Tab> QTextBlockFormat::tabPositions() const
QList<QVariant> variantsList = qvariant_cast<QList<QVariant> >(variant);
QList<QVariant>::Iterator iter = variantsList.begin();
while(iter != variantsList.end()) {
- answer.append( qVariantValue<QTextOption::Tab>(*iter));
+ answer.append( qvariant_cast<QTextOption::Tab>(*iter));
++iter;
}
return answer;
@@ -2089,6 +2111,51 @@ QList<QTextOption::Tab> QTextBlockFormat::tabPositions() const
/*!
+ \fn void QTextBlockFormat::setLineHeight(qreal height, int heightType)
+ \since 4.8
+
+ This sets the line height for the paragraph to the value in height
+ which is dependant on heightType, described by the LineHeightTypes enum.
+
+ \sa LineHeightTypes, lineHeight(), lineHeightType()
+*/
+
+
+/*!
+ \fn qreal QTextBlockFormat::lineHeight(qreal scriptLineHeight, qreal scaling) const
+ \since 4.8
+
+ This returns what the height of the lines in the paragraph will be depending
+ on the given height of the script line and the scaling. The value that is returned
+ is also dependant on the given LineHeightType of the paragraph as well as the LineHeight
+ setting that has been set for the paragraph. The scaling is needed for the heights
+ that include a fixed number of pixels, to scale them appropriately for printing.
+
+ \sa LineHeightTypes, setLineHeight(), lineHeightType()
+*/
+
+
+/*!
+ \fn qreal QTextBlockFormat::lineHeight() const
+ \since 4.8
+
+ This returns the LineHeight property for the paragraph.
+
+ \sa LineHeightTypes, setLineHeight(), lineHeightType()
+*/
+
+
+/*!
+ \fn qreal QTextBlockFormat::lineHeightType() const
+ \since 4.8
+
+ This returns the LineHeightType property of the paragraph.
+
+ \sa LineHeightTypes, setLineHeight(), lineHeight()
+*/
+
+
+/*!
\fn void QTextBlockFormat::setNonBreakableLines(bool b)
If \a b is true, the lines in the paragraph are treated as
@@ -2235,6 +2302,44 @@ QTextListFormat::QTextListFormat(const QTextFormat &fmt)
\sa setIndent()
*/
+/*!
+ \fn void QTextListFormat::setNumberPrefix(const QString &numberPrefix)
+ \since 4.8
+
+ Sets the list format's number prefix. This can be used with all
+ sorted list types. It does not have any effect on unsorted list types.
+
+ \sa numberPrefix()
+*/
+
+/*!
+ \fn int QTextListFormat::numberPrefix() const
+ \since 4.8
+
+ Returns the list format's number prefix.
+
+ \sa setNumberPrefix()
+*/
+
+/*!
+ \fn void QTextListFormat::setNumberSuffix(const QString &numberSuffix)
+ \since 4.8
+
+ Sets the list format's number suffix. This can be used with all
+ sorted list types. It does not have any effect on unsorted list types.
+ The default suffix is ".".
+
+ \sa numberSuffix()
+*/
+
+/*!
+ \fn int QTextListFormat::numberSuffix() const
+ \since 4.8
+
+ Returns the list format's number suffix.
+
+ \sa setNumberSuffix()
+*/
/*!
\class QTextFrameFormat
diff --git a/src/gui/text/qtextformat.h b/src/gui/text/qtextformat.h
index eb9146fc22..9a573a0467 100644
--- a/src/gui/text/qtextformat.h
+++ b/src/gui/text/qtextformat.h
@@ -164,6 +164,8 @@ public:
TextIndent = 0x1034,
TabPositions = 0x1035,
BlockIndent = 0x1040,
+ LineHeight = 0x1048,
+ LineHeightType = 0x1049,
BlockNonBreakableLines = 0x1050,
BlockTrailingHorizontalRulerWidth = 0x1060,
@@ -202,6 +204,8 @@ public:
// list properties
ListStyle = 0x3000,
ListIndent = 0x3001,
+ ListNumberPrefix = 0x3002,
+ ListNumberSuffix = 0x3003,
// table and frame properties
FrameBorder = 0x4000,
@@ -529,6 +533,14 @@ inline void QTextCharFormat::setTableCellColumnSpan(int _tableCellColumnSpan)
class Q_GUI_EXPORT QTextBlockFormat : public QTextFormat
{
public:
+ enum LineHeightTypes {
+ SingleHeight = 0,
+ ProportionalHeight = 1,
+ FixedHeight = 2,
+ MinimumHeight = 3,
+ LineDistanceHeight = 4
+ };
+
QTextBlockFormat();
bool isValid() const { return isBlockFormat(); }
@@ -566,6 +578,14 @@ public:
inline int indent() const
{ return intProperty(BlockIndent); }
+ inline void setLineHeight(qreal height, int heightType)
+ { setProperty(LineHeight, height); setProperty(LineHeightType, heightType); }
+ inline qreal lineHeight(qreal scriptLineHeight, qreal scaling) const;
+ inline qreal lineHeight() const
+ { return doubleProperty(LineHeight); }
+ inline int lineHeightType() const
+ { return intProperty(LineHeightType); }
+
inline void setNonBreakableLines(bool b)
{ setProperty(BlockNonBreakableLines, b); }
inline bool nonBreakableLines() const
@@ -590,6 +610,23 @@ inline void QTextBlockFormat::setAlignment(Qt::Alignment aalignment)
inline void QTextBlockFormat::setIndent(int aindent)
{ setProperty(BlockIndent, aindent); }
+inline qreal QTextBlockFormat::lineHeight(qreal scriptLineHeight, qreal scaling = 1.0) const
+{
+ switch(intProperty(LineHeightType)) {
+ case SingleHeight:
+ return(scriptLineHeight);
+ case ProportionalHeight:
+ return(scriptLineHeight * doubleProperty(LineHeight) / 100.0);
+ case FixedHeight:
+ return(doubleProperty(LineHeight) * scaling);
+ case MinimumHeight:
+ return(qMax(scriptLineHeight, doubleProperty(LineHeight) * scaling));
+ case LineDistanceHeight:
+ return(scriptLineHeight + doubleProperty(LineHeight) * scaling);
+ }
+ return(0);
+}
+
class Q_GUI_EXPORT QTextListFormat : public QTextFormat
{
public:
@@ -617,6 +654,14 @@ public:
inline int indent() const
{ return intProperty(ListIndent); }
+ inline void setNumberPrefix(const QString &numberPrefix);
+ inline QString numberPrefix() const
+ { return stringProperty(ListNumberPrefix); }
+
+ inline void setNumberSuffix(const QString &numberSuffix);
+ inline QString numberSuffix() const
+ { return stringProperty(ListNumberSuffix); }
+
protected:
explicit QTextListFormat(const QTextFormat &fmt);
friend class QTextFormat;
@@ -628,6 +673,12 @@ inline void QTextListFormat::setStyle(Style astyle)
inline void QTextListFormat::setIndent(int aindent)
{ setProperty(ListIndent, aindent); }
+inline void QTextListFormat::setNumberPrefix(const QString &np)
+{ setProperty(ListNumberPrefix, np); }
+
+inline void QTextListFormat::setNumberSuffix(const QString &ns)
+{ setProperty(ListNumberSuffix, ns); }
+
class Q_GUI_EXPORT QTextImageFormat : public QTextCharFormat
{
public:
diff --git a/src/gui/text/qtexthtmlparser.cpp b/src/gui/text/qtexthtmlparser.cpp
index e685197c47..3513a280c6 100644
--- a/src/gui/text/qtexthtmlparser.cpp
+++ b/src/gui/text/qtexthtmlparser.cpp
@@ -1250,6 +1250,20 @@ void QTextHtmlParserNode::applyCssDeclarations(const QVector<QCss::Declaration>
case QCss::QtBlockIndent:
blockFormat.setIndent(decl.d->values.first().variant.toInt());
break;
+ case QCss::LineHeight: {
+ qreal lineHeight;
+ if (decl.realValue(&lineHeight, "px")) {
+ blockFormat.setLineHeight(lineHeight, QTextBlockFormat::FixedHeight);
+ } else {
+ bool ok;
+ QString value = decl.d->values.first().toString();
+ lineHeight = value.toDouble(&ok);
+ if (ok)
+ blockFormat.setLineHeight(lineHeight, QTextBlockFormat::ProportionalHeight);
+ else
+ blockFormat.setLineHeight(0, QTextBlockFormat::SingleHeight);
+ }
+ break; }
case QCss::TextIndent: {
qreal indent = 0;
if (decl.realValue(&indent, "px"))
@@ -1323,6 +1337,12 @@ void QTextHtmlParserNode::applyCssDeclarations(const QVector<QCss::Declaration>
case QCss::ListStyle:
setListStyle(decl.d->values);
break;
+ case QCss::QtListNumberPrefix:
+ textListNumberPrefix = decl.d->values.first().variant.toString();
+ break;
+ case QCss::QtListNumberSuffix:
+ textListNumberSuffix = decl.d->values.first().variant.toString();
+ break;
default: break;
}
}
diff --git a/src/gui/text/qtexthtmlparser_p.h b/src/gui/text/qtexthtmlparser_p.h
index 5e2b456c9f..4c44efd851 100644
--- a/src/gui/text/qtexthtmlparser_p.h
+++ b/src/gui/text/qtexthtmlparser_p.h
@@ -180,6 +180,8 @@ struct QTextHtmlParserNode {
uint displayMode : 3; // QTextHtmlElement::DisplayMode
uint hasHref : 1;
QTextListFormat::Style listStyle;
+ QString textListNumberPrefix;
+ QString textListNumberSuffix;
QString imageName;
qreal imageWidth;
qreal imageHeight;
diff --git a/src/gui/text/qtextlayout.cpp b/src/gui/text/qtextlayout.cpp
index a996f59a86..354e8a9c3e 100644
--- a/src/gui/text/qtextlayout.cpp
+++ b/src/gui/text/qtextlayout.cpp
@@ -52,6 +52,8 @@
#include "qtextformat_p.h"
#include "qstyleoption.h"
#include "qpainterpath.h"
+#include "qglyphs.h"
+#include "qglyphs_p.h"
#include <limits.h>
#include <qdebug.h>
@@ -165,7 +167,7 @@ static QFixed alignLine(QTextEngine *eng, const QScriptLine &line)
/*!
Returns the inline object's rectangle.
- \sa ascent() descent() width()
+ \sa ascent(), descent(), width()
*/
QRectF QTextInlineObject::rect() const
{
@@ -176,7 +178,7 @@ QRectF QTextInlineObject::rect() const
/*!
Returns the inline object's width.
- \sa ascent() descent() rect()
+ \sa ascent(), descent(), rect()
*/
qreal QTextInlineObject::width() const
{
@@ -186,7 +188,7 @@ qreal QTextInlineObject::width() const
/*!
Returns the inline object's ascent.
- \sa descent() width() rect()
+ \sa descent(), width(), rect()
*/
qreal QTextInlineObject::ascent() const
{
@@ -196,7 +198,7 @@ qreal QTextInlineObject::ascent() const
/*!
Returns the inline object's descent.
- \sa ascent() width() rect()
+ \sa ascent(), width(), rect()
*/
qreal QTextInlineObject::descent() const
{
@@ -207,18 +209,17 @@ qreal QTextInlineObject::descent() const
Returns the inline object's total height. This is equal to
ascent() + descent() + 1.
- \sa ascent() descent() width() rect()
+ \sa ascent(), descent(), width(), rect()
*/
qreal QTextInlineObject::height() const
{
return eng->layoutData->items[itm].height().toReal();
}
-
/*!
Sets the inline object's width to \a w.
- \sa width() ascent() descent() rect()
+ \sa width(), ascent(), descent(), rect()
*/
void QTextInlineObject::setWidth(qreal w)
{
@@ -228,7 +229,7 @@ void QTextInlineObject::setWidth(qreal w)
/*!
Sets the inline object's ascent to \a a.
- \sa ascent() setDescent() width() rect()
+ \sa ascent(), setDescent(), width(), rect()
*/
void QTextInlineObject::setAscent(qreal a)
{
@@ -238,7 +239,7 @@ void QTextInlineObject::setAscent(qreal a)
/*!
Sets the inline object's decent to \a d.
- \sa descent() setAscent() width() rect()
+ \sa descent(), setAscent(), width(), rect()
*/
void QTextInlineObject::setDescent(qreal d)
{
@@ -246,7 +247,7 @@ void QTextInlineObject::setDescent(qreal d)
}
/*!
- The position of the inline object within the text layout.
+ The position of the inline object within the text layout.
*/
int QTextInlineObject::textPosition() const
{
@@ -254,8 +255,8 @@ int QTextInlineObject::textPosition() const
}
/*!
- Returns an integer describing the format of the inline object
- within the text layout.
+ Returns an integer describing the format of the inline object
+ within the text layout.
*/
int QTextInlineObject::formatIndex() const
{
@@ -263,7 +264,7 @@ int QTextInlineObject::formatIndex() const
}
/*!
- Returns format of the inline object within the text layout.
+ Returns format of the inline object within the text layout.
*/
QTextFormat QTextInlineObject::format() const
{
@@ -273,7 +274,7 @@ QTextFormat QTextInlineObject::format() const
}
/*!
- Returns if the object should be laid out right-to-left or left-to-right.
+ Returns if the object should be laid out right-to-left or left-to-right.
*/
Qt::LayoutDirection QTextInlineObject::textDirection() const
{
@@ -325,7 +326,6 @@ Qt::LayoutDirection QTextInlineObject::textDirection() const
boundingRect(), and a minimumWidth() and a maximumWidth().
\sa QStaticText
-
*/
/*!
@@ -398,16 +398,19 @@ QTextLayout::~QTextLayout()
Sets the layout's font to the given \a font. The layout is
invalidated and must be laid out again.
- \sa text()
+ \sa font()
*/
void QTextLayout::setFont(const QFont &font)
{
d->fnt = font;
+ d->feCache.reset();
}
/*!
Returns the current font that is used for the layout, or a default
font if none is set.
+
+ \sa setFont()
*/
QFont QTextLayout::font() const
{
@@ -441,10 +444,10 @@ QString QTextLayout::text() const
}
/*!
- Sets the text option structure that controls the layout process to the
- given \a option.
+ Sets the text option structure that controls the layout process to the
+ given \a option.
- \sa textOption() QTextOption
+ \sa textOption()
*/
void QTextLayout::setTextOption(const QTextOption &option)
{
@@ -452,9 +455,9 @@ void QTextLayout::setTextOption(const QTextOption &option)
}
/*!
- Returns the current text option used to control the layout process.
+ Returns the current text option used to control the layout process.
- \sa setTextOption() QTextOption
+ \sa setTextOption()
*/
QTextOption QTextLayout::textOption() const
{
@@ -464,6 +467,8 @@ QTextOption QTextLayout::textOption() const
/*!
Sets the \a position and \a text of the area in the layout that is
processed before editing occurs.
+
+ \sa preeditAreaPosition(), preeditAreaText()
*/
void QTextLayout::setPreeditArea(int position, const QString &text)
{
@@ -492,6 +497,8 @@ void QTextLayout::setPreeditArea(int position, const QString &text)
/*!
Returns the position of the area in the text layout that will be
processed before editing occurs.
+
+ \sa preeditAreaText()
*/
int QTextLayout::preeditAreaPosition() const
{
@@ -500,6 +507,8 @@ int QTextLayout::preeditAreaPosition() const
/*!
Returns the text that is inserted in the layout before editing occurs.
+
+ \sa preeditAreaPosition()
*/
QString QTextLayout::preeditAreaText() const
{
@@ -508,8 +517,7 @@ QString QTextLayout::preeditAreaText() const
/*!
- Sets the additional formats supported by the text layout to \a
- formatList.
+ Sets the additional formats supported by the text layout to \a formatList.
\sa additionalFormats(), clearAdditionalFormats()
*/
@@ -535,6 +543,7 @@ void QTextLayout::setAdditionalFormats(const QList<FormatRange> &formatList)
}
if (d->block.docHandle())
d->block.docHandle()->documentChange(d->block.position(), d->block.length());
+ d->feCache.reset();
}
/*!
@@ -599,6 +608,8 @@ bool QTextLayout::cacheEnabled() const
/*!
Begins the layout process.
+
+ \sa endLayout()
*/
void QTextLayout::beginLayout()
{
@@ -616,6 +627,8 @@ void QTextLayout::beginLayout()
/*!
Ends the layout process.
+
+ \sa beginLayout()
*/
void QTextLayout::endLayout()
{
@@ -634,35 +647,33 @@ void QTextLayout::endLayout()
d->freeMemory();
}
-/*! \since 4.4
+/*!
+ \since 4.4
-Clears the line information in the layout. After having called
-this function, lineCount() returns 0.
- */
+ Clears the line information in the layout. After having called
+ this function, lineCount() returns 0.
+*/
void QTextLayout::clearLayout()
{
d->clearLineData();
}
-
/*!
Returns the next valid cursor position after \a oldPos that
respects the given cursor \a mode.
+ Returns value of \a oldPos, if \a oldPos is not a valid cursor position.
- \sa isValidCursorPosition() previousCursorPosition()
+ \sa isValidCursorPosition(), previousCursorPosition()
*/
int QTextLayout::nextCursorPosition(int oldPos, CursorMode mode) const
{
-// qDebug("looking for next cursor pos for %d", oldPos);
const HB_CharAttributes *attributes = d->attributes();
- if (!attributes)
- return 0;
- int len = d->block.isValid() ?
- (d->block.length() - 1)
- : d->layoutData->string.length();
-
- if (oldPos >= len)
+ int len = d->block.isValid() ? d->block.length() - 1
+ : d->layoutData->string.length();
+ Q_ASSERT(len <= d->layoutData->string.length());
+ if (!attributes || oldPos < 0 || oldPos >= len)
return oldPos;
+
if (mode == SkipCharacters) {
oldPos++;
while (oldPos < len && !attributes[oldPos].charStop)
@@ -679,22 +690,23 @@ int QTextLayout::nextCursorPosition(int oldPos, CursorMode mode) const
while (oldPos < len && d->atSpace(oldPos))
oldPos++;
}
-// qDebug(" -> %d", oldPos);
+
return oldPos;
}
/*!
Returns the first valid cursor position before \a oldPos that
respects the given cursor \a mode.
+ Returns value of \a oldPos, if \a oldPos is not a valid cursor position.
- \sa isValidCursorPosition() nextCursorPosition()
+ \sa isValidCursorPosition(), nextCursorPosition()
*/
int QTextLayout::previousCursorPosition(int oldPos, CursorMode mode) const
{
-// qDebug("looking for previous cursor pos for %d", oldPos);
const HB_CharAttributes *attributes = d->attributes();
- if (!attributes || oldPos <= 0)
- return 0;
+ if (!attributes || oldPos <= 0 || oldPos > d->layoutData->string.length())
+ return oldPos;
+
if (mode == SkipCharacters) {
oldPos--;
while (oldPos && !attributes[oldPos].charStop)
@@ -712,7 +724,7 @@ int QTextLayout::previousCursorPosition(int oldPos, CursorMode mode) const
oldPos--;
}
}
-// qDebug(" -> %d", oldPos);
+
return oldPos;
}
@@ -739,7 +751,6 @@ bool QTextLayout::isValidCursorPosition(int pos) const
return attributes[pos].charStop;
}
-
/*!
Returns a new text line to be laid out if there is text to be
inserted into the layout; otherwise returns an invalid text line.
@@ -801,7 +812,7 @@ int QTextLayout::lineCount() const
/*!
Returns the \a{i}-th line of text in this text layout.
- \sa lineCount() lineForTextPosition()
+ \sa lineCount(), lineForTextPosition()
*/
QTextLine QTextLayout::lineAt(int i) const
{
@@ -811,7 +822,7 @@ QTextLine QTextLayout::lineAt(int i) const
/*!
Returns the line that contains the cursor position specified by \a pos.
- \sa isValidCursorPosition() lineAt()
+ \sa isValidCursorPosition(), lineAt()
*/
QTextLine QTextLayout::lineForTextPosition(int pos) const
{
@@ -902,8 +913,9 @@ qreal QTextLayout::maximumWidth() const
return d->maxWidth.toReal();
}
+
/*!
- \internal
+ \internal
*/
void QTextLayout::setFlags(int flags)
{
@@ -1028,6 +1040,35 @@ QScriptItem &QTextLineItemIterator::next()
return *si;
}
+static QFixed offsetInLigature(const unsigned short *logClusters,
+ const QGlyphLayout &glyphs,
+ int pos, int max, int glyph_pos)
+{
+ int offsetInCluster = 0;
+ for (int i = pos - 1; i >= 0; i--) {
+ if (logClusters[i] == glyph_pos)
+ offsetInCluster++;
+ else
+ break;
+ }
+
+ // in the case that the offset is inside a (multi-character) glyph,
+ // interpolate the position.
+ if (offsetInCluster > 0) {
+ int clusterLength = 0;
+ for (int i = pos - offsetInCluster; i < max; i++) {
+ if (logClusters[i] == glyph_pos)
+ clusterLength++;
+ else
+ break;
+ }
+ if (clusterLength)
+ return glyphs.advances_x[glyph_pos] * offsetInCluster / clusterLength;
+ }
+
+ return 0;
+}
+
bool QTextLineItemIterator::getSelectionBounds(QFixed *selectionX, QFixed *selectionWidth) const
{
*selectionX = *selectionWidth = 0;
@@ -1067,8 +1108,19 @@ bool QTextLineItemIterator::getSelectionBounds(QFixed *selectionX, QFixed *selec
swidth += glyphs.effectiveAdvance(g);
}
- *selectionX = x + soff;
- *selectionWidth = swidth;
+ // If the starting character is in the middle of a ligature,
+ // selection should only contain the right part of that ligature
+ // glyph, so we need to get the width of the left part here and
+ // add it to *selectionX
+ QFixed leftOffsetInLigature = offsetInLigature(logClusters, glyphs, from,
+ to, start_glyph);
+ *selectionX = x + soff + leftOffsetInLigature;
+ *selectionWidth = swidth - leftOffsetInLigature;
+ // If the ending character is also part of a ligature, swidth does
+ // not contain that part yet, we also need to find out the width of
+ // that left part
+ *selectionWidth += offsetInLigature(logClusters, glyphs, to,
+ eng->length(item), end_glyph);
}
return true;
}
@@ -1114,9 +1166,26 @@ static inline QRectF clipIfValid(const QRectF &rect, const QRectF &clip)
return clip.isValid() ? (rect & clip) : rect;
}
+
+/*!
+ Returns the glyph indexes and positions for all glyphs in this QTextLayout. This is an
+ expensive function, and should not be called in a time sensitive context.
+
+ \since 4.8
+
+ \sa draw(), QPainter::drawGlyphs()
+*/
+QList<QGlyphs> QTextLayout::glyphs() const
+{
+ QList<QGlyphs> glyphs;
+ for (int i=0; i<d->lines.size(); ++i)
+ glyphs += QTextLine(i, d).glyphs(-1, -1);
+
+ return glyphs;
+}
+
/*!
- Draws the whole layout on the painter \a p at the position specified by
- \a pos.
+ Draws the whole layout on the painter \a p at the position specified by \a pos.
The rendered layout includes the given \a selections and is clipped within
the rectangle specified by \a clip.
*/
@@ -1290,12 +1359,12 @@ void QTextLayout::draw(QPainter *p, const QPointF &pos, const QVector<FormatRang
}
/*!
- \fn void QTextLayout::drawCursor(QPainter *painter, const QPointF &position, int cursorPosition) const
- \overload
+ \fn void QTextLayout::drawCursor(QPainter *painter, const QPointF &position, int cursorPosition) const
+ \overload
- Draws a text cursor with the current pen at the given \a position using the
- \a painter specified.
- The corresponding position within the text is specified by \a cursorPosition.
+ Draws a text cursor with the current pen at the given \a position using the
+ \a painter specified.
+ The corresponding position within the text is specified by \a cursorPosition.
*/
void QTextLayout::drawCursor(QPainter *p, const QPointF &pos, int cursorPosition) const
{
@@ -1303,11 +1372,11 @@ void QTextLayout::drawCursor(QPainter *p, const QPointF &pos, int cursorPosition
}
/*!
- \fn void QTextLayout::drawCursor(QPainter *painter, const QPointF &position, int cursorPosition, int width) const
+ \fn void QTextLayout::drawCursor(QPainter *painter, const QPointF &position, int cursorPosition, int width) const
- Draws a text cursor with the current pen and the specified \a width at the given \a position using the
- \a painter specified.
- The corresponding position within the text is specified by \a cursorPosition.
+ Draws a text cursor with the current pen and the specified \a width at the given \a position using the
+ \a painter specified.
+ The corresponding position within the text is specified by \a cursorPosition.
*/
void QTextLayout::drawCursor(QPainter *p, const QPointF &pos, int cursorPosition, int width) const
{
@@ -1438,7 +1507,7 @@ void QTextLayout::drawCursor(QPainter *p, const QPointF &pos, int cursorPosition
/*!
Returns the line's bounding rectangle.
- \sa x() y() textLength() width()
+ \sa x(), y(), textLength(), width()
*/
QRectF QTextLine::rect() const
{
@@ -1464,7 +1533,7 @@ QRectF QTextLine::naturalTextRect() const
/*!
Returns the line's x position.
- \sa rect() y() textLength() width()
+ \sa rect(), y(), textLength(), width()
*/
qreal QTextLine::x() const
{
@@ -1474,7 +1543,7 @@ qreal QTextLine::x() const
/*!
Returns the line's y position.
- \sa x() rect() textLength() width()
+ \sa x(), rect(), textLength(), width()
*/
qreal QTextLine::y() const
{
@@ -1484,7 +1553,7 @@ qreal QTextLine::y() const
/*!
Returns the line's width as specified by the layout() function.
- \sa naturalTextWidth() x() y() textLength() rect()
+ \sa naturalTextWidth(), x(), y(), textLength(), rect()
*/
qreal QTextLine::width() const
{
@@ -1495,7 +1564,7 @@ qreal QTextLine::width() const
/*!
Returns the line's ascent.
- \sa descent() height()
+ \sa descent(), height()
*/
qreal QTextLine::ascent() const
{
@@ -1505,7 +1574,7 @@ qreal QTextLine::ascent() const
/*!
Returns the line's descent.
- \sa ascent() height()
+ \sa ascent(), height()
*/
qreal QTextLine::descent() const
{
@@ -1517,7 +1586,7 @@ qreal QTextLine::descent() const
if leading is not included. If leading is included, this equals to
ascent() + descent() + leading() + 1.
- \sa ascent() descent() leading() setLeadingIncluded()
+ \sa ascent(), descent(), leading(), setLeadingIncluded()
*/
qreal QTextLine::height() const
{
@@ -1529,24 +1598,25 @@ qreal QTextLine::height() const
Returns the line's leading.
- \sa ascent() descent() height()
+ \sa ascent(), descent(), height()
*/
qreal QTextLine::leading() const
{
return eng->lines[i].leading.toReal();
}
-/*! \since 4.6
+/*!
+ \since 4.6
- Includes positive leading into the line's height if \a included is true;
- otherwise does not include leading.
+ Includes positive leading into the line's height if \a included is true;
+ otherwise does not include leading.
- By default, leading is not included.
+ By default, leading is not included.
- Note that negative leading is ignored, it must be handled
- in the code using the text lines by letting the lines overlap.
+ Note that negative leading is ignored, it must be handled
+ in the code using the text lines by letting the lines overlap.
- \sa leadingIncluded()
+ \sa leadingIncluded()
*/
void QTextLine::setLeadingIncluded(bool included)
@@ -1555,20 +1625,21 @@ void QTextLine::setLeadingIncluded(bool included)
}
-/*! \since 4.6
+/*!
+ \since 4.6
- Returns true if positive leading is included into the line's height; otherwise returns false.
+ Returns true if positive leading is included into the line's height;
+ otherwise returns false.
- By default, leading is not included.
+ By default, leading is not included.
- \sa setLeadingIncluded()
+ \sa setLeadingIncluded()
*/
bool QTextLine::leadingIncluded() const
{
return eng->lines[i].leadingIncluded;
}
-
/*!
Returns the width of the line that is occupied by text. This is
always \<= to width(), and is the minimum width that could be used
@@ -1579,14 +1650,15 @@ qreal QTextLine::naturalTextWidth() const
return eng->lines[i].textWidth.toReal();
}
-/*! \since 4.7
- Returns the horizontal advance of the text. The advance of the text
- is the distance from its position to the next position at which
- text would naturally be drawn.
+/*!
+ \since 4.7
+ Returns the horizontal advance of the text. The advance of the text
+ is the distance from its position to the next position at which
+ text would naturally be drawn.
- By adding the advance to the position of the text line and using this
- as the position of a second text line, you will be able to position
- the two lines side-by-side without gaps in-between.
+ By adding the advance to the position of the text line and using this
+ as the position of a second text line, you will be able to position
+ the two lines side-by-side without gaps in-between.
*/
qreal QTextLine::horizontalAdvance() const
{
@@ -1764,7 +1836,8 @@ static inline void addNextCluster(int &pos, int end, QScriptLine &line, int &gly
++line.length;
} while (pos < end && logClusters[pos] == glyphPosition);
do { // calculate the textWidth for the rest of the current cluster.
- line.textWidth += glyphs.advances_x[glyphPosition] * !glyphs.attributes[glyphPosition].dontPrint;
+ if (!glyphs.attributes[glyphPosition].dontPrint)
+ line.textWidth += glyphs.advances_x[glyphPosition];
++glyphPosition;
} while (glyphPosition < current.num_glyphs && !glyphs.attributes[glyphPosition].clusterStart);
@@ -1842,14 +1915,14 @@ void QTextLine::layout_helper(int maxGlyphs)
lbh.currentPosition = qMax(line.from, current.position);
end = current.position + eng->length(item);
lbh.glyphs = eng->shapedGlyphs(&current);
+ QFontEngine *fontEngine = eng->fontEngine(current);
+ if (lbh.fontEngine != fontEngine) {
+ lbh.fontEngine = fontEngine;
+ lbh.minimumRightBearing = qMin(QFixed(),
+ QFixed::fromReal(fontEngine->minRightBearing()));
+ }
}
const QScriptItem &current = eng->layoutData->items[item];
- QFontEngine *fontEngine = eng->fontEngine(current);
- if (lbh.fontEngine != fontEngine) {
- lbh.fontEngine = fontEngine;
- lbh.minimumRightBearing = qMin(QFixed(),
- QFixed::fromReal(fontEngine->minRightBearing()));
- }
lbh.tmpData.leading = qMax(lbh.tmpData.leading + lbh.tmpData.ascent,
current.leading + current.ascent) - qMax(lbh.tmpData.ascent,
@@ -2014,9 +2087,10 @@ found:
eng->maxWidth += lbh.spaceData.textWidth;
if (eng->option.flags() & QTextOption::IncludeTrailingSpaces)
line.textWidth += lbh.spaceData.textWidth;
- line.length += lbh.spaceData.length;
- if (lbh.spaceData.length)
+ if (lbh.spaceData.length) {
+ line.length += lbh.spaceData.length;
line.hasTrailingSpaces = true;
+ }
line.justified = false;
line.gridfitted = false;
@@ -2170,6 +2244,151 @@ static void setPenAndDrawBackground(QPainter *p, const QPen &defaultPen, const Q
}
+namespace {
+ struct GlyphInfo
+ {
+ GlyphInfo(const QGlyphLayout &layout, const QPointF &position,
+ const QTextItemInt::RenderFlags &renderFlags)
+ : glyphLayout(layout), itemPosition(position), flags(renderFlags)
+ {
+ }
+
+ QGlyphLayout glyphLayout;
+ QPointF itemPosition;
+ QTextItem::RenderFlags flags;
+ };
+}
+
+/*!
+ \internal
+
+ Returns the glyph indexes and positions for all glyphs in this QTextLine which reside in
+ QScriptItems that overlap with the range defined by \a from and \a length. The arguments
+ specify characters, relative to the text in the layout. Note that it is not possible to
+ use this function to retrieve a subset of the glyphs in a QScriptItem.
+
+ \since 4.8
+
+ \sa QTextLayout::glyphs()
+*/
+QList<QGlyphs> QTextLine::glyphs(int from, int length) const
+{
+ const QScriptLine &line = eng->lines[i];
+
+ if (line.length == 0)
+ return QList<QGlyphs>();
+
+ QHash<QFontEngine *, GlyphInfo> glyphLayoutHash;
+
+ QTextLineItemIterator iterator(eng, i);
+ qreal y = line.y.toReal() + line.base().toReal();
+ while (!iterator.atEnd()) {
+ QScriptItem &si = iterator.next();
+ if (si.analysis.flags >= QScriptAnalysis::TabOrObject)
+ continue;
+
+ QPointF pos(iterator.x.toReal(), y);
+ if (from >= 0 && length >= 0 &&
+ (from >= si.position + eng->length(&si) || from + length <= si.position))
+ continue;
+
+ QFont font = eng->font(si);
+
+ QTextItem::RenderFlags flags;
+ if (font.overline())
+ flags |= QTextItem::Overline;
+ if (font.underline())
+ flags |= QTextItem::Underline;
+ if (font.strikeOut())
+ flags |= QTextItem::StrikeOut;
+ if (si.analysis.bidiLevel % 2)
+ flags |= QTextItem::RightToLeft;
+
+ QGlyphLayout glyphLayout = eng->shapedGlyphs(&si).mid(iterator.glyphsStart,
+ iterator.glyphsEnd - iterator.glyphsStart);
+
+ if (glyphLayout.numGlyphs > 0) {
+ QFontEngine *mainFontEngine = font.d->engineForScript(si.analysis.script);
+ if (mainFontEngine->type() == QFontEngine::Multi) {
+ QFontEngineMulti *multiFontEngine = static_cast<QFontEngineMulti *>(mainFontEngine);
+ int start = 0;
+ int end;
+ int which = glyphLayout.glyphs[0] >> 24;
+ for (end = 0; end < glyphLayout.numGlyphs; ++end) {
+ const int e = glyphLayout.glyphs[end] >> 24;
+ if (e == which)
+ continue;
+
+ QGlyphLayout subLayout = glyphLayout.mid(start, end - start);
+ glyphLayoutHash.insertMulti(multiFontEngine->engine(which),
+ GlyphInfo(subLayout, pos, flags));
+
+ start = end;
+ which = e;
+ }
+
+ QGlyphLayout subLayout = glyphLayout.mid(start, end - start);
+ glyphLayoutHash.insertMulti(multiFontEngine->engine(which),
+ GlyphInfo(subLayout, pos, flags));
+
+ } else {
+ glyphLayoutHash.insertMulti(mainFontEngine,
+ GlyphInfo(glyphLayout, pos, flags));
+ }
+ }
+ }
+
+ QHash<QPair<QFontEngine *, int>, QGlyphs> glyphsHash;
+
+ QList<QFontEngine *> keys = glyphLayoutHash.uniqueKeys();
+ for (int i=0; i<keys.size(); ++i) {
+ QFontEngine *fontEngine = keys.at(i);
+
+ // Make a font for this particular engine
+ QFont font = fontEngine->createExplicitFont();
+
+ QList<GlyphInfo> glyphLayouts = glyphLayoutHash.values(fontEngine);
+ for (int j=0; j<glyphLayouts.size(); ++j) {
+ const QPointF &pos = glyphLayouts.at(j).itemPosition;
+ const QGlyphLayout &glyphLayout = glyphLayouts.at(j).glyphLayout;
+ const QTextItem::RenderFlags &flags = glyphLayouts.at(j).flags;
+
+ font.setOverline(flags.testFlag(QTextItem::Overline));
+ font.setUnderline(flags.testFlag(QTextItem::Underline));
+ font.setStrikeOut(flags.testFlag(QTextItem::StrikeOut));
+
+ QVarLengthArray<glyph_t> glyphsArray;
+ QVarLengthArray<QFixedPoint> positionsArray;
+
+ fontEngine->getGlyphPositions(glyphLayout, QTransform(), flags, glyphsArray,
+ positionsArray);
+ Q_ASSERT(glyphsArray.size() == positionsArray.size());
+
+ QVector<quint32> glyphs;
+ QVector<QPointF> positions;
+ for (int i=0; i<glyphsArray.size(); ++i) {
+ glyphs.append(glyphsArray.at(i) & 0xffffff);
+ positions.append(positionsArray.at(i).toPointF() + pos);
+ }
+
+ QGlyphs glyphIndexes;
+ glyphIndexes.setGlyphIndexes(glyphs);
+ glyphIndexes.setPositions(positions);
+
+ QPair<QFontEngine *, int> key(fontEngine, int(flags));
+
+ if (!glyphsHash.contains(key))
+ glyphsHash.insert(key, QGlyphs());
+
+ QGlyphs &target = glyphsHash[key];
+ target += glyphIndexes;
+ target.setFont(font);
+ }
+ }
+
+ return glyphsHash.values();
+}
+
/*!
\fn void QTextLine::draw(QPainter *painter, const QPointF &position, const QTextLayout::FormatRange *selection) const
@@ -2219,8 +2438,12 @@ void QTextLine::draw(QPainter *p, const QPointF &pos, const QTextLayout::FormatR
QTextCharFormat format;
if (eng->hasFormats() || selection) {
- if (!suppressColors)
- format = eng->format(&si);
+ format = eng->format(&si);
+ if (suppressColors) {
+ format.clearForeground();
+ format.clearBackground();
+ format.clearProperty(QTextFormat::TextUnderlineColor);
+ }
if (selection)
format.merge(selection->format);
@@ -2366,21 +2589,20 @@ void QTextLine::draw(QPainter *p, const QPointF &pos, const QTextLayout::FormatR
}
/*!
- \fn int QTextLine::cursorToX(int cursorPos, Edge edge) const
+ \fn int QTextLine::cursorToX(int cursorPos, Edge edge) const
- \overload
+ \overload
*/
-
/*!
- Converts the cursor position \a cursorPos to the corresponding x position
- inside the line, taking account of the \a edge.
+ Converts the cursor position \a cursorPos to the corresponding x position
+ inside the line, taking account of the \a edge.
- If \a cursorPos is not a valid cursor position, the nearest valid
- cursor position will be used instead, and cpos will be modified to
- point to this valid cursor position.
+ If \a cursorPos is not a valid cursor position, the nearest valid
+ cursor position will be used instead, and cpos will be modified to
+ point to this valid cursor position.
- \sa xToCursor()
+ \sa xToCursor()
*/
qreal QTextLine::cursorToX(int *cursorPos, Edge edge) const
{
@@ -2479,14 +2701,6 @@ qreal QTextLine::cursorToX(int *cursorPos, Edge edge) const
if(pos == l)
x += si->width;
} else {
- int offsetInCluster = 0;
- for (int i=pos-1; i >= 0; i--) {
- if (logClusters[i] == glyph_pos)
- offsetInCluster++;
- else
- break;
- }
-
if (reverse) {
int end = qMin(lineEnd, si->position + l) - si->position;
int glyph_end = end == l ? si->num_glyphs : logClusters[end];
@@ -2498,17 +2712,7 @@ qreal QTextLine::cursorToX(int *cursorPos, Edge edge) const
for (int i = glyph_start; i < glyph_pos; i++)
x += glyphs.effectiveAdvance(i);
}
- if (offsetInCluster > 0) { // in the case that the offset is inside a (multi-character) glyph, interpolate the position.
- int clusterLength = 0;
- for (int i=pos - offsetInCluster; i < line.length; i++) {
- if (logClusters[i] == glyph_pos)
- clusterLength++;
- else
- break;
- }
- if (clusterLength)
- x+= glyphs.advances_x[glyph_pos] * offsetInCluster / clusterLength;
- }
+ x += offsetInLigature(logClusters, glyphs, pos, line.length, glyph_pos);
}
*cursorPos = pos + si->position;
@@ -2516,12 +2720,12 @@ qreal QTextLine::cursorToX(int *cursorPos, Edge edge) const
}
/*!
- \fn int QTextLine::xToCursor(qreal x, CursorPosition cpos) const
+ \fn int QTextLine::xToCursor(qreal x, CursorPosition cpos) const
- Converts the x-coordinate \a x, to the nearest matching cursor
- position, depending on the cursor position type, \a cpos.
+ Converts the x-coordinate \a x, to the nearest matching cursor
+ position, depending on the cursor position type, \a cpos.
- \sa cursorToX()
+ \sa cursorToX()
*/
int QTextLine::xToCursor(qreal _x, CursorPosition cpos) const
{
diff --git a/src/gui/text/qtextlayout.h b/src/gui/text/qtextlayout.h
index 44451ecbd2..0f64c338d5 100644
--- a/src/gui/text/qtextlayout.h
+++ b/src/gui/text/qtextlayout.h
@@ -49,6 +49,7 @@
#include <QtCore/qobject.h>
#include <QtGui/qevent.h>
#include <QtGui/qtextformat.h>
+#include <QtGui/qglyphs.h>
QT_BEGIN_HEADER
@@ -166,6 +167,8 @@ public:
qreal minimumWidth() const;
qreal maximumWidth() const;
+ QList<QGlyphs> glyphs() const;
+
QTextEngine *engine() const { return d; }
void setFlags(int flags);
private:
@@ -236,7 +239,10 @@ public:
private:
QTextLine(int line, QTextEngine *e) : i(line), eng(e) {}
void layout_helper(int numGlyphs);
+ QList<QGlyphs> glyphs(int from, int length) const;
+
friend class QTextLayout;
+ friend class QTextFragment;
int i;
QTextEngine *eng;
};
diff --git a/src/gui/text/qtextlist.cpp b/src/gui/text/qtextlist.cpp
index 3528d932ed..21935aa915 100644
--- a/src/gui/text/qtextlist.cpp
+++ b/src/gui/text/qtextlist.cpp
@@ -191,6 +191,13 @@ QString QTextList::itemText(const QTextBlock &blockIt) const
QString result;
const int style = format().style();
+ QString numberPrefix;
+ QString numberSuffix = QLatin1String(".");
+
+ if (format().hasProperty(QTextFormat::ListNumberPrefix))
+ numberPrefix = format().numberPrefix();
+ if (format().hasProperty(QTextFormat::ListNumberSuffix))
+ numberSuffix = format().numberSuffix();
switch (style) {
case QTextListFormat::ListDecimal:
@@ -232,7 +239,7 @@ QString QTextList::itemText(const QTextBlock &blockIt) const
if (q > 0) {
int startDigit = i + (i+3)/4;
int numDigits;
- if (i % 4) {
+ if (i % 4) {
// c[i] == 4|5|9|40|50|90|400|500|900
if ((i-2) % 4) {
// c[i] == 4|9|40|90|400|900 => with subtraction (IV, IX, XL, XC, ...)
@@ -263,8 +270,9 @@ QString QTextList::itemText(const QTextBlock &blockIt) const
Q_ASSERT(false);
}
if (blockIt.textDirection() == Qt::RightToLeft)
- return result.prepend(QLatin1Char('.'));
- return result + QLatin1Char('.');
+ return numberSuffix + result + numberPrefix;
+ else
+ return numberPrefix + result + numberSuffix;
}
/*!
diff --git a/src/gui/text/qtextobject.cpp b/src/gui/text/qtextobject.cpp
index e323fd0f64..c5b6e14a74 100644
--- a/src/gui/text/qtextobject.cpp
+++ b/src/gui/text/qtextobject.cpp
@@ -1655,6 +1655,35 @@ QTextBlock::iterator &QTextBlock::iterator::operator--()
than the \a other text fragment; otherwise returns false.
*/
+/*!
+ Returns the glyphs of this text fragment. The positions of the glyphs are
+ relative to the position of the QTextBlock's layout.
+
+ \sa QGlyphs, QTextBlock::layout(), QTextLayout::position(), QPainter::drawGlyphs()
+*/
+QList<QGlyphs> QTextFragment::glyphs() const
+{
+ if (!p || !n)
+ return QList<QGlyphs>();
+
+ int pos = position();
+ int len = length();
+ if (len == 0)
+ return QList<QGlyphs>();
+
+ int blockNode = p->blockMap().findNode(pos);
+
+ const QTextBlockData *blockData = p->blockMap().fragment(blockNode);
+ QTextLayout *layout = blockData->layout;
+
+ QList<QGlyphs> ret;
+ for (int i=0; i<layout->lineCount(); ++i) {
+ QTextLine textLine = layout->lineAt(i);
+ ret += textLine.glyphs(pos, len);
+ }
+
+ return ret;
+}
/*!
Returns the position of this text fragment in the document.
diff --git a/src/gui/text/qtextobject.h b/src/gui/text/qtextobject.h
index d5c1e8df79..fface3ffea 100644
--- a/src/gui/text/qtextobject.h
+++ b/src/gui/text/qtextobject.h
@@ -44,6 +44,7 @@
#include <QtCore/qobject.h>
#include <QtGui/qtextformat.h>
+#include <QtGui/qglyphs.h>
QT_BEGIN_HEADER
@@ -315,6 +316,8 @@ public:
int charFormatIndex() const;
QString text() const;
+ QList<QGlyphs> glyphs() const;
+
private:
const QTextDocumentPrivate *p;
int n;
diff --git a/src/gui/text/qtextodfwriter.cpp b/src/gui/text/qtextodfwriter.cpp
index 0c9655b6fd..c2e47f3df6 100644
--- a/src/gui/text/qtextodfwriter.cpp
+++ b/src/gui/text/qtextodfwriter.cpp
@@ -636,7 +636,15 @@ void QTextOdfWriter::writeListFormat(QXmlStreamWriter &writer, QTextListFormat f
|| style == QTextListFormat::ListUpperRoman) {
writer.writeStartElement(textNS, QString::fromLatin1("list-level-style-number"));
writer.writeAttribute(styleNS, QString::fromLatin1("num-format"), bulletChar(style));
- writer.writeAttribute(styleNS, QString::fromLatin1("num-suffix"), QString::fromLatin1("."));
+
+ if (format.hasProperty(QTextFormat::ListNumberSuffix))
+ writer.writeAttribute(styleNS, QString::fromLatin1("num-suffix"), format.numberSuffix());
+ else
+ writer.writeAttribute(styleNS, QString::fromLatin1("num-suffix"), QString::fromLatin1("."));
+
+ if (format.hasProperty(QTextFormat::ListNumberPrefix))
+ writer.writeAttribute(styleNS, QString::fromLatin1("num-prefix"), format.numberPrefix());
+
} else {
writer.writeStartElement(textNS, QString::fromLatin1("list-level-style-bullet"));
writer.writeAttribute(textNS, QString::fromLatin1("bullet-char"), bulletChar(style));
diff --git a/src/gui/text/text.pri b/src/gui/text/text.pri
index af8daa5d99..daafdd9db4 100644
--- a/src/gui/text/text.pri
+++ b/src/gui/text/text.pri
@@ -25,7 +25,7 @@ HEADERS += \
text/qabstracttextdocumentlayout.h \
text/qtextdocumentlayout_p.h \
text/qtextcursor.h \
- text/qtextcursor_p.h \
+ text/qtextcursor_p.h \
text/qtextdocumentfragment.h \
text/qtextdocumentfragment_p.h \
text/qtextimagehandler_p.h \
@@ -39,7 +39,9 @@ HEADERS += \
text/qzipwriter_p.h \
text/qtextodfwriter_p.h \
text/qstatictext_p.h \
- text/qstatictext.h
+ text/qstatictext.h \
+ text/qglyphs.h \
+ text/qglyphs_p.h
SOURCES += \
text/qfont.cpp \
@@ -69,7 +71,8 @@ SOURCES += \
text/qcssparser.cpp \
text/qzip.cpp \
text/qtextodfwriter.cpp \
- text/qstatictext.cpp
+ text/qstatictext.cpp \
+ text/qglyphs.cpp
win32 {
SOURCES += \
@@ -89,10 +92,16 @@ unix:x11 {
text/qfontengine_ft.cpp
}
-!embedded:!x11:mac {
+!embedded:!qpa:!x11:mac {
+ HEADERS += \
+ text/qfontengine_mac_p.h
+ OBJECTIVE_HEADERS += \
+ text/qfontengine_coretext_p.h
SOURCES += \
- text/qfont_mac.cpp
- OBJECTIVE_SOURCES += text/qfontengine_mac.mm
+ text/qfont_mac.cpp
+ OBJECTIVE_SOURCES += \
+ text/qfontengine_coretext.mm \
+ text/qfontengine_mac.mm
}
embedded {
@@ -110,6 +119,19 @@ embedded {
DEFINES += QT_NO_FONTCONFIG
}
+qpa {
+ SOURCES += \
+ text/qfont_qpa.cpp \
+ text/qfontengine_qpa.cpp \
+ text/qplatformfontdatabase_qpa.cpp
+
+ HEADERS += \
+ text/qplatformfontdatabase_qpa.h
+
+ DEFINES += QT_NO_FONTCONFIG
+ DEFINES += QT_NO_FREETYPE
+}
+
symbian {
SOURCES += \
text/qfont_s60.cpp
@@ -129,6 +151,7 @@ symbian {
}
}
+!qpa {
contains(QT_CONFIG, freetype) {
SOURCES += \
../3rdparty/freetype/src/base/ftbase.c \
@@ -202,6 +225,7 @@ contains(QT_CONFIG, freetype) {
contains(QT_CONFIG, fontconfig) {
CONFIG += opentype
}
+}#!qpa
DEFINES += QT_NO_OPENTYPE
INCLUDEPATH += ../3rdparty/harfbuzz/src