Files
z-bar-qt/Plugins/ZShell/Components/carouselview.cpp
T
zach 654632128f
C++ / fmt (pull_request) Successful in 4s
JS/TS / fmt (pull_request) Successful in 9s
JS/TS / lint (pull_request) Successful in 22s
Rust / fmt (pull_request) Successful in 56s
Python / static (pull_request) Successful in 1m0s
C++ / build (pull_request) Successful in 2m9s
Rust / build (pull_request) Successful in 2m8s
Rust / clippy (pull_request) Successful in 1m9s
Python / verify (pull_request) Successful in 2m57s
C++ / clang-tidy (pull_request) Successful in 3m58s
clean-up plugin files
2026-08-16 18:14:04 +02:00

715 lines
18 KiB
C++

#include "carouselview.hpp"
#include <QQmlContext>
#include <QQmlProperty>
#include <QMouseEvent>
#include <QWheelEvent>
#include <QGuiApplication>
#include <QStyleHints>
#include <cmath>
namespace ZShell::components {
namespace {
constexpr qreal kDragThreshold = 4.0;
constexpr qreal kFlickFriction = 0.0022;
constexpr qreal kMinFlickVelocity = 60.0;
constexpr qreal kMaxFlickVelocity = 6000.0;
} // namespace
CarouselView::CarouselView(QQuickItem* parent) : QQuickItem(parent) {
setAcceptedMouseButtons(Qt::LeftButton);
setFlag(QQuickItem::ItemHasContents, false);
setClip(false);
m_glideAnim = new QVariantAnimation(this);
m_glideAnim->setEasingCurve(m_glideEasingType);
connect(
m_glideAnim,
&QVariantAnimation::valueChanged,
this,
[this](const QVariant& v) {
m_contentX = v.toReal();
wrapContentIfNeeded();
updateCurrentIndexFromContentX(true);
relayout();
});
connect(m_glideAnim, &QVariantAnimation::finished, this, [this]() {
updateCurrentIndexFromContentX(true);
});
m_flickAnim = new QVariantAnimation(this);
m_flickAnim->setEasingCurve(QEasingCurve::Linear);
connect(
m_flickAnim,
&QVariantAnimation::valueChanged,
this,
[this](const QVariant& v) {
m_contentX = v.toReal();
wrapContentIfNeeded();
updateCurrentIndexFromContentX(true);
relayout();
});
connect(m_flickAnim, &QVariantAnimation::finished, this, [this]() {
snapToNearest();
});
}
CarouselView::~CarouselView() {
releaseAllItems();
}
void CarouselView::setDelegate(QQmlComponent* c) {
if (m_delegate == c) return;
m_delegate = c;
releaseAllItems();
emit delegateChanged();
relayout();
}
void CarouselView::setModel(const QVariantList& m) {
m_model = m;
emit modelChanged();
int newCount = m_model.size();
if (newCount == 0) {
m_currentRealIndex = -1;
releaseAllItems();
rebuildArrangement();
return;
}
if (!m_initializedLayout) {
m_centerBlockStart = (kLoopMultiplier / 2) * newCount;
m_currentVirtualIndex = m_centerBlockStart;
m_contentX = contentXForIndex(m_currentVirtualIndex);
m_currentRealIndex = realIndexOf(m_currentVirtualIndex);
m_previewRealIndex = m_currentRealIndex;
m_initializedLayout = true;
rebuildArrangement();
relayout();
return;
}
rebuildArrangement();
centerInstantlyOnReal(qBound(0, m_currentRealIndex, newCount - 1));
}
void CarouselView::setFocalWidth(qreal v) {
if (qFuzzyCompare(m_focalWidth, v)) return;
m_focalWidth = v;
emit focalWidthChanged();
rebuildArrangement();
relayout();
}
void CarouselView::setMinEdgeWidth(qreal v) {
if (qFuzzyCompare(m_minEdgeWidth, v)) return;
m_minEdgeWidth = v;
emit minEdgeWidthChanged();
rebuildArrangement();
relayout();
}
void CarouselView::setItemSpacing(qreal v) {
if (qFuzzyCompare(m_itemSpacing, v)) return;
m_itemSpacing = v;
emit itemSpacingChanged();
rebuildArrangement();
relayout();
}
void CarouselView::setTileHeight(qreal v) {
if (qFuzzyCompare(m_tileHeight, v)) return;
m_tileHeight = v;
emit tileHeightChanged();
for (const Slot& s : std::as_const(m_slots)) {
if (s.active && s.item)
QQmlProperty::write(
s.item, QStringLiteral("tileHeight"), m_tileHeight);
}
}
void CarouselView::setMaxWidth(qreal v) {
if (qFuzzyCompare(m_maxWidth, v)) return;
m_maxWidth = v;
emit maxWidthChanged();
rebuildArrangement();
relayout();
}
void CarouselView::setGlideDuration(int v) {
if (m_glideDuration == v) return;
m_glideDuration = v;
emit glideDurationChanged();
}
void CarouselView::setGlideEasingType(QEasingCurve::Type t) {
if (m_glideEasingType == t) return;
m_glideEasingType = t;
m_glideAnim->setEasingCurve(t);
emit glideEasingTypeChanged();
}
void CarouselView::setDelegateProperties(const QVariantMap& v) {
m_delegateProperties = v;
emit delegatePropertiesChanged();
for (const Slot& s : std::as_const(m_slots)) {
if (s.active && s.item) {
for (auto it = m_delegateProperties.constBegin();
it != m_delegateProperties.constEnd();
++it)
QQmlProperty::write(s.item, it.key(), it.value());
}
}
}
void CarouselView::setCurrentIndex(int idx) {
goToIndex(idx);
}
void CarouselView::geometryChange(const QRectF& newGeo, const QRectF& oldGeo) {
QQuickItem::geometryChange(newGeo, oldGeo);
if (!qFuzzyCompare(newGeo.width(), oldGeo.width()) ||
!qFuzzyCompare(newGeo.height(), oldGeo.height())) {
rebuildArrangement();
if (m_initializedLayout)
m_contentX = contentXForIndex(m_currentVirtualIndex);
relayout();
}
}
void CarouselView::rebuildArrangement() {
Arrangement& a = m_arrangement;
a = Arrangement{};
const qreal W = m_maxWidth;
const qreal F = m_focalWidth;
const qreal M = m_minEdgeWidth;
const qreal sp = m_itemSpacing;
if (W <= 0 || F <= 0) {
a.sizes = {F};
a.centers = {0};
return;
}
int bestN = 0;
QVector<qreal> bestSizes = {F};
qreal bestWidth = F;
for (int n = 1;; ++n) {
const qreal ratio = std::pow(M / F, 1.0 / n);
QVector<qreal> sizes = {F};
qreal sideWidth = 0;
for (int i = 1; i <= n; ++i) {
const qreal size = (i == n) ? M : F * std::pow(ratio, i);
sizes.push_back(size);
sideWidth += size;
}
const qreal requiredWidth = F + 2 * n * sp + 2 * sideWidth;
if (requiredWidth > W) break;
bestN = n;
bestSizes = sizes;
bestWidth = requiredWidth;
if (n > 64) break;
}
a.n = bestN;
a.sizes = bestSizes;
a.width = bestWidth;
QVector<qreal> centers = {0};
qreal center = 0;
for (int i = 1; i <= bestN; ++i) {
center += bestSizes[i - 1] / 2.0 + sp + bestSizes[i] / 2.0;
centers.push_back(center);
}
a.centers = centers;
qreal extra = 0;
for (int i = 1; i <= bestN; ++i)
extra += pitch() - bestSizes[i];
a.effectiveExtraWidth = extra;
setImplicitWidth(m_maxWidth);
setWidth(a.width);
}
qreal CarouselView::keylineCenter(int io) const {
const int n = m_arrangement.n;
const int i = std::abs(io);
if (i == 0) return 0;
const int sign = io < 0 ? -1 : 1;
if (i <= n) return sign * m_arrangement.centers[i];
if (i == n + 1) {
const qreal lastCenter = m_arrangement.centers[n];
const qreal lastSize = m_arrangement.sizes[n];
return sign * (lastCenter + lastSize / 2.0 + m_itemSpacing +
m_minEdgeWidth / 2.0);
}
const qreal outgoingCenter = std::abs(keylineCenter(sign * (n + 1)));
return sign * (outgoingCenter + m_minEdgeWidth / 2.0 + m_itemSpacing);
}
qreal CarouselView::keylineSize(int io) const {
const int n = m_arrangement.n;
const int i = std::abs(io);
if (i == 0) return m_focalWidth;
if (i <= n) return m_arrangement.sizes[i];
if (i == n + 1) return m_minEdgeWidth;
return 0;
}
qreal CarouselView::sampleCenter(qreal childLoc) const {
const int n = m_arrangement.n;
if (n <= 0) return 0;
const int minIo = -(n + 2);
const int maxIo = n + 2;
const qreal p = pitch();
const int a = static_cast<int>(std::floor(childLoc / p));
if (a < minIo) return keylineCenter(minIo);
if (a >= maxIo) return keylineCenter(maxIo);
const int b = a + 1;
const qreal t = (childLoc - a * p) / p;
return keylineCenter(a) + (keylineCenter(b) - keylineCenter(a)) * t;
}
qreal CarouselView::sampleSize(qreal childLoc) const {
const int n = m_arrangement.n;
if (n <= 0) return 0;
const int minIo = -(n + 2);
const int maxIo = n + 2;
const qreal p = pitch();
const int a = static_cast<int>(std::floor(childLoc / p));
if (a < minIo) return keylineSize(minIo);
if (a >= maxIo) return keylineSize(maxIo);
const int b = a + 1;
const qreal t = (childLoc - a * p) / p;
return keylineSize(a) + (keylineSize(b) - keylineSize(a)) * t;
}
int CarouselView::realIndexOf(int virtualIndex) const {
const int count = m_model.size();
if (count == 0) return -1;
return ((virtualIndex % count) + count) % count;
}
qreal CarouselView::contentXForIndex(qreal index) const {
return index * pitch() + pitch() / 2.0 - width() / 2.0;
}
int CarouselView::indexForContentX(qreal x) const {
return static_cast<int>(
std::round((x + width() / 2.0 - pitch() / 2.0) / pitch()));
}
qreal CarouselView::snapTargetX(qreal x) const {
return contentXForIndex(indexForContentX(x));
}
void CarouselView::wrapContentIfNeeded() {
const int count = m_model.size();
if (count == 0) return;
const qreal blockWidth = count * pitch();
const qreal centerX = contentXForIndex(m_centerBlockStart);
const int blocksFromCenter =
static_cast<int>(std::round((m_contentX - centerX) / blockWidth));
if (std::abs(blocksFromCenter) >= 2) {
const qreal shift = blocksFromCenter * blockWidth;
m_contentX -= shift;
if (m_glideAnim->state() == QAbstractAnimation::Running) {
const qreal newEnd = m_glideAnim->endValue().toReal() - shift;
m_glideAnim->setEndValue(newEnd);
}
if (m_flickAnim->state() == QAbstractAnimation::Running) {
const qreal newEnd = m_flickAnim->endValue().toReal() - shift;
m_flickAnim->setEndValue(newEnd);
}
const int indexShift = static_cast<int>(std::round(shift / pitch()));
for (Slot& s : m_slots) {
if (s.active) s.virtualIndex -= indexShift;
}
}
}
void CarouselView::updateCurrentIndexFromContentX(bool emitPreview) {
const int count = m_model.size();
if (count == 0) return;
const int newVirtual = static_cast<int>(
std::round((m_contentX + width() / 2.0 - pitch() / 2.0) / pitch()));
if (newVirtual == m_currentVirtualIndex) return;
m_currentVirtualIndex = newVirtual;
const int newReal = realIndexOf(newVirtual);
if (newReal != m_currentRealIndex) {
m_currentRealIndex = newReal;
emit currentIndexChanged();
}
if (emitPreview && newReal != m_previewRealIndex) {
m_previewRealIndex = newReal;
if (newReal >= 0)
emit previewIndexChanged(newReal, m_model.at(newReal));
}
}
QQuickItem* CarouselView::acquireItem() {
if (!m_delegate) return nullptr;
QQmlContext* ctx = QQmlEngine::contextForObject(this);
QVariantMap initial;
initial.insert(QStringLiteral("isCurrent"), false);
initial.insert(QStringLiteral("modelData"), QVariant());
initial.insert(QStringLiteral("tileHeight"), m_tileHeight);
initial.insert(QStringLiteral("tileWidth"), m_focalWidth);
for (auto it = m_delegateProperties.constBegin();
it != m_delegateProperties.constEnd();
++it)
initial.insert(it.key(), it.value());
QObject* obj = m_delegate->createWithInitialProperties(initial, ctx);
if (!obj) {
qWarning(
"CarouselView: failed to create delegate instance: %s",
qPrintable(m_delegate->errorString()));
return nullptr;
}
QQuickItem* item = qobject_cast<QQuickItem*>(obj);
if (!item) {
qWarning("CarouselView: delegate root is not an Item");
delete obj;
return nullptr;
}
item->setParentItem(this);
QQmlEngine::setObjectOwnership(item, QQmlEngine::CppOwnership);
const QMetaMethod activateSignal = item->metaObject()->method(
item->metaObject()->indexOfSignal("requestActivate()"));
if (activateSignal.isValid()) {
static const QMetaMethod slot = metaObject()->method(
metaObject()->indexOfSlot("handleDelegateActivate()"));
connect(item, activateSignal, this, slot);
}
return item;
}
void CarouselView::applyPropertiesToItem(QQuickItem* item, int realIndex) const {
if (!item) return;
const bool isCurrent = (realIndex == m_currentRealIndex);
QQmlProperty::write(item, QStringLiteral("isCurrent"), isCurrent);
QQmlProperty::write(
item,
QStringLiteral("modelData"),
realIndex >= 0 && realIndex < m_model.size() ? m_model.at(realIndex)
: QVariant());
QQmlProperty::write(item, QStringLiteral("tileHeight"), m_tileHeight);
}
void CarouselView::updateSlotContent(Slot& slot, int virtualIndex) {
if (!slot.item) slot.item = acquireItem();
if (!slot.item) return;
slot.virtualIndex = virtualIndex;
slot.realIndex = realIndexOf(virtualIndex);
slot.active = slot.realIndex >= 0;
slot.item->setVisible(slot.active);
if (slot.active) applyPropertiesToItem(slot.item, slot.realIndex);
}
void CarouselView::positionSlot(const Slot& slot) const {
if (!slot.item || !slot.active) return;
const qreal childLoc = slot.virtualIndex * pitch() + pitch() / 2.0 -
m_contentX - width() / 2.0;
const qreal center = sampleCenter(childLoc);
const qreal size = sampleSize(childLoc);
const qreal slotX = childLoc + width() / 2.0 - pitch() / 2.0;
const qreal itemX = (center - childLoc) + (pitch() - size) / 2.0 + slotX;
QQmlProperty::write(slot.item, QStringLiteral("tileWidth"), size);
slot.item->setX(itemX);
slot.item->setY(0);
slot.item->setVisible(size > 0.5);
}
void CarouselView::releaseAllItems() {
for (Slot& s : m_slots) {
if (s.item) s.item->deleteLater();
}
m_slots.clear();
}
void CarouselView::relayout() {
const int count = m_model.size();
if (count == 0 || width() <= 0 || m_focalWidth <= 0) {
for (Slot& s : m_slots)
if (s.item) s.item->setVisible(false);
return;
}
const int n = m_arrangement.n;
const int half = n + 3;
const int lo = m_currentVirtualIndex - half;
const int hi = m_currentVirtualIndex + half;
const int needed = hi - lo + 1;
while (m_slots.size() < needed)
m_slots.append(Slot{});
QHash<int, int> virtualToSlot;
virtualToSlot.reserve(m_slots.size());
for (int i = 0; i < m_slots.size(); ++i) {
if (m_slots[i].active) virtualToSlot.insert(m_slots[i].virtualIndex, i);
}
QVector<bool> slotUsedThisPass(m_slots.size(), false);
for (int v = lo; v <= hi; ++v) {
auto it = virtualToSlot.find(v);
if (it != virtualToSlot.end()) {
slotUsedThisPass[it.value()] = true;
applyPropertiesToItem(
m_slots[it.value()].item, m_slots[it.value()].realIndex);
continue;
}
int freeSlot = -1;
for (int i = 0; i < m_slots.size(); ++i) {
if (slotUsedThisPass[i]) continue;
if (m_slots[i].active && m_slots[i].virtualIndex >= lo &&
m_slots[i].virtualIndex <= hi)
continue;
freeSlot = i;
break;
}
if (freeSlot < 0) {
m_slots.append(Slot{});
slotUsedThisPass.append(false);
freeSlot = m_slots.size() - 1;
}
updateSlotContent(m_slots[freeSlot], v);
slotUsedThisPass[freeSlot] = true;
}
for (int i = 0; i < m_slots.size(); ++i) {
if (!slotUsedThisPass[i] && m_slots[i].item) {
m_slots[i].active = false;
m_slots[i].item->setVisible(false);
}
}
for (const Slot& s : std::as_const(m_slots))
positionSlot(s);
}
void CarouselView::cancelAnimations() {
if (m_glideAnim->state() == QAbstractAnimation::Running)
m_glideAnim->stop();
if (m_flickAnim->state() == QAbstractAnimation::Running)
m_flickAnim->stop();
}
void CarouselView::glideTo(qreal dest) {
if (std::abs(dest - m_contentX) < 0.5) return;
cancelAnimations();
m_glideAnim->setDuration(m_glideDuration);
m_glideAnim->setStartValue(m_contentX);
m_glideAnim->setEndValue(dest);
m_glideAnim->start();
}
void CarouselView::snapToNearest() {
glideTo(snapTargetX(m_contentX));
}
void CarouselView::goToIndex(int realIndex) {
const int count = m_model.size();
if (count == 0) return;
realIndex = qBound(0, realIndex, count - 1);
const int curBlock =
static_cast<int>(std::floor(qreal(m_currentVirtualIndex) / count));
const int current = m_currentVirtualIndex;
int target = curBlock * count + realIndex;
if (target - current > count / 2)
target -= count;
else if (current - target > count / 2)
target += count;
glideTo(contentXForIndex(target));
}
void CarouselView::incrementCurrentIndex() {
if (m_model.isEmpty()) return;
glideTo(contentXForIndex(m_currentVirtualIndex + 1));
}
void CarouselView::decrementCurrentIndex() {
if (m_model.isEmpty()) return;
glideTo(contentXForIndex(m_currentVirtualIndex - 1));
}
void CarouselView::jumpToIndex(int realIndex) {
centerInstantlyOnReal(realIndex);
}
void CarouselView::centerInstantlyOnReal(int realIndex) {
const int count = m_model.size();
if (count == 0) return;
realIndex = qBound(0, realIndex, count - 1);
cancelAnimations();
const int curBlock =
static_cast<int>(std::floor(qreal(m_currentVirtualIndex) / count));
const int current = m_currentVirtualIndex;
int target = curBlock * count + realIndex;
if (target - current > count / 2)
target -= count;
else if (current - target > count / 2)
target += count;
m_currentVirtualIndex = target;
m_contentX = contentXForIndex(target);
const bool changed = (realIndex != m_currentRealIndex);
m_currentRealIndex = realIndex;
m_previewRealIndex = realIndex;
if (changed) emit currentIndexChanged();
emit previewIndexChanged(realIndex, m_model.at(realIndex));
relayout();
}
void CarouselView::mousePressEvent(QMouseEvent* event) {
m_dragging = true;
m_dragActive = false;
m_pressPos = event->position();
m_pressContentX = m_contentX;
m_dragTimer.start();
m_lastMoveX = event->position().x();
m_lastMoveT = 0;
m_velocity = 0;
event->accept();
}
void CarouselView::mouseMoveEvent(QMouseEvent* event) {
if (!m_dragging) return;
const qreal dx = event->position().x() - m_pressPos.x();
if (!m_dragActive && std::abs(dx) > kDragThreshold) {
m_dragActive = true;
m_pressContentX = m_contentX;
cancelAnimations();
grabMouse();
}
if (!m_dragActive) return;
m_contentX = m_pressContentX - dx;
wrapContentIfNeeded();
updateCurrentIndexFromContentX(true);
relayout();
const qint64 t = m_dragTimer.elapsed();
const qint64 dt = t - m_lastMoveT;
if (dt > 0) {
const qreal instVel =
(m_lastMoveX - event->position().x()) / (dt / 1000.0);
m_velocity = m_velocity * 0.7 + instVel * 0.3;
}
m_lastMoveX = event->position().x();
m_lastMoveT = t;
event->accept();
}
void CarouselView::mouseReleaseEvent(QMouseEvent* event) {
if (!m_dragging) return;
m_dragging = false;
ungrabMouse();
if (!m_dragActive) {
event->accept();
return;
}
m_dragActive = false;
qreal v = qBound(-kMaxFlickVelocity, m_velocity, kMaxFlickVelocity);
if (std::abs(v) < kMinFlickVelocity) {
snapToNearest();
event->accept();
return;
}
const qreal duration = std::abs(v) / (kFlickFriction * 1000.0); // ms
const qreal distance = (v * (duration / 1000.0)) / 2.0;
const qreal rawDest = m_contentX + distance;
const qreal dest = snapTargetX(rawDest);
cancelAnimations();
m_flickAnim->setDuration(
static_cast<int>(qBound<qreal>(120, duration, 900)));
m_flickAnim->setEasingCurve(QEasingCurve::OutCubic);
m_flickAnim->setStartValue(m_contentX);
m_flickAnim->setEndValue(dest);
m_flickAnim->start();
event->accept();
}
void CarouselView::mouseUngrabEvent() {
m_dragging = false;
m_dragActive = false;
}
void CarouselView::wheelEvent(QWheelEvent* event) {
const int steps = event->angleDelta().y() / 120;
if (steps > 0)
decrementCurrentIndex();
else if (steps < 0)
incrementCurrentIndex();
event->accept();
}
void CarouselView::handleDelegateActivate() {
QQuickItem* item = qobject_cast<QQuickItem*>(sender());
if (!item) return;
for (const Slot& s : std::as_const(m_slots)) {
if (s.item == item && s.active) {
if (s.realIndex == m_currentRealIndex) {
emit activated(s.realIndex, m_model.at(s.realIndex));
} else {
goToIndex(s.realIndex);
}
return;
}
}
}
} // namespace ZShell::components