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 a part of digiKam project
 * https://www.digikam.org
 *
 * Date        : 2007-05-01
 * Description : ItemInfo common data
 *
 * SPDX-FileCopyrightText: 2007-2013 by Marcel Wiesweg <marcel dot wiesweg at gmx dot de>
 * SPDX-FileCopyrightText: 2014-2025 by Gilles Caulier <caulier dot gilles at gmail dot com>
 * SPDX-FileCopyrightText:      2013 by Michael G. Hansen <mike at mghansen dot de>
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 *
 * ============================================================ */

#include "iteminfocache.h"

// Local includes

#include "coredb.h"
#include "coredbalbuminfo.h"
#include "iteminfo.h"
#include "iteminfolist.h"
#include "iteminfodata.h"
#include "digikam_debug.h"

namespace Digikam
{

ItemInfoCache::ItemInfoCache()
{
    qRegisterMetaType<ItemInfo>("ItemInfo");
    qRegisterMetaType<ItemInfoList>("ItemInfoList");
    qRegisterMetaType<QList<ItemInfo> >("QList<ItemInfo>");

    CoreDbWatch* const dbwatch = CoreDbAccess::databaseWatch();<--- Variable 'dbwatch' can be declared as pointer to const

    connect(dbwatch, SIGNAL(imageChange(ImageChangeset)),
            this, SLOT(slotImageChanged(ImageChangeset)),
            Qt::DirectConnection);

    connect(dbwatch, SIGNAL(imageTagChange(ImageTagChangeset)),
            this, SLOT(slotImageTagChanged(ImageTagChangeset)),
            Qt::DirectConnection);

    connect(dbwatch, SIGNAL(albumChange(AlbumChangeset)),
            this, SLOT(slotAlbumChange(AlbumChangeset)),
            Qt::DirectConnection);
}

static bool lessThanForAlbumShortInfo(const AlbumShortInfo& first, const AlbumShortInfo& second)
{
    return (first.id < second.id);
}

void ItemInfoCache::checkAlbums()
{
    if (m_needUpdateAlbums)
    {
        // list comes sorted from db

        QList<AlbumShortInfo> infos = CoreDbAccess().db()->getAlbumShortInfos();

        ItemInfoWriteLocker lock;
        m_albums                    = infos;
        m_needUpdateAlbums          = false;
    }
}

int ItemInfoCache::getImageGroupedCount(qlonglong id)
{
    if (m_needUpdateGrouped)
    {
        QList<qlonglong> ids = CoreDbAccess().db()->getRelatedImagesToByType(DatabaseRelation::Grouped);

        ItemInfoWriteLocker lock;
        m_grouped            = ids;
        m_needUpdateGrouped  = false;
    }

    ItemInfoReadLocker lock;

    return m_grouped.count(id);
}

QExplicitlySharedDataPointer<ItemInfoData> ItemInfoCache::infoForId(qlonglong id)
{
    {
        ItemInfoReadLocker lock;
        QExplicitlySharedDataPointer<ItemInfoData> ptr(m_infoHash.value(id));

        if (ptr)
        {
            return ptr;
        }
    }

    ItemInfoWriteLocker lock;
    ItemInfoData* const data = new ItemInfoData();
    data->id                 = id;
    m_infoHash[id]           = data;

    return QExplicitlySharedDataPointer<ItemInfoData>(data);
}

void ItemInfoCache::cacheByName(const QExplicitlySharedDataPointer<ItemInfoData>& infoPtr)
{
    // Called with Write lock

    if (!infoPtr || (infoPtr->id == -1) || infoPtr->name.isEmpty())
    {
        return;
    }

    // Called in a context where we can assume that the entry is not yet cached by name (newly created data)

    m_nameHash.remove(m_dataHash.value(infoPtr->id), infoPtr);
    m_dataHash.insert(infoPtr->id, infoPtr->name);
    m_nameHash.insert(infoPtr->name, infoPtr);
}

QExplicitlySharedDataPointer<ItemInfoData> ItemInfoCache::infoForPath(int albumRootId,
                                                                      const QString& relativePath, const QString& name)
{
    ItemInfoReadLocker lock;

    // We check all entries in the multi hash with matching file name

    QMultiHash<QString, QExplicitlySharedDataPointer<ItemInfoData> >::const_iterator it;

    for (it = m_nameHash.constFind(name) ; (it != m_nameHash.constEnd()) && (it.key() == name) ; ++it)
    {
        // first check that album root matches

        if (it.value()->albumRootId != albumRootId)
        {
            continue;
        }

        // check that relativePath matches. We get relativePath from entry's id and compare to given name.

        QList<AlbumShortInfo>::const_iterator albumIt = findAlbum(it.value()->albumId);

        if ((albumIt == m_albums.constEnd()) || (albumIt->relativePath != relativePath))
        {
            continue;
        }

        // we have now a match by name, albumRootId and relativePath

        return it.value();
    }

    return QExplicitlySharedDataPointer<ItemInfoData>();
}

void ItemInfoCache::dropInfo(const QExplicitlySharedDataPointer<ItemInfoData>& infoPtr)
{
    if (!infoPtr)
    {
        return;
    }

    ItemInfoWriteLocker lock;

    // When we have the last ItemInfoData, the reference counter is at 3.
    // Because 2 QExplicitlySharedDataPointers are in cache and 1 is held by m_data.

    if (infoPtr.data()->ref > 3)
    {
        return;
    }

    m_nameHash.remove(m_dataHash.value(infoPtr->id), infoPtr);
    m_nameHash.remove(infoPtr->name, infoPtr);
    m_infoHash.remove(infoPtr->id);
    m_dataHash.remove(infoPtr->id);
}

QList<AlbumShortInfo>::const_iterator ItemInfoCache::findAlbum(int id)
{
    // Called with read lock

    AlbumShortInfo info;
    info.id = id;

    // we use the fact that d->infos is sorted by id

    QList<AlbumShortInfo>::const_iterator it;
    it = std::lower_bound(m_albums.constBegin(),
                          m_albums.constEnd(), info,
                          lessThanForAlbumShortInfo);

    if ((it == m_albums.constEnd()) || (info.id < (*it).id))
    {
        return m_albums.constEnd();
    }

    return it;
}

QString ItemInfoCache::albumRelativePath(int albumId)
{
    checkAlbums();
    ItemInfoReadLocker lock;
    QList<AlbumShortInfo>::const_iterator it = findAlbum(albumId);

    if (it != m_albums.constEnd())
    {
        return it->relativePath;
    }

    return QString();
}

void ItemInfoCache::invalidate()
{
    ItemInfoWriteLocker lock;
    QHash<qlonglong, QExplicitlySharedDataPointer<ItemInfoData> >::iterator it;

    for (it = m_infoHash.begin() ; it != m_infoHash.end() ; ++it)
    {
        (*it)->invalid = true;
        (*it)->id      = -1;
    }

    m_albums.clear();
    m_grouped.clear();
    m_nameHash.clear();
    m_infoHash.clear();
    m_dataHash.clear();
    m_needUpdateAlbums  = true;
    m_needUpdateGrouped = true;
}

void ItemInfoCache::slotImageChanged(const ImageChangeset& changeset)
{
    ItemInfoWriteLocker lock;
    const auto ids = changeset.ids();

    for (const qlonglong& imageId : ids)
    {
        QHash<qlonglong, QExplicitlySharedDataPointer<ItemInfoData> >::iterator it = m_infoHash.find(imageId);

        if (it != m_infoHash.end())
        {
            // invalidate the relevant field. It will be lazy-loaded at first access.

            DatabaseFields::Set changes = changeset.changes();

            if (changes & DatabaseFields::ItemCommentsAll)
            {
                (*it)->defaultCommentCached = false;
                (*it)->defaultTitleCached   = false;
            }

            if (changes & DatabaseFields::Category)
            {
                (*it)->categoryCached = false;
            }

            if (changes & DatabaseFields::Format)
            {
                (*it)->formatCached = false;
            }

            if (changes & DatabaseFields::PickLabel)
            {
                (*it)->pickLabelCached = false;
            }

            if (changes & DatabaseFields::ColorLabel)
            {
                (*it)->colorLabelCached = false;
            }

            if (changes & DatabaseFields::Rating)
            {
                (*it)->ratingCached = false;
            }

            if (changes & DatabaseFields::CreationDate)
            {
                (*it)->creationDateCached = false;
            }

            if (changes & DatabaseFields::ModificationDate)
            {
                (*it)->modificationDateCached = false;
            }

            if (changes & DatabaseFields::Orientation)
            {
                (*it)->orientationCached = false;
            }

            if (changes & DatabaseFields::FileSize)
            {
                (*it)->fileSizeCached = false;
            }

            if (changes & DatabaseFields::UniqueHash)
            {
                (*it)->uniqueHashCached = false;
            }

            if (changes & DatabaseFields::ManualOrder)
            {
                (*it)->manualOrderCached = false;
            }

            if ((changes & DatabaseFields::Width) || (changes & DatabaseFields::Height))
            {
                (*it)->imageSizeCached = false;
            }

            if (
                (changes & DatabaseFields::LatitudeNumber)  ||
                (changes & DatabaseFields::LongitudeNumber) ||
                (changes & DatabaseFields::Altitude)
               )
            {
                (*it)->positionsCached = false;
            }

            if (changes & DatabaseFields::ImageRelations)
            {
                (*it)->groupImageCached = false;
                m_needUpdateGrouped     = true;
            }

            if (changes.hasFieldsFromVideoMetadata())
            {
                const DatabaseFields::VideoMetadata changedVideoMetadata = changes.getVideoMetadata();
                (*it)->videoMetadataCached                              &= ~changedVideoMetadata;
                (*it)->hasVideoMetadata                                  = true;

                (*it)->databaseFieldsHashRaw.removeAllFields(changedVideoMetadata);
            }

            if (changes.hasFieldsFromImageMetadata())
            {
                const DatabaseFields::ImageMetadata changedImageMetadata = changes.getImageMetadata();
                (*it)->imageMetadataCached                              &= ~changedImageMetadata;
                (*it)->hasImageMetadata                                  = true;

                (*it)->databaseFieldsHashRaw.removeAllFields(changedImageMetadata);
            }
        }
        else
        {
            m_needUpdateGrouped = true;
        }
    }
}

void ItemInfoCache::slotImageTagChanged(const ImageTagChangeset& changeset)
{
    if (changeset.propertiesWereChanged())
    {
        ItemInfoWriteLocker lock;
        const auto ids = changeset.ids();

        for (const qlonglong& imageId : ids)
        {
            QHash<qlonglong, QExplicitlySharedDataPointer<ItemInfoData> >::iterator it = m_infoHash.find(imageId);

            if (it != m_infoHash.end())
            {
                (*it)->faceCountCached            = false;
                (*it)->faceSuggestionsCached      = false;
                (*it)->unconfirmedFaceCountCached = false;
            }
        }

        return;
    }

    ItemInfoWriteLocker lock;
    const auto ids = changeset.ids();

    for (const qlonglong& imageId : ids)
    {
        QHash<qlonglong, QExplicitlySharedDataPointer<ItemInfoData> >::iterator it = m_infoHash.find(imageId);

        if (it != m_infoHash.end())
        {
            (*it)->tagIdsCached     = false;
            (*it)->colorLabelCached = false;
            (*it)->pickLabelCached  = false;
        }
    }
}

void ItemInfoCache::slotAlbumChange(const AlbumChangeset& changeset)
{
    switch (changeset.operation())
    {
        case AlbumChangeset::Added:
        case AlbumChangeset::Deleted:
        case AlbumChangeset::Renamed:
        case AlbumChangeset::PropertiesChanged:
        {
            m_needUpdateAlbums = true;
            break;
        }

        case AlbumChangeset::Unknown:
        {
            break;
        }
    }
}

} // namespace Digikam

#include "moc_iteminfocache.cpp"