aboutsummaryrefslogtreecommitdiffstats
path: root/src/remotereceiver.cpp
blob: d3de7f740f81dcf101776e66fdb9a5013da61de6 (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
/****************************************************************************
**
** Copyright (C) 2016 Pelagicore AG
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QmlLive tool.
**
** $QT_BEGIN_LICENSE:GPL-QTAS$
** Commercial License Usage
** Licensees holding valid commercial Qt Automotive Suite 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 or (at your option) any later version
** approved by the KDE Free Qt Foundation. The licenses are as published by
** the Free Software Foundation and appearing in the file LICENSE.GPL3
** 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.
**
** $QT_END_LICENSE$
**
** SPDX-License-Identifier: GPL-3.0
**
****************************************************************************/

#include "remotereceiver.h"
#include "ipc/ipcserver.h"
#include "ipc/ipcclient.h"
#include "livenodeengine.h"

#include <QTcpSocket>

#ifdef QMLLIVE_DEBUG
#define DEBUG qDebug()
#else
#define DEBUG if (0) qDebug()
#endif


/*!
 * \class RemoteReceiver
 * \brief Receives commands form the remote publisher
 * \inmodule qmllive
 *
 * Receives commands from a remote publisher to publish workspace files and to
 * setup the active document.
 */

/*!
 * \enum RemoteReceiver::ConnectionOption
 *
 * This enum type is used to select optional connection related features:
 *
 * \value NoConnectionOption
 *        No optional feature is enabled.
 * \value UpdateDocumentsOnConnect
 *        The remote publisher will be asked to publish all workspace files on
 *        connect. This applies to the very first connection only.
 * \value BlockingConnect
 *        Call to \l listen() will block until a connection from remote publisher
 *        is open and (optional) PIN exchange and (optional) initial documents
 *        update finishes.
 *
 * \sa listen()
 */

/*!
 * Standard Constructor using \a parent as parent
 */
RemoteReceiver::RemoteReceiver(QObject *parent)
    : QObject(parent)
    , m_server(new IpcServer(this))
    , m_node(0)
    , m_connectionAcknowledged(false)
    , m_socket(0)
    , m_client(0)
    , m_bulkUpdateInProgress(false)
    , m_updateDocumentsOnConnectState(UpdateNotStarted)
    , m_logSentPosition(0)
{
    void (IpcServer::*IpcServer__clientConnected_socket)(QTcpSocket*) = &IpcServer::clientConnected;
    void (IpcServer::*IpcServer__clientConnected_address)(const QHostAddress &) = &IpcServer::clientConnected;
    void (IpcServer::*IpcServer__clientDisconnected_address)(const QHostAddress &) = &IpcServer::clientDisconnected;

    connect(m_server, &IpcServer::received, this, &RemoteReceiver::handleCall);
    connect(m_server, IpcServer__clientConnected_socket, this, &RemoteReceiver::onClientConnected);
    connect(m_server, IpcServer__clientConnected_address, this, &RemoteReceiver::clientConnected);
    connect(m_server, IpcServer__clientDisconnected_address, this, &RemoteReceiver::clientDisconnected);
}

/*!
 * Listens on remote publisher connections on \a port with given \a options. If
 * \a options contains BlockingConnect the return value indicates whether PIN
 * exchange and/or initial documents update was successful. Otherwise the
 * return value is always \c true.
 */
bool RemoteReceiver::listen(int port, ConnectionOptions options)
{
    m_connectionOptions = options;
    m_server->listen(port);

    if (m_connectionOptions & BlockingConnect) {
        qInfo() << "Waiting for connection from QmlLive Bench…";

        QEventLoop loop;

        if (!m_pin.isEmpty()) {
            bool pinOk = false;
            connect(this, &RemoteReceiver::pinOk, [&loop, &pinOk](bool ok) {
                pinOk = ok;
                loop.quit();
            });
            loop.exec();
            if (!pinOk) {
                qWarning() << "Refused connection from QmlLive Bench: Wrong pin";
                return false;
            }
        }

        if (m_connectionOptions & UpdateDocumentsOnConnect) {
            bool finishedOk = false;
            connect(this, &RemoteReceiver::updateDocumentsOnConnectFinished, [&loop, &finishedOk](bool ok) {
                finishedOk = ok;
                loop.quit();
            });
            loop.exec();
            if (!finishedOk) {
                qWarning() << "Initial workspace synchronization with QmlLive Bench failed";
                return false;
            }
        }

        qInfo() << "QmlLive Bench connected";
    }

    return true;
}

/*!
 * Sets the \a pin to access this live node
 */
void RemoteReceiver::setPin(const QString &pin)
{
    m_pin = pin;
}

/*!
 * Returns the current pin
 */
QString RemoteReceiver::pin() const
{
    return m_pin;
}

/*!
 * Set maximum allowed client connection to \a max
 */
void RemoteReceiver::setMaxConnections(int max)
{
    m_server->setMaxConnections(max);
}

/*!
 * Handle RPC calls with \a method and data as \a content
 */
void RemoteReceiver::handleCall(const QString &method, const QByteArray &content)
{
    DEBUG << "RemoteReceiver::handleIpcCall: " << method;

    if (method == "checkPin(QString)") {
        QString pin;
        QDataStream in(content);
        in >> pin;
        if (m_pin == pin && m_client) {
            m_connectionAcknowledged = true;
            emit pinOk(true);
            m_client->send("pinOK(bool)", QByteArray::number(1));
            maybeStartUpdateDocumentsOnConnect();
        } else if (m_client) {
            emit pinOk(false);
            m_client->send("pinOK(bool)", QByteArray::number(0));
            return;
        }
    }

    if (!m_connectionAcknowledged) {
        qWarning() << "Connecting without Pin Authentication is not allowed";
        return;
    }

    if (method == "setXOffset(int)") {
        int offset;
        QDataStream in(content);
        in >> offset;
        emit xOffsetChanged(offset);
    } else if (method == "setYOffset(int)") {
        int offset;
        QDataStream in(content);
        in >> offset;
        emit yOffsetChanged(offset);
    } else if (method == "setRotation(int)") {
        int rotation;
        QDataStream in(content);
        in >> rotation;
        emit rotationChanged(rotation);
    } else if (method == "beginBulkSend()") {
        if (!m_bulkUpdateInProgress) {
            m_bulkUpdateInProgress = true;
            emit beginBulkUpdate();
            if (m_updateDocumentsOnConnectState == UpdateRequested)
                m_updateDocumentsOnConnectState = UpdateStarted;
        } else {
            qCritical() << "Ignoring nested 'beginBulkSend()' call";
        }
    } else if (method == "endBulkSend()") {
        if (m_bulkUpdateInProgress) {
            m_bulkUpdateInProgress = false;
            emit endBulkUpdate();
            if (m_updateDocumentsOnConnectState == UpdateStarted) {
                m_updateDocumentsOnConnectState = UpdateFinished;
                finishConnectionInitialization();
                emit updateDocumentsOnConnectFinished(true);
            }
        } else {
            qCritical() << "Ignoring unpaired 'endBulkSend()' call";
        }
    } else if (method == "sendDocument(QString,QByteArray)") {
        QString document;
        QByteArray data;
        QDataStream in(content);
        in >> document;
        in >> data;
        emit updateDocument(LiveDocument(document), data);
    } else if (method == "activateDocument(QString)") {
        QString document;
        QDataStream in(content);
        in >> document;
        qDebug() << "\tactivate document: " << document;
        emit activateDocument(LiveDocument(document));
    } else if (method == "ping()") {
        if (m_client)
            m_client->send("pong()", QByteArray());
    }
}

/*!
 * Register the \a node to be notified about changes
 */
void RemoteReceiver::registerNode(LiveNodeEngine *node)
{
    if (m_node) { disconnect(m_node); }
    m_node = node;
    connect(m_node, &LiveNodeEngine::logErrors, this, &RemoteReceiver::appendToLog);
    connect(m_node, &LiveNodeEngine::clearLog, this, &RemoteReceiver::clearLog);
    connect(m_node, &LiveNodeEngine::activeDocumentChanged, this, &RemoteReceiver::onActiveDocumentChanged);
    connect(this, &RemoteReceiver::activateDocument, m_node, &LiveNodeEngine::loadDocument);
    connect(this, &RemoteReceiver::updateDocument, m_node, &LiveNodeEngine::updateDocument);
    connect(this, &RemoteReceiver::xOffsetChanged, m_node, &LiveNodeEngine::setXOffset);
    connect(this, &RemoteReceiver::yOffsetChanged, m_node, &LiveNodeEngine::setYOffset);
    connect(this, &RemoteReceiver::rotationChanged, m_node, &LiveNodeEngine::setRotation);
}

/*!
 * Handles client connection and if required requests pin authentication
 */
void RemoteReceiver::onClientConnected(QTcpSocket *socket)
{
    if (m_client)
        delete m_client;

    m_client = new IpcClient(socket, this);

    m_socket = socket;

    if (!m_pin.isEmpty()) {
        m_client->send("needsPinAuthentication()", QByteArray());
        m_connectionAcknowledged = false;
    } else {
        m_connectionAcknowledged = true;
        maybeStartUpdateDocumentsOnConnect();
    }
}

void RemoteReceiver::onClientDisconnected(QTcpSocket *socket)
{
    Q_ASSERT(socket == m_socket);
    Q_UNUSED(socket);

    if (m_updateDocumentsOnConnectState != UpdateNotStarted) {
        if (m_updateDocumentsOnConnectState != UpdateFinished) {
            emit updateDocumentsOnConnectFinished(false);
            m_updateDocumentsOnConnectState = UpdateFinished;
        }
    }
    if (m_bulkUpdateInProgress)
        emit endBulkUpdate();
}
void RemoteReceiver::maybeStartUpdateDocumentsOnConnect()
{
    if (m_connectionOptions & UpdateDocumentsOnConnect
            && m_updateDocumentsOnConnectState == UpdateNotStarted) {
        m_client->send("needsPublishWorkspace()", QByteArray());
        m_updateDocumentsOnConnectState = UpdateRequested;
    } else {
        finishConnectionInitialization();
    }
}

void RemoteReceiver::finishConnectionInitialization()
{
    if (!m_node->activeDocument().isNull())
        onActiveDocumentChanged(m_node->activeDocument());

    m_logSentPosition = 0;
    flushLog();
}

/*!
 * Called to send \a errors to remote for remote logging
 */
void RemoteReceiver::appendToLog(const QList<QQmlError> &errors)
{
    m_log.append(errors);

    if (!m_client)
        return;

    flushLog();
}

void RemoteReceiver::flushLog()
{
    for (; m_logSentPosition < m_log.count(); ++m_logSentPosition) {
        const QQmlError &err = m_log.at(m_logSentPosition);
        if (!err.isValid())
            continue;

        QtMsgType type = QtDebugMsg;

        if (err.description().contains(QString::fromLatin1("error"), Qt::CaseInsensitive) ||
            err.description().contains(QString::fromLatin1("is not installed"), Qt::CaseInsensitive) ||
            err.description().contains(QString::fromLatin1("is not a type"), Qt::CaseInsensitive))
            type = QtCriticalMsg;
        else if (err.description().contains(QString::fromLatin1("warning"), Qt::CaseInsensitive))
            type = QtWarningMsg;

        QByteArray bytes;
        QDataStream out(&bytes, QIODevice::WriteOnly);
        out << type;
        out << err.description();
        out << err.url();
        out << err.line();
        out << err.column();

        m_client->send("qmlLog(QtMsgType, QString, QUrl, int, int)", bytes);
    }
}

/*!
 * Called to clear remote logging output
 */
void RemoteReceiver::clearLog()
{
    m_log.clear();
    m_logSentPosition = 0;

    if (!m_client)
        return;

    m_client->send("clearLog()", QByteArray());
}

/*!
 * Called to notify bench about active document change
 */
void RemoteReceiver::onActiveDocumentChanged(const LiveDocument &document)
{
    if (!m_client)
        return;

    QByteArray bytes;
    QDataStream out(&bytes, QIODevice::WriteOnly);
    out << document.relativeFilePath();

    m_client->send("activeDocumentChanged(QString)", bytes);
}

/*!
 * \fn void RemoteReceiver::activateDocument(const LiveDocument& document)
 *
 * This signal is emitted when the remote active document \a document has changed
 */

/*!
 * \fn void RemoteReceiver::reload()
 *
 * This signal is emitted to notify that a relaod is requested by the remote client
 */

/*!
 * \fn void RemoteReceiver::clientConnected(const QHostAddress& address)
 *
 * This signal is emitted when a new client with address \a address has been connected
 */

/*!
 * \fn void RemoteReceiver::clientDisconnected(const QHostAddress& address)
 *
 * This signal is emitted when a client with address \a address has been disconnected
 */

/*!
 * \fn void RemoteReceiver::pinOk(bool ok)
 *
 * This signal is emitted to notiify that the pin entered on the remote side is valid, if \a ok equals true
 */

/*!
 * \fn void RemoteReceiver::xOffsetChanged(int offset)
 *
 * This signal is emitted to notify the view to apply the x-offset \a offset
 */

/*!
 * \fn void RemoteReceiver::yOffsetChanged(int offset)
 *
 * This signal is emitted to notify the view to apply the y-offset \a offset
 */

/*!
 * \fn void RemoteReceiver::rotationChanged(int rotation)
 *
 * This signal is emitted to notify the view to apply the rotation with the angle \a rotation
 */

/*!
 * \fn void RemoteReceiver::beginBulkUpdate()
 *
 * This signal is emitted before an expected sequence of \l updateDocument emissions.
 */

/*!
 * \fn void RemoteReceiver::endBulkUpdate()
 *
 * This signal is emitted after an expected sequence of \l updateDocument emissions.
 */

/*!
 * \fn void RemoteReceiver::updateDocumentsOnConnectFinished(bool ok)
 *
 * This signal is emitted to notify that the (optional) initial update of all
 * workspace documents finished. \a ok indicates its result.
 *
 * \sa UpdateDocumentsOnConnect
 */

/*!
 * \fn void RemoteReceiver::updateDocument(const LiveDocument &document, const QByteArray &content)
 *
 * This signal is emitted to notify that a \a document has changed its \a content
 */