File: Database.cpp

package info (click to toggle)
kphotoalbum 4.2-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 21,324 kB
  • sloc: cpp: 35,900; python: 743; xml: 483; sh: 146; perl: 34; makefile: 16
file content (340 lines) | stat: -rw-r--r-- 9,872 bytes parent folder | download
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
/*
  Copyright (C) 2006-2010 Tuomas Suutari <thsuut@utu.fi>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program (see the file COPYING); if not, write to the
  Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
  MA 02110-1301 USA.
*/
#include "Database.h"

#include "DB/IdList.h"
#include "DB/Id.h"
#include "SQLCategory.h"
#include "DB/ImageInfo.h"
#include "DB/ImageInfoPtr.h"
#include "Utilities/Util.h"
#include "DB/GroupCounter.h"
#include "SQLImageInfoCollection.h"
#include "Browser/BrowserWidget.h"
#include "SQLImageDateCollection.h"
#include "DB/MediaCount.h"
#include "DatabaseInitialization.h"
#include "QueryErrors.h"
#include <QList>
#ifdef HAVE_EXIV2
#   include "Exif/Database.h"
#endif

namespace
{
    QStringList stripImageDirectoryFromList(const QStringList& absolutePaths)
    {
        QStringList relativePaths = absolutePaths;
        for (QStringList::iterator i = relativePaths.begin();
             i != relativePaths.end(); ++i) {
        *i = Utilities::stripImageDirectory(*i);
        }
        return relativePaths;
    }
}

SQLDB::Database::Database(const DatabaseAddress& address):
    _address(address),
    _connection(initializeKPhotoAlbumDatabase(_address)),
    _qh(*_connection),
    _categoryCollection(_qh),
    _members(_qh),
    _infoCollection(_qh),
    _md5map(_qh)
{
    connect(categoryCollection(),
            SIGNAL(itemRemoved(DB::Category*, const QString&)),
            &_infoCollection,
            SLOT(deleteTag(DB::Category*, const QString&)));
    connect(categoryCollection(),
            SIGNAL(itemRenamed(DB::Category*, const QString&, const QString&)),
            &_infoCollection,
            SLOT(renameTag(DB::Category*, const QString&, const QString&)));
}

bool SQLDB::Database::operator==(const DB::ImageDB& other) const
{
    const SQLDB::Database* sqlOther =
        dynamic_cast<const SQLDB::Database*>(&other);
    if (!sqlOther)
        return false;

    return _address == sqlOther->_address;
}

uint SQLDB::Database::totalCount() const
{
    return _qh.mediaItemCount();
}

DB::MediaCount SQLDB::Database::count(const DB::ImageSearchInfo& searchInfo)
{
    QList<DB::RawId> mediaIds;
    QList<DB::RawId>* scope = 0;
    bool all = (searchInfo.query().count() == 0);
    if (!all) {
        mediaIds = _qh.searchMediaItems(searchInfo);
        scope = &mediaIds;
    }

    return DB::MediaCount(_qh.mediaItemCount(DB::Image, scope),
                          _qh.mediaItemCount(DB::Video, scope));
}

DB::IdList SQLDB::Database::search(
    const DB::ImageSearchInfo& info,
    bool requireOnDisk) const
{
    QList<DB::RawId> matches = _qh.searchMediaItems(info);
    QList<DB::RawId> result;
    QString imageRoot = Settings::SettingsData::instance()->imageDirectory();
    for(QList<DB::RawId>::Iterator it = matches.begin(); it != matches.end(); ++it) {
        QString fullPath = imageRoot + _infoCollection.filenameForId(*it);
        if (requireOnDisk && !DB::ImageInfo::imageOnDisk(fullPath))
            continue;
        result.append(*it);
    }
    return DB::IdList(result);
}

void SQLDB::Database::renameCategory(const QString& /*oldName*/, const QString /*newName*/)
{
    // TODO: this
}

QMap<QString, uint> SQLDB::Database::classify(const DB::ImageSearchInfo& info,
                                              const QString& category,
                                              DB::MediaType typemask)
{
    DB::CategoryPtr catptr = categoryCollection()->categoryForName(category);
    SQLCategory* sqlcatptr = static_cast<SQLCategory*>(catptr.data());
    if (sqlcatptr)
        return sqlcatptr->classify(info, typemask);
    else
        return QMap<QString, uint>();
}

DB::IdList SQLDB::Database::imageList()
{
    return DB::IdList(_qh.mediaItemIds(DB::anyMediaType));
}


DB::IdList SQLDB::Database::images()
{
    return imageList();
}

void SQLDB::Database::addImages( const DB::ImageInfoList& images )
{
    if (!images.isEmpty()) {
        _qh.insertMediaItemsLast(images);
        emit totalChanged(totalCount());
    }
}

void SQLDB::Database::renameImage( DB::ImageInfoPtr info, const QString& newName )
{
    info->setFileName( newName );
    info->delaySavingChanges(false);
}

// TODO: Rename this function
// This function also removes the files from the database
void SQLDB::Database::addToBlockList(const DB::IdList& list)
{
    const QStringList absolutePaths = CONVERT(list);
    QStringList relativePaths;
    Q_FOREACH(const QString& absPath, absolutePaths)
        relativePaths.push_back(Utilities::stripImageDirectory(absPath));
    _qh.addIgnoredFiles(relativePaths);
    deleteList(list);
}

bool SQLDB::Database::isBlocking(const QString& fileName)
{
    return _qh.isIgnored(fileName);
}

void SQLDB::Database::deleteList(const DB::IdList& filesToRemove)
{
#ifdef HAVE_EXIV2
    Q_FOREACH(const QString& fileName, this->CONVERT(filesToRemove))
        Exif::Database::instance()->remove(fileName);
#endif
    Q_FOREACH(const DB::Id id, filesToRemove)
        _qh.removeMediaItem(id.rawId());
    if (!filesToRemove.isEmpty()) {
        emit totalChanged(totalCount());
        emit imagesDeleted( filesToRemove );
    }
}

DB::ImageInfoPtr SQLDB::Database::info( const QString& fileName, DB::PathType type ) const
{
    // PENDING(blackie) This code first converts to absolute, and then strips, that's just plane stupid....
    QString name = fileName;
    if ( type == DB::RelativeToImageRoot )
        name = Settings::SettingsData::instance()->imageDirectory() + fileName;

    return _infoCollection.
        getImageInfoOf(Utilities::stripImageDirectory(name));
}

DB::MemberMap& SQLDB::Database::memberMap()
{
    return _members;
}

void SQLDB::Database::save(const QString& /*fileName*/, bool isAutoSave)
{
    qDebug("NYI: void SQLDB::Database::save( const QString& fileName )" );
    _infoCollection.clearCache();

#ifndef DEBUG_QUERY_TIMES
    Q_UNUSED(isAutoSave)
#else
    if (isAutoSave)
        return;

    QStringList timeQueryList;

    for (QList< QPair<QString, uint> >::const_iterator i =
             _qh.queryTimes.begin(); i != _qh.queryTimes.end(); ++i) {
        timeQueryList <<
            QString::number((*i).second).rightJustified(8) +
            QString::fromLatin1(" ") + (*i).first;
    }

    timeQueryList.sort();

    for (QStringList::const_iterator i = timeQueryList.begin();
         i != timeQueryList.end(); ++i)
        qDebug("%s", (*i).local8Bit().data());
#endif
}

DB::MD5Map* SQLDB::Database::md5Map()
{
    return &_md5map;
}

void SQLDB::Database::lockDB(bool lock, bool exclude)
{
    if (lock)
        _infoCollection.setLock(Settings::SettingsData::instance()->
                                currentLock(), !exclude);
    else
        _infoCollection.unsetLock();
}

DB::CategoryCollection* SQLDB::Database::categoryCollection()
{
    return &_categoryCollection;
}

KSharedPtr<DB::ImageDateCollection> SQLDB::Database::rangeCollection()
{
    return KSharedPtr<DB::ImageDateCollection>
        (static_cast<DB::ImageDateCollection*>
         (new SQLImageDateCollection(_qh
                                     /*, search(Browser::instance()->currentContext(), false)*/
                                     )));
}

void SQLDB::Database::reorder(
    const DB::Id& file,
    const DB::IdList& selection,
    bool after)
{
    Q_ASSERT(!file.isNull());
    _qh.moveMediaItems(selection.rawIdList(), file.rawId(), after);
}

void SQLDB::Database::sortAndMergeBackIn(const DB::IdList& files)
{
    _qh.sortFiles(files.rawIdList());
}

DB::Id SQLDB::Database::findFirstItemInRange(
    const DB::IdList& files,
    const DB::ImageDate& range,
    bool includeRanges) const
{
    return _qh.findFirstFileInTimeRange(
        range, includeRanges, files.rawIdList());
}

QStringList SQLDB::Database::CONVERT(const DB::IdList& result)
{
    QStringList files;
    Q_FOREACH(DB::Id id, result) {
        files.push_back(
            Utilities::imageFileNameToAbsolute(
                _qh.mediaItemFilename(id.rawId())));
        Q_ASSERT(!files[files.size() - 1].isNull());
    }
    return files;
}

DB::Id SQLDB::Database::ID_FOR_FILE(const QString& filename) const
{
    return DB::Id::createContextless(_qh.mediaItemId(Utilities::imageFileNameToRelative(filename)));
}

DB::ImageInfoPtr SQLDB::Database::info(const DB::Id& id) const
{
    Q_ASSERT(!id.isNull());
    return _infoCollection.getImageInfoOf(id);
}

bool SQLDB::Database::stack(const DB::IdList& files)
{
    try {
        const DB::StackID newStackId = _qh.stackFiles(files.rawIdList());
        Q_FOREACH(DB::ImageInfoPtr info, files.fetchInfos()) {
            Q_ASSERT(!info.isNull());
            info->setStackId(newStackId);
        }
        return true;
    }
    catch (SQLDB::OperationNotPossible&) {
        return false;
    }
}

void SQLDB::Database::unstack(const DB::IdList& files)
{
    _qh.unstackFiles(files.rawIdList());
    Q_FOREACH(DB::ImageInfoPtr info, files.fetchInfos()) {
        Q_ASSERT(!info.isNull());
        info->setStackId(DB::StackID());
    }
}

DB::IdList SQLDB::Database::getStackFor(const DB::Id& referenceFile) const
{
    Q_ASSERT(!referenceFile.isNull());
    if (!referenceFile.isNull())
        return DB::IdList(_qh.getStackOfFile(referenceFile.rawId()));
    else
        return DB::IdList();
}

#include "Database.moc"