1 /****************************************************************************
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtGui module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
44 #include "qtextureglyphcache_p.h"
46 #include "private/qnumeric_p.h"
47 #include "private/qnativeimage_p.h"
48 #include "private/qfontengine_ft_p.h"
52 // #define CACHE_DEBUG
54 // returns the highest number closest to v, which is a power of 2
55 // NB! assumes 32 bit ints
56 static inline int qt_next_power_of_two(int v)
68 int QTextureGlyphCache::calculateSubPixelPositionCount(glyph_t glyph) const
70 // Test 12 different subpixel positions since it factors into 3*4 so it gives
71 // the coverage we need.
74 for (int i=0; i<12; ++i) {
75 QImage img = textureMapForGlyph(glyph, QFixed::fromReal(i / 12.0));
77 if (images.isEmpty()) {
80 m_current_fontengine->addGlyphsToPath(&glyph, &point, 1, &path, QTextItem::RenderFlags());
82 // Glyph is space, return 0 to indicate that we need to keep trying
89 for (int j=0; j<images.size(); ++j) {
90 if (images.at(j) == img) {
100 return images.size();
103 QFixed QTextureGlyphCache::subPixelPositionForX(QFixed x) const
105 if (m_subPixelPositionCount <= 1)
108 QFixed subPixelPosition;
110 subPixelPosition = x - x.floor();
111 QFixed fraction = (subPixelPosition / QFixed::fromReal(1.0 / m_subPixelPositionCount)).floor();
113 // Compensate for precision loss in fixed point to make sure we are always drawing at a subpixel position over
114 // the lower boundary for the selected rasterization by adding 1/64.
115 subPixelPosition = fraction / QFixed(m_subPixelPositionCount) + QFixed::fromReal(0.015625);
117 return subPixelPosition;
120 bool QTextureGlyphCache::populate(QFontEngine *fontEngine, int numGlyphs, const glyph_t *glyphs,
121 const QFixedPoint *positions)
124 printf("Populating with %d glyphs\n", numGlyphs);
125 qDebug() << " -> current transformation: " << m_transform;
128 m_current_fontengine = fontEngine;
129 const int margin = glyphMargin();
130 const int paddingDoubled = glyphPadding() * 2;
132 bool supportsSubPixelPositions = fontEngine->supportsSubPixelPositions();
133 if (m_subPixelPositionCount == 0) {
134 if (!supportsSubPixelPositions) {
135 m_subPixelPositionCount = 1;
137 #if !defined(Q_WS_X11)
139 while (m_subPixelPositionCount == 0 && i < numGlyphs)
140 m_subPixelPositionCount = calculateSubPixelPositionCount(glyphs[i++]);
142 m_subPixelPositionCount = 4;
147 QHash<GlyphAndSubPixelPosition, Coord> listItemCoordinates;
150 QFontEngine::GlyphFormat format;
152 case Raster_A8: format = QFontEngine::Format_A8; break;
153 case Raster_RGBMask: format = QFontEngine::Format_A32; break;
154 default: format = QFontEngine::Format_Mono; break;
157 // check each glyph for its metrics and get the required rowHeight.
158 for (int i=0; i < numGlyphs; ++i) {
159 const glyph_t glyph = glyphs[i];
161 QFixed subPixelPosition;
162 if (supportsSubPixelPositions) {
163 QFixed x = positions != 0 ? positions[i].x : QFixed();
164 subPixelPosition = subPixelPositionForX(x);
167 if (coords.contains(GlyphAndSubPixelPosition(glyph, subPixelPosition)))
169 if (listItemCoordinates.contains(GlyphAndSubPixelPosition(glyph, subPixelPosition)))
171 glyph_metrics_t metrics = fontEngine->alphaMapBoundingBox(glyph, subPixelPosition, m_transform, format);
174 printf("(%4x): w=%.2f, h=%.2f, xoff=%.2f, yoff=%.2f, x=%.2f, y=%.2f\n",
176 metrics.width.toReal(),
177 metrics.height.toReal(),
178 metrics.xoff.toReal(),
179 metrics.yoff.toReal(),
183 GlyphAndSubPixelPosition key(glyph, subPixelPosition);
184 int glyph_width = metrics.width.ceil().toInt();
185 int glyph_height = metrics.height.ceil().toInt();
186 if (glyph_height == 0 || glyph_width == 0) {
187 // Avoid multiple calls to boundingBox() for non-printable characters
188 Coord c = { 0, 0, 0, 0, 0, 0 };
189 coords.insert(key, c);
192 glyph_width += margin * 2 + 4;
193 glyph_height += margin * 2 + 4;
194 // align to 8-bit boundary
195 if (m_type == QFontEngineGlyphCache::Raster_Mono)
196 glyph_width = (glyph_width+7)&~7;
198 Coord c = { 0, 0, // will be filled in later
200 glyph_height, // texture coords
201 metrics.x.truncate(),
202 -metrics.y.truncate() }; // baseline for horizontal scripts
204 listItemCoordinates.insert(key, c);
205 rowHeight = qMax(rowHeight, glyph_height);
207 if (listItemCoordinates.isEmpty())
210 rowHeight += margin * 2 + paddingDoubled;
213 if (fontEngine->maxCharWidth() <= QT_DEFAULT_TEXTURE_GLYPH_CACHE_WIDTH)
214 m_w = QT_DEFAULT_TEXTURE_GLYPH_CACHE_WIDTH;
216 m_w = qt_next_power_of_two(fontEngine->maxCharWidth());
219 // now actually use the coords and paint the wanted glyps into cache.
220 QHash<GlyphAndSubPixelPosition, Coord>::iterator iter = listItemCoordinates.begin();
221 int requiredWidth = m_w;
222 while (iter != listItemCoordinates.end()) {
223 Coord c = iter.value();
225 m_currentRowHeight = qMax(m_currentRowHeight, c.h + margin * 2);
227 if (m_cx + c.w > requiredWidth) {
228 int new_width = requiredWidth*2;
229 while (new_width < m_cx + c.w)
231 if (new_width <= maxTextureWidth()) {
232 requiredWidth = new_width;
234 // no room on the current line, start new glyph strip
236 m_cy += m_currentRowHeight + paddingDoubled;
237 m_currentRowHeight = c.h + margin * 2; // New row
241 if (maxTextureHeight() > 0 && m_cy + c.h > maxTextureHeight()) {
242 // We can't make a cache of the required size, so we bail out
249 coords.insert(iter.key(), c);
250 m_pendingGlyphs.insert(iter.key(), c);
252 m_cx += c.w + paddingDoubled;
259 void QTextureGlyphCache::fillInPendingGlyphs()
261 if (m_pendingGlyphs.isEmpty())
264 int requiredHeight = m_h;
265 int requiredWidth = m_w; // Use a minimum size to avoid a lot of initial reallocations
267 QHash<GlyphAndSubPixelPosition, Coord>::iterator iter = m_pendingGlyphs.begin();
268 while (iter != m_pendingGlyphs.end()) {
269 Coord c = iter.value();
270 requiredHeight = qMax(requiredHeight, c.y + c.h);
271 requiredWidth = qMax(requiredWidth, c.x + c.w);
276 if (isNull() || requiredHeight > m_h || requiredWidth > m_w) {
278 createCache(qt_next_power_of_two(requiredWidth), qt_next_power_of_two(requiredHeight));
280 resizeCache(qt_next_power_of_two(requiredWidth), qt_next_power_of_two(requiredHeight));
284 QHash<GlyphAndSubPixelPosition, Coord>::iterator iter = m_pendingGlyphs.begin();
285 while (iter != m_pendingGlyphs.end()) {
286 GlyphAndSubPixelPosition key = iter.key();
287 fillTexture(iter.value(), key.glyph, key.subPixelPosition);
293 m_pendingGlyphs.clear();
296 QImage QTextureGlyphCache::textureMapForGlyph(glyph_t g, QFixed subPixelPosition) const
298 #if defined(Q_WS_X11)
299 if (m_transform.type() > QTransform::TxTranslate && m_current_fontengine->type() == QFontEngine::Freetype) {
300 QFontEngineFT::GlyphFormat format = QFontEngineFT::Format_None;
301 QImage::Format imageFormat = QImage::Format_Invalid;
304 format = QFontEngineFT::Format_A32;
305 imageFormat = QImage::Format_RGB32;
308 format = QFontEngineFT::Format_A8;
309 imageFormat = QImage::Format_Indexed8;
312 format = QFontEngineFT::Format_Mono;
313 imageFormat = QImage::Format_Mono;
317 QFontEngineFT *ft = static_cast<QFontEngineFT*> (m_current_fontengine);
318 QFontEngineFT::QGlyphSet *gset = ft->loadTransformedGlyphSet(m_transform);
319 QFixedPoint positions[1];
320 positions[0].x = subPixelPosition;
322 if (gset && ft->loadGlyphs(gset, &g, 1, positions, format)) {
323 QFontEngineFT::Glyph *glyph = gset->getGlyph(g, subPixelPosition);
324 const int bytesPerLine = (format == QFontEngineFT::Format_Mono ? ((glyph->width + 31) & ~31) >> 3
325 : (glyph->width + 3) & ~3);
326 return QImage(glyph->data, glyph->width, glyph->height, bytesPerLine, imageFormat);
330 if (m_type == QFontEngineGlyphCache::Raster_RGBMask)
331 return m_current_fontengine->alphaRGBMapForGlyph(g, subPixelPosition, glyphMargin(), m_transform);
333 return m_current_fontengine->alphaMapForGlyph(g, subPixelPosition, m_transform);
338 /************************************************************************
339 * QImageTextureGlyphCache
342 void QImageTextureGlyphCache::resizeTextureData(int width, int height)
344 m_image = m_image.copy(0, 0, width, height);
347 void QImageTextureGlyphCache::createTextureData(int width, int height)
350 case QFontEngineGlyphCache::Raster_Mono:
351 m_image = QImage(width, height, QImage::Format_Mono);
353 case QFontEngineGlyphCache::Raster_A8: {
354 m_image = QImage(width, height, QImage::Format_Indexed8);
356 QVector<QRgb> colors(256);
357 QRgb *it = colors.data();
358 for (int i=0; i<256; ++i, ++it)
359 *it = 0xff000000 | i | (i<<8) | (i<<16);
360 m_image.setColorTable(colors);
362 case QFontEngineGlyphCache::Raster_RGBMask:
363 m_image = QImage(width, height, QImage::Format_RGB32);
368 int QImageTextureGlyphCache::glyphMargin() const
370 #if (defined(Q_WS_MAC) && defined(QT_MAC_USE_COCOA)) || defined(Q_WS_X11)
373 return m_type == QFontEngineGlyphCache::Raster_RGBMask ? 2 : 0;
377 void QImageTextureGlyphCache::fillTexture(const Coord &c, glyph_t g, QFixed subPixelPosition)
379 QImage mask = textureMapForGlyph(g, subPixelPosition);
382 printf("fillTexture of %dx%d at %d,%d in the cache of %dx%d\n", c.w, c.h, c.x, c.y, m_image.width(), m_image.height());
383 if (mask.width() > c.w || mask.height() > c.h) {
384 printf(" ERROR; mask is bigger than reserved space! %dx%d instead of %dx%d\n", mask.width(), mask.height(), c.w,c.h);
389 if (m_type == QFontEngineGlyphCache::Raster_RGBMask) {
390 QImage ref(m_image.bits() + (c.x * 4 + c.y * m_image.bytesPerLine()),
391 qMax(mask.width(), c.w), qMax(mask.height(), c.h), m_image.bytesPerLine(),
394 p.setCompositionMode(QPainter::CompositionMode_Source);
395 p.fillRect(0, 0, c.w, c.h, QColor(0,0,0,0)); // TODO optimize this
396 p.drawImage(0, 0, mask);
398 } else if (m_type == QFontEngineGlyphCache::Raster_Mono) {
399 if (mask.depth() > 1) {
400 // TODO optimize this
401 mask = mask.alphaChannel();
403 mask = mask.convertToFormat(QImage::Format_Mono);
406 int mw = qMin(mask.width(), c.w);
407 int mh = qMin(mask.height(), c.h);
408 uchar *d = m_image.bits();
409 int dbpl = m_image.bytesPerLine();
411 for (int y = 0; y < c.h; ++y) {
412 uchar *dest = d + (c.y + y) *dbpl + c.x/8;
415 uchar *src = mask.scanLine(y);
416 for (int x = 0; x < c.w/8; ++x) {
423 for (int x = 0; x < c.w/8; ++x)
428 int mw = qMin(mask.width(), c.w);
429 int mh = qMin(mask.height(), c.h);
430 uchar *d = m_image.bits();
431 int dbpl = m_image.bytesPerLine();
433 if (mask.depth() == 1) {
434 for (int y = 0; y < c.h; ++y) {
435 uchar *dest = d + (c.y + y) *dbpl + c.x;
437 uchar *src = (uchar *) mask.scanLine(y);
438 for (int x = 0; x < c.w; ++x) {
440 dest[x] = (src[x >> 3] & (1 << (7 - (x & 7)))) > 0 ? 255 : 0;
444 } else if (mask.depth() == 8) {
445 for (int y = 0; y < c.h; ++y) {
446 uchar *dest = d + (c.y + y) *dbpl + c.x;
448 uchar *src = (uchar *) mask.scanLine(y);
449 for (int x = 0; x < c.w; ++x) {
459 // QPainter p(&m_image);
461 QPoint base(c.x + glyphMargin(), c.y + glyphMargin() + c.baseLineY-1);
462 if (m_image.rect().contains(base))
463 m_image.setPixel(base, 255);
464 m_image.save(QString::fromLatin1("cache-%1.png").arg(qint64(this)));