#include "carouselview.hpp" #include #include #include #include #include #include #include namespace ZShell::components { namespace { constexpr qreal kDragThreshold = 4.0; // px before a press becomes a drag constexpr qreal kFlickFriction = 0.0022; // px/ms^2 deceleration constexpr qreal kMinFlickVelocity = 60.0; // px/sec below which we just snap 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(); } // ---------------------------------------------------------------- properties 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(); // Re-anchor on the currently selected path if possible, otherwise clamp. 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; } // Model contents changed under us (e.g. search text filtered the list). // Re-anchor instantly on the clamped selection -- no glide, since this // isn't a user-initiated navigation. 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); } // ---------------------------------------------------------------- geometry void CarouselView::geometryChange(const QRectF& newGeo, const QRectF& oldGeo) { QQuickItem::geometryChange(newGeo, oldGeo); if (!qFuzzyCompare(newGeo.width(), oldGeo.width()) || !qFuzzyCompare(newGeo.height(), oldGeo.height())) { // Recentre on the same virtual index rather than letting contentX // drift, exactly like the QML version's onWidthChanged handler -- // but here it happens in the same pass as the arrangement rebuild, // so x/width for every slot are recomputed together. rebuildArrangement(); if (m_initializedLayout) m_contentX = contentXForIndex(m_currentVirtualIndex); relayout(); } } // ---------------------------------------------------------------- arrangement math // Direct port of the QML `arrangement` computed property + keylineCenter/ // keylineSize/sampleCenter/sampleSize helpers. Kept numerically identical on // purpose so behaviour doesn't change, just *when* it's applied. void CarouselView::rebuildArrangement() { Arrangement& a = m_arrangement; a = Arrangement{}; // IMPORTANT: this must be the external constraint (m_maxWidth), never // width() -- width() is a *result* of this computation (see below), and // using it here would make the arrangement depend on its own previous // output. On first layout, before width() has ever been set, that // bootstraps to W==0 -> n==0 -> every side item falls back to a flat // minEdgeWidth with no taper at all, which is what caused items to slide // off looking "pushed out" instead of shrinking. 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 bestSizes = {F}; qreal bestWidth = F; for (int n = 1;; ++n) { const qreal ratio = std::pow(M / F, 1.0 / n); QVector 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; // Safety valve: arrangement size is bounded by how many halvings fit, // this just guards against pathological inputs (F <= M etc). if (n > 64) break; } a.n = bestN; a.sizes = bestSizes; a.width = bestWidth; QVector 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); // This mirrors the original `width: arrangement.width` binding. It's // safe against feedback because the arrangement above only ever reads // m_maxWidth, never width() -- so if a.width doesn't change, setWidth() // here is a no-op and geometryChange() won't recurse. 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(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(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; } // ---------------------------------------------------------------- index math 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( 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(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); } // Also shift every currently-live slot's virtual index bookkeeping so // it doesn't think it needs to be recycled just because of the wrap. const int indexShift = static_cast(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( 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)); } } // ---------------------------------------------------------------- pool / delegates 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(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); // slot's "column" spans one pitch, centred at width()/2 + center; item is // centred within that column, matching the QML delegate's x expression. 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(); } // ---------------------------------------------------------------- layout pass 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; // Window of virtual indices that can ever be visible, plus a small buffer // so items don't pop in/out right at the edge during a fast flick. const int half = n + 3; const int lo = m_currentVirtualIndex - half; const int hi = m_currentVirtualIndex + half; const int needed = hi - lo + 1; // Grow the pool if needed (shrinking is unnecessary: idle items are just // marked inactive/invisible, which is cheap and avoids churn). while (m_slots.size() < needed) m_slots.append(Slot{}); // Figure out which virtual indices are already backed by a slot. QHash virtualToSlot; // virtualIndex -> slot list position 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 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; // Content (isCurrent / modelData) may still need refreshing if // currentRealIndex changed since last pass. applyPropertiesToItem( m_slots[it.value()].item, m_slots[it.value()].realIndex); continue; } // find a free slot: one not used this pass and not already at a // virtual index inside [lo, hi] (those are all still needed). 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) { // Shouldn't happen given the pool growth above, but guard anyway. 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); } // ---------------------------------------------------------------- animation 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)); } // ---------------------------------------------------------------- public API 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(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(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(); } // ---------------------------------------------------------------- input void CarouselView::mousePressEvent(QMouseEvent* event) { // Deliberately do NOT cancel animations here. A press that turns out to // be a plain tap (never crosses the drag threshold) should leave any // in-flight glide/flick completely untouched. We only touch the // animation once we know it's actually a drag (see mouseMoveEvent). m_dragging = true; m_dragActive = false; m_pressPos = event->position(); // Capture wherever contentX currently is, even mid-animation -- if this // does turn into a drag, it should pick up smoothly from the visual // position, not teleport to some rest position first. 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; // re-anchor to the live (possibly mid-animation) value 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); // Light smoothing so a single jittery sample doesn't dominate the flick. 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) { // A plain click/tap with no drag: let it fall through to the // delegate's own StateLayer/MouseArea via requestActivate(). event->accept(); return; } m_dragActive = false; qreal v = qBound(-kMaxFlickVelocity, m_velocity, kMaxFlickVelocity); if (std::abs(v) < kMinFlickVelocity) { snapToNearest(); event->accept(); return; } // Simple constant-deceleration flick: distance = v^2 / (2*friction). const qreal duration = std::abs(v) / (kFlickFriction * 1000.0); // ms const qreal distance = (v * (duration / 1000.0)) / 2.0; // average-velocity approximation const qreal rawDest = m_contentX + distance; const qreal dest = snapTargetX(rawDest); cancelAnimations(); m_flickAnim->setDuration( static_cast(qBound(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(); } // ---------------------------------------------------------------- delegate signal void CarouselView::handleDelegateActivate() { QQuickItem* item = qobject_cast(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