summaryrefslogtreecommitdiffstats
path: root/src/imports/serviceframework/qdeclarativeservice.cpp
blob: 93080eb98632625f5aa99b6e58d22fee5e0a2b11 (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
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtSystems module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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 Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or 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.GPL2 and 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-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qdeclarativeservice_p.h"

#include <QQmlEngine>
#include <QQmlInfo>

#include <qservicereply.h>

QT_BEGIN_NAMESPACE

/*!
    \qmltype ServiceLoader
    \instantiates QDeclarativeService

    \brief The ServiceLoader element holds an instance of a service object.
    \inherits QObject
    \inqmlmodule QtServiceFramework
    \ingroup qml-serviceframework

    The ServiceLoader element is part of the Qt ServiceFramework API and
    provides a client instance of the service object. This element allows the specification of
    the Service::interfaceName to locate the default service implemented at this interface.

    To request a service more specifically, you can filter available ServiceDescriptors with
    the ServiceFilter element, and then request service objects based off them.

    Either way, the ServiceLoader element will provide you with the QtObject provided by that service
    interface. You can then use its properties, signals, and slots as defined by its interface.

    Example:
    \code
    import QtQuick 2.0
    import QtServiceFramework 5.0

    QtObject {
        property alias serviceObject: service.serviceObject //In case you want to expose it upwards
        ServiceLoader {
            interfaceName: "com.qt.nokia.example.interface"
            onStatusChanged: {
                if (status == Service.Ready)
                    foo(serviceObject); //In case you want to do something with it as soon as it loads
                else if (status == Service.Error)
                    errorHandling(errorString()); //In case you want to do error handling.
            }
        }
    }
    \endcode

    \sa ServiceList
*/
QDeclarativeServiceLoader::QDeclarativeServiceLoader()
    : m_serviceDescriptor(0), m_status(Null), m_asynchronous(true),
    m_serviceObject(0), m_componentComplete(false), m_serviceManager(0),
    m_serviceReply(0)
{
}

QDeclarativeServiceLoader::~QDeclarativeServiceLoader()
{
    //Manager has qobject ownership
    delete m_serviceObject;//QOBJECT parented?
    delete m_serviceReply;
}

/*!
    \qmlmethod string ServiceLoader::errorString()

    This method returns a human readable description of the last error.

    If the status is not ServiceLoader.Error, errorString() will return an empty string.
*/
/*!
    \qmlproperty Status ServiceLoader::status

    This property contains the status of the service object. It will be one of the following:

    \list
    \li ServiceLoader.Null - the service is inactive or no service has been set
    \li ServiceLoader.Ready - the service has been loaded
    \li ServiceLoader.Loading - the service is currently being loaded
    \li ServiceLoader.Error - an error occurred while loading the service
    \endlist

    If you want to do something immediately after the service loads, the recommended route is
    to monitor this property. For example:
    \code
    ServiceLoader {
        onStatusChanged: {
            if (status == ServiceLoader.Ready)
                doStuffWith(serviceObject)
            else if (status == ServiceLoader.Error)
                console.debug(errorString())
        }
    }
    \endcode

*/
/*!
    \qmlproperty bool ServiceLoader::asynchronous

    If asynchronous is false, then the element will block the main thread until a service object
    is found or an error occurs. This will skip the Loading status. This is generally not
    recommended, as blocking the main thread can lead to significant problems with user interface
    responsiveness.

    Default is true.
*/
/*!
    \qmlproperty string ServiceLoader::interfaceName

    Set this to select a service based off of the interface name. The service name,
    and service version, will be selected for you if a match is found.
*/
/*!
    \qmlproperty ServiceDescriptor* ServiceLoader::serviceDescriptor

    Set this to select a specific service. ServiceDescriptors can be obtained
    from the ServiceFilter element.

*/


/*!
    \qmlproperty QObject* ServiceLoader::serviceObject

    This property holds an instance of the service object which
    can be used to make metaobject calls to the service.

    serviceObject is only valid when the status property is set to
    ServiceLoader.Ready. Otherwise, it should be a null reference.
*/
void QDeclarativeServiceLoader::componentComplete()
{
    if (!m_interfaceName.isEmpty() || m_serviceDescriptor)
        startLoading();
    m_componentComplete = true;
}

void QDeclarativeServiceLoader::startLoading()
{
    if (m_serviceReply) // Cancel pending requests
        delete m_serviceReply; //Auto-disconnects signals

    if (m_serviceObject) {
        m_serviceObject->deleteLater();
        m_serviceObject = 0;
        emit serviceObjectChanged(0);// In sync only, you might get an extra signal
    }

    if (!m_serviceDescriptor && m_interfaceName.isEmpty()) { //Actually an 'unset' request
        setStatus(Null);
        return;
    }

    if (!m_serviceManager)
        m_serviceManager = new QServiceManager(this);

    if (m_asynchronous) {
        if (m_serviceDescriptor)
            m_serviceReply = m_serviceManager->loadInterfaceRequest(*m_serviceDescriptor);
        else
            m_serviceReply = m_serviceManager->loadInterfaceRequest(m_interfaceName);
        connect(m_serviceReply, SIGNAL(finished()),
                this, SLOT(finishLoading()));
        setStatus(Loading);
    } else {
        finishLoading();
    }
}

QString stringForError(QServiceManager::Error error)// ### Should we just expose the enum? Or merely pick better strings?
{
    switch (error) {
    case QServiceManager::NoError: return QLatin1String("No error occurred.");
    case QServiceManager::StorageAccessError: return QLatin1String("Storage access error.");
    case QServiceManager::InvalidServiceLocation: return QLatin1String("Invalid service location.");
    case QServiceManager::InvalidServiceXml: return QLatin1String("Invalid service XML.");
    //case QService::InvalidInterfaceDescriptor: return QLatin1String("Invalid interface descriptor.");
    case QServiceManager::PluginLoadingFailed: return QLatin1String("Error loading service plugin.");
    case QServiceManager::ComponentNotFound: return QLatin1String("Service component not found.");
    case QServiceManager::ServiceCapabilityDenied: return QLatin1String("You do not have permission to access this service capability.");
    default: break;
    }
    return QLatin1String("Unknown error.");
}

void QDeclarativeServiceLoader::finishLoading()
{
    Q_ASSERT(m_serviceManager);
    QServiceManager::Error error;
    QObject* prevObject = m_serviceObject;
    if (m_serviceReply) {
        if (!m_serviceReply->isFinished())
            return; //TODO: Evaluate/handle this error condition
        error = m_serviceReply->error();
        m_serviceObject = m_serviceReply->proxyObject();
        m_serviceReply->deleteLater();
        m_serviceReply = 0;
    } else {
        if (m_asynchronous)
            qDebug() << "Uh oh..."; //TODO: Evaluate/handle this 'error' condition
        if (m_serviceDescriptor)
            m_serviceObject = m_serviceManager->loadInterface(*m_serviceDescriptor);
        else
            m_serviceObject = m_serviceManager->loadInterface(m_interfaceName);
        error = m_serviceManager->error();
    }

    if (error != QServiceManager::NoError) {
        m_serviceObject = 0;
        if (!m_asynchronous)
            emit serviceObjectChanged(0);// In sync we didn't emit the intermediate state
        m_errorString = stringForError(error);
        setStatus(Error);
    } else {
        setStatus(Ready);
        connect(m_serviceObject, SIGNAL(errorUnrecoverableIPCFault(QService::UnrecoverableIPCError)),
                this, SLOT(IPCFault(QService::UnrecoverableIPCError)));
    }

    if (prevObject != m_serviceObject)
        emit serviceObjectChanged(m_serviceObject);

    delete m_serviceManager;
    m_serviceManager = 0;
}

void QDeclarativeServiceLoader::IPCFault(QService::UnrecoverableIPCError errorValue)
{
    switch (errorValue) {
    default:
    case QService::ErrorUnknown:
        m_errorString = QLatin1String("IPC Error: Unkown Error");
        break;
    case QService::ErrorServiceNoLongerAvailable:
        m_errorString = QLatin1String("IPC Error: Service no longer available");
        break;
    case QService::ErrorOutofMemory:
        m_errorString = QLatin1String("IPC Error: Out of memory");
        break;
    case QService::ErrorPermissionDenied:
        m_errorString = QLatin1String("IPC Error: Permission Denied");
        break;
    case QService::ErrorInvalidArguments:
        m_errorString = QLatin1String("IPC Error: Invalid Arguments");
        break;
    }
    setStatus(Error);
    m_serviceObject->deleteLater();
}

/*!
    \qmltype ServiceDescriptor
    \instantiates QDeclarativeServiceDescriptor

    \brief The ServiceDescriptor element holds a description of a service.
    \inherits QObject

    \ingroup qml-serviceframework

    The ServiceDescriptor element is a simplified reflection of the ServiceDescriptor class,
    and is used merely to contain data that can uniquely identify a service.

    It cannot be created manually, use a ServiceList to search for service descriptions.

    \sa ServiceList
*/
/*!
    \qmlproperty QString ServiceDescriptor::serviceName

    This property holds the interface name of the service.
*/
/*!
    \qmlproperty QString ServiceDescriptor::interfaceName

    This property holds the interface name of the service.
*/

/*!
    \qmlproperty int ServiceDescriptor::majorVersion

    This property holds the major version number of the service.
*/
/*!
    \qmlproperty int ServiceDescriptor::minorVersion

    This property holds the minor version number of the service.
*/
//TODO: Fix doc or remove property
/*!
    \qmlproperty bool ServiceDescriptor::valid

    I have no clue what this property does, but it's probably important.
*/
/*!
    \qmltype ServiceFilter
    \instantiates QDeclarativeServiceFilter

    \brief The ServiceFilter element holds a list of \l ServiceDescriptor objects.
    \inherits QObject

    \ingroup qml-serviceframework

    The ServiceFilter element is part of the Qt ServiceFramework API and
    provides a list of \l QServiceDesciptor objects at the interface ServiceFilter::interfaceName with
    minimum version match ServiceFilter::minVersion properties. This list can be used to
    select the desired service and instantiate a service object for access via the QMetaObject.

    This element is a simplified reflection of the QServiceFilter class that provides a list
    of ServiceDescriptors. Similarly, if the ServiceFilter::serviceName
    and ServiceFilter::versionMatch are not provided they will respectively default to an empty
    string with a minimum verison match.

    Example:
    \code
    Item {
        ServiceFilter {
            id: serviceFilter
            interfaceName: "com.qt.nokia.example.interface"
        }
        ServiceLoader {
            serviceDescriptor: serviceFilter.serviceDescriptions[0] //To get the first matching service
        }
        Repeater{ //To instantiate an object for all matching services.
            model: serviceFilter.serviceDescriptions
            Item {
                ServiceLoader {
                    serviceDescriptor: modelData
                }
            }
        }
    }
    \endcode

    \sa ServiceLoader ServiceDescriptor
*/
QDeclarativeServiceFilter::QDeclarativeServiceFilter(QObject* parent)
    : QObject(parent),
      m_majorVersion(1), // ### Is '1' the correct unset number?
      m_minorVersion(0),
      m_exactVersionMatching(false),
      m_monitorServiceRegistrations(false),
      m_serviceManager(0),
      m_componentComplete(false)
{
}

QDeclarativeServiceFilter::~QDeclarativeServiceFilter()
{
}
/*!
    \qmlproperty QString ServiceFilter::serviceName

    This property holds the interface name of the services that
    corresponds to setting QServiceFilter::setService().
*/
/*!
    \qmlproperty QString ServiceFilter::interfaceName

    This property holds the interface name of the services that
    corresponds to setting QServiceFilter::setInterface().
*/

/*!
    \qmlproperty int ServiceFilter::majorVersion

    This property holds the major version number of the service filter that
    corresponds to QServiceFilter::majorVersion().
*/
/*!
    \qmlproperty int ServiceFilter::minorVersion

    This property holds the minor version number of the service filter that
    corresponds to QServiceFilter::minorVersion().
*/

/*!
    \qmlproperty int ServiceFilter::monitorServiceRegistrations

    This property controls the behaviour of the list when new services are
    registered or deregistered. Setting this property to true means the list
    will be automatically updated when a service is added or removed.

    Continuing to monitor the services can be expensive, so it is recommended
    that you only enable this feature if you need it.

    Caution, your service descriptor object will be deleted if the service
    is unregistered, even if the service is still running. This is primarily
    of note if you are using the serviceDescriptions list as a model with
    Service element delegates.
*/

/*!
    \qmlproperty bool ServiceFilter::versionMatch

    This property holds the version match rule of the service filter that
    corresponds to QServiceFilter::versionMatchRule(). Within QML the values
    ServiceFilter.Exact and ServiceFilter.Minimum correspond to
    QServiceFilter::ExactVersionMatch and QServiceFilter::MinimumVersionMatch
    respectively.
*/

void QDeclarativeServiceFilter::setMonitorServiceRegistrations(bool updates)
{
    if (m_monitorServiceRegistrations == updates)
        return;

    if (updates == false) {
        disconnect(this, SLOT(servicesAddedRemoved()));
        if (m_serviceManager)
            delete m_serviceManager;
        m_serviceManager = 0;
    } else {
        if (!m_serviceManager)
            m_serviceManager = new QServiceManager(this);
        connect(m_serviceManager, SIGNAL(serviceAdded(QString,QService::Scope)),
                this, SLOT(servicesAddedRemoved()));
        connect(m_serviceManager, SIGNAL(serviceRemoved(QString,QService::Scope)),
                this, SLOT(servicesAddedRemoved()));
    }

    emit monitorServiceRegistrationsChanged(updates);
    m_monitorServiceRegistrations = updates;
}

void QDeclarativeServiceFilter::servicesAddedRemoved()
{
    // invoke in another event loop run ### Why?
    QMetaObject::invokeMethod(this, "updateServiceList", Qt::QueuedConnection);
}

QList<QDeclarativeServiceDescriptor> makeDeclarative(QList<QServiceInterfaceDescriptor> in)
{
    QList<QDeclarativeServiceDescriptor> out;
    foreach (const QServiceInterfaceDescriptor &d, in)
        out << QDeclarativeServiceDescriptor(d);
    return out;
}

void QDeclarativeServiceFilter::updateServiceList()
{
    if (!m_componentComplete)
        return;

    if (!m_serviceManager)
        m_serviceManager = new QServiceManager(this);
    const QString version = QString::number(m_majorVersion) + "." + QString::number(m_minorVersion);

    QServiceFilter filter;

    if (!m_serviceName.isEmpty())
        filter.setServiceName(m_serviceName);

    if (!m_interfaceName.isEmpty())
        filter.setInterface(m_interfaceName, version, m_exactVersionMatching ?
                QServiceFilter::ExactVersionMatch : QServiceFilter::MinimumVersionMatch);

    QList<QDeclarativeServiceDescriptor> list = makeDeclarative(m_serviceManager->findInterfaces(filter));

    if (list != m_services) {
        m_services = list;
        emit serviceDescriptionsChanged();
    }

    if (!m_monitorServiceRegistrations) {
        delete m_serviceManager;
        m_serviceManager = 0;
    }

}

/*!
    \qmlproperty QQmlListProperty ServiceFilter::serviceDescriptions

    This property holds the list of \l ServiceDescriptor objects that match
    the ServiceFilter::interfaceName and minimum ServiceFilter::versionNumber properties.
*/

void QDeclarativeServiceFilter::componentComplete()
{
    m_componentComplete = true;
    updateServiceList();
}

void QDeclarativeServiceFilter::s_append(QQmlListProperty<QDeclarativeServiceDescriptor> *prop, QDeclarativeServiceDescriptor *service)
{
    QDeclarativeServiceFilter* list = static_cast<QDeclarativeServiceFilter*>(prop->object);
    list->m_services.append(*service);//### This does not maintain the reference
    list->serviceDescriptionsChanged();
}
int QDeclarativeServiceFilter::s_count(QQmlListProperty<QDeclarativeServiceDescriptor> *prop)
{
    return static_cast<QDeclarativeServiceFilter*>(prop->object)->m_services.count();
}

QDeclarativeServiceDescriptor* QDeclarativeServiceFilter::s_at(QQmlListProperty<QDeclarativeServiceDescriptor> *prop, int index)
{
    return &(static_cast<QDeclarativeServiceFilter*>(prop->object)->m_services[index]);
}

void QDeclarativeServiceFilter::s_clear(QQmlListProperty<QDeclarativeServiceDescriptor> *prop)
{
    QDeclarativeServiceFilter* list = static_cast<QDeclarativeServiceFilter*>(prop->object);
    list->m_services.clear();
    list->serviceDescriptionsChanged();
}
#include "moc_qdeclarativeservice_p.cpp"

QT_END_NAMESPACE