C

Qt Quick Ultralite map example

// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial

#pragma once

#include <qul/maptilefetcher.h>
#include <qul/private/filecache.h>
#include <string>
#include <unordered_map>
#include <list>

namespace Qul {
namespace Private {
class FileCache;
} // namespace Private
} // namespace Qul

class OfflineTileFetcher : public Qul::MapTileFetcher
{
    typedef std::basic_string<char, std::char_traits<char>, Qul::PlatformInterface::Allocator<char> > QulString;

    struct CustomHash
    {
        std::size_t operator()(const QulString &s) const
        {
            std::size_t hash = 0;
            for (size_t i = 0; i < s.size(); ++i) {
                hash = hash * 31 + s.at(i); // A simple hash function
            }
            return hash;
        }
    };

    typedef std::unordered_map<QulString,
                               Qul::SharedImage,
                               CustomHash,
                               std::equal_to<QulString>,
                               Qul::PlatformInterface::Allocator<std::pair<const QulString, Qul::SharedImage> > >
        TileCacheMap;
    typedef std::list<QulString, Qul::PlatformInterface::Allocator<QulString> > CacheOrderList;

public:
    OfflineTileFetcher();

    bool getTileImage(const Qul::Private::TileSpec &spec, Qul::Private::TileImage &tileImage) override;

private:
    void removeOldestImage();

    TileCacheMap tileCache;
    QulString generateTileUrl(const char *baseDir, const Qul::Private::TileSpec &spec) const;
    Qul::Private::FileCache *m_fileCache;

    CacheOrderList cacheOrder;
    size_t maxCacheSize;
};