summaryrefslogtreecommitdiff
path: root/src/frontend/display/bthtmlreaddisplay.cpp
blob: eace51f6984e1b6462c33f811c7ce4d5de730ddc (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
/*********
*
* This file is part of BibleTime's source code, http://www.bibletime.info/.
*
* Copyright 1999-2016 by the BibleTime developers.
* The BibleTime source code is licensed under the GNU General Public License version 2.0.
*
**********/

#include "frontend/display/bthtmlreaddisplay.h"

#include <memory>
#include <QMenu>
#include <QDebug>
#include <QString>
#include <QTimer>
#include "backend/keys/cswordkey.h"
#include "backend/managers/referencemanager.h"
#include "bibletime.h"
#include "frontend/cdragdrop.h"
#include "frontend/cinfodisplay.h"
#include "frontend/cmdiarea.h"
#include "frontend/display/bthtmljsobject.h"
#include "frontend/displaywindow/cdisplaywindow.h"
#include "frontend/displaywindow/creadwindow.h"
#include "util/btassert.h"
#include "util/btconnect.h"
#include "util/directory.h"

#ifdef USEWEBENGINE
#include <QWebEngineScript>
#include <QWebEngineScriptCollection>
#endif

using namespace InfoDisplay;

#ifdef USEWEBENGINE
static QString javascriptFile = "btwebengine.js";
#else
static QString javascriptFile = "bthtml.js";
#endif

static QString s_javascript; // Initialized from javascript file

// This is s work around for Qt bug 51565
// It is also documented in BibleTime bug #53
static void clearChildFocusWidget(QWidget * widget) {
    QWidget * childFocusedWidget = widget->focusWidget();
    if (childFocusedWidget)
        childFocusedWidget->clearFocus();
}

BtHtmlReadDisplay::BtHtmlReadDisplay(CReadWindow* readWindow, QWidget* parentWidget)
    : BtWebEnginePage(parentWidget), CReadDisplay(readWindow), m_magTimerId(0), m_view(nullptr), m_jsObject(nullptr)

{
    m_view = new BtHtmlReadDisplayView(this, parentWidget ? parentWidget : readWindow, readWindow);
    m_view->setAcceptDrops(true);
    m_view->setPage(this);
    setParent(m_view);
    m_view->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    loadJSObject();
    loadScripts();
    m_view->setHtml("");    // This sets focus on a child widget
    clearChildFocusWidget(m_view);

    BT_CONNECT(this, SIGNAL(loadFinished(bool)),
               this, SLOT(slotLoadFinished(bool)));
}

BtHtmlReadDisplay::~BtHtmlReadDisplay() {
    setView(nullptr);
}

void BtHtmlReadDisplay::loadScripts() {
    namespace DU = util::directory;

    QString jScript;
#ifdef USEWEBENGINE
     jScript = readJavascript(":/qtwebchannel/qwebchannel.js");
#endif
    QString jsFile = DU::getJavascriptDir().canonicalPath() + "/" + javascriptFile;
    jScript += readJavascript(jsFile);

#ifdef USEWEBENGINE
    // Directly load javascript into QWebEngine
    QWebEngineScript script;
    script.setInjectionPoint(QWebEngineScript::DocumentReady);
    script.setWorldId(QWebEngineScript::MainWorld);
    script.setSourceCode(jScript);
    script.setName("script1");
    scripts().insert(script);
#else
    // Save javascript and load each time the document is loaded (setHtml)
    s_javascript = jScript;
#endif
}

QString BtHtmlReadDisplay::readJavascript(const QString& jsFileName) {
    QString javascript;
    QFile file(jsFileName);
    if (file.open(QFile::ReadOnly)) {
        while (!file.atEnd()) {
            QString line = file.readLine();
            javascript = javascript + line;
        }
        file.close();
    } else {
        qWarning() << objectName() << ": Missing " +jsFileName;
    }
    return javascript;
}

// When the QWebFrame is cleared, this function is called to install the
// javascript object (BtHtmlJsObject class) into the Javascript model.
// It is called only once with QWebEngine.
void BtHtmlReadDisplay::loadJSObject() {
    // Starting with Qt 4.7.4 with QtWebKit 2.2 stronger security checking occurs.
    // The BtHtmlJsObject that is associated with a given load of a page is rejected
    // as causing a cross site security problem when a new page is loaded. Deleting
    // the object and creating it new for each page loaded allows the object to access
    // javascript variables without this security issue.
    if (m_jsObject != nullptr)
        delete m_jsObject;
    m_jsObject = new BtHtmlJsObject(this);
    addJavaScriptObject("btHtmlJsObject", m_jsObject);
}

const QString BtHtmlReadDisplay::text( const CDisplay::TextType format, const CDisplay::TextPart part) {
    switch (part) {
        case Document: {
            if (format == HTMLText) {
                return getCurrentSource();
            }
            else {
                CDisplayWindow* window = parentWindow();
                CSwordKey* const key = window->key();
                const CSwordModuleInfo *module = key->module();
                //This is never used for Bibles, so it is not implemented for
                //them.  If it should be, see CReadDisplay::print() for example
                //code.
                BT_ASSERT(module->type() == CSwordModuleInfo::Lexicon ||
                         module->type() == CSwordModuleInfo::Commentary ||
                         module->type() == CSwordModuleInfo::GenericBook);
                if (module->type() == CSwordModuleInfo::Lexicon ||
                        module->type() == CSwordModuleInfo::Commentary ||
                        module->type() == CSwordModuleInfo::GenericBook) {

                    FilterOptions filterOptions;
                    CSwordBackend::instance()->setFilterOptions(filterOptions);

                    return QString(key->strippedText()).append("\n(")
                           .append(key->key())
                           .append(", ")
                           .append(key->module()->name())
                           .append(")");
                }
            }
        }

        case SelectedText: {
            if (!hasSelection()) {
                return QString::null;
            }
            else if (format == HTMLText) {
                //    \todo It does not appear this is ever called
            }
            else { //plain text requested
                return selectedText();
            }
        }

        case AnchorOnly: {
            QString moduleName;
            QString keyName;
            ReferenceManager::Type type;
            ReferenceManager::decodeHyperlink(activeAnchor(), moduleName, keyName, type);

            return keyName;
        }

        case AnchorTextOnly: {
            QString moduleName;
            QString keyName;
            ReferenceManager::Type type;
            ReferenceManager::decodeHyperlink(activeAnchor(), moduleName, keyName, type);

            if (CSwordModuleInfo *module = CSwordBackend::instance()->findModuleByName(moduleName)) {
                std::unique_ptr<CSwordKey> key(CSwordKey::createInstance(module));
                key->setKey(keyName);

                return key->strippedText();
            }
            return QString::null;
        }

        case AnchorWithText: {
            QString moduleName;
            QString keyName;
            ReferenceManager::Type type;
            ReferenceManager::decodeHyperlink(activeAnchor(), moduleName, keyName, type);

            if (CSwordModuleInfo *module = CSwordBackend::instance()->findModuleByName(moduleName)) {
                std::unique_ptr<CSwordKey> key(CSwordKey::createInstance(module));
                key->setKey(keyName);

                FilterOptions filterOptions;
                CSwordBackend::instance()->setFilterOptions(filterOptions);

                return QString(key->strippedText()).append("\n(")
                       .append(key->key())
                       .append(", ")
                       .append(key->module()->name())
                       .append(")");
                /*    ("%1\n(%2, %3)")
                    .arg()
                    .arg(key->key())
                    .arg(key->module()->name());*/
            }
            return QString::null;
        }
        default:
            return QString::null;
    }
    return QString::null;
}

// Puts html text and javascript into BtWebEngineView
void BtHtmlReadDisplay::setText( const QString& newText ) {
    QString jsText = newText;

#ifndef USEWEBENGINE
    // Inject javascript into the document
    jsText.replace(
        QString("</body>"),
        QString("<script  type=\"text/javascript\">").append(s_javascript).append("</script></body>")
    );

    // Disconnect any previous connections and connect to slot that loads the javascript object
    QWebFrame* frame = mainFrame();
    disconnect(frame, SIGNAL(javaScriptWindowObjectCleared()), nullptr, nullptr);
    BT_CONNECT(frame, SIGNAL(javaScriptWindowObjectCleared()),
               this, SLOT(loadJSObject()));
#endif

    // Send text to the html viewer
    m_view->setHtml(jsText);

    this->currentSource = jsText;
}

QString BtHtmlReadDisplay::getCurrentSource( ) {
    return this->currentSource;
}

// See if any text is selected
bool BtHtmlReadDisplay::hasSelection() const {
    return !selectedText().isEmpty();
}

// Reimplementation
// Returns the BtHtmlReadDisplayView object
QWidget* BtHtmlReadDisplay::view() {
    return m_view;
}

// Select all text in the viewer
void BtHtmlReadDisplay::selectAll() {
    BtWebEnginePage::selectAll();
}

// Scroll BtWebEngineView to the correct location as specified by the anchor
void BtHtmlReadDisplay::moveToAnchor( const QString& anchor ) {
#ifdef USEWEBENGINE
    // Rendering in QWebEngine is asynchronous, must delay before scroll to anchor
    // TODO - find a better solution
    m_currentAnchorCache = anchor;
    QTimer::singleShot(180, this, SLOT(slotDelayedMoveToAnchor()));
#else
    mainFrame()->scrollToAnchor(anchor);
#endif
}

void BtHtmlReadDisplay::slotDelayedMoveToAnchor() {
    m_jsObject->moveToAnchor(m_currentAnchorCache);
}

// Scroll the BtWebEngineView to the correct location specified by anchor
void BtHtmlReadDisplay::slotGoToAnchor(const QString& anchor) {
    m_jsObject->moveToAnchor(anchor);
}

// Save the Lemma (Strongs number) attribute
void BtHtmlReadDisplay::setLemma(const QString& lemma) {
    m_nodeInfo = lemma;
}

// Open the Find text dialog
void BtHtmlReadDisplay::openFindTextDialog() {
    BibleTime* bibleTime = parentWindow()->mdi()->bibleTimeWindow();
    bibleTime->openFindWidget();
}

// Send "completed" signal when the text is finished loading into the viewer
void BtHtmlReadDisplay::slotLoadFinished(bool) {
    emit completed();
}

// For debugging javascript - set breakpoint in this function to catch javascript error messages
#ifdef DEBUG_JS
void BtHtmlReadDisplay::javaScriptConsoleMessage (const QString& message, int lineNumber, const QString& sourceID ) {
}
#endif




// ----------------- BtHtmlReadDisplayView -------------------------------------

BtHtmlReadDisplayView::BtHtmlReadDisplayView(BtHtmlReadDisplay* displayWidget, QWidget* parent, CReadWindow* readWindow)
    : BtWebEngineView(parent), m_display(displayWidget), m_readWindow(readWindow) {
}

BtHtmlReadDisplayView::~BtHtmlReadDisplayView() {
    setPage(nullptr);
}

// Create the right mouse context menus
void BtHtmlReadDisplayView::contextMenuEvent(QContextMenuEvent* event) {
    if (QMenu* popup = m_display->installedPopup()) {
        popup->exec(event->globalPos());
    }
}

// Reimplementation from QWidget
void BtHtmlReadDisplayView::dropEvent( QDropEvent* e ) {
    if (e->mimeData()->hasFormat("BibleTime/Bookmark")) {
        //see docs for BTMimeData and QMimeData
        const QMimeData* mimedata = e->mimeData();
        if (mimedata != nullptr) {
            const BTMimeData* btmimedata = qobject_cast<const BTMimeData*>(mimedata);
            if (btmimedata != nullptr) {
                BookmarkItem item = (qobject_cast<const BTMimeData*>(e->mimeData()))->bookmark();
                m_display->connectionsProxy()->emitReferenceDropped(item.key());
                e->acceptProposedAction();
                return;
            }
        }
    };
    //don't accept the action!
//    e->ignore();
}

// Reimplementation from BtWebEngineView
void BtHtmlReadDisplayView::dragEnterEvent( QDragEnterEvent* e ) {
    if ( ! e->mimeData()->hasFormat("BibleTime/Bookmark"))
        return;

    const QMimeData* mimedata = e->mimeData();
    if (mimedata == nullptr)
        return;

    const BTMimeData* btmimedata = qobject_cast<const BTMimeData*>(mimedata);
    if (btmimedata == nullptr)
        return;

    BookmarkItem item = (qobject_cast<const BTMimeData*>(e->mimeData()))->bookmark();
    QString moduleName = item.module();
    CSwordModuleInfo *m = CSwordBackend::instance()->findModuleByName(moduleName);
    BT_ASSERT(m);

    CSwordModuleInfo::ModuleType bookmarkType = m->type();
    CSwordModuleInfo::ModuleType windowType = CSwordModuleInfo::Unknown;
    if (m_readWindow)
        windowType = m_readWindow->moduleType();

    // Is bible reference bookmark compatible with the window type?
    if ((bookmarkType == CSwordModuleInfo::Bible ||
        bookmarkType == CSwordModuleInfo::Commentary)) {
            if (windowType == CSwordModuleInfo::Bible ||
                windowType == CSwordModuleInfo::Commentary)
                e->acceptProposedAction();
#ifdef USEWEBENGINE
            BtWebEngineView::dragEnterEvent(e);  // Fix crash, QTBUG-54896, BT bug #70
#endif
            return;
    }

    // Is reference type compatible with window type
    if (bookmarkType == windowType) {
            e->acceptProposedAction();
#ifdef USEWEBENGINE
            BtWebEngineView::dragEnterEvent(e);  // Fix crash, QTBUG-54896, BT bug #70
#endif
            return;
    }

    return;
}

// Reimplementation from BtWebEngineView
void BtHtmlReadDisplayView::dragMoveEvent( QDragMoveEvent* e ) {
    if (e->mimeData()->hasFormat("BibleTime/Bookmark")) {
        e->acceptProposedAction();
        return;
    }
    //don't accept the action!
    e->ignore();
}

bool BtHtmlReadDisplayView::event(QEvent* e) {
    // If the mouse leaves the widget clear the previous attribute
    // in bthtmljsobject. This cancels any time out event that
    // is in progress.
    if ( e->type() == QEvent::Leave )
        m_display->m_jsObject->clearPrevAttribute();
    return QWidget::event(e);
}