summaryrefslogtreecommitdiffstats
path: root/src/assistant/assistant/main.cpp
blob: e4d5a4f387a50e2a20ca9af54a7a9a84e22e5d70 (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
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Assistant of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** 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 Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "tracer.h"

#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QLibraryInfo>
#include <QtCore/QLocale>
#include <QtCore/QScopedPointer>
#include <QtCore/QStringList>
#include <QtCore/QTranslator>
#include <QtCore/QUrl>

#include <QtWidgets/QApplication>
#include <QtGui/QDesktopServices>

#include <QtHelp/QHelpEngine>
#include <QtHelp/QHelpSearchEngine>

#include <QtNetwork/QLocalSocket>

#include <QtSql/QSqlDatabase>

#if !defined(QT_NO_WEBKIT)
#include <QtGui/QFont>
#include <QWebSettings>
#endif

#include "../shared/collectionconfiguration.h"
#include "helpenginewrapper.h"
#include "mainwindow.h"
#include "cmdlineparser.h"

// #define TRACING_REQUESTED
// #define DEBUG_TRANSLATIONS

QT_USE_NAMESPACE

namespace {

void
updateLastPagesOnUnregister(QHelpEngineCore& helpEngine, const QString& nsName)
{
    TRACE_OBJ
    int lastPage = CollectionConfiguration::lastTabPage(helpEngine);
    QStringList currentPages = CollectionConfiguration::lastShownPages(helpEngine);
    if (!currentPages.isEmpty()) {
        QStringList zoomList = CollectionConfiguration::lastZoomFactors(helpEngine);
        while (zoomList.count() < currentPages.count())
            zoomList.append(CollectionConfiguration::DefaultZoomFactor);

        for (int i = currentPages.count(); --i >= 0;) {
            if (QUrl(currentPages.at(i)).host() == nsName) {
                zoomList.removeAt(i);
                currentPages.removeAt(i);
                lastPage = (lastPage == (i + 1)) ? 1 : lastPage;
            }
        }

        CollectionConfiguration::setLastShownPages(helpEngine, currentPages);
        CollectionConfiguration::setLastTabPage(helpEngine, lastPage);
        CollectionConfiguration::setLastZoomFactors(helpEngine, zoomList);
    }
}

bool
updateUserCollection(QHelpEngineCore& user, const QHelpEngineCore& caller)
{
    TRACE_OBJ
    if (!CollectionConfiguration::isNewer(caller, user))
        return false;
    CollectionConfiguration::copyConfiguration(caller, user);
    return true;
}

void stripNonexistingDocs(QHelpEngineCore& collection)
{
    TRACE_OBJ
    const QStringList &namespaces = collection.registeredDocumentations();
    foreach (const QString &ns, namespaces) {
        QFileInfo fi(collection.documentationFileName(ns));
        if (!fi.exists() || !fi.isFile())
            collection.unregisterDocumentation(ns);
    }
}

QString indexFilesFolder(const QString &collectionFile)
{
    TRACE_OBJ
    QString indexFilesFolder = QLatin1String(".fulltextsearch");
    if (!collectionFile.isEmpty()) {
        QFileInfo fi(collectionFile);
        indexFilesFolder = QLatin1Char('.') +
            fi.fileName().left(fi.fileName().lastIndexOf(QLatin1String(".qhc")));
    }
    return indexFilesFolder;
}

/*
 * Returns the expected absolute file path of the cached collection file
 * correspondinging to the given collection's file.
 * It may or may not exist yet.
 */
QString constructCachedCollectionFilePath(const QHelpEngineCore &collection)
{
    TRACE_OBJ
    const QString &filePath = collection.collectionFile();
    const QString &fileName = QFileInfo(filePath).fileName();
    const QString &cacheDir = CollectionConfiguration::cacheDir(collection);
    const QString &dir = !cacheDir.isEmpty()
        && CollectionConfiguration::cacheDirIsRelativeToCollection(collection)
            ? QFileInfo(filePath).dir().absolutePath()
                + QDir::separator() + cacheDir
            : MainWindow::collectionFileDirectory(false, cacheDir);
    return dir + QDir::separator() + fileName;
}

bool synchronizeDocs(QHelpEngineCore &collection,
                     QHelpEngineCore &cachedCollection,
                     CmdLineParser &cmd)
{
    TRACE_OBJ
    const QDateTime &lastCollectionRegisterTime =
        CollectionConfiguration::lastRegisterTime(collection);
    if (!lastCollectionRegisterTime.isValid() || lastCollectionRegisterTime
        < CollectionConfiguration::lastRegisterTime(cachedCollection))
        return true;

    const QStringList &docs = collection.registeredDocumentations();
    const QStringList &cachedDocs = cachedCollection.registeredDocumentations();

    /*
     * Ensure that the cached collection contains all docs that
     * the collection contains.
     */
    foreach (const QString &doc, docs) {
        if (!cachedDocs.contains(doc)) {
            const QString &docFile = collection.documentationFileName(doc);
            if (!cachedCollection.registerDocumentation(docFile)) {
                cmd.showMessage(QCoreApplication::translate("Assistant",
                                    "Error registering documentation file '%1': %2").
                                arg(docFile).arg(cachedCollection.error()), true);
                return false;
            }
        }
    }

    CollectionConfiguration::updateLastRegisterTime(cachedCollection);

    return true;
}

bool removeSearchIndex(const QString &collectionFile)
{
    TRACE_OBJ
    QString path = QFileInfo(collectionFile).path();
    path += QLatin1Char('/') + indexFilesFolder(collectionFile);

    QLocalSocket localSocket;
    localSocket.connectToServer(QString(QLatin1String("QtAssistant%1"))
                                .arg(QLatin1String(QT_VERSION_STR)));

    QDir dir(path); // check if there is no other instance ruinning
    if (!dir.exists() || localSocket.waitForConnected())
        return false;

    QStringList lst = dir.entryList(QDir::Files | QDir::Hidden);
    foreach (const QString &item, lst)
        dir.remove(item);
    return true;
}

bool rebuildSearchIndex(QCoreApplication *app, const QString &collectionFile,
                        CmdLineParser &cmd)
{
    TRACE_OBJ
    QHelpEngine engine(collectionFile);
    if (!engine.setupData()) {
        cmd.showMessage(QCoreApplication::translate("Assistant", "Error: %1")
                        .arg(engine.error()), true);
        return false;
    }

    QHelpSearchEngine * const searchEngine = engine.searchEngine();
    QObject::connect(searchEngine, SIGNAL(indexingFinished()), app,
                     SLOT(quit()));
    searchEngine->reindexDocumentation();
    return app->exec() == 0;
}

QCoreApplication* createApplication(int &argc, char *argv[])
{
    TRACE_OBJ
#ifndef Q_OS_WIN
    // Look for arguments that imply command-line mode.
    const char * cmdModeArgs[] = {
        "-help", "-register", "-unregister", "-remove-search-index",
        "-rebuild-search-index"
    };
    for (int i = 1; i < argc; ++i) {
        for (size_t j = 0; j < sizeof cmdModeArgs/sizeof *cmdModeArgs; ++j) {
            if (strcmp(argv[i], cmdModeArgs[j]) == 0)
                return new QCoreApplication(argc, argv);
        }
    }
#endif
    return new QApplication(argc, argv);
}

bool registerDocumentation(QHelpEngineCore &collection, CmdLineParser &cmd,
                           bool printSuccess)
{
    TRACE_OBJ
    if (!collection.registerDocumentation(cmd.helpFile())) {
        cmd.showMessage(QCoreApplication::translate("Assistant",
                     "Could not register documentation file\n%1\n\nReason:\n%2")
                     .arg(cmd.helpFile()).arg(collection.error()), true);
        return false;
    }
    if (printSuccess)
        cmd.showMessage(QCoreApplication::translate("Assistant",
                            "Documentation successfully registered."),
                        false);
    CollectionConfiguration::updateLastRegisterTime(collection);
    return true;
}

bool unregisterDocumentation(QHelpEngineCore &collection,
    const QString &namespaceName, CmdLineParser &cmd, bool printSuccess)
{
    TRACE_OBJ
    if (!collection.unregisterDocumentation(namespaceName)) {
        cmd.showMessage(QCoreApplication::translate("Assistant",
                             "Could not unregister documentation"
                             " file\n%1\n\nReason:\n%2").
                        arg(cmd.helpFile()).arg(collection.error()), true);
        return false;
    }
    updateLastPagesOnUnregister(collection, namespaceName);
    if (printSuccess)
        cmd.showMessage(QCoreApplication::translate("Assistant",
                            "Documentation successfully unregistered."),
                        false);
    return true;
}

void setupTranslation(const QString &fileName, const QString &dir)
{
    QTranslator *translator = new QTranslator(QCoreApplication::instance());
    if (translator->load(fileName, dir))
        QCoreApplication::installTranslator(translator);
#ifdef DEBUG_TRANSLATIONS
    else if (!fileName.endsWith(QLatin1String("en_US"))
             && !fileName.endsWith(QLatin1String("_C"))) {
        qDebug("Could not load translation file %s in directory %s.",
               qPrintable(fileName), qPrintable(dir));
    }
#endif
}

void setupTranslations()
{
    TRACE_OBJ
    const QString& locale = QLocale::system().name();
    const QString &resourceDir
        = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
    setupTranslation(QLatin1String("assistant_") + locale, resourceDir);
    setupTranslation(QLatin1String("qt_") + locale, resourceDir);
    setupTranslation(QLatin1String("qt_help_") + locale, resourceDir);
}

} // Anonymous namespace.

int main(int argc, char *argv[])
{
    TRACE_OBJ
    QScopedPointer<QCoreApplication> a(createApplication(argc, argv));
    a->addLibraryPath(a->applicationDirPath() + QLatin1String("/plugins"));
    setupTranslations();

#if !defined(QT_NO_WEBKIT)
    if (qobject_cast<QApplication *>(a.data())) {
        QFont f;
        f.setStyleHint(QFont::SansSerif);
        QWebSettings::globalSettings()->setFontFamily(QWebSettings::StandardFont, f.defaultFamily());
    }
#endif

    // Parse arguments.
    CmdLineParser cmd(a->arguments());
    CmdLineParser::Result res = cmd.parse();
    if (res == CmdLineParser::Help)
        return 0;
    else if (res == CmdLineParser::Error)
        return -1;

    /*
     * Create the collection objects that we need. We always have the
     * cached collection file. Depending on whether the user specified
     * one, we also may have an input collection file.
     */
    const QString collectionFile = cmd.collectionFile();
    const bool collectionFileGiven = !collectionFile.isEmpty();
    QScopedPointer<QHelpEngineCore> collection;
    if (collectionFileGiven) {
        collection.reset(new QHelpEngineCore(collectionFile));
        if (!collection->setupData()) {
            cmd.showMessage(QCoreApplication::translate("Assistant",
                                "Error reading collection file '%1': %2.").
                arg(collectionFile).arg(collection->error()), true);
            return EXIT_FAILURE;
        }
    }
    const QString &cachedCollectionFile = collectionFileGiven
        ? constructCachedCollectionFilePath(*collection)
        : MainWindow::defaultHelpCollectionFileName();
    if (collectionFileGiven && !QFileInfo(cachedCollectionFile).exists()
        && !collection->copyCollectionFile(cachedCollectionFile)) {
        cmd.showMessage(QCoreApplication::translate("Assistant",
                            "Error creating collection file '%1': %2.").
                arg(cachedCollectionFile).arg(collection->error()), true);
        return EXIT_FAILURE;
    }
    QHelpEngineCore cachedCollection(cachedCollectionFile);
    if (!cachedCollection.setupData()) {
        cmd.showMessage(QCoreApplication::translate("Assistant",
                            "Error reading collection file '%1': %2.").
                        arg(cachedCollectionFile).
                        arg(cachedCollection.error()), true);
        return EXIT_FAILURE;
    }

    stripNonexistingDocs(cachedCollection);
    if (collectionFileGiven) {
        if (CollectionConfiguration::isNewer(*collection, cachedCollection))
            CollectionConfiguration::copyConfiguration(*collection,
                                                       cachedCollection);
        if (!synchronizeDocs(*collection, cachedCollection, cmd))
            return EXIT_FAILURE;
    }

    if (cmd.registerRequest() != CmdLineParser::None) {
        const QStringList &cachedDocs =
            cachedCollection.registeredDocumentations();
        const QString &namespaceName =
            QHelpEngineCore::namespaceName(cmd.helpFile());
        if (cmd.registerRequest() == CmdLineParser::Register) {
            if (collectionFileGiven
                && !registerDocumentation(*collection, cmd, true))
                return EXIT_FAILURE;
            if (!cachedDocs.contains(namespaceName)
                && !registerDocumentation(cachedCollection, cmd, !collectionFileGiven))
                return EXIT_FAILURE;
            return EXIT_SUCCESS;
        }
        if (cmd.registerRequest() == CmdLineParser::Unregister) {
            if (collectionFileGiven
                && !unregisterDocumentation(*collection, namespaceName, cmd, true))
                return EXIT_FAILURE;
            if (cachedDocs.contains(namespaceName)
                && !unregisterDocumentation(cachedCollection, namespaceName,
                                            cmd, !collectionFileGiven))
                return EXIT_FAILURE;
            return EXIT_SUCCESS;
        }
    }

    if (cmd.removeSearchIndex()) {
        return removeSearchIndex(cachedCollectionFile)
            ? EXIT_SUCCESS : EXIT_FAILURE;
    }

    if (cmd.rebuildSearchIndex()) {
        return rebuildSearchIndex(a.data(), cachedCollectionFile, cmd)
            ? EXIT_SUCCESS : EXIT_FAILURE;
    }

    if (!QSqlDatabase::isDriverAvailable(QLatin1String("QSQLITE"))) {
        cmd.showMessage(QCoreApplication::translate("Assistant",
                            "Cannot load sqlite database driver!"),
                        true);
        return EXIT_FAILURE;
    }

    if (!cmd.currentFilter().isEmpty()) {
        if (collectionFileGiven)
            collection->setCurrentFilter(cmd.currentFilter());
        cachedCollection.setCurrentFilter(cmd.currentFilter());
    }

    if (collectionFileGiven)
        cmd.setCollectionFile(cachedCollectionFile);

    MainWindow *w = new MainWindow(&cmd);
    w->show();
    a->connect(a.data(), SIGNAL(lastWindowClosed()), a.data(), SLOT(quit()));

    /*
     * We need to be careful here: The main window has to be deleted before
     * the help engine wrapper, which has to be deleted before the
     * QApplication.
     */
    const int retval = a->exec();
    delete w;
    HelpEngineWrapper::removeInstance();
    return retval;
}