summaryrefslogtreecommitdiff
path: root/src/gui/text/qfontdatabase_wayland.cpp
blob: 89f9f7faa5aade09de5e9df9827961032e1df12d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
/****************************************************************************
**
** 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 "qdir.h"
#include "qlibraryinfo.h"
#include "qabstractfileengine.h"
#include <QtCore/qsettings.h>
#include "qfontengine_ft_p.h"

#include <ft2build.h>
#include FT_FREETYPE_H

#include "private/qfactoryloader_p.h"
#include "private/qcore_unix_p.h" // overrides QT_OPEN
#include "qabstractfontengine_wayland.h"
#include "qabstractfontengine_p.h"
#include <qdatetime.h>
#include "qplatformdefs.h"

// for mmap
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <errno.h>

class QFontEngineFT;

QT_BEGIN_NAMESPACE

#ifndef QT_NO_LIBRARY
Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
    (QFontEngineFactoryInterface_iid, QLatin1String("/fontengines"), Qt::CaseInsensitive))
#endif

const quint8 DatabaseVersion = 4;

// QFontDatabasePrivate::addFont() went into qfontdatabase.cpp

// QFontDatabasePrivate::addTTFile() went into qfontdatabase.cpp

static void registerFont(QFontDatabasePrivate::ApplicationFont *fnt);

/*!
    \internal
*/

#if defined(QFONTDATABASE_DEBUG) && defined(QT_FONTS_ARE_RESOURCES)
class FriendlyResource : public QResource
{
public:
    bool isDir () const { return QResource::isDir(); }
    bool isFile () const { return QResource::isFile(); }
    QStringList children () const { return QResource::children(); }
};
#endif
/*!
    \internal
*/
static void initializeDb()
{
    QFontDatabasePrivate *db = privateDb();
    if (!db || db->count)
        return;

    QString fontpath("");
#ifndef QT_FONTS_ARE_RESOURCES
    QString fontDirFile = fontpath + QLatin1String("/fontdir");

    if(!QFile::exists(fontpath)) {
        qFatal("QFontDatabase: Cannot find font directory %s - is Qt installed correctly?",
               fontpath.toLocal8Bit().constData());
    }

    if (db->reregisterAppFonts) {
        db->reregisterAppFonts = false;
        for (int i = 0; i < db->applicationFonts.count(); ++i)
            if (!db->applicationFonts.at(i).families.isEmpty()) {
                registerFont(&db->applicationFonts[i]);
            }
    }

    QString dbFileName = QLatin1String("/fontdb");

    QFile binaryDb(dbFileName + QLatin1String(".tmp"));
    binaryDb.open(QIODevice::WriteOnly | QIODevice::Truncate);

    // Load in font definition file
    FILE* fontdef=fopen(fontDirFile.toLocal8Bit().constData(),"r");
    if (fontdef) {
        char buf[200]="";
        char name[200]="";
        char render[200]="";
        char file[200]="";
        char isitalic[10]="";
        char flags[10]="";
        do {
            fgets(buf,200,fontdef);
            if (buf[0] != '#') {
                int weight=50;
                int size=0;
                sscanf(buf,"%s %s %s %s %d %d %s",name,file,render,isitalic,&weight,&size,flags);
                QString filename;
                if (file[0] != '/')
                    filename.append(fontpath).append(QLatin1Char('/'));
                filename += QLatin1String(file);
                bool italic = isitalic[0] == 'y';
                bool smooth = QByteArray(flags).contains('s');
            }
        } while (!feof(fontdef));
        fclose(fontdef);
    }


    QDir dir(fontpath, QLatin1String("*.qpf"));
    for (int i=0; i<int(dir.count()); i++) {
        int u0 = dir[i].indexOf(QLatin1Char('_'));
        int u1 = dir[i].indexOf(QLatin1Char('_'), u0+1);
        int u2 = dir[i].indexOf(QLatin1Char('_'), u1+1);
        int u3 = dir[i].indexOf(QLatin1Char('.'), u1+1);
        if (u2 < 0) u2 = u3;

        QString familyname = dir[i].left(u0);
        int pixelSize = dir[i].mid(u0+1,u1-u0-1).toInt()/10;
        bool italic = dir[i].mid(u2-1,1) == QLatin1String("i");
        int weight = dir[i].mid(u1+1,u2-u1-1-(italic?1:0)).toInt();
    }

#ifndef QT_NO_FREETYPE
    dir.setNameFilters(QStringList() << QLatin1String("*.ttf")
                       << QLatin1String("*.ttc") << QLatin1String("*.pfa")
                       << QLatin1String("*.pfb"));
    dir.refresh();
    for (int i = 0; i < int(dir.count()); ++i) {
        const QByteArray file = QFile::encodeName(dir.absoluteFilePath(dir[i]));
//        qDebug() << "looking at" << file;
        db->addTTFile(file);
    }
#endif

#else //QT_FONTS_ARE_RESOURCES
#ifdef QFONTDATABASE_DEBUG
    {
        QResource fontdir(fontpath);
        FriendlyResource *fr = static_cast<FriendlyResource*>(&fontdir);
        qDebug() << "fontdir" << fr->isValid() << fr->isDir() << fr->children();

    }
#endif
    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 //QT_FONTS_ARE_RESOURCES


#ifdef QFONTDATABASE_DEBUG
    // print the database
    for (int f = 0; f < db->count; f++) {
        QtFontFamily *family = db->families[f];
        FD_DEBUG("'%s' %s", qPrintable(family->name), (family->fixedPitch ? "fixed" : ""));
#if 0
        for (int i = 0; i < QFont::LastPrivateScript; ++i) {
            FD_DEBUG("\t%s: %s", qPrintable(QFontDatabase::scriptName((QFont::Script) i)),
                     ((family->scripts[i] & QtFontFamily::Supported) ? "Supported" :
                      (family->scripts[i] & QtFontFamily::UnSupported) == QtFontFamily::UnSupported ?
                      "UnSupported" : "Unknown"));
        }
#endif

        for (int fd = 0; fd < family->count; fd++) {
            QtFontFoundry *foundry = family->foundries[fd];
            FD_DEBUG("\t\t'%s'", qPrintable(foundry->name));
            for (int s = 0; s < foundry->count; s++) {
                QtFontStyle *style = foundry->styles[s];
                FD_DEBUG("\t\t\tstyle: style=%d weight=%d\n"
                         "\t\t\tstretch=%d",
                         style->key.style, style->key.weight,
                         style->key.stretch);
                if (style->smoothScalable)
                    FD_DEBUG("\t\t\t\tsmooth scalable");
                else if (style->bitmapScalable)
                    FD_DEBUG("\t\t\t\tbitmap scalable");
                if (style->pixelSizes) {
                    FD_DEBUG("\t\t\t\t%d pixel sizes",  style->count);
                    for (int z = 0; z < style->count; ++z) {
                        QtFontSize *size = style->pixelSizes + z;
                        FD_DEBUG("\t\t\t\t  size %5d",
                                  size->pixelSize);
                    }
                }
            }
        }
    }
#endif // QFONTDATABASE_DEBUG

#ifndef QT_NO_LIBRARY
    QStringList pluginFoundries = loader()->keys();
//    qDebug() << "plugin foundries:" << pluginFoundries;
    for (int i = 0; i < pluginFoundries.count(); ++i) {
        const QString foundry(pluginFoundries.at(i));

        QFontEngineFactoryInterface *factory = qobject_cast<QFontEngineFactoryInterface *>(loader()->instance(foundry));
        if (!factory) {
            qDebug() << "Could not load plugin for foundry" << foundry;
            continue;
        }

        QList<QFontEngineInfo> fonts = factory->availableFontEngines();
        for (int i = 0; i < fonts.count(); ++i) {
            QFontEngineInfo info = fonts.at(i);

            int weight = info.weight();
            if (weight <= 0)
                weight = QFont::Normal;

            db->addFont(info.family(), foundry.toLatin1().constData(),
                        weight, info.style() != QFont::StyleNormal,
                        qRound(info.pixelSize()), /*file*/QByteArray(),
                        /*fileIndex*/0, /*antiAliased*/true,
                        info.writingSystems());
        }
    }
#endif

    {
        bool coveredWritingSystems[QFontDatabase::WritingSystemsCount] = { 0 };

        for (int i = 0; i < db->count; ++i) {
            QtFontFamily *family = db->families[i];
            bool add = false;
            if (family->count == 0)
                continue;
            for (int ws = 1; ws < QFontDatabase::WritingSystemsCount; ++ws) {
                if (coveredWritingSystems[ws])
                    continue;
                if (family->writingSystems[ws] & QtFontFamily::Supported) {
                    coveredWritingSystems[ws] = true;
                    add = true;
                }
            }
        }
    }
}

static inline void load(const QString & = QString(), int = -1)
{
    initializeDb();
}

#ifndef QT_NO_FREETYPE

#if (FREETYPE_MAJOR*10000+FREETYPE_MINOR*100+FREETYPE_PATCH) >= 20105
#define X_SIZE(face,i) ((face)->available_sizes[i].x_ppem)
#define Y_SIZE(face,i) ((face)->available_sizes[i].y_ppem)
#else
#define X_SIZE(face,i) ((face)->available_sizes[i].width << 6)
#define Y_SIZE(face,i) ((face)->available_sizes[i].height << 6)
#endif

#endif // QT_NO_FREETYPE

static
QFontEngine *loadSingleEngine(int script, const QFontPrivate *fp,
                              const QFontDef &request,
                              QtFontFamily *family, QtFontFoundry *foundry,
                              QtFontStyle *style, QtFontSize *size)
{
    Q_UNUSED(script);
    Q_UNUSED(fp);
    Q_UNUSED(family);
    Q_ASSERT(size);

    int pixelSize = size->pixelSize;
    if (!pixelSize || (style->smoothScalable && pixelSize == SMOOTH_SCALABLE))
        pixelSize = request.pixelSize;

    int f = ::open(size->fileName, O_RDONLY, 0);
    if (f >= 0) {
	qDebug() << "fontengine is not valid!";
    }
    if ( foundry->name != QLatin1String("qt") ) { ///#### is this the best way????
        QFontDef def = request;
        def.pixelSize = pixelSize;

        QScopedPointer<QFontEngine> engine;

#ifndef QT_NO_LIBRARY
        QFontEngineFactoryInterface *factory = qobject_cast<QFontEngineFactoryInterface *>(loader()->instance(foundry->name));
        if (factory) {
            QFontEngineInfo info;
            info.setFamily(request.family);
            info.setPixelSize(request.pixelSize);
            info.setStyle(QFont::Style(request.style));
            info.setWeight(request.weight);
            // #### antialiased

            QAbstractFontEngine *customEngine = factory->create(info);
            if (customEngine) {
                engine.reset(new QProxyFontEngine(customEngine, def));
            }
        }
#endif // QT_NO_LIBRARY
        if ((engine.isNull())) {
            QFontEngine::FaceId faceId;
            faceId.index = size->fileIndex;
        }
        if (!engine.isNull()) {
            return engine.take();
        }
    } else
    {
    }
    return new QFontEngineBox(pixelSize);
}

static
QFontEngine *loadEngine(int script, const QFontPrivate *fp,
                        const QFontDef &request,
                        QtFontFamily *family, QtFontFoundry *foundry,
                        QtFontStyle *style, QtFontSize *size)
{
    QScopedPointer<QFontEngine> engine(loadSingleEngine(script, fp, request, family, foundry,
                                       style, size));
    if (!engine.isNull()
        && script == QUnicodeTables::Common
        && !(request.styleStrategy & QFont::NoFontMerging) && !engine->symbol) {

        engine.take();
    }
    return engine.take();
}

static void registerFont(QFontDatabasePrivate::ApplicationFont *fnt)
{
    QFontDatabasePrivate *db = privateDb();
    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();

    QScopedPointer<QFontEngine> fe;
    if (fp) {
        if (fp->rawMode) {
            fe.reset(loadEngine(script, fp, request, 0, 0, 0, 0));

            // if we fail to load the rawmode font, use a 12pixel box engine instead
            if (fe.isNull())
                fe.reset(new QFontEngineBox(12));
            return fe.take();
        }

        QFontCache::Key key(request, script);
        fe.reset(QFontCache::instance()->findEngine(key));
        if (! fe.isNull())
            return fe.take();
    }

    QString family_name, foundry_name;
    QtFontStyle::Key styleKey;
    styleKey.style = request.style;
    styleKey.weight = request.weight;
    styleKey.stretch = request.stretch;
    char pitch = request.ignorePitch ? '*' : request.fixedPitch ? 'm' : 'p';

    parseFontName(request.family, foundry_name, family_name);

    FM_DEBUG("QFontDatabase::findFont\n"
             "  request:\n"
             "    family: %s [%s], script: %d\n"
             "    weight: %d, style: %d\n"
             "    stretch: %d\n"
             "    pixelSize: %g\n"
             "    pitch: %c",
             family_name.isEmpty() ? "-- first in script --" : family_name.toLatin1().constData(),
             foundry_name.isEmpty() ? "-- any --" : foundry_name.toLatin1().constData(),
             script, request.weight, request.style, request.stretch, request.pixelSize, pitch);

    if (qt_enable_test_font && request.family == QLatin1String("__Qt__Box__Engine__")) {
        fe.reset(new QTestFontEngine(request.pixelSize));
        fe->fontDef = request;
    }

    if (fe.isNull())
    {
        QtFontDesc desc;
        match(script, request, family_name, foundry_name, force_encoding_id, &desc);

        if (desc.family != 0 && desc.foundry != 0 && desc.style != 0
            ) {
            FM_DEBUG("  BEST:\n"
                     "    family: %s [%s]\n"
                     "    weight: %d, style: %d\n"
                     "    stretch: %d\n"
                     "    pixelSize: %d\n"
                     "    pitch: %c\n"
                     "    encoding: %d\n",
                     desc.family->name.toLatin1().constData(),
                     desc.foundry->name.isEmpty() ? "-- none --" : desc.foundry->name.toLatin1().constData(),
                     desc.style->key.weight, desc.style->key.style,
                     desc.style->key.stretch, desc.size ? desc.size->pixelSize : 0xffff,
                     'p', 0
                );

            fe.reset(loadEngine(script, fp, request, desc.family, desc.foundry, desc.style, desc.size
                ));
        } else {
            FM_DEBUG("  NO MATCH FOUND\n");
        }
    }

#ifndef QT_NO_FREETYPE
    if (! fe.isNull()) {
        if (scriptRequiresOpenType(script) && fe->type() == QFontEngine::Freetype) {
            HB_Face hbFace = static_cast<QFontEngineFT *>(fe.data())->harfbuzzFace();
            if (!hbFace || !hbFace->supported_scripts[script]) {
                FM_DEBUG("  OpenType support missing for script\n");
                fe.reset(0);
            }
        }
    }
#endif

    if (! fe.isNull()) {
        if (fp) {
            QFontDef def = request;
            if (def.family.isEmpty()) {
                def.family = fp->request.family;
                def.family = def.family.left(def.family.indexOf(QLatin1Char(',')));
            }
            QFontCache::Key key(def, script);
            QFontCache::instance()->insertEngine(key, fe.data());
        }
    }

    if (fe.isNull()) {
        if (!request.family.isEmpty())
            return 0;

        FM_DEBUG("returning box engine");

        fe.reset(new QFontEngineBox(request.pixelSize));

        if (fp) {
            QFontCache::Key key(request, script);
            QFontCache::instance()->insertEngine(key, fe.data());
        }
    }

    if (fp && fp->dpi > 0) {
        fe->fontDef.pointSize = qreal(double((fe->fontDef.pixelSize * 72) / fp->dpi));
    } else {
        fe->fontDef.pointSize = request.pointSize;
    }

    return fe.take();
}

void QFontDatabase::load(const QFontPrivate *d, int script)
{
    QFontDef req = d->request;

    if (req.pixelSize == -1)
        req.pixelSize = qRound(req.pointSize*d->dpi/72);
    if (req.pointSize < 0)
        req.pointSize = req.pixelSize*72.0/d->dpi;

    if (!d->engineData) {
        QFontCache::Key key(req, script);

        // look for the requested font in the engine data cache
        d->engineData = QFontCache::instance()->findEngineData(key);

        if (!d->engineData) {
            // create a new one
            d->engineData = new QFontEngineData;
            QT_TRY {
                QFontCache::instance()->insertEngineData(key, d->engineData);
            } QT_CATCH(...) {
                delete d->engineData;
                d->engineData = 0;
                QT_RETHROW;
            }
        } else {
            d->engineData->ref.ref();
        }
    }

    // the cached engineData could have already loaded the engine we want
    if (d->engineData->engines[script]) return;

    //    double scale = 1.0; // ### TODO: fix the scale calculations

    // list of families to try
    QStringList family_list;

    if (!req.family.isEmpty()) {
        family_list = req.family.split(QLatin1Char(','));

        // append the substitute list for each family in family_list
        QStringList subs_list;
        QStringList::ConstIterator it = family_list.constBegin(), end = family_list.constEnd();
        for (; it != end; ++it)
            subs_list += QFont::substitutes(*it);
        family_list += subs_list;

        // append the default fallback font for the specified script
        // family_list << ... ; ###########

        // add the default family
        QString defaultFamily = QApplication::font().family();
        if (! family_list.contains(defaultFamily))
            family_list << defaultFamily;

        // add QFont::defaultFamily() to the list, for compatibility with
        // previous versions
        family_list << QApplication::font().defaultFamily();
    }

    // null family means find the first font matching the specified script
    family_list << QString();

    // load the font
    QFontEngine *engine = 0;
    QStringList::ConstIterator it = family_list.constBegin(), end = family_list.constEnd();
    for (; !engine && it != end; ++it) {
        req.family = *it;

        engine = QFontDatabase::findFont(script, d, req);
        if (engine && (engine->type()==QFontEngine::Box) && !req.family.isEmpty())
            engine = 0;
    }

    engine->ref.ref();
    d->engineData->engines[script] = engine;
}


QT_END_NAMESPACE