summaryrefslogtreecommitdiffstats
path: root/src/serviceframework/databasemanager.cpp
blob: ce3bc9ca21e8c8ce5c6469b1eef7785937dd635e (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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "databasemanager_p.h"
#include "qserviceinterfacedescriptor_p.h"
#include <QFileSystemWatcher>
#include <QHash>

QTM_BEGIN_NAMESPACE

DatabaseFileWatcher::DatabaseFileWatcher(DatabaseManager *parent)
    : QObject(parent),
      m_manager(parent),
      m_watcher(0)
{
}

QString DatabaseFileWatcher::closestExistingParent(const QString &path)
{
    if (QFile::exists(path))
        return path;

    int lastSep = path.lastIndexOf(QDir::separator());
    if (lastSep < 0)
        return QString();
    return closestExistingParent(path.mid(0, lastSep));
}

void DatabaseFileWatcher::restartDirMonitoring(const QString &dbPath, const QString &previousDirPath)
{
    if (m_watcher->files().contains(dbPath))
        return;

    QString existing = closestExistingParent(dbPath);
    if (existing.isEmpty()) {
        qWarning() << "QServiceManager: can't find existing directory for path to database" << dbPath
            << "serviceAdded() and serviceRemoved() will not be emitted";
        return;
    }
    if (existing == dbPath) {
        ServiceDatabase *db = 0;
        DatabaseManager::DbScope scope;
        if (m_manager->m_userDb && dbPath == m_manager->m_userDb->databasePath()) {
            db = m_manager->m_userDb;
            scope = DatabaseManager::UserOnlyScope;
        } else if (dbPath == m_manager->m_systemDb->databasePath()) {
            db = m_manager->m_systemDb;
            scope = DatabaseManager::SystemScope;
        }

        if (db) {
            if (!previousDirPath.isEmpty())
                m_watcher->removePath(previousDirPath);
            QMutableListIterator<QString> i(m_monitoredDbPaths);
            while (i.hasNext()) {
                if (i.next() == dbPath)
                    i.remove();
            }

            QStringList newServices = m_manager->getServiceNames(QString(), scope);
            for (int i=0; i<newServices.count(); i++)
                emit m_manager->serviceAdded(newServices[i], scope);
            setEnabled(db, true);
        }
    } else {
        if (previousDirPath != existing) {
            if (!previousDirPath.isEmpty())
                m_watcher->removePath(previousDirPath);
            if (!m_watcher->directories().contains(existing))
                m_watcher->addPath(existing);
            if (!m_monitoredDbPaths.contains(dbPath))
                m_monitoredDbPaths << dbPath;
        }
    }
}

void DatabaseFileWatcher::setEnabled(ServiceDatabase *database, bool enabled)
{
    if (!m_watcher) {
        m_watcher = new QFileSystemWatcher(this);
        connect(m_watcher, SIGNAL(fileChanged(QString)),
            SLOT(databaseChanged(QString)));
        connect(m_watcher, SIGNAL(directoryChanged(QString)),
            SLOT(databaseDirectoryChanged(QString)));
    }

    QString path = database->databasePath();
    if (enabled) {
        if (QFile::exists(path)) {
            m_knownServices[path] = database->getServiceNames(QString());
            m_watcher->addPath(path);
        } else {
            restartDirMonitoring(path, QString());
        }
    } else {
        m_watcher->removePath(path);
        m_knownServices.remove(path);
    }
}

void DatabaseFileWatcher::databaseDirectoryChanged(const QString &path)
{
    for (int i=0; i<m_monitoredDbPaths.count(); i++) {
        if (m_monitoredDbPaths[i].contains(path))
            restartDirMonitoring(m_monitoredDbPaths[i], path);
    }
}

void DatabaseFileWatcher::databaseChanged(const QString &path)
{
    if (m_manager->m_userDb && path == m_manager->m_userDb->databasePath())
        notifyChanges(m_manager->m_userDb, DatabaseManager::UserScope);
    else if (path == m_manager->m_systemDb->databasePath())
        notifyChanges(m_manager->m_systemDb, DatabaseManager::SystemScope);

    // if database was deleted, the path may have been dropped
    if (!m_watcher->files().contains(path) && QFile::exists(path))
        m_watcher->addPath(path);
}

void DatabaseFileWatcher::notifyChanges(ServiceDatabase *database, DatabaseManager::DbScope scope)
{
    #ifdef Q_OS_SYMBIAN
        scope = DatabaseManager::SystemScope;
    #endif

    QString dbPath = database->databasePath();
    if (!QFile::exists(dbPath)) {
        m_knownServices.remove(dbPath);
        restartDirMonitoring(dbPath, QString());
        return;
    }

    QStringList currentServices = database->getServiceNames(QString());
    if (database->lastError().code() !=DBError::NoError) {
        qWarning("QServiceManager: failed to get current service names for serviceAdded() and serviceRemoved() signals");
        return;
    }

    const QStringList &knownServicesRef = m_knownServices[dbPath];

    QSet<QString> currentServicesSet = currentServices.toSet();
    QSet<QString> knownServicesSet = knownServicesRef.toSet();
    if (currentServicesSet == knownServicesSet)
        return;

    QStringList newServices;
    for (int i=0; i<currentServices.count(); i++) {
        if (!knownServicesSet.contains(currentServices[i]))
            newServices << currentServices[i];
    }

    QStringList removedServices;
    for (int i=0; i<knownServicesRef.count(); i++) {
        if (!currentServicesSet.contains(knownServicesRef[i]))
            removedServices << knownServicesRef[i];
    }

    m_knownServices[dbPath] = currentServices;
    for (int i=0; i<newServices.count(); i++)
        emit m_manager->serviceAdded(newServices[i], scope);
    for (int i=0; i<removedServices.count(); i++)
        emit m_manager->serviceRemoved(removedServices[i], scope);
}

bool lessThan(const QServiceInterfaceDescriptor &d1,
                                        const QServiceInterfaceDescriptor &d2)
{
        return (d1.majorVersion() < d2.majorVersion())
                || ( d1.majorVersion() == d2.majorVersion()
                && d1.minorVersion() < d2.minorVersion());
}

/*
    \class DatabaseManager
    The database manager is responsible for receiving queries about
    services and managing user and system scope databases in order to
    respond to those queries.

    It provides operations for
    - registering and unregistering services
    - querying for services and interfaces
    - setting and getting default interface implementations

    and provides notifications by emitting signals for added
    or removed services.

    Implementation note:
    When one of the above operations is first invoked a connection with the
    appropriate database(s) is opened.  This connection remains
    open until the DatabaseManager is destroyed.

    If the system scope database cannot be opened when performing
    user scope operations.  The operations are carried out as per normal
    but only acting on the user scope database.  Each operation invokation
    will try to open a connection with the system scope database.

    Terminology note:
    When referring to user scope regarding operations, it generally
    means access to both the user and system databases with the
    data from both combined into a single dataset.
    When referring to a user scope database it means the
    user database only.

    \since 1.0
*/

/*
   Constructor
*/
DatabaseManager::DatabaseManager()
    : m_userDb(NULL),
      m_systemDb(new ServiceDatabase),
      m_fileWatcher(0),
      m_hasAccessedUserDb(false),
      m_alreadyWarnedOpenError(false)
{
    #ifndef Q_OS_SYMBIAN
        m_userDb = new ServiceDatabase;
        initDbPath(UserScope);
    #endif
    initDbPath(SystemScope);
}

/*
   Destructor
*/
DatabaseManager::~DatabaseManager()
{
    delete m_fileWatcher;
    m_fileWatcher = 0;

    //Aside: databases are implicitly closed
    //during deletion
    if(m_userDb){
        m_userDb->close();
        delete m_userDb;
    }
    m_userDb = 0;

    if(m_systemDb){
        m_systemDb->close();
        delete m_systemDb;
    }
    m_systemDb = 0;
}


/*
    Initialises database path of m_userDb
    or m_systemDb, but does not open any
    database connections
*/
void DatabaseManager::initDbPath(DbScope scope)
{
    #ifdef Q_OS_SYMBIAN
        scope = SystemScope;
    #endif

    QSettings::Scope settingsScope;
    QString dbIdentifier;
    ServiceDatabase *db;
    if (scope == SystemScope) {
        settingsScope = QSettings::SystemScope;
        dbIdentifier = "_system";
        db = m_systemDb;
    } else {
        settingsScope = QSettings::UserScope;
        dbIdentifier = "_user";
        db = m_userDb;
    }

#ifdef QT_SIMULATOR
    dbIdentifier.append("_simulator");
#endif

    #ifdef Q_OS_SYMBIAN
        QDir dir(QDir::toNativeSeparators("C:\\Data\\temp\\QtServiceFW"));
    #else
        QSettings settings(QSettings::IniFormat, settingsScope,
                QLatin1String("Nokia"), QLatin1String("QtServiceFramework"));
        QFileInfo fi(settings.fileName());
        QDir dir = fi.dir();
    #endif
    QString qtVersion(qVersion());
    qtVersion = qtVersion.left(qtVersion.size() -2); //strip off patch version
    QString dbName = QString("QtServiceFramework_") + qtVersion + dbIdentifier + QLatin1String(".db");
    db->setDatabasePath(dir.path() + QDir::separator() + dbName);
}

/*
    Adds the details \a  service into the service database corresponding to
    \a scope.

    Returns true if the operation succeeded and false otherwise.
    The last error is set when this function is called.
*/
bool DatabaseManager::registerService(ServiceMetaDataResults &service, DbScope scope)
{
    #ifdef Q_OS_SYMBIAN
        scope = SystemScope;
    #endif

    if (scope == DatabaseManager::SystemScope) {
        if(!openDb(DatabaseManager::SystemScope)) {
            return false;
        }  else {
            if (!m_systemDb->registerService(service)) {
                m_lastError = m_systemDb->lastError();
                return false;
            } else { //must be successful registration
                m_lastError.setError(DBError::NoError);
                return true;
            }
        }
    } else { //must  be registering service at user scope
        if (!openDb(DatabaseManager::UserScope)) {
            return false;
        } else {
            if (!m_userDb->registerService(service)) {
                m_lastError = m_userDb->lastError();
                return false;
            } else { //must be successful registration
                m_lastError.setError(DBError::NoError);
                return true;
            }
        }
    }
}

/*
    Removes the details of \serviceName from the database corresponding to \a
    scope.

    Returns true if the operation succeeded, false otherwise.
    The last error is set when this function is called.
*/
bool DatabaseManager::unregisterService(const QString &serviceName, DbScope scope)
{
    #ifdef Q_OS_SYMBIAN
        scope = SystemScope;
    #endif

    if(scope == DatabaseManager::SystemScope) {
        if (!openDb(DatabaseManager::SystemScope))
            return false;
   else {
            if (!m_systemDb->unregisterService(serviceName)) {
                m_lastError = m_systemDb->lastError();
                return false;
            } else { //must be successful unregistration
                m_lastError.setError(DBError::NoError);
                return true;
            }
        }
    } else {
        if (!openDb(DatabaseManager::UserScope)) {
            return false;
        } else {
            if (!m_userDb->unregisterService(serviceName)){
                m_lastError = m_userDb->lastError();
                return false;
            } else { //must be successful unregistration
                m_lastError.setError(DBError::NoError);
                return true;
            }
        }
    }
}

/*
    Removes the initialization specific information of \serviceName from the database
    corresponding to a \scope.

    Returns true if teh operation succeeded, false otherwise.
    The last error is set when this function is called.
  */
bool DatabaseManager::serviceInitialized(const QString &serviceName, DbScope scope)
{
    ServiceDatabase *db = (scope == DatabaseManager::SystemScope) ? m_systemDb : m_userDb;

    if (!openDb(scope)) {
        return false;
    } else {
        if (!db->serviceInitialized(serviceName)) {
            m_lastError = db->lastError();
            return false;
        } else {
            m_lastError.setError(DBError::NoError);
            return true;
        }
    }
}

/*
    Retrieves a list of interface descriptors that fulfill the constraints specified
    by \a filter at a given \a scope.

    The last error is set when this function is called.
*/
QList<QServiceInterfaceDescriptor>  DatabaseManager::getInterfaces(const QServiceFilter &filter, DbScope scope)
{
    #ifdef Q_OS_SYMBIAN
        QService::Scope requestedScope;
        if (scope == UserScope) {
            requestedScope = QService::UserScope;
        } else {
            requestedScope = QService::SystemScope;
        }
        scope = SystemScope;
    #endif

    QList<QServiceInterfaceDescriptor> descriptors;

    int userDescriptorCount = 0;
    if (scope == UserScope) {
        if (!openDb(UserScope))
            return descriptors;

        descriptors =  m_userDb->getInterfaces(filter);
        if (m_userDb->lastError().code() != DBError::NoError ) {
            descriptors.clear();
            m_lastError = m_userDb->lastError();
            return descriptors;
        }

        userDescriptorCount = descriptors.count();
        for (int i=0; i < userDescriptorCount; ++i) {
            descriptors[i].d->scope = QService::UserScope;
        }
    }

    if (openDb(SystemScope)) {
        descriptors.append(m_systemDb->getInterfaces(filter));
        if (m_systemDb->lastError().code() != DBError::NoError) {
            descriptors.clear();
            m_lastError = m_systemDb->lastError();
            return descriptors;
        }

        for (int i = userDescriptorCount; i < descriptors.count(); ++i) {
            #ifdef Q_OS_SYMBIAN
                descriptors[i].d->scope = requestedScope;
            #else
                descriptors[i].d->scope = QService::SystemScope;
            #endif
        }
    } else {
        if ( scope == SystemScope) {
            //openDb() should already have handled lastError
            descriptors.clear();
            return descriptors;
        }
    }

    m_lastError.setError(DBError::NoError);
    return descriptors;
}


/*
    Retrieves a list of the names of services that provide the interface
    specified by \a interfaceName.

    The last error is set when this function is called.
*/
QStringList DatabaseManager::getServiceNames(const QString &interfaceName, DatabaseManager::DbScope scope)
{
    #ifdef Q_OS_SYMBIAN
        scope = SystemScope;
    #endif

    QStringList serviceNames;
    if (scope == UserScope || scope == UserOnlyScope) {
        if(!openDb(DatabaseManager::UserScope))
            return serviceNames;
        serviceNames = m_userDb->getServiceNames(interfaceName);
        if(m_userDb->lastError().code() != DBError::NoError) {
            serviceNames.clear();
            m_lastError = m_userDb->lastError();
            return serviceNames;
        }
        if (scope == UserOnlyScope) {
            m_lastError.setError(DBError::NoError);
            return serviceNames;
        }
    }

    if(openDb(DatabaseManager::SystemScope)) {
        QStringList systemServiceNames;
        systemServiceNames = m_systemDb->getServiceNames(interfaceName);
        if(m_systemDb->lastError().code() != DBError::NoError) {
            serviceNames.clear();
            m_lastError = m_systemDb->lastError();
            return serviceNames;
        }
        foreach(const QString &systemServiceName, systemServiceNames) {
            if(!serviceNames.contains(systemServiceName, Qt::CaseInsensitive))
                serviceNames.append(systemServiceName);
        }

    } else {
        if ( scope == SystemScope) {
            //openDb() should have already handled lastError
            serviceNames.clear();
            return serviceNames;
        }
    }

    m_lastError.setError(DBError::NoError);
    return serviceNames;
}

/*
    Returns the default interface implementation descriptor for a given
    \a interfaceName and \a scope.

    The last error is set when this function is called.
*/
QServiceInterfaceDescriptor DatabaseManager::interfaceDefault(const QString &interfaceName, DbScope scope)
{
    #ifdef Q_OS_SYMBIAN
        QService::Scope requestedScope;
        if (scope == UserScope) {
            requestedScope = QService::UserScope;
        } else {
            requestedScope = QService::SystemScope;
        }
        scope = SystemScope;
    #endif

    QServiceInterfaceDescriptor descriptor;
    if (scope == UserScope) {
        if (!openDb(UserScope))
            return QServiceInterfaceDescriptor();
        QString interfaceID;
        descriptor = m_userDb->interfaceDefault(interfaceName, &interfaceID);

        if (m_userDb->lastError().code() == DBError::NoError) {
            descriptor.d->scope = QService::UserScope;
            return descriptor;
        } else if (m_userDb->lastError().code() == DBError::ExternalIfaceIDFound) {
            //default hasn't been found in user db, but we have found an ID
            //that may refer to an interface implementation in the system db
            if (!openDb(SystemScope)) {
                QString errorText("No default service found for interface: \"%1\"");
                m_lastError.setError(DBError::NotFound, errorText.arg(interfaceName));
                return QServiceInterfaceDescriptor();
            }

            descriptor = m_systemDb->getInterface(interfaceID);
            //found the service from the system database
            if (m_systemDb->lastError().code() == DBError::NoError) {
                m_lastError.setError(DBError::NoError);
                descriptor.d->scope = QService::SystemScope;
                return descriptor;
            } else if(m_systemDb->lastError().code() == DBError::NotFound){
                //service implementing interface doesn't exist in the system db
                //so the user db must contain a stale entry so remove it
                m_userDb->removeExternalDefaultServiceInterface(interfaceID);

                QList<QServiceInterfaceDescriptor> descriptors;
                descriptors = getInterfaces(QServiceFilter(interfaceName), UserScope);

                //make the latest interface implementation the new
                //default if there is one
                if (descriptors.count() > 0 ) {
                    descriptor = latestDescriptor(descriptors);
                    setInterfaceDefault(descriptor, UserScope);
                    m_lastError.setError(DBError::NoError);
                    return descriptor;
                } else {
                    QString errorText("No default service found for interface: \"%1\"");
                    m_lastError.setError(DBError::NotFound, errorText.arg(interfaceName));
                    return QServiceInterfaceDescriptor();
                }
            } else {
                m_lastError.setError(DBError::NoError);
                return QServiceInterfaceDescriptor();
            }
        } else if (m_userDb->lastError().code() == DBError::NotFound) {
            //do nothing, the search for a default in the system db continues
            //further down
        } else { //error occurred at user db level, so return
            m_lastError = m_userDb->lastError();
            return QServiceInterfaceDescriptor();
        }
    }

    //search at system scope because we haven't found a default at user scope
    //or because we're specifically only querying at system scope
    if (!openDb(SystemScope)) {
        if (scope == SystemScope) {
            m_lastError = m_systemDb->lastError();
            return QServiceInterfaceDescriptor();
        } else if (scope == UserScope && m_userDb && m_userDb->lastError().code() == DBError::NotFound) {
            m_lastError = m_userDb->lastError();
            return QServiceInterfaceDescriptor();
        }
    } else {
        descriptor = m_systemDb->interfaceDefault(interfaceName);
        if (m_systemDb->lastError().code() == DBError::NoError) {
            #ifdef Q_OS_SYMBIAN
                descriptor.d->scope = requestedScope;
            #else
                descriptor.d->scope = QService::SystemScope;
            #endif
            return descriptor;
        } else if (m_systemDb->lastError().code() == DBError::NotFound) {
            m_lastError = m_systemDb->lastError();
            return QServiceInterfaceDescriptor();
        } else {
            m_lastError = m_systemDb->lastError();
            return QServiceInterfaceDescriptor();
        }
    }

    //should not be possible to reach here
    m_lastError.setError(DBError::UnknownError);
    return QServiceInterfaceDescriptor();
}

/*
    Sets the default interface implemenation for \a interfaceName to the matching
    interface implementation provided by \a service.

    If \a service provides more than one interface implementation, the newest
    version of the interface is set as the default.

    Returns true if the operation was succeeded, false otherwise
    The last error is set when this function is called.
*/
bool DatabaseManager::setInterfaceDefault(const QString &serviceName, const
        QString &interfaceName, DbScope scope) 
{
    QList<QServiceInterfaceDescriptor> descriptors;
    QServiceFilter filter;
    filter.setServiceName(serviceName);
    filter.setInterface(interfaceName);

    descriptors = getInterfaces(filter, scope);
    if (m_lastError.code() != DBError::NoError)
        return false;

    if (descriptors.count() == 0) {
        QString errorText("No implementation for interface \"%1\" "
                "found for service \"%2\"");
        m_lastError.setError(DBError::NotFound,
                errorText.arg(interfaceName)
                .arg(serviceName));
        return false;
    }

    //find the descriptor with the latest version
    int latestIndex = 0;
        for (int i = 1; i < descriptors.count(); ++i) {
            if (lessThan(descriptors[latestIndex], descriptors[i]))
                latestIndex = i;
    }

    return setInterfaceDefault(descriptors[latestIndex], scope);
}

/*
    Sets the interface implementation specified by \a descriptor to be the default
    implementation for the particular interface specified in the descriptor.

    Returns true if the operation succeeded, false otherwise.
    The last error is set when this function is called.
*/
bool DatabaseManager::setInterfaceDefault(const QServiceInterfaceDescriptor &descriptor, DbScope scope)
{
    #ifdef Q_OS_SYMBIAN
        Q_UNUSED(scope);
        if (!openDb(SystemScope)) {
            return false;
        } else {
            if (m_systemDb->setInterfaceDefault(descriptor)) {
                m_lastError.setError(DBError::NoError);
                return true;
            } else {
                m_lastError = m_systemDb->lastError();
                return false;
            }
        }
    #else
        if (scope == UserScope) {
            if (!openDb(UserScope))
                return false;
            if (descriptor.scope() == QService::UserScope) { //if a user scope descriptor, just set it in the user db
                if(m_userDb->setInterfaceDefault(descriptor)) {
                    m_lastError.setError(DBError::NoError);
                    return true;
                } else {
                    m_lastError = m_userDb->lastError();
                    return false;
                }
            } else { //otherwise we need to get the interfaceID from the system db and set this
                     //as an external default interface ID in the user db
                if (!openDb(SystemScope))
                    return false;

                QString interfaceDescriptorID = m_systemDb->getInterfaceID(descriptor);
                if (m_systemDb->lastError().code() == DBError::NoError) {
                    if(m_userDb->setInterfaceDefault(descriptor, interfaceDescriptorID)) {
                        m_lastError.setError(DBError::NoError);
                        return true;
                    } else {
                        m_lastError = m_userDb->lastError();
                        return false;
                    }
                } else {
                    m_lastError = m_systemDb->lastError();
                    return false;
                }
            }
        } else {  //scope == SystemScope
            if (descriptor.scope() == QService::UserScope) {
                QString errorText("Cannot set default service at system scope with a user scope "
                                    "interface descriptor");
                m_lastError.setError(DBError::InvalidDescriptorScope, errorText);
                return false;
            } else {
                if (!openDb(SystemScope)) {
                    return false;
                } else {
                    if (m_systemDb->setInterfaceDefault(descriptor)) {
                        m_lastError.setError(DBError::NoError);
                        return true;
                    } else {
                        m_lastError = m_systemDb->lastError();
                        return false;
                    }
                }
            }
        }
    #endif
}

/*
    Opens a database connection with the database at a specific \a scope.

    The last error is set when this function is called.
*/
bool DatabaseManager::openDb(DbScope scope)
{
    #ifdef Q_OS_SYMBIAN
        scope = SystemScope;
    #endif

    if (scope == SystemScope && m_systemDb->isOpen() && !QFile::exists(m_systemDb->databasePath())) {
        delete m_systemDb;
        m_systemDb = new ServiceDatabase;
        initDbPath(SystemScope);
        m_alreadyWarnedOpenError = false;
    } else if (scope != SystemScope && m_userDb->isOpen() && !QFile::exists(m_userDb->databasePath())) {
        delete m_userDb;
        m_userDb = new ServiceDatabase;
        initDbPath(UserScope);
        m_alreadyWarnedOpenError = false;
    }

    ServiceDatabase *db;
    if (scope == SystemScope) {
        db = m_systemDb;
    }
    else {
        db = m_userDb;
        m_hasAccessedUserDb = true;
    }

    if (db->isOpen())
        return true;

    bool isOpen = db->open();
    if (!isOpen) {
#ifdef QT_SFW_SERVICEDATABASE_DEBUG
        qWarning() << "DatabaseManger::openDb():-"
                    << "Problem:" << qPrintable(m_lastError.text());
#endif
        if (scope == SystemScope && m_hasAccessedUserDb == true) {
                if (QFile::exists(m_systemDb->databasePath()) && !m_alreadyWarnedOpenError)
                    qWarning() << "Service Framework:- Unable to access system database for a user scope "
                        "operation; resorting to using only the user database.  Future operations "
                        "will attempt to access the system database but no further warnings will be issued";
        }

        QString warning;
        if (db->lastError().code() == DBError::InvalidDatabaseFile) {
            warning = QString("Service Framework:- Database file is corrupt or invalid: ") + db->databasePath();
            m_lastError = db->lastError();
        } else {
            warning = QString("Service Framework:- Unable to open or create database at: ") +  db->databasePath();
            QString errorText("Unable to open service framework database: %1");
            m_lastError.setError(DBError::CannotOpenServiceDb,
                errorText.arg(db->databasePath()));
        }

        if (m_alreadyWarnedOpenError
                || (scope == SystemScope && m_hasAccessedUserDb && !QFile::exists(m_systemDb->databasePath()))) {
            //do nothing, don't output warning if already warned or we're accessing the system database
            //from user scope and the system database doesn't exist
        } else {
            qWarning() << qPrintable(warning);
            m_alreadyWarnedOpenError = true;
        }

        return false;
    }

    //if we are opening the system database while the user database is open,
    //cleanup and reset any old external defaults
    //from the user scope database
    if (scope == SystemScope && m_userDb && m_userDb->isOpen()) {
        QList<QPair<QString,QString> > externalDefaultsInfo;
        externalDefaultsInfo = m_userDb->externalDefaultsInfo();
        QServiceInterfaceDescriptor descriptor;
        QPair<QString,QString> defaultInfo;

        for (int i = 0; i < externalDefaultsInfo.count(); ++i) {
            defaultInfo = externalDefaultsInfo[i];
            descriptor = m_userDb->getInterface(defaultInfo.second);
            if (m_userDb->lastError().code() == DBError::NotFound) {
                m_userDb->removeExternalDefaultServiceInterface(defaultInfo.second);
                QList<QServiceInterfaceDescriptor> descriptors;
                descriptors = getInterfaces(QServiceFilter(defaultInfo.first), UserScope);

                if (descriptors.count() > 0 ) {
                    descriptor = latestDescriptor(descriptors);
                    setInterfaceDefault(descriptor, UserScope);
                }
            }
        }
    }

    m_lastError.setError(DBError::NoError);
    return true;
}

/*
    Returns the interface descriptor with the highest version from the
    list of interface \a descriptors
*/
QServiceInterfaceDescriptor DatabaseManager::latestDescriptor(
                                    const QList<QServiceInterfaceDescriptor> &descriptors)
{
    if (descriptors.count() == 0)
        return QServiceInterfaceDescriptor();

    int latestIndex = 0;
    for (int i = 1; i < descriptors.count(); ++i) {
        if (lessThan(descriptors[latestIndex], descriptors[i]))
            latestIndex = i;
    }

    return descriptors[latestIndex];
}

/*
    Sets whether change notifications for added and removed services are
    \a enabled or not at a given \a scope.
*/
void DatabaseManager::setChangeNotificationsEnabled(DbScope scope, bool enabled)
{
    #ifdef Q_OS_SYMBIAN
        scope = SystemScope;
    #endif

    if (!m_fileWatcher) m_fileWatcher = new
    DatabaseFileWatcher(this); m_fileWatcher->setEnabled(scope == SystemScope ?
            m_systemDb : m_userDb, enabled);
}

#include "moc_databasemanager_p.cpp"

QTM_END_NAMESPACE