Replace 'i < len-1 && func(i+1)' by 'i+1 < len && func(i+1)'
[profile/ivi/qtbase.git] / src / gui / painting / qtextureglyphcache.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 <qmath.h>
43
44 #include "qtextureglyphcache_p.h"
45
46 #include "private/qnumeric_p.h"
47 #include "private/qnativeimage_p.h"
48 #include "private/qfontengine_ft_p.h"
49
50 QT_BEGIN_NAMESPACE
51
52 // #define CACHE_DEBUG
53
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)
57 {
58     v--;
59     v |= v >> 1;
60     v |= v >> 2;
61     v |= v >> 4;
62     v |= v >> 8;
63     v |= v >> 16;
64     ++v;
65     return v;
66 }
67
68 int QTextureGlyphCache::calculateSubPixelPositionCount(glyph_t glyph) const
69 {
70     // Test 12 different subpixel positions since it factors into 3*4 so it gives
71     // the coverage we need.
72
73     QList<QImage> images;
74     for (int i=0; i<12; ++i) {
75         QImage img = textureMapForGlyph(glyph, QFixed::fromReal(i / 12.0));
76
77         if (images.isEmpty()) {
78             QPainterPath path;
79             QFixedPoint point;
80             m_current_fontengine->addGlyphsToPath(&glyph, &point, 1, &path, QTextItem::RenderFlags());
81
82             // Glyph is space, return 0 to indicate that we need to keep trying
83             if (path.isEmpty())
84                 break;
85
86             images.append(img);
87         } else {
88             bool found = false;
89             for (int j=0; j<images.size(); ++j) {
90                 if (images.at(j) == img) {
91                     found = true;
92                     break;
93                 }
94             }
95             if (!found)
96                 images.append(img);
97         }
98     }
99
100     return images.size();
101 }
102
103 QFixed QTextureGlyphCache::subPixelPositionForX(QFixed x) const
104 {
105     if (m_subPixelPositionCount <= 1)
106         return QFixed();
107
108     QFixed subPixelPosition;
109     if (x != 0) {
110         subPixelPosition = x - x.floor();
111         QFixed fraction = (subPixelPosition / QFixed::fromReal(1.0 / m_subPixelPositionCount)).floor();
112
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);
116     }
117     return subPixelPosition;
118 }
119
120 bool QTextureGlyphCache::populate(QFontEngine *fontEngine, int numGlyphs, const glyph_t *glyphs,
121                                                 const QFixedPoint *positions)
122 {
123 #ifdef CACHE_DEBUG
124     printf("Populating with %d glyphs\n", numGlyphs);
125     qDebug() << " -> current transformation: " << m_transform;
126 #endif
127
128     m_current_fontengine = fontEngine;
129     const int margin = glyphMargin();
130     const int paddingDoubled = glyphPadding() * 2;
131
132     bool supportsSubPixelPositions = fontEngine->supportsSubPixelPositions();
133     if (m_subPixelPositionCount == 0) {
134         if (!supportsSubPixelPositions) {
135             m_subPixelPositionCount = 1;
136         } else {
137 #if !defined(Q_WS_X11)
138             int i = 0;
139             while (m_subPixelPositionCount == 0 && i < numGlyphs)
140                 m_subPixelPositionCount = calculateSubPixelPositionCount(glyphs[i++]);
141 #else
142             m_subPixelPositionCount = 4;
143 #endif
144         }
145     }
146
147     QHash<GlyphAndSubPixelPosition, Coord> listItemCoordinates;
148     int rowHeight = 0;
149
150     QFontEngine::GlyphFormat format;
151     switch (m_type) {
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;
155     }
156
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];
160
161         QFixed subPixelPosition;
162         if (supportsSubPixelPositions) {
163             QFixed x = positions != 0 ? positions[i].x : QFixed();
164             subPixelPosition = subPixelPositionForX(x);
165         }
166
167         if (coords.contains(GlyphAndSubPixelPosition(glyph, subPixelPosition)))
168             continue;
169         if (listItemCoordinates.contains(GlyphAndSubPixelPosition(glyph, subPixelPosition)))
170             continue;
171         glyph_metrics_t metrics = fontEngine->alphaMapBoundingBox(glyph, subPixelPosition, m_transform, format);
172
173 #ifdef CACHE_DEBUG
174         printf("(%4x): w=%.2f, h=%.2f, xoff=%.2f, yoff=%.2f, x=%.2f, y=%.2f\n",
175                glyph,
176                metrics.width.toReal(),
177                metrics.height.toReal(),
178                metrics.xoff.toReal(),
179                metrics.yoff.toReal(),
180                metrics.x.toReal(),
181                metrics.y.toReal());
182 #endif        
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);
190             continue;
191         }
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;
197
198         Coord c = { 0, 0, // will be filled in later
199                     glyph_width,
200                     glyph_height, // texture coords
201                     metrics.x.truncate(),
202                     -metrics.y.truncate() }; // baseline for horizontal scripts
203
204         listItemCoordinates.insert(key, c);
205         rowHeight = qMax(rowHeight, glyph_height);
206     }
207     if (listItemCoordinates.isEmpty())
208         return true;
209
210     rowHeight += margin * 2 + paddingDoubled;
211
212     if (m_w == 0) {
213         if (fontEngine->maxCharWidth() <= QT_DEFAULT_TEXTURE_GLYPH_CACHE_WIDTH)
214             m_w = QT_DEFAULT_TEXTURE_GLYPH_CACHE_WIDTH;
215         else
216             m_w = qt_next_power_of_two(fontEngine->maxCharWidth());
217     }
218
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();
224
225         m_currentRowHeight = qMax(m_currentRowHeight, c.h + margin * 2);
226
227         if (m_cx + c.w > requiredWidth) {
228             int new_width = requiredWidth*2;
229             while (new_width < m_cx + c.w)
230                 new_width *= 2;
231             if (new_width <= maxTextureWidth()) {
232                 requiredWidth = new_width;
233             } else {
234                 // no room on the current line, start new glyph strip
235                 m_cx = 0;
236                 m_cy += m_currentRowHeight + paddingDoubled;
237                 m_currentRowHeight = c.h + margin * 2; // New row
238             }
239         }
240
241         if (maxTextureHeight() > 0 && m_cy + c.h > maxTextureHeight()) {
242             // We can't make a cache of the required size, so we bail out
243             return false;
244         }
245
246         c.x = m_cx;
247         c.y = m_cy;
248
249         coords.insert(iter.key(), c);
250         m_pendingGlyphs.insert(iter.key(), c);
251
252         m_cx += c.w + paddingDoubled;
253         ++iter;
254     }
255     return true;
256
257 }
258
259 void QTextureGlyphCache::fillInPendingGlyphs()
260 {
261     if (m_pendingGlyphs.isEmpty())
262         return;
263
264     int requiredHeight = m_h;
265     int requiredWidth = m_w; // Use a minimum size to avoid a lot of initial reallocations
266     {
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);
272             ++iter;
273         }
274     }
275
276     if (isNull() || requiredHeight > m_h || requiredWidth > m_w) {
277         if (isNull())
278             createCache(qt_next_power_of_two(requiredWidth), qt_next_power_of_two(requiredHeight));
279         else
280             resizeCache(qt_next_power_of_two(requiredWidth), qt_next_power_of_two(requiredHeight));
281     }
282
283     {
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);
288
289             ++iter;
290         }
291     }
292
293     m_pendingGlyphs.clear();
294 }
295
296 QImage QTextureGlyphCache::textureMapForGlyph(glyph_t g, QFixed subPixelPosition) const
297 {
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;
302         switch (m_type) {
303         case Raster_RGBMask:
304             format = QFontEngineFT::Format_A32;
305             imageFormat = QImage::Format_RGB32;
306             break;
307         case Raster_A8:
308             format = QFontEngineFT::Format_A8;
309             imageFormat = QImage::Format_Indexed8;
310             break;
311         case Raster_Mono:
312             format = QFontEngineFT::Format_Mono;
313             imageFormat = QImage::Format_Mono;
314             break;
315         };
316
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;
321
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);
327         }
328     } else
329 #endif
330     if (m_type == QFontEngineGlyphCache::Raster_RGBMask)
331         return m_current_fontengine->alphaRGBMapForGlyph(g, subPixelPosition, glyphMargin(), m_transform);
332     else
333         return m_current_fontengine->alphaMapForGlyph(g, subPixelPosition, m_transform);
334
335     return QImage();
336 }
337
338 /************************************************************************
339  * QImageTextureGlyphCache
340  */
341
342 void QImageTextureGlyphCache::resizeTextureData(int width, int height)
343 {
344     m_image = m_image.copy(0, 0, width, height);
345 }
346
347 void QImageTextureGlyphCache::createTextureData(int width, int height)
348 {
349     switch (m_type) {
350     case QFontEngineGlyphCache::Raster_Mono:
351         m_image = QImage(width, height, QImage::Format_Mono);
352         break;
353     case QFontEngineGlyphCache::Raster_A8: {
354         m_image = QImage(width, height, QImage::Format_Indexed8);
355         m_image.fill(0);
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);
361         break;   }
362     case QFontEngineGlyphCache::Raster_RGBMask:
363         m_image = QImage(width, height, QImage::Format_RGB32);
364         break;
365     }
366 }
367
368 int QImageTextureGlyphCache::glyphMargin() const
369 {
370 #if (defined(Q_WS_MAC) && defined(QT_MAC_USE_COCOA)) || defined(Q_WS_X11)
371     return 0;
372 #else
373     return m_type == QFontEngineGlyphCache::Raster_RGBMask ? 2 : 0;
374 #endif
375 }
376
377 void QImageTextureGlyphCache::fillTexture(const Coord &c, glyph_t g, QFixed subPixelPosition)
378 {
379     QImage mask = textureMapForGlyph(g, subPixelPosition);
380
381 #ifdef CACHE_DEBUG
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);
385         return;
386     }
387 #endif
388
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(),
392                    m_image.format());
393         QPainter p(&ref);
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);
397         p.end();
398     } else if (m_type == QFontEngineGlyphCache::Raster_Mono) {
399         if (mask.depth() > 1) {
400             // TODO optimize this
401             mask = mask.alphaChannel();
402             mask.invertPixels();
403             mask = mask.convertToFormat(QImage::Format_Mono);
404         }
405
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();
410
411         for (int y = 0; y < c.h; ++y) {
412             uchar *dest = d + (c.y + y) *dbpl + c.x/8;
413
414             if (y < mh) {
415                 uchar *src = mask.scanLine(y);
416                 for (int x = 0; x < c.w/8; ++x) {
417                     if (x < (mw+7)/8)
418                         dest[x] = src[x];
419                     else
420                         dest[x] = 0;
421                 }
422             } else {
423                 for (int x = 0; x < c.w/8; ++x)
424                     dest[x] = 0;
425             }
426         }
427     } else { // A8
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();
432
433         if (mask.depth() == 1) {
434             for (int y = 0; y < c.h; ++y) {
435                 uchar *dest = d + (c.y + y) *dbpl + c.x;
436                 if (y < mh) {
437                     uchar *src = (uchar *) mask.scanLine(y);
438                     for (int x = 0; x < c.w; ++x) {
439                         if (x < mw)
440                             dest[x] = (src[x >> 3] & (1 << (7 - (x & 7)))) > 0 ? 255 : 0;
441                     }
442                 }
443             }
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;
447                 if (y < mh) {
448                     uchar *src = (uchar *) mask.scanLine(y);
449                     for (int x = 0; x < c.w; ++x) {
450                         if (x < mw)
451                             dest[x] = src[x];
452                     }
453                 }
454             }
455         }
456     }
457
458 #ifdef CACHE_DEBUG
459 //     QPainter p(&m_image);
460 //     p.drawLine(
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)));
465 #endif
466 }
467
468 QT_END_NAMESPACE