aboutsummaryrefslogtreecommitdiffstats
path: root/main.cpp
blob: 65903814d14b21c9b7d6ea6e7e69d76ff0209c20 (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
/****************************************************************************
**
** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt Design Viewer of the Qt Toolkit.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/

#include <QtGui/private/qzipreader_p.h>

#include <QGuiApplication>
#include <QDebug>
#include <QQuickView>
#include <QQmlEngine>
#include <QDirIterator>
#include <QBuffer>
#include <QRegularExpression>
#include <QQmlComponent>
#include <QQuickItem>
#include <QQuickWindow>
#include <QPointer>
#include <QResource>
#include <QFileInfoList>
#include <QTemporaryFile>
#include <QTemporaryDir>
#include <QFontDatabase>
#include <QFontInfo>
#include <QDir>
#if defined(Q_OS_ANDROID)
#include <QApplication>
#include <QMessageBox>
#endif

#ifdef Q_OS_WASM
#include <emscripten.h>

std::function<void(char *, size_t, char *)> g_setFileDataCallback;
extern "C" EMSCRIPTEN_KEEPALIVE void qt_callSetFileData(char *content, size_t contentSize,
                                                        char *fileName)
{
    if (g_setFileDataCallback == nullptr)
        return;

    g_setFileDataCallback(content, contentSize, fileName);
    g_setFileDataCallback = nullptr;
}

void fetchProject(QByteArray *data, QString *fileName)
{
    // Call qt_callSetFileData to make sure the emscripten linker does not
    // optimize it away, which may happen if the function is called from JavaScript
    // only. Set g_setFileDataCallback to null to make it a no-op.
    ::g_setFileDataCallback = nullptr;
    ::qt_callSetFileData(nullptr, 0, nullptr);

    auto setFileDataCallback = [data, fileName](char *content, size_t contentSize, char *projectFilename){
        *data->setRawData(content, contentSize);
        *fileName = QString::fromUtf8(projectFilename);
    };
    g_setFileDataCallback = setFileDataCallback;

    EM_ASM_({
        // Copy the file file content to the C++ heap.
        // Note: this could be simplified by passing the content as an
        // "array" type to ccall and then let it copy to C++ memory.
        // However, this built-in solution does not handle files larger
        // than ~15M (Chrome). Instead, allocate memory manually and
        // pass a pointer to the C++ side (which will free() it when done).

        // TODO: consider slice()ing the file to read it picewise and
        // then assembling it in a QByteArray on the C++ side.

        const contentSize = contentArray.byteLength;
        const heapPointer = _malloc(contentSize);
        const heapBytes = new Uint8Array(Module.HEAPU8.buffer, heapPointer, contentSize);
        heapBytes.set(contentArray);

        // Null out the first data copy to enable GC
        reader = null;
        contentArray = null;

        // Call the C++ file data ready callback
        ccall("qt_callSetFileData", null,
            ["number", "number", "string"], [heapPointer, contentSize, projectfileName]);
    });
}

void printWarning(const QString &error)
{
    QString escaped = error;
    escaped.replace("'", "\'");
    escaped.replace("\n", "\\n");
    emscripten_run_script("alert('" + escaped.toUtf8() + "');");
}

void printError(const QString &error)
{
    printWarning(error);
    emscripten_run_script("location.hash = ''; location.reload();");
}

void setScreenSize(const QSize &size)
{
    const QString command =
            QString::fromLatin1("setScreenSize(%1, %2);").arg(size.width()).arg(size.height());
    emscripten_run_script(command.toUtf8());
}
#elif defined(Q_OS_ANDROID)
std::function<int(QStringList)> showFatalMessageAndDie;

void fetchProject(QByteArray *data, QString *fileName)
{
    *fileName = QCoreApplication::arguments().at(1);
    QFile file(*fileName);
    if (file.open(QIODevice::ReadOnly))
        *data = file.readAll();
}

void printError(const QString &error)
{
    qDebug() << error;
}

void setScreenSize(const QSize &size)
{
    qDebug() << "Screen size: " << size.width() << "x" << size.height();
}
#else

void fetchProject(QByteArray *data, QString *fileName)
{
    if (QCoreApplication::arguments().count() < 2) {
        qWarning() << "Pass a package file name as argument";
        return;
    }

    *fileName = QCoreApplication::arguments().at(1);
    QFile file(*fileName);
    if (file.open(QIODevice::ReadOnly))
        *data = file.readAll();
}

void printError(const QString &error)
{
    fprintf(stderr, "%s\n", qPrintable(error));
}

void setScreenSize(const QSize &size)
{
    fprintf(stderr, "Screen size: %d x %d\n", size.width(), size.height());
}
#endif // Q_OS_WASM

QString unpackProject(const QByteArray &project, const QString &targetDir, bool skipExtract = false)
{
    QDir().mkpath(targetDir);

    QBuffer buffer;
    buffer.setData(project);
    buffer.open(QIODevice::ReadOnly);

    if (!skipExtract) {
        QZipReader reader(&buffer);
        reader.extractAll(targetDir);
    }

    QDir projectLocationDir(targetDir);
    // maybe it was not a zip file so try it as resource binary
    if (projectLocationDir.isEmpty()) {
        if (!skipExtract)
            qDebug() << "File could not be extracted. Trying to open it as a resource file.";
        const uchar* data = reinterpret_cast<const uchar*>(project.data());
        const QString resourcePath("/qtdesignviewer");
        const QFileInfo sourceInfo(resourcePath);
        const QDir sourceDir(sourceInfo.dir());
        if (QResource::registerResource(data, resourcePath)) {
            return ":" + resourcePath;
        } else {
            printError("Can not load the resource data.");
        }
    }
    return targetDir;
}

QString findFile(const QString &dir, const QString &filter)
{
    QDirIterator it(dir, {filter}, QDir::NoFilter, QDirIterator::Subdirectories);
    return it.next();
}

void parseQmlprojectFile(const QString &fileName, QString *mainFile, QStringList *importPaths)
{
    /* if filename comes from a resource qml need qrc:/ at the mainfile and importPaths,
     * but all other c++ call like QFileInfo::exists do not understand that, there we
     * need to keep the : only at the beginning
     */
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly)) {
        printError("Could not open " + fileName + ": " + file.errorString());
        return;
    }
    const QString text = QString::fromUtf8(file.readAll());
    const QRegularExpression mainFileRegExp("mainFile:\\s*\"(.*)\"");
    const QRegularExpressionMatch mainFileMatch = mainFileRegExp.match(text);
    if (mainFileMatch.hasMatch()) {
        QString basePath = QFileInfo(fileName).path() + "/";

        *mainFile = basePath + mainFileMatch.captured(1);
        if (mainFile->startsWith(QLatin1String(":/")))

        *mainFile = "qrc:" + mainFile->mid(1);

        const QRegularExpression qt6ProjectRegExp("qt6Project:\\s*true");
        const QRegularExpressionMatch qt6ProjectMatch = qt6ProjectRegExp.match(text);
        if (!qt6ProjectMatch.hasMatch()) {
            printWarning("This is not a Qt6 project.\nQt5 projects might work, but they are not officially supported.");
        }

        const QRegularExpression importPathsRegExp("importPaths:\\s*\\[\\s*(.*)\\s*\\]");
        const QRegularExpressionMatch importPathsMatch = importPathsRegExp.match(text);
        if (importPathsMatch.hasMatch()) {
            for (const QString &path : importPathsMatch.captured(1).split(",")) {
                QString cleanedPath = path.trimmed();
                cleanedPath = basePath + cleanedPath.mid(1, cleanedPath.length() - 2);
                if (QFileInfo::exists(cleanedPath)) {
                    if (cleanedPath.startsWith(QLatin1String(":/")))
                        cleanedPath = "qrc:" + cleanedPath.mid(1);
                    importPaths->append(cleanedPath);
                }
            }
        }
    } else {
        return;
    }
}

int main(int argc, char *argv[])
{
    qDebug().noquote() << QString("Built on %1 %2\n").arg(__DATE__, __TIME__);

#if defined(Q_OS_ANDROID)
    QString mainQml;

    showFatalMessageAndDie = [&argc,&argv](QStringList messages) {
        QApplication *app = static_cast<QApplication*>(QApplication::instance());
        const bool createdLocally = (app == nullptr);
        if (createdLocally)
            app = new QApplication(argc, argv);
        messages.append("\nThis app is supposed to be run from Qt Design Studio.");
        QMessageBox msg(QMessageBox::Critical, "Fatal error", messages.join("\n"), QMessageBox::Ok);
        QObject::connect(&msg, &QMessageBox::finished, [&app](int){app->exit(-1);});
        msg.show();
        int retVal = app->exec();
        if (createdLocally) {
            delete app;
        }
        return retVal;
    };
    if (argc < 2) {
        return showFatalMessageAndDie({QString("Qml project to show has not been defined.")});
    }
#endif
    QSurfaceFormat format = QSurfaceFormat::defaultFormat();
    format.setVersion(3,0);
    QSurfaceFormat::setDefaultFormat(format);

#if defined(Q_OS_ANDROID)
    QApplication app(argc, argv);
    QApplication::setApplicationName(QStringLiteral("Qt Design Viewer"));
#else
    QGuiApplication app(argc, argv);
#endif
    QString projectFileName;
    QByteArray projectData;
    fetchProject(&projectData, &projectFileName);

#ifdef Q_OS_WASM
    QString projectLocation = "/home/web_user/";
#else // Q_OS_WASM
    QTemporaryDir tempDir("qmlprojector");
    QString projectLocation = tempDir.path();
#endif // Q_OS_WASM

#if defined(Q_OS_ANDROID)
    const bool skipZipOpenAttempt = projectFileName.endsWith(".qmlrc");
    projectLocation = unpackProject(projectData, projectLocation, skipZipOpenAttempt);
#else
    projectLocation = unpackProject(projectData, projectLocation);
#endif
    QString mainQmlFile;
    QStringList importPaths;
    const QString qmlProjectFile = findFile(projectLocation, "*.qmlproject");
    if (!qmlProjectFile.isEmpty()) {
        parseQmlprojectFile(qmlProjectFile, &mainQmlFile, &importPaths);
    } else {
        mainQmlFile = findFile(projectLocation, "main.qml");
        if (mainQmlFile.isEmpty())
            mainQmlFile = findFile(projectLocation, QFileInfo(projectFileName).baseName() + ".qml");
    }
    if (mainQmlFile.isEmpty()) {
        printError("No \"*.qmlproject\", \"main.qml\" or \"" + QFileInfo(projectFileName).baseName()
                   + ".qml\" found in \"" + projectFileName + "\".");
        return -1;
    }
    QUrl mainQmlUrl = QUrl::fromUserInput(mainQmlFile);

    const QString qtquickcontrols2File = findFile(projectLocation, "qtquickcontrols2.conf");
    if (!qtquickcontrols2File.isEmpty())
        qputenv("QT_QUICK_CONTROLS_CONF", qtquickcontrols2File.toLatin1());

    QQmlEngine engine;
    for (const QString &importPath : importPaths)
        engine.addImportPath(importPath);
    QPointer<QQmlComponent> component = new QQmlComponent(&engine);
    component->loadUrl(mainQmlUrl);
    while (component->isLoading())
        QCoreApplication::processEvents();
    if (!component->isReady()) {
        printError(component->errorString());
#if defined(Q_OS_ANDROID)
        showFatalMessageAndDie({"Error while loading Qml component.", component->errorString()});
#endif
        return -1;
    }
    QObject *topLevel = component->create();
    if (!topLevel && component->isError()) {
        printError("Create error");
#if defined(Q_OS_ANDROID)
        showFatalMessageAndDie({"Error while creating Qml component.", component->errorString()});
#endif
        return -1;
    }
    QScopedPointer<QQuickWindow> window(qobject_cast<QQuickWindow *>(topLevel));
    if (window) {
        engine.setIncubationController(window->incubationController());
        setScreenSize(QSize()); // Full browser size. TODO: Find out initial ApplicationWindow size
    } else {
        QQuickItem *contentItem = qobject_cast<QQuickItem *>(topLevel);
        if (contentItem) {
            QQuickView* view = new QQuickView(&engine, nullptr);
            window.reset(view);
            view->setContent(mainQmlUrl, component, contentItem);
            view->setResizeMode(QQuickView::SizeViewToRootObject);
            setScreenSize(QSize(contentItem->width(), contentItem->height()));
        }
    }

    window->show();

    const int exitcode = app.exec();
    delete component;
    return exitcode;
}