Fix uses of qRound on non-floating-point types.
[profile/ivi/qtbase.git] / src / gui / text / qfontengine_s60.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of the QtGui module of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 **
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 **
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
29 **
30 ** Other Usage
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qfontengine_s60_p.h"
43 #include "qtextengine_p.h"
44 #include "qendian.h"
45 #include "qglobal.h"
46 #include <private/qapplication_p.h>
47 #include "qimage.h"
48 #include <private/qt_s60_p.h>
49 #include <private/qpixmap_s60_p.h>
50
51 #include <e32base.h>
52 #include <e32std.h>
53 #include <eikenv.h>
54 #include <gdi.h>
55 #if defined(Q_SYMBIAN_HAS_GLYPHOUTLINE_API)
56 #include <graphics/gdi/gdiplatapi.h>
57 #endif // Q_SYMBIAN_HAS_GLYPHOUTLINE_API
58
59 // Replication of TGetFontTableParam & friends.
60 // There is unfortunately no compile time flag like SYMBIAN_FONT_TABLE_API
61 // that would help us to only replicate these things for Symbian versions
62 // that do not yet have the font table Api. Symbian's public SDK does
63 // generally not define any usable macros.
64 class QSymbianTGetFontTableParam
65 {
66 public:
67     TUint32 iTag;
68     TAny *iContent;
69     TInt iLength;
70 };
71 const TUid QSymbianKFontGetFontTable      = {0x102872C1};
72 const TUid QSymbianKFontReleaseFontTable  = {0x2002AC24};
73
74 QT_BEGIN_NAMESPACE
75
76 QSymbianTypeFaceExtras::QSymbianTypeFaceExtras(CFont* cFont, COpenFont *openFont)
77     : m_cFont(cFont)
78     , m_symbolCMap(false)
79     , m_openFont(openFont)
80 {
81     if (!symbianFontTableApiAvailable()) {
82         TAny *trueTypeExtension = NULL;
83         m_openFont->ExtendedInterface(KUidOpenFontTrueTypeExtension, trueTypeExtension);
84         m_trueTypeExtension = static_cast<MOpenFontTrueTypeExtension*>(trueTypeExtension);
85         Q_ASSERT(m_trueTypeExtension);
86     }
87 }
88
89 QSymbianTypeFaceExtras::~QSymbianTypeFaceExtras()
90 {
91     if (symbianFontTableApiAvailable())
92         S60->screenDevice()->ReleaseFont(m_cFont);
93 }
94
95 QByteArray QSymbianTypeFaceExtras::getSfntTable(uint tag) const
96 {
97     if (symbianFontTableApiAvailable()) {
98         QSymbianTGetFontTableParam fontTableParams = { tag, 0, 0 };
99         if (m_cFont->ExtendedFunction(QSymbianKFontGetFontTable, &fontTableParams) == KErrNone) {
100             const char* const fontTableContent =
101                     static_cast<const char *>(fontTableParams.iContent);
102             const QByteArray fontTable(fontTableContent, fontTableParams.iLength);
103             m_cFont->ExtendedFunction(QSymbianKFontReleaseFontTable, &fontTableParams);
104             return fontTable;
105         }
106         return QByteArray();
107     } else {
108         Q_ASSERT(m_trueTypeExtension->HasTrueTypeTable(tag));
109         TInt error = KErrNone;
110         TInt tableByteLength = 0;
111         TAny *table = m_trueTypeExtension->GetTrueTypeTable(error, tag, &tableByteLength);
112         Q_CHECK_PTR(table);
113         const QByteArray result(static_cast<const char*>(table), tableByteLength);
114         m_trueTypeExtension->ReleaseTrueTypeTable(table);
115         return result;
116     }
117 }
118
119 bool QSymbianTypeFaceExtras::getSfntTableData(uint tag, uchar *buffer, uint *length) const
120 {
121     bool result = true;
122     if (symbianFontTableApiAvailable()) {
123         QSymbianTGetFontTableParam fontTableParams = { tag, 0, 0 };
124         if (m_cFont->ExtendedFunction(QSymbianKFontGetFontTable, &fontTableParams) == KErrNone) {
125             if (*length > 0 && *length < fontTableParams.iLength) {
126                 result = false; // Caller did not allocate enough memory
127             } else {
128                 *length = fontTableParams.iLength;
129                 if (buffer)
130                     memcpy(buffer, fontTableParams.iContent, fontTableParams.iLength);
131             }
132             m_cFont->ExtendedFunction(QSymbianKFontReleaseFontTable, &fontTableParams);
133         } else {
134             result = false;
135         }
136     } else {
137         if (!m_trueTypeExtension->HasTrueTypeTable(tag))
138             return false;
139
140         TInt error = KErrNone;
141         TInt tableByteLength;
142         TAny *table = m_trueTypeExtension->GetTrueTypeTable(error, tag, &tableByteLength);
143         Q_CHECK_PTR(table);
144
145         if (error != KErrNone) {
146             return false;
147         } else if (*length > 0 && *length < tableByteLength) {
148             result = false; // Caller did not allocate enough memory
149         } else {
150             *length = tableByteLength;
151             if (buffer)
152                 memcpy(buffer, table, tableByteLength);
153         }
154
155         m_trueTypeExtension->ReleaseTrueTypeTable(table);
156     }
157     return result;
158 }
159
160 const uchar *QSymbianTypeFaceExtras::cmap() const
161 {
162     if (m_cmapTable.isNull()) {
163         const QByteArray cmapTable = getSfntTable(MAKE_TAG('c', 'm', 'a', 'p'));
164         int size = 0;
165         const uchar *cmap = QFontEngine::getCMap(reinterpret_cast<const uchar *>
166                 (cmapTable.constData()), cmapTable.size(), &m_symbolCMap, &size);
167         m_cmapTable = QByteArray(reinterpret_cast<const char *>(cmap), size);
168     }
169     return reinterpret_cast<const uchar *>(m_cmapTable.constData());
170 }
171
172 bool QSymbianTypeFaceExtras::isSymbolCMap() const
173 {
174     return m_symbolCMap;
175 }
176
177 CFont *QSymbianTypeFaceExtras::fontOwner() const
178 {
179     return m_cFont;
180 }
181
182 QFixed QSymbianTypeFaceExtras::unitsPerEm() const
183 {
184     if (m_unitsPerEm.value() != 0)
185         return m_unitsPerEm;
186     const QByteArray head = getSfntTable(MAKE_TAG('h', 'e', 'a', 'd'));
187     const int unitsPerEmOffset = 18;
188     if (head.size() > unitsPerEmOffset + sizeof(quint16)) {
189         const uchar* tableData = reinterpret_cast<const uchar*>(head.constData());
190         const uchar* unitsPerEm = tableData + unitsPerEmOffset;
191         m_unitsPerEm = qFromBigEndian<quint16>(unitsPerEm);
192     } else {
193         // Bitmap font? Corrupt font?
194         // We return -1 and let the QFontEngineS60 return the pixel size.
195         m_unitsPerEm = -1;
196     }
197     return m_unitsPerEm;
198 }
199
200 bool QSymbianTypeFaceExtras::symbianFontTableApiAvailable()
201 {
202     enum FontTableApiAvailability {
203         Unknown,
204         Available,
205         Unavailable
206     };
207     static FontTableApiAvailability availability =
208             QSysInfo::symbianVersion() < QSysInfo::SV_SF_3 ?
209                 Unavailable : Unknown;
210     if (availability == Unknown) {
211         // Actually, we should ask CFeatureDiscovery::IsFeatureSupportedL()
212         // with FfFontTable here. But since at the time of writing, the
213         // FfFontTable flag check either gave false positives or false
214         // negatives. Here comes an implicit check via CFont::ExtendedFunction.
215         QSymbianTGetFontTableParam fontTableParams = {
216             MAKE_TAG('O', 'S', '/', '2'), 0, 0 };
217         QSymbianFbsHeapLock lock(QSymbianFbsHeapLock::Unlock);
218         CFont *font;
219         const TInt getFontErr = S60->screenDevice()->GetNearestFontInTwips(font, TFontSpec());
220         Q_ASSERT(getFontErr == KErrNone);
221         if (font->ExtendedFunction(QSymbianKFontGetFontTable, &fontTableParams) == KErrNone) {
222             font->ExtendedFunction(QSymbianKFontReleaseFontTable, &fontTableParams);
223             availability = Available;
224         } else {
225             availability = Unavailable;
226         }
227         S60->screenDevice()->ReleaseFont(font);
228         lock.relock();
229     }
230     return availability == Available;
231 }
232
233 // duplicated from qfontengine_xyz.cpp
234 static inline unsigned int getChar(const QChar *str, int &i, const int len)
235 {
236     unsigned int uc = str[i].unicode();
237     if (uc >= 0xd800 && uc < 0xdc00 && i < len-1) {
238         uint low = str[i+1].unicode();
239        if (low >= 0xdc00 && low < 0xe000) {
240             uc = (uc - 0xd800)*0x400 + (low - 0xdc00) + 0x10000;
241             ++i;
242         }
243     }
244     return uc;
245 }
246
247 extern QString qt_symbian_fontNameWithAppFontMarker(const QString &fontName); // qfontdatabase_s60.cpp
248
249 CFont *QFontEngineS60::fontWithSize(qreal size) const
250 {
251     CFont *result = 0;
252     const QString family = qt_symbian_fontNameWithAppFontMarker(QFontEngine::fontDef.family);
253     TFontSpec fontSpec(qt_QString2TPtrC(family), TInt(size));
254     fontSpec.iFontStyle.SetBitmapType(EAntiAliasedGlyphBitmap);
255     fontSpec.iFontStyle.SetPosture(QFontEngine::fontDef.style == QFont::StyleNormal?EPostureUpright:EPostureItalic);
256     fontSpec.iFontStyle.SetStrokeWeight(QFontEngine::fontDef.weight > QFont::Normal?EStrokeWeightBold:EStrokeWeightNormal);
257     const TInt errorCode = S60->screenDevice()->GetNearestFontToDesignHeightInPixels(result, fontSpec);
258     Q_ASSERT(result && (errorCode == 0));
259     return result;
260 }
261
262 void QFontEngineS60::setFontScale(qreal scale)
263 {
264     if (qFuzzyCompare(scale, qreal(1))) {
265         if (!m_originalFont)
266             m_originalFont = fontWithSize(m_originalFontSizeInPixels);
267         m_activeFont = m_originalFont;
268     } else {
269         const qreal scaledFontSizeInPixels = m_originalFontSizeInPixels * scale;
270         if (!m_scaledFont ||
271                 (TInt(scaledFontSizeInPixels) != TInt(m_scaledFontSizeInPixels))) {
272             releaseFont(m_scaledFont);
273             m_scaledFontSizeInPixels = scaledFontSizeInPixels;
274             m_scaledFont = fontWithSize(m_scaledFontSizeInPixels);
275         }
276         m_activeFont = m_scaledFont;
277     }
278 }
279
280 void QFontEngineS60::releaseFont(CFont *&font)
281 {
282     if (font) {
283         S60->screenDevice()->ReleaseFont(font);
284         font = 0;
285     }
286 }
287
288 QFontEngineS60::QFontEngineS60(const QFontDef &request, const QSymbianTypeFaceExtras *extras)
289     : m_extras(extras)
290     , m_originalFont(0)
291     , m_originalFontSizeInPixels((request.pixelSize >= 0)?
292             request.pixelSize:pointsToPixels(request.pointSize))
293     , m_scaledFont(0)
294     , m_scaledFontSizeInPixels(0)
295     , m_activeFont(0)
296 {
297     QFontEngine::fontDef = request;
298     setFontScale(1.0);
299     cache_cost = sizeof(QFontEngineS60);
300 }
301
302 QFontEngineS60::~QFontEngineS60()
303 {
304     releaseFont(m_originalFont);
305     releaseFont(m_scaledFont);
306 }
307
308 QFixed QFontEngineS60::emSquareSize() const
309 {
310     const QFixed unitsPerEm = m_extras->unitsPerEm();
311     return unitsPerEm.toInt() == -1 ?
312                 QFixed::fromReal(m_originalFontSizeInPixels) : unitsPerEm;
313 }
314
315 bool QFontEngineS60::stringToCMap(const QChar *characters, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const
316 {
317     if (*nglyphs < len) {
318         *nglyphs = len;
319         return false;
320     }
321
322     HB_Glyph *g = glyphs->glyphs;
323     const unsigned char* cmap = m_extras->cmap();
324     const bool isRtl = (flags & QTextEngine::RightToLeft);
325     for (int i = 0; i < len; ++i) {
326         const unsigned int uc = getChar(characters, i, len);
327         *g++ = QFontEngine::getTrueTypeGlyphIndex(cmap,
328                         (isRtl && !m_extras->isSymbolCMap()) ? QChar::mirroredChar(uc) : uc);
329     }
330
331     glyphs->numGlyphs = g - glyphs->glyphs;
332     *nglyphs = glyphs->numGlyphs;
333
334     if (flags & QTextEngine::GlyphIndicesOnly)
335         return true;
336
337     recalcAdvances(glyphs, flags);
338     return true;
339 }
340
341 void QFontEngineS60::recalcAdvances(QGlyphLayout *glyphs, QTextEngine::ShaperFlags flags) const
342 {
343     Q_UNUSED(flags);
344     TOpenFontCharMetrics metrics;
345     const TUint8 *glyphBitmapBytes;
346     TSize glyphBitmapSize;
347     for (int i = 0; i < glyphs->numGlyphs; i++) {
348         getCharacterData(glyphs->glyphs[i], metrics, glyphBitmapBytes, glyphBitmapSize);
349         glyphs->advances_x[i] = metrics.HorizAdvance();
350         glyphs->advances_y[i] = 0;
351     }
352 }
353
354 #ifdef Q_SYMBIAN_HAS_GLYPHOUTLINE_API
355 static bool parseGlyphPathData(const char *dataStr, const char *dataEnd, QPainterPath &path,
356                                qreal fontPixelSize, const QPointF &offset, bool hinted);
357 #endif //Q_SYMBIAN_HAS_GLYPHOUTLINE_API
358
359 void QFontEngineS60::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions,
360                                      int nglyphs, QPainterPath *path,
361                                      QTextItem::RenderFlags flags)
362 {
363 #ifdef Q_SYMBIAN_HAS_GLYPHOUTLINE_API
364     Q_UNUSED(flags)
365     RGlyphOutlineIterator iterator;
366     const TInt error = iterator.Open(*m_activeFont, glyphs, nglyphs);
367     if (KErrNone != error)
368         return;
369     const qreal fontSizeInPixels = qreal(m_activeFont->HeightInPixels());
370     int count = 0;
371     do {
372         const TUint8* outlineUint8 = iterator.Outline();
373         const char* const outlineChar = reinterpret_cast<const char*>(outlineUint8);
374         const char* const outlineEnd = outlineChar + iterator.OutlineLength();
375         parseGlyphPathData(outlineChar, outlineEnd, *path, fontSizeInPixels,
376                 positions[count++].toPointF(), false);
377     } while(KErrNone == iterator.Next() && count <= nglyphs);
378     iterator.Close();
379 #else // Q_SYMBIAN_HAS_GLYPHOUTLINE_API
380     QFontEngine::addGlyphsToPath(glyphs, positions, nglyphs, path, flags);
381 #endif //Q_SYMBIAN_HAS_GLYPHOUTLINE_API
382 }
383
384 QImage QFontEngineS60::alphaMapForGlyph(glyph_t glyph)
385 {
386     // Note: On some Symbian versions (apparently <= Symbian^1), this
387     // function will return gray values 0x00, 0x10 ... 0xe0, 0xf0 due
388     // to a bug. The glyphs are nowhere perfectly opaque.
389     // This has been fixed for Symbian^3.
390
391     TOpenFontCharMetrics metrics;
392     const TUint8 *glyphBitmapBytes;
393     TSize glyphBitmapSize;
394     getCharacterData(glyph, metrics, glyphBitmapBytes, glyphBitmapSize);
395     QImage result(glyphBitmapBytes, glyphBitmapSize.iWidth, glyphBitmapSize.iHeight, glyphBitmapSize.iWidth, QImage::Format_Indexed8);
396     result.setColorTable(grayPalette());
397     return result;
398 }
399
400 glyph_metrics_t QFontEngineS60::boundingBox(const QGlyphLayout &glyphs)
401 {
402    if (glyphs.numGlyphs == 0)
403         return glyph_metrics_t();
404
405     QFixed w = 0;
406     for (int i = 0; i < glyphs.numGlyphs; ++i)
407         w += glyphs.effectiveAdvance(i);
408
409     return glyph_metrics_t(0, -ascent(), w - lastRightBearing(glyphs), ascent()+descent()+1, w, 0);
410 }
411
412 glyph_metrics_t QFontEngineS60::boundingBox_const(glyph_t glyph) const
413 {
414     TOpenFontCharMetrics metrics;
415     const TUint8 *glyphBitmapBytes;
416     TSize glyphBitmapSize;
417     getCharacterData(glyph, metrics, glyphBitmapBytes, glyphBitmapSize);
418     const glyph_metrics_t result(
419         metrics.HorizBearingX(),
420         -metrics.HorizBearingY(),
421         metrics.Width(),
422         metrics.Height(),
423         metrics.HorizAdvance(),
424         0
425     );
426     return result;
427 }
428
429 glyph_metrics_t QFontEngineS60::boundingBox(glyph_t glyph)
430 {
431     return boundingBox_const(glyph);
432 }
433
434 QFixed QFontEngineS60::ascent() const
435 {
436     // Workaround for QTBUG-8013
437     // Stroke based fonts may return an incorrect FontMaxAscent of 0.
438     const QFixed ascent = m_originalFont->FontMaxAscent();
439     return (ascent > 0) ? ascent : QFixed::fromReal(m_originalFontSizeInPixels) - descent();
440 }
441
442 QFixed QFontEngineS60::descent() const
443 {
444     return m_originalFont->FontMaxDescent();
445 }
446
447 QFixed QFontEngineS60::leading() const
448 {
449     return 0;
450 }
451
452 qreal QFontEngineS60::maxCharWidth() const
453 {
454     return m_originalFont->MaxCharWidthInPixels();
455 }
456
457 const char *QFontEngineS60::name() const
458 {
459     return "QFontEngineS60";
460 }
461
462 bool QFontEngineS60::canRender(const QChar *string, int len)
463 {
464     const unsigned char *cmap = m_extras->cmap();
465     for (int i = 0; i < len; ++i) {
466         const unsigned int uc = getChar(string, i, len);
467         if (QFontEngine::getTrueTypeGlyphIndex(cmap, uc) == 0)
468             return false;
469     }
470     return true;
471 }
472
473 QByteArray QFontEngineS60::getSfntTable(uint tag) const
474 {
475     return m_extras->getSfntTable(tag);
476 }
477
478 bool QFontEngineS60::getSfntTableData(uint tag, uchar *buffer, uint *length) const
479 {
480     return m_extras->getSfntTableData(tag, buffer, length);
481 }
482
483 QFontEngine::Type QFontEngineS60::type() const
484 {
485     return QFontEngine::S60FontEngine;
486 }
487
488 void QFontEngineS60::getCharacterData(glyph_t glyph, TOpenFontCharMetrics& metrics, const TUint8*& bitmap, TSize& bitmapSize) const
489 {
490     // Setting the most significant bit tells GetCharacterData
491     // that 'code' is a Glyph ID, rather than a UTF-16 value
492     const TUint specialCode = (TUint)glyph | 0x80000000;
493
494     const CFont::TCharacterDataAvailability availability =
495             m_activeFont->GetCharacterData(specialCode, metrics, bitmap, bitmapSize);
496     const glyph_t fallbackGlyph = '?';
497     if (availability != CFont::EAllCharacterData) {
498         const CFont::TCharacterDataAvailability fallbackAvailability =
499                 m_activeFont->GetCharacterData(fallbackGlyph, metrics, bitmap, bitmapSize);
500         Q_ASSERT(fallbackAvailability == CFont::EAllCharacterData);
501     }
502 }
503
504 #ifdef Q_SYMBIAN_HAS_GLYPHOUTLINE_API
505 static inline void skipSpacesAndComma(const char* &str, const char* const strEnd)
506 {
507     while (str <= strEnd && (*str == ' ' || *str == ','))
508         ++str;
509 }
510
511 static bool parseGlyphPathData(const char *svgPath, const char *svgPathEnd, QPainterPath &path,
512                                qreal fontPixelSize, const QPointF &offset, bool hinted)
513 {
514     Q_UNUSED(hinted)
515     QPointF p1, p2, firstSubPathPoint;
516     qreal *elementValues[] =
517         {&p1.rx(), &p1.ry(), &p2.rx(), &p2.ry()};
518     const int unitsPerEm = 2048; // See: http://en.wikipedia.org/wiki/Em_%28typography%29
519     const qreal resizeFactor = fontPixelSize / unitsPerEm;
520
521     while (svgPath < svgPathEnd) {
522         skipSpacesAndComma(svgPath, svgPathEnd);
523         const char pathElem = *svgPath++;
524         skipSpacesAndComma(svgPath, svgPathEnd);
525
526         if (pathElem != 'Z') {
527             char *endStr = 0;
528             int elementValuesCount = 0;
529             for (int i = 0; i < 4; ++i) { // 4 = size of elementValues[]
530                 qreal coordinateValue = strtod(svgPath, &endStr);
531                 if (svgPath == endStr)
532                     break;
533                 if (i % 2) // Flip vertically
534                     coordinateValue = -coordinateValue;
535                 *elementValues[i] = coordinateValue * resizeFactor;
536                 elementValuesCount++;
537                 svgPath = endStr;
538                 skipSpacesAndComma(svgPath, svgPathEnd);
539             }
540             p1 += offset;
541             if (elementValuesCount == 2)
542                 p2 = firstSubPathPoint;
543             else
544                 p2 += offset;
545         }
546
547         switch (pathElem) {
548         case 'M':
549             firstSubPathPoint = p1;
550             path.moveTo(p1);
551             break;
552         case 'Z':
553             path.closeSubpath();
554             break;
555         case 'L':
556             path.lineTo(p1);
557             break;
558         case 'Q':
559             path.quadTo(p1, p2);
560             break;
561         default:
562             return false;
563         }
564     }
565     return true;
566 }
567 #endif // Q_SYMBIAN_HAS_GLYPHOUTLINE_API
568
569 QT_END_NAMESPACE