[vlc-commits] [Git][videolan/vlc][master] 10 commits: qt: fix an oversized request when the list count shrinks during a fetch

Felix Paul Kühne (@fkuehne) gitlab at videolan.org
Thu Nov 5 19:44:36 UTC 2026



Felix Paul Kühne pushed to branch master at VideoLAN / VLC


Commits:
bf4eab7e by Leon Vitanos at 2026-11-05T19:49:33+01:00
qt: fix an oversized request when the list count shrinks during a fetch

- - - - -
04d183cb by Leon Vitanos at 2026-11-05T19:49:33+01:00
qt: do not reset list models when limit or offset changes

- - - - -
3f46f161 by Leon Vitanos at 2026-11-05T19:49:33+01:00
qt: add a chunk size property to BaseModel

- - - - -
5f896665 by Leon Vitanos at 2026-11-05T19:49:33+01:00
qml: limit home page model chunk size to one row

- - - - -
c8537427 by Pierre Lamot at 2026-11-05T19:49:33+01:00
qt: add tests for BaseModel limit and offset changes

- - - - -
970cacaf by Leon Vitanos at 2026-11-05T19:49:33+01:00
qt: reuse loaded items when the list offset grows

- - - - -
f8d800e4 by Leon Vitanos at 2026-11-05T19:49:33+01:00
qt: do not notify data changes past the list row count

- - - - -
3fdccc90 by Leon Vitanos at 2026-11-05T19:49:33+01:00
qt: do not notify the view when deleting an item hidden by the limit

- - - - -
77cdb203 by Pierre Lamot at 2026-11-05T19:49:33+01:00
qt: add more tests for BaseModel limit and offset changes

- - - - -
1e8e165e by Pierre Lamot at 2026-11-05T19:49:33+01:00
qt: respect the list limit when inserting or deleting items

- - - - -


11 changed files:

- modules/gui/qt/Makefile.am
- modules/gui/qt/medialibrary/qml/HomePage.qml
- modules/gui/qt/meson.build
- modules/gui/qt/style/VLCStyle.qml
- modules/gui/qt/tests/test_base_model.cpp
- modules/gui/qt/util/base_model.cpp
- modules/gui/qt/util/base_model.hpp
- modules/gui/qt/util/base_model_p.hpp
- modules/gui/qt/util/listcache.hpp
- modules/gui/qt/util/listcache.hxx
- modules/gui/qt/widgets/qml/ExpandGridItemView.qml


Changes:

=====================================
modules/gui/qt/Makefile.am
=====================================
@@ -1741,18 +1741,8 @@ endif
 endif
 endif
 
-base_model_test_SOURCES = tests/test_base_model.cpp \
-        util/base_model.cpp util/base_model.hpp util/base_model_p.hpp
-
-nodist_base_model_test_SOURCES = util/base_model.moc.cpp \
-        util/listcache.moc.cpp \
-        util/locallistcacheloader.moc.cpp
-
-base_model_test_CXXFLAGS = $(AM_CXXFLAGS) $(QT_CFLAGS) -fPIC $(CXXFLAGS_qt)
-base_model_test_LDADD = $(QT_LIBS) $(LIBS_qt)
-base_model_test_LDFLAGS = $(AM_LDFLAGS) $(QT_LDFLAGS)
-check_PROGRAMS = base_model_test
-TESTS = base_model_test
+check_PROGRAMS =
+TESTS =
 
 if HAVE_QT_QTEST
 
@@ -1762,6 +1752,25 @@ QT_QTEST_COMMON_cxxflags = $(AM_CXXFLAGS) $(QT_CFLAGS) $(QT_QTEST_CFLAGS) -fPIC
 QT_QTEST_COMMON_ldadd = $(QT_LIBS) $(LIBS_qt) $(QT_QTEST_LIBS) $(LIBVLCCORE) $(LIBVLC)
 QT_QTEST_COMMON_ldflags = $(AM_LDFLAGS) $(QT_LDFLAGS) $(QT_QTEST_LDFLAGS)
 
+# base_model_test
+
+base_model_test_SOURCES = tests/test_base_model.cpp \
+        util/base_model.cpp util/base_model.hpp util/base_model_p.hpp
+
+nodist_base_model_test_SOURCES = tests/test_base_model.moc \
+        util/base_model.moc.cpp \
+        util/listcache.moc.cpp \
+        util/locallistcacheloader.moc.cpp
+
+BUILT_SOURCES += tests/test_base_model.moc
+CLEANFILES += tests/test_base_model.moc
+base_model_test_CPPFLAGS = $(QT_QTEST_COMMON_cppflags)
+base_model_test_CXXFLAGS = $(QT_QTEST_COMMON_cxxflags)
+base_model_test_LDADD = $(QT_QTEST_COMMON_ldadd)
+base_model_test_LDFLAGS = $(QT_QTEST_COMMON_ldflags)
+check_PROGRAMS += base_model_test
+TESTS += base_model_test
+
 
 # test_ml_model
 


=====================================
modules/gui/qt/medialibrary/qml/HomePage.qml
=====================================
@@ -237,6 +237,8 @@ Widgets.PageExt {
                     sortOrder: root.sort.order
                     searchPattern: root.search.pattern
 
+                    chunkSize: VLCStyle.gridView_maxNbItemPerRow_wide
+
                     // FIXME: Make limit 0 load no items, instead of loading all items.
                     limit: MainCtx.gridView ? Math.max(continueWatchingRow.currentItem?.nbItemPerRow ?? null, 1) : 5
                 }
@@ -319,6 +321,8 @@ Widgets.PageExt {
                     sortOrder: root.sort.order
                     searchPattern: root.search.pattern
 
+                    chunkSize: VLCStyle.gridView_maxNbItemPerRow_square
+
                     // FIXME: Make limit 0 load no items, instead of loading all items.
                     limit: MainCtx.gridView ? Math.max(favoritesRow.currentItem?.nbItemPerRow ?? null, 1) : 5
                 }
@@ -393,6 +397,8 @@ Widgets.PageExt {
                     sortOrder: root.sort.order
                     searchPattern: root.search.pattern
 
+                    chunkSize: VLCStyle.gridView_maxNbItemPerRow_wide
+
                     // FIXME: Make limit 0 load no items, instead of loading all items.
                     limit: MainCtx.gridView ? Math.max(newVideoRow.currentItem?.nbItemPerRow ?? null, 1) : 5
                 }
@@ -473,6 +479,8 @@ Widgets.PageExt {
                     sortOrder: root.sort.order
                     searchPattern: root.search.pattern
 
+                    chunkSize: VLCStyle.gridView_maxNbItemPerRow_square
+
                     // FIXME: Make limit 0 load no items, instead of loading all items.
                     limit: MainCtx.gridView ? Math.max(newMusicRow.currentItem?.nbItemPerRow ?? null, 1) : 5
                 }


=====================================
modules/gui/qt/meson.build
=====================================
@@ -1286,25 +1286,28 @@ if qt6_dep.found()
         'plugin_dir' : 'gui',
     }
 
-    vlc_tests += {
-        'name': 'base_model_test',
-        'sources': files(
-            'tests/test_base_model.cpp',
-            'util/base_model.cpp',
-            'util/base_model.hpp',
-            'util/base_model_p.hpp'),
-        'moc_headers': files(
-            'util/base_model.hpp',
-            'util/listcache.hpp',
-            'util/locallistcacheloader.hpp'),
-        'suite': ['qt'],
-        'link_with': [libvlccore],
-        'link_args': qt_link_args,
-        'dependencies': [qt6_dep, qt_extra_deps],
-    }
-
     qtest_qt6_dep = dependency('qt6', version: '=' + qt6_dep.version(), modules: ['Test'], required: false)
     if qtest_qt6_dep.found()
+        vlc_tests += {
+            'name': 'base_model_test',
+            'sources': files(
+                'tests/test_base_model.cpp',
+                'util/base_model.cpp',
+                'util/base_model.hpp',
+                'util/base_model_p.hpp'),
+            'moc_sources': files(
+                'tests/test_base_model.cpp'
+            ),
+            'moc_headers': files(
+                'util/base_model.hpp',
+                'util/listcache.hpp',
+                'util/locallistcacheloader.hpp'),
+            'suite': ['qt'],
+            'link_with': [libvlccore],
+            'link_args': qt_link_args,
+            'dependencies': [qt6_dep, qt_extra_deps, qtest_qt6_dep],
+        }
+
         vlc_tests += {
             'name': 'test_qt_ml_model',
             'sources': files(


=====================================
modules/gui/qt/style/VLCStyle.qml
=====================================
@@ -236,6 +236,9 @@ QtObject {
     readonly property int gridView_spacing: margin_small + margin_xxxsmall
     readonly property int tableView_spacing: gridView_spacing + margin_large
 
+    readonly property int gridView_maxNbItemPerRow_wide: 6
+    readonly property int gridView_maxNbItemPerRow_square: 10
+
     readonly property int layoutTitle_top_padding: margin_large
     readonly property int layoutTitle_bottom_padding: margin_normal + margin_xxxsmall
 


=====================================
modules/gui/qt/tests/test_base_model.cpp
=====================================
@@ -25,12 +25,15 @@
 #include "../util/base_model_p.hpp"
 #include "../util/locallistcacheloader.hpp"
 
+#include <algorithm>
+#include <deque>
+#include <functional>
 #include <memory>
 #include <vector>
 
 #include <QCoreApplication>
-#include <QElapsedTimer>
-#include <QDebug>
+#include <QSignalSpy>
+#include <QTest>
 
 
 struct Item
@@ -136,71 +139,629 @@ void Model::append(int id)
     d->invalidateCache();
 }
 
-void await(int msec)
+/*
+ * Loader whose tasks only complete when the test asks for it, this allows to
+ * interleave model changes (limit, offset, ...) with pending loads
+ */
+struct ManualBackend
 {
-    QElapsedTimer timer;
-    timer.start();
-    while (!timer.hasExpired(msec))
+    enum class Type { Count, Load, CountAndLoad };
+
+    struct Request
+    {
+        size_t id;
+        Type type;
+        size_t offset;
+        size_t limit;
+    };
+
+    struct Task
     {
-        QCoreApplication::processEvents(QEventLoop::AllEvents, msec);
+        Request req;
+        std::function<void(size_t, size_t)> countCb;
+        std::function<void(size_t, std::vector<ItemPtr>&)> loadCb;
+        std::function<void(size_t, size_t, std::vector<ItemPtr>&)> countAndLoadCb;
+    };
+
+    std::vector<ItemPtr> items;
+    std::deque<Task> pending;
+    //every request issued since the last call to clearHistory
+    std::vector<Request> history;
+    std::vector<size_t> cancelled;
+    size_t nextId = 1;
+
+    void setItems(int count)
+    {
+        items.clear();
+        for (int i = 0; i < count; ++i)
+            items.push_back(std::make_shared<Item>(i));
     }
+
+    void clearHistory()
+    {
+        history.clear();
+        cancelled.clear();
+    }
+
+    size_t push(Task&& task)
+    {
+        task.req.id = nextId++;
+        history.push_back(task.req);
+        pending.push_back(std::move(task));
+        return history.back().id;
+    }
+
+    bool isCancelled(size_t id) const
+    {
+        return std::find(cancelled.cbegin(), cancelled.cend(), id) != cancelled.cend();
+    }
+
+    std::vector<ItemPtr> slice(size_t offset, size_t limit) const
+    {
+        std::vector<ItemPtr> data;
+        if (offset >= items.size())
+            return data;
+        //limit may be huge, don't compute offset + limit
+        size_t count = std::min(limit, items.size() - offset);
+        if (limit == 0)
+            count = items.size() - offset;
+        std::copy_n(items.cbegin() + offset, count, std::back_inserter(data));
+        return data;
+    }
+
+    //complete the oldest pending task, returns false if there is none
+    bool runNext()
+    {
+        if (pending.empty())
+            return false;
+        Task task = std::move(pending.front());
+        pending.pop_front();
+        switch (task.req.type)
+        {
+        case Type::Count:
+            task.countCb(task.req.id, items.size());
+            break;
+        case Type::Load:
+        {
+            auto data = slice(task.req.offset, task.req.limit);
+            task.loadCb(task.req.id, data);
+            break;
+        }
+        case Type::CountAndLoad:
+        {
+            auto data = slice(task.req.offset, task.req.limit);
+            task.countAndLoadCb(task.req.id, items.size(), data);
+            break;
+        }
+        }
+        return true;
+    }
+
+    //returns false if the cache keeps requesting data
+    bool runAll()
+    {
+        for (int i = 0; i < 100 && runNext(); ++i)
+            ;
+        return pending.empty();
+    }
+};
+
+struct ManualLoader : public ListCacheLoader<ItemPtr>
+{
+    explicit ManualLoader(std::shared_ptr<ManualBackend> backend)
+        : m_backend(std::move(backend))
+    {}
+
+    void cancelTask(size_t taskId) override
+    {
+        m_backend->cancelled.push_back(taskId);
+        auto& pending = m_backend->pending;
+        pending.erase(std::remove_if(pending.begin(), pending.end(),
+                                     [taskId](const ManualBackend::Task& t) { return t.req.id == taskId; }),
+                      pending.end());
+    }
+
+    size_t countTask(std::function<void(size_t taskId, size_t count)> cb) override
+    {
+        ManualBackend::Task task;
+        task.req = {0, ManualBackend::Type::Count, 0, 0};
+        task.countCb = std::move(cb);
+        return m_backend->push(std::move(task));
+    }
+
+    size_t loadTask(size_t offset, size_t limit,
+                    std::function<void(size_t taskId, std::vector<ItemPtr>& data)> cb) override
+    {
+        ManualBackend::Task task;
+        task.req = {0, ManualBackend::Type::Load, offset, limit};
+        task.loadCb = std::move(cb);
+        return m_backend->push(std::move(task));
+    }
+
+    size_t countAndLoadTask(size_t offset, size_t limit,
+                            std::function<void(size_t taskId, size_t count, std::vector<ItemPtr>& data)> cb) override
+    {
+        ManualBackend::Task task;
+        task.req = {0, ManualBackend::Type::CountAndLoad, offset, limit};
+        task.countAndLoadCb = std::move(cb);
+        return m_backend->push(std::move(task));
+    }
+
+    std::shared_ptr<ManualBackend> m_backend;
+};
+
+class ManualModelPrivate;
+
+class ManualModel : public BaseModel
+{
+    Q_DECLARE_PRIVATE(ManualModel);
+
+public:
+    ManualModel(QObject *parent = nullptr);
+
+    QVariant data(const QModelIndex & index, int role) const override;
+
+    ManualBackend& backend();
+
+    //remove an item from the cache as a medialibrary event would do
+    void deleteFromCache(int id);
+
+    //insert an item in the cache as a medialibrary event would do
+    void insertInCache(int id, int position);
+};
+
+class ManualModelPrivate : public BaseModelPrivateT<ItemPtr>
+{
+    Q_DECLARE_PUBLIC(ManualModel)
+public:
+    using BaseModelPrivateT<ItemPtr>::BaseModelPrivateT;
+
+    std::unique_ptr<ListCacheLoader<ItemPtr>> createLoader() const override
+    {
+        return std::make_unique<ManualLoader>(m_backend);
+    }
+
+    bool initializeModel() override
+    {
+        return true;
+    }
+
+    std::shared_ptr<ManualBackend> m_backend = std::make_shared<ManualBackend>();
+};
+
+ManualModel::ManualModel(QObject *parent)
+    : BaseModel(new ManualModelPrivate(this), parent)
+{
 }
 
-void test_invalidate_on_invalidate()
+QVariant ManualModel::data(const QModelIndex &index, int role) const
 {
-    Model m;
-    m.invalidateCache(); // need to force initialize model (FIXME??)
+    Q_D(const ManualModel);
+    Q_UNUSED(role);
+
+    const ItemPtr *item = d->item(index.row());
+    if (!item)
+        return {};
+
+    return (*item)->id;
+}
+
+ManualBackend& ManualModel::backend()
+{
+    Q_D(ManualModel);
+    return *d->m_backend;
+}
+
+void ManualModel::deleteFromCache(int id)
+{
+    Q_D(ManualModel);
+    d->m_cache->deleteItem([id](const ItemPtr& item) { return item->id == id; });
+}
 
-    // bug of MR!4485 MR!4684
-    m.connect(&m, &Model::loadingChanged, [&m]() { m.setLimit(1); });
-    await(1);
-    assert(!m.loading());
+void ManualModel::insertInCache(int id, int position)
+{
+    Q_D(ManualModel);
+    d->m_cache->insertItem(std::make_shared<Item>(id), position);
 }
 
+using Ranges = QList<std::pair<int, int>>;
 
-void test_null_reset()
+//rows ranges reported by rowsInserted/rowsRemoved
+static Ranges rowRanges(const QSignalSpy& spy)
 {
-    Model m;
-    // should not crash or give out warning
-    // bug of MR!4786
-    m.resetCache();
+    Ranges ranges;
+    for (const QList<QVariant>& args : spy)
+        ranges.append({args.at(1).toInt(), args.at(2).toInt()});
+    return ranges;
 }
 
-void test_sanity()
+static QVariant idAt(const QAbstractListModel& m, int row)
 {
-    Model m;
+    return m.data(m.index(row), 0);
+}
+
+//create a model with @a itemCount items, and complete its first load
+static bool initModel(ManualModel& m, int itemCount, unsigned chunkSize,
+                      unsigned limit, unsigned offset = 0)
+{
+    m.backend().setItems(itemCount);
+    m.setChunkSize(chunkSize);
+    m.setLimit(limit);
+    m.setOffset(offset);
     m.invalidateCache(); // need to force initialize model (FIXME??)
+    bool ret = m.backend().runAll();
+    m.backend().clearHistory();
+    return ret;
+}
 
-    m.setLimit(2);
-    m.append(1);
-    m.append(2);
-    await(1);
-    assert(m.getCount() == 2);
+class TestBaseModel : public QObject
+{
+    Q_OBJECT
 
-    m.setLimit(1);
-    await(1);
-    assert(m.getCount() == 1);
-    assert(m.getMaximumCount() == 2);
+private slots:
+    void testNullReset()
+    {
+        Model m;
+        // should not crash or give out warning
+        // bug of MR!4786
+        m.resetCache();
+    }
 
-    m.setLimit(2);
-    await(1);
-    assert(m.getCount() == 2);
-    for (int i = 0; i < 2; ++i)
+    void testInvalidateOnInvalidate()
     {
-        assert(m.data(m.index(i), 0) == i + 1);
+        Model m;
+        m.invalidateCache(); // need to force initialize model (FIXME??)
+
+        // bug of MR!4485 MR!4684
+        m.connect(&m, &Model::loadingChanged, [&m]() { m.setLimit(1); });
+        QTRY_VERIFY(!m.loading());
     }
-}
 
-int main(int argc, char **argv)
-{
-    QCoreApplication a(argc, argv);
-    QMetaObject::invokeMethod(&a, [&a]()
+    void testSanity()
     {
-        test_null_reset();
-        test_invalidate_on_invalidate();
-        test_sanity();
+        Model m;
+        m.invalidateCache(); // need to force initialize model (FIXME??)
+
+        m.setLimit(2);
+        m.append(1);
+        m.append(2);
+        QTRY_COMPARE(m.getCount(), 2u);
+
+        m.setLimit(1);
+        QTRY_COMPARE(m.getCount(), 1u);
+        QCOMPARE(m.getMaximumCount(), 2u);
+
+        m.setLimit(2);
+        QTRY_COMPARE(m.getCount(), 2u);
+        for (int i = 0; i < 2; ++i)
+            QCOMPARE(idAt(m, i), QVariant(i + 1));
+    }
 
-        a.quit();
-    }, Qt::QueuedConnection);
-    return a.exec();
-}
+    //changing the limit within loaded data must not reset or reload the model
+    void testLimitChangeWithinLoadedData()
+    {
+        ManualModel m;
+        QVERIFY(initModel(m, 50, 20, 10));
+        QCOMPARE(m.getCount(), 10u);
+        QCOMPARE(m.getLoadedCount(), 20u);
+
+        QSignalSpy resetSpy(&m, &QAbstractItemModel::modelReset);
+        QSignalSpy insertedSpy(&m, &QAbstractItemModel::rowsInserted);
+        QSignalSpy removedSpy(&m, &QAbstractItemModel::rowsRemoved);
+
+        m.setLimit(15);
+        QCOMPARE(resetSpy.count(), 0);
+        QCOMPARE(rowRanges(insertedSpy), Ranges({{10, 14}}));
+        QCOMPARE(m.getCount(), 15u);
+        QCOMPARE(idAt(m, 12), QVariant(12));
+        QVERIFY(m.backend().history.empty());
+
+        m.setLimit(5);
+        QCOMPARE(resetSpy.count(), 0);
+        QCOMPARE(rowRanges(removedSpy), Ranges({{5, 14}}));
+        QCOMPARE(m.getCount(), 5u);
+        QVERIFY(m.backend().history.empty());
+    }
+
+    //growing the limit past the loaded data exposes rows that are loaded on access
+    void testLimitGrowPastLoadedData()
+    {
+        ManualModel m;
+        QVERIFY(initModel(m, 50, 20, 10));
+
+        QSignalSpy resetSpy(&m, &QAbstractItemModel::modelReset);
+        QSignalSpy insertedSpy(&m, &QAbstractItemModel::rowsInserted);
+
+        m.setLimit(30);
+        QCOMPARE(resetSpy.count(), 0);
+        QCOMPARE(rowRanges(insertedSpy), Ranges({{10, 29}}));
+        QCOMPARE(m.getCount(), 30u);
+
+        //row is not loaded yet, accessing it requests the missing data
+        QVERIFY(!idAt(m, 25).isValid());
+        QCOMPARE(m.backend().history.size(), 1u);
+        QCOMPARE(m.backend().history.front().offset, 20u);
+
+        QVERIFY(m.backend().runAll());
+        QCOMPARE(idAt(m, 25), QVariant(25));
+        QCOMPARE(idAt(m, 29), QVariant(29));
+        QCOMPARE(resetSpy.count(), 0);
+    }
+
+    //fetching more data must not notify rows past the limit, dataChanged with an
+    //invalid index prevents the view from updating the newly loaded rows
+    void testFetchDataChangedWithinRowCount()
+    {
+        ManualModel m;
+        QVERIFY(initModel(m, 50, 20, 10));
+
+        QSignalSpy changedSpy(&m, &QAbstractItemModel::dataChanged);
+
+        m.setLimit(25);
+        QVERIFY(m.backend().runAll());
+        idAt(m, 22);
+
+        QVERIFY(m.backend().runAll());
+        QCOMPARE(idAt(m, 24), QVariant(24));
+
+        //dataChanged must stay within [0, rowCount[
+        QVERIFY(!changedSpy.isEmpty());
+        for (const QList<QVariant>& args : changedSpy)
+        {
+            const auto topLeft = args.at(0).value<QModelIndex>();
+            const auto bottomRight = args.at(1).value<QModelIndex>();
+            QVERIFY(topLeft.isValid());
+            QVERIFY(bottomRight.isValid());
+            QVERIFY(bottomRight.row() < 25);
+        }
+    }
+
+    //shrinking the limit while more data is being fetched must not underflow
+    //the number of items requested to the loader
+    void testLimitShrinkDuringFetch()
+    {
+        ManualModel m;
+        QVERIFY(initModel(m, 100, 10, 0));
+        QCOMPARE(m.getLoadedCount(), 10u);
+
+        //request rows [10, 20[
+        idAt(m, 15);
+        QCOMPARE(m.backend().pending.size(), 1u);
+        //view scrolls further while the fetch is pending
+        idAt(m, 45);
+        QCOMPARE(m.backend().pending.size(), 1u);
+
+        m.backend().clearHistory();
+        m.setLimit(5);
+
+        //complete the pending fetch, the view still refers row 45 which is now
+        //past the limit
+        QVERIFY(m.backend().runAll());
+        for (const ManualBackend::Request& req : m.backend().history)
+            QVERIFY2(req.limit <= m.getMaximumCount(),
+                     qPrintable(QString("requested %1 items at offset %2").arg(req.limit).arg(req.offset)));
+        QCOMPARE(m.getCount(), 5u);
+    }
+
+    //the number of rows must account for the offset
+    void testOffsetCount_data()
+    {
+        QTest::addColumn<int>("itemCount");
+        QTest::addColumn<unsigned>("limit");
+        QTest::addColumn<unsigned>("offset");
+        QTest::addColumn<unsigned>("expectedCount");
+
+        QTest::newRow("no limit") << 50 << 0u << 45u << 5u;
+        QTest::newRow("limit past the end") << 50 << 10u << 45u << 5u;
+        QTest::newRow("limit before the end") << 50 << 2u << 45u << 2u;
+        QTest::newRow("offset past the end") << 50 << 0u << 60u << 0u;
+    }
+
+    void testOffsetCount()
+    {
+        QFETCH(int, itemCount);
+        QFETCH(unsigned, limit);
+        QFETCH(unsigned, offset);
+        QFETCH(unsigned, expectedCount);
+
+        ManualModel m;
+        QVERIFY(initModel(m, itemCount, 20, limit, offset));
+        QCOMPARE(m.getCount(), expectedCount);
+        QCOMPARE(m.getMaximumCount(), static_cast<unsigned>(itemCount));
+        if (expectedCount > 0)
+        {
+            QCOMPARE(idAt(m, 0), QVariant(static_cast<int>(offset)));
+            QCOMPARE(idAt(m, expectedCount - 1), QVariant(static_cast<int>(offset + expectedCount - 1)));
+        }
+    }
+
+    void testOffsetCountLimitGrow()
+    {
+        ManualModel m;
+        QVERIFY(initModel(m, 50, 20, 2, 45));
+        QCOMPARE(m.getCount(), 2u);
+
+        m.setLimit(10);
+        QVERIFY(m.backend().runAll());
+        QCOMPARE(m.getCount(), 5u);
+    }
+
+    //changing the offset must update the model without resetting it
+    void testOffsetChangeNoReset()
+    {
+        ManualModel m;
+        QVERIFY(initModel(m, 50, 20, 0));
+
+        QSignalSpy resetSpy(&m, &QAbstractItemModel::modelReset);
+
+        m.setOffset(5);
+        QVERIFY(m.backend().runAll());
+        QCOMPARE(resetSpy.count(), 0);
+        QCOMPARE(idAt(m, 0), QVariant(5));
+        QCOMPARE(idAt(m, 10), QVariant(15));
+    }
+
+    //changing the offset while a load is pending must not display the result of
+    //the outdated load
+    void testOffsetChangeDuringLoad()
+    {
+        ManualModel m;
+        QVERIFY(initModel(m, 50, 20, 0, 30));
+
+        m.setOffset(10);
+        QCOMPARE(m.backend().pending.size(), 1u);
+        m.setOffset(20);
+
+        for (int i = 0; i < 100 && m.backend().runNext(); ++i)
+        {
+            //row 0 is either the original data or the final one
+            QVERIFY(idAt(m, 0) != QVariant(10));
+        }
+        QCOMPARE(idAt(m, 0), QVariant(20));
+    }
+
+    //removing an item hidden by the limit must not notify the view
+    void testDeleteHiddenItem()
+    {
+        ManualModel m;
+        QVERIFY(initModel(m, 20, 20, 0));
+        QCOMPARE(m.getLoadedCount(), 20u);
+
+        m.setLimit(5);
+        QVERIFY(m.backend().runAll());
+        QCOMPARE(m.getCount(), 5u);
+
+        QSignalSpy removedSpy(&m, &QAbstractItemModel::rowsRemoved);
+        m.deleteFromCache(10);
+        QCOMPARE(rowRanges(removedSpy), Ranges());
+        QCOMPARE(m.getCount(), 5u);
+    }
+
+    //removing a visible item must let the next item past the limit take its place
+    void testDeleteVisibleItemWithLimit()
+    {
+        ManualModel m;
+        QVERIFY(initModel(m, 20, 20, 5));
+        QCOMPARE(m.getLoadedCount(), 20u);
+
+        QSignalSpy removedSpy(&m, &QAbstractItemModel::rowsRemoved);
+        m.deleteFromCache(0);
+        QCOMPARE(rowRanges(removedSpy), Ranges({{0, 0}}));
+        QCOMPARE(m.getMaximumCount(), 19u);
+        QCOMPARE(m.getCount(), 5u);
+        QCOMPARE(idAt(m, 0), QVariant(1));
+        QCOMPARE(idAt(m, 4), QVariant(5));
+    }
+
+    //inserting an item must not grow the model past the limit
+    void testInsertItemWithLimit()
+    {
+        ManualModel m;
+        QVERIFY(initModel(m, 20, 20, 5));
+
+        m.insertInCache(100, 0);
+        QCOMPARE(m.getMaximumCount(), 21u);
+        QCOMPARE(m.getCount(), 5u);
+        QCOMPARE(idAt(m, 0), QVariant(100));
+        QCOMPARE(idAt(m, 4), QVariant(3));
+    }
+
+    //decreasing the offset reloads the data without resetting the model
+    void testOffsetDecrease()
+    {
+        ManualModel m;
+        QVERIFY(initModel(m, 50, 20, 0, 10));
+        QCOMPARE(idAt(m, 0), QVariant(10));
+
+        QSignalSpy resetSpy(&m, &QAbstractItemModel::modelReset);
+
+        m.setOffset(5);
+        QVERIFY(m.backend().runAll());
+        QCOMPARE(resetSpy.count(), 0);
+        QCOMPARE(m.getCount(), 45u);
+        QCOMPARE(idAt(m, 0), QVariant(5));
+        QCOMPARE(idAt(m, 10), QVariant(15));
+    }
+
+    //a fetch pending when the offset grows within the loaded data is still
+    //valid and must be kept
+    void testOffsetShiftDuringFetch()
+    {
+        ManualModel m;
+        QVERIFY(initModel(m, 100, 10, 0));
+
+        //request rows [10, 20[
+        idAt(m, 15);
+        QCOMPARE(m.backend().pending.size(), 1u);
+        const size_t fetchId = m.backend().pending.front().req.id;
+
+        m.setOffset(5);
+        QVERIFY(!m.backend().isCancelled(fetchId));
+
+        QVERIFY(m.backend().runAll());
+        QCOMPARE(m.getCount(), 95u);
+        QCOMPARE(idAt(m, 0), QVariant(5));
+        QCOMPARE(idAt(m, 4), QVariant(9));
+        QCOMPARE(idAt(m, 10), QVariant(15));
+    }
+
+    //a fetch pending when the offset skips past the loaded data targets
+    //outdated rows and must be cancelled
+    void testOffsetSkipPastLoadedDataDuringFetch()
+    {
+        ManualModel m;
+        QVERIFY(initModel(m, 100, 10, 0));
+
+        //request rows [10, 20[
+        idAt(m, 15);
+        QCOMPARE(m.backend().pending.size(), 1u);
+        const size_t fetchId = m.backend().pending.front().req.id;
+        m.backend().clearHistory();
+
+        m.setOffset(50);
+        QVERIFY(m.backend().isCancelled(fetchId));
+
+        QVERIFY(m.backend().runAll());
+        QCOMPARE(m.getCount(), 50u);
+        idAt(m, 0);
+        QVERIFY(m.backend().runAll());
+        QCOMPARE(idAt(m, 0), QVariant(50));
+        for (const ManualBackend::Request& req : m.backend().history)
+            QVERIFY2(req.offset >= 50,
+                     qPrintable(QString("requested %1 items at offset %2").arg(req.limit).arg(req.offset)));
+    }
+
+    //the view may change the limit while it is notified of an offset change
+    void testLimitChangeDuringOffsetChange()
+    {
+        ManualModel m;
+        QVERIFY(initModel(m, 50, 20, 10));
+
+        QSignalSpy insertedSpy(&m, &QAbstractItemModel::rowsInserted);
+        QSignalSpy removedSpy(&m, &QAbstractItemModel::rowsRemoved);
+        int rowCount = m.rowCount();
+        bool rowCountConsistent = true;
+        const auto checkRowCount = [&](int first, int last, int sign) {
+            rowCount += sign * (last - first + 1);
+            rowCountConsistent &= (rowCount == m.rowCount());
+        };
+        connect(&m, &QAbstractItemModel::rowsInserted, &m,
+                [&](const QModelIndex&, int first, int last) { checkRowCount(first, last, 1); });
+        connect(&m, &QAbstractItemModel::rowsRemoved, &m,
+                [&](const QModelIndex&, int first, int last) { checkRowCount(first, last, -1); });
+        connect(&m, &QAbstractItemModel::rowsRemoved, &m,
+                [&m]() { m.setLimit(5); }, Qt::SingleShotConnection);
+
+        m.setOffset(3);
+        QVERIFY(m.backend().runAll());
+        QVERIFY(rowCountConsistent);
+        QCOMPARE(m.getCount(), 5u);
+        QCOMPARE(rowCount, 5);
+        QCOMPARE(idAt(m, 0), QVariant(3));
+        QCOMPARE(idAt(m, 4), QVariant(7));
+    }
+
+};
+
+QTEST_GUILESS_MAIN(TestBaseModel)
+#include "test_base_model.moc"


=====================================
modules/gui/qt/util/base_model.cpp
=====================================
@@ -23,8 +23,6 @@ BaseModel::BaseModel(BaseModelPrivate* priv, QObject* parent)
     : QAbstractListModel(parent)
     , d_ptr(priv)
 {
-    connect(this, &BaseModel::offsetChanged,  this, &BaseModel::resetCache);
-    connect(this, &BaseModel::limitChanged,  this, &BaseModel::resetCache);
     connect(this, &BaseModel::sortCriteriaChanged,  this, &BaseModel::resetCache);
     connect(this, &BaseModel::sortOrderChanged,  this, &BaseModel::resetCache);
     connect(this, &BaseModel::searchPatternChanged,  this, &BaseModel::resetCache);
@@ -88,6 +86,7 @@ void BaseModel::setLimit(unsigned int limit)
     if (d->m_limit == limit)
         return;
     d->m_limit = limit;
+    d->updateCache();
     emit limitChanged();
 }
 
@@ -103,9 +102,25 @@ void BaseModel::setOffset(unsigned int offset)
     if (d->m_offset == offset)
         return;
     d->m_offset = offset;
+    d->updateCache();
     emit offsetChanged();
 }
 
+unsigned int BaseModel::getChunkSize() const
+{
+    Q_D(const BaseModel);
+    return d->m_chunkSize;
+}
+
+void BaseModel::setChunkSize(unsigned int chunkSize)
+{
+    Q_D(BaseModel);
+    if (chunkSize == 0 || d->m_chunkSize == chunkSize)
+        return;
+    d->m_chunkSize = chunkSize;
+    emit chunkSizeChanged();
+}
+
 const QString& BaseModel::searchPattern() const
 {
     Q_D(const BaseModel);


=====================================
modules/gui/qt/util/base_model.hpp
=====================================
@@ -45,6 +45,8 @@ class BaseModel : public QAbstractListModel, public QQmlParserStatus
     //skip in N first elements
     Q_PROPERTY(unsigned int offset READ getOffset WRITE setOffset NOTIFY offsetChanged FINAL)
 
+    Q_PROPERTY(unsigned int chunkSize READ getChunkSize WRITE setChunkSize NOTIFY chunkSizeChanged FINAL)
+
     //number of elements in the model (limit is accounted)
     Q_PROPERTY(unsigned int count READ getCount NOTIFY countChanged FINAL)
 
@@ -74,6 +76,8 @@ public:
     void setLimit(unsigned int limit);
     unsigned int getOffset() const;
     void setOffset(unsigned int offset);
+    unsigned int getChunkSize() const;
+    void setChunkSize(unsigned int chunkSize);
 
     unsigned int getCount() const;
     unsigned int getLoadedCount() const;
@@ -91,6 +95,7 @@ signals:
     void searchPatternChanged();
     void limitChanged() const;
     void offsetChanged() const;
+    void chunkSizeChanged() const;
     void countChanged(unsigned int) const;
     void maximumCountChanged(unsigned int) const;
     void loadingChanged() const;


=====================================
modules/gui/qt/util/base_model_p.hpp
=====================================
@@ -35,6 +35,7 @@ public:
     virtual void validateCache() const = 0;
     virtual void resetCache() = 0;
     virtual void invalidateCache() = 0;
+    virtual void updateCache() = 0;
     virtual bool loading() const = 0;
 
     virtual unsigned int getLoadedCount() const = 0;
@@ -116,6 +117,7 @@ protected:
     QString m_sortCriteria = {};
     unsigned int m_limit = 0;
     unsigned int m_offset = 0;
+    unsigned int m_chunkSize = 100;
     bool m_qmlInitializing = false;
 };
 
@@ -130,6 +132,7 @@ public:
     void validateCache() const override;
     void resetCache() override;
     void invalidateCache() override;
+    void updateCache() override;
 
     bool loading() const override;
 
@@ -212,7 +215,7 @@ void BaseModelPrivateT<T>::validateCache() const
         return;
 
     auto loader = createLoader();
-    m_cache = std::make_unique<ListCache<T>>(std::move(loader), false, m_limit, m_offset);
+    m_cache = std::make_unique<ListCache<T>>(std::move(loader), false, m_limit, m_offset, m_chunkSize);
     validateCacheImpl(m_cache.get());
 }
 
@@ -229,6 +232,15 @@ void BaseModelPrivateT<T>::invalidateCache()
     invalidateCacheImpl(m_cache);
 }
 
+template<typename T>
+void BaseModelPrivateT<T>::updateCache()
+{
+    if (!m_cache)
+        return;
+    m_cache->setLimit(m_limit);
+    m_cache->setOffset(m_offset);
+}
+
 template<typename T>
 bool BaseModelPrivateT<T>::loading() const
 {


=====================================
modules/gui/qt/util/listcache.hpp
=====================================
@@ -254,6 +254,8 @@ public:
     void invalidate();
 
 
+    void setLimit(size_t limit);
+    void setOffset(size_t offset);
 
 private:
     static uint32_t cacheDataLength(const void* data);
@@ -264,6 +266,9 @@ private:
     void asyncFetchMore();
     void asyncCountAndLoad();
     void partialUpdate();
+    size_t countWithLimit(size_t maximumCount) const;
+    //update the number of visible rows to match the limit, returns whether it changed
+    bool applyLimit();
     size_t fixupIndexForMove(size_t index) const;
 
     bool m_useMove = false;


=====================================
modules/gui/qt/util/listcache.hxx
=====================================
@@ -164,7 +164,8 @@ int ListCache<T>::updateItem(ItemType&& newItem)
 
     int pos = std::distance(m_cachedData->list.begin(), it);
     *it = std::move(newItem);
-    emit localDataChanged(pos, pos);
+    if (static_cast<size_t>(pos) < m_cachedData->queryCount)
+        emit localDataChanged(pos, pos);
     return pos;
 }
 
@@ -187,14 +188,21 @@ int ListCache<T>::deleteItem(const std::function<bool (const ItemType&)>&& f)
         return -1;
 
     int pos = std::distance(m_cachedData->list.begin(), it);
+    const bool visible = static_cast<size_t>(pos) < m_cachedData->queryCount;
 
-    emit beginRemoveRows(pos, pos);
+    if (visible)
+        emit beginRemoveRows(pos, pos);
     m_cachedData->list.erase(it, it+1);
     size_t delta = m_cachedData->loadedCount - m_cachedData->list.size();
     m_cachedData->loadedCount -= delta;
     m_cachedData->maximumCount -= delta;
-    m_cachedData->queryCount -= delta;
-    emit endRemoveRows();
+    if (visible)
+    {
+        m_cachedData->queryCount -= delta;
+        emit endRemoveRows();
+    }
+    //an item past the limit may take the place of the removed one
+    applyLimit();
     emit localSizeChanged(m_cachedData->queryCount, m_cachedData->maximumCount);
 
     return pos;
@@ -216,12 +224,21 @@ void ListCache<T>::insertItem(ItemType&& item, int position)
     if (unlikely(position < 0 || position > (int)m_cachedData->list.size()))
         return;
 
-    emit beginInsertRows(position, position);
+    //items inserted past the limit are not visible
+    const bool visible = static_cast<size_t>(position) <= m_cachedData->queryCount;
+
+    if (visible)
+        emit beginInsertRows(position, position);
     m_cachedData->list.insert(m_cachedData->list.begin() + position, std::move(item));
     m_cachedData->loadedCount++;
     m_cachedData->maximumCount++;
-    m_cachedData->queryCount++;
-    emit endInsertRows();
+    if (visible)
+    {
+        m_cachedData->queryCount++;
+        emit endInsertRows();
+    }
+    //the inserted item may push the last row past the limit
+    applyLimit();
     emit localSizeChanged(m_cachedData->queryCount, m_cachedData->maximumCount);
 }
 
@@ -242,12 +259,24 @@ void ListCache<T>::insertItemList(IterType first, IterType last, int position)
         return;
 
     size_t count = std::distance(first, last);
-    emit beginInsertRows(position, position + (int)count - 1);
+    if (count == 0)
+        return;
+
+    //items inserted past the limit are not visible
+    const bool visible = static_cast<size_t>(position) <= m_cachedData->queryCount;
+
+    if (visible)
+        emit beginInsertRows(position, position + (int)count - 1);
     std::move(first, last, std::inserter(m_cachedData->list, m_cachedData->list.begin() + position));
     m_cachedData->loadedCount += count;
     m_cachedData->maximumCount += count;
-    m_cachedData->queryCount += count;
-    emit endInsertRows();
+    if (visible)
+    {
+        m_cachedData->queryCount += count;
+        emit endInsertRows();
+    }
+    //the inserted items may push the last rows past the limit
+    applyLimit();
     emit localSizeChanged(m_cachedData->queryCount, m_cachedData->maximumCount);
 }
 
@@ -313,6 +342,8 @@ void ListCache<T>::deleteRange(int first, int last)
     m_cachedData->queryCount -= rangeSize;
     m_cachedData->maximumCount -= rangeSize;
     emit endRemoveRows();
+    //items past the limit may take the place of the removed ones
+    applyLimit();
     emit localSizeChanged(m_cachedData->queryCount, m_cachedData->maximumCount);
 }
 
@@ -395,6 +426,96 @@ void  ListCache<T>::fetchMore()
         asyncFetchMore();
 }
 
+template<typename T>
+size_t ListCache<T>::countWithLimit(size_t maximumCount) const
+{
+    const size_t count = (maximumCount > m_offset) ? maximumCount - m_offset : 0;
+    if (m_limit == 0)
+        return count;
+    return std::min(m_limit, count);
+}
+
+template<typename T>
+bool ListCache<T>::applyLimit()
+{
+    assert(m_cachedData);
+
+    const size_t newQueryCount = countWithLimit(m_cachedData->maximumCount);
+    const size_t oldQueryCount = m_cachedData->queryCount;
+    if (newQueryCount == oldQueryCount)
+        return false;
+
+    if (newQueryCount < oldQueryCount)
+    {
+        emit beginRemoveRows(newQueryCount, oldQueryCount - 1);
+        m_cachedData->queryCount = newQueryCount;
+        emit endRemoveRows();
+    }
+    else
+    {
+        emit beginInsertRows(oldQueryCount, newQueryCount - 1);
+        m_cachedData->queryCount = newQueryCount;
+        emit endInsertRows();
+    }
+    return true;
+}
+
+template<typename T>
+void ListCache<T>::setLimit(size_t limit)
+{
+    m_limit = limit;
+    if (!m_cachedData || m_oldData)
+        return;
+
+    if (applyLimit())
+        emit localSizeChanged(m_cachedData->queryCount, m_cachedData->maximumCount);
+}
+
+template<typename T>
+void ListCache<T>::setOffset(size_t offset)
+{
+    if (m_offset == offset)
+        return;
+
+    if (m_cachedData && !m_oldData && !m_countTask && offset > m_offset)
+    {
+        const size_t delta = offset - m_offset;
+        const size_t droppedItems = std::min(delta, m_cachedData->loadedCount);
+        const size_t removedRows = std::min(delta, m_cachedData->queryCount);
+        m_offset = offset;
+
+        //a pending append still targets m_offset + loadedCount, unless we skipped past it
+        if (m_appendTask && delta > m_cachedData->loadedCount)
+        {
+            m_loader->cancelTask(m_appendTask);
+            m_appendTask = 0;
+        }
+
+        if (removedRows > 0)
+            emit beginRemoveRows(0, removedRows - 1);
+        m_cachedData->list.erase(m_cachedData->list.begin(), m_cachedData->list.begin() + droppedItems);
+        m_cachedData->loadedCount -= droppedItems;
+        m_cachedData->queryCount -= removedRows;
+        if (removedRows > 0)
+            emit endRemoveRows();
+
+        m_maxReferedIndex = (m_maxReferedIndex > delta) ? m_maxReferedIndex - delta : 0;
+        if (applyLimit() || removedRows > 0)
+            emit localSizeChanged(m_cachedData->queryCount, m_cachedData->maximumCount);
+        if (!m_appendTask)
+            asyncFetchMore();
+        return;
+    }
+
+    m_offset = offset;
+    if (m_countTask)
+    {
+        m_loader->cancelTask(m_countTask);
+        m_countTask = 0;
+    }
+    invalidate();
+}
+
 template<typename T>
 void ListCache<T>::invalidate()
 {
@@ -525,6 +646,8 @@ void ListCache<T>::partialUpdate()
             emit localSizeChanged(m_cachedData->queryCount, m_cachedData->maximumCount);
         }
     }
+
+    setLimit(m_limit);
 }
 
 template<typename T>
@@ -549,9 +672,7 @@ void ListCache<T>::asyncCountAndLoad()
                 m_needReload = true;
             }
 
-            size_t queryCount = (m_limit > 0)
-                ? std::min(m_limit, maximumCount)
-                : maximumCount;
+            size_t queryCount = countWithLimit(maximumCount);
 
             //note: should we drop items past queryCount?
             m_cachedData = std::make_unique<CacheData>(std::move(list),
@@ -601,13 +722,13 @@ template<typename T>
 void ListCache<T>::asyncFetchMore()
 {
     assert(m_cachedData);
+    m_maxReferedIndex = std::min(m_cachedData->queryCount, m_maxReferedIndex);
     if (m_maxReferedIndex <= m_cachedData->loadedCount)
         return;
 
     if (m_appendTask)
         m_loader->cancelTask(m_appendTask);
 
-    m_maxReferedIndex = std::min(m_cachedData->queryCount, m_maxReferedIndex);
     size_t count = ((m_maxReferedIndex - m_cachedData->loadedCount) / m_chunkSize + 1 ) * m_chunkSize;
 
     m_appendTask = m_loader->loadTask(
@@ -625,7 +746,9 @@ void ListCache<T>::asyncFetchMore()
                 int updatedOffset = m_cachedData->loadedCount;
                 std::move(list.begin(), list.end(), std::back_inserter(m_cachedData->list));
                 m_cachedData->loadedCount += updatedCount;
-                emit localDataChanged(updatedOffset, updatedOffset + updatedCount - 1);
+                const int visibleEnd = static_cast<int>(std::min(m_cachedData->loadedCount, m_cachedData->queryCount));
+                if (updatedOffset < visibleEnd)
+                    emit localDataChanged(updatedOffset, visibleEnd - 1);
             }
 
             m_appendTask = 0;


=====================================
modules/gui/qt/widgets/qml/ExpandGridItemView.qml
=====================================
@@ -67,6 +67,8 @@ Widgets.ExpandGridView {
 
         availableWidth: root._availableContentWidth
 
-        maxNbItemPerRow: basePictureWidth === basePictureHeight ? 10 : 6
+        maxNbItemPerRow: basePictureWidth === basePictureHeight
+                         ? VLCStyle.gridView_maxNbItemPerRow_square
+                         : VLCStyle.gridView_maxNbItemPerRow_wide
     }
 }



View it on GitLab: https://code.videolan.org/videolan/vlc/-/compare/e3d68013c95c4ce34e585b4645be6616063b3aaa...1e8e165eb6490aff047ea8fa2416bdca51d7724f

-- 
View it on GitLab: https://code.videolan.org/videolan/vlc/-/compare/e3d68013c95c4ce34e585b4645be6616063b3aaa...1e8e165eb6490aff047ea8fa2416bdca51d7724f
You're receiving this email because of your account on code.videolan.org. Manage all notifications: https://code.videolan.org/-/profile/notifications | Help: https://code.videolan.org/help




More information about the vlc-commits mailing list