]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kitemlistview.h
Don't animate items if the number of grid elements has been changed
[dolphin.git] / src / kitemviews / kitemlistview.h
1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
3 * *
4 * Based on the Itemviews NG project from Trolltech Labs: *
5 * http://qt.gitorious.org/qt-labs/itemviews-ng *
6 * *
7 * This program is free software; you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation; either version 2 of the License, or *
10 * (at your option) any later version. *
11 * *
12 * This program is distributed in the hope that it will be useful, *
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU General Public License for more details. *
16 * *
17 * You should have received a copy of the GNU General Public License *
18 * along with this program; if not, write to the *
19 * Free Software Foundation, Inc., *
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
21 ***************************************************************************/
22
23 #ifndef KITEMLISTVIEW_H
24 #define KITEMLISTVIEW_H
25
26 #include <libdolphin_export.h>
27
28 #include <kitemviews/kitemlistgroupheader.h>
29 #include <kitemviews/kitemliststyleoption.h>
30 #include <kitemviews/kitemlistviewanimation_p.h>
31 #include <kitemviews/kitemlistwidget.h>
32 #include <kitemviews/kitemmodelbase.h>
33 #include <QGraphicsWidget>
34 #include <QSet>
35
36 class KItemListController;
37 class KItemListGroupHeaderCreatorBase;
38 class KItemListHeader;
39 class KItemListSizeHintResolver;
40 class KItemListRubberBand;
41 class KItemListViewAnimation;
42 class KItemListViewLayouter;
43 class KItemListWidget;
44 class KItemListWidgetCreatorBase;
45 class KItemListViewCreatorBase;
46 class QTimer;
47
48 /**
49 * @brief Represents the view of an item-list.
50 *
51 * The view is responsible for showing the items of the model within
52 * a GraphicsItem. Each visible item is represented by a KItemListWidget.
53 *
54 * The created view must be applied to the KItemListController with
55 * KItemListController::setView(). For showing a custom model it is not
56 * mandatory to derive from KItemListView, all that is necessary is
57 * to set a widget-creator that is capable to create KItemListWidgets
58 * showing the model items. A widget-creator can be set with
59 * KItemListView::setWidgetCreator().
60 *
61 * @see KItemListWidget
62 * @see KItemModelBase
63 */
64 class LIBDOLPHINPRIVATE_EXPORT KItemListView : public QGraphicsWidget
65 {
66 Q_OBJECT
67
68 Q_PROPERTY(qreal scrollOffset READ scrollOffset WRITE setScrollOffset)
69 Q_PROPERTY(qreal itemOffset READ itemOffset WRITE setItemOffset)
70
71 public:
72 KItemListView(QGraphicsWidget* parent = 0);
73 virtual ~KItemListView();
74
75 void setScrollOrientation(Qt::Orientation orientation);
76 Qt::Orientation scrollOrientation() const;
77
78 void setItemSize(const QSizeF& size);
79 QSizeF itemSize() const;
80
81 // TODO: add note that offset is not checked against maximumOffset, only against 0.
82 void setScrollOffset(qreal offset);
83 qreal scrollOffset() const;
84
85 qreal maximumScrollOffset() const;
86
87 void setItemOffset(qreal scrollOffset);
88 qreal itemOffset() const;
89
90 qreal maximumItemOffset() const;
91
92 void setVisibleRoles(const QList<QByteArray>& roles);
93 QList<QByteArray> visibleRoles() const;
94
95 /**
96 * If set to true an automatic scrolling is done as soon as the
97 * mouse is moved near the borders of the view. Per default
98 * the automatic scrolling is turned off.
99 */
100 void setAutoScroll(bool enabled);
101 bool autoScroll() const;
102
103 /**
104 * If set to true selection-toggles will be shown when hovering
105 * an item. Per default the selection-toggles are disabled.
106 */
107 void setEnabledSelectionToggles(bool enabled);
108 bool enabledSelectionToggles() const;
109
110 /**
111 * @return Controller of the item-list. The controller gets
112 * initialized by KItemListController::setView() and will
113 * result in calling KItemListController::onControllerChanged().
114 */
115 KItemListController* controller() const;
116
117 /**
118 * @return Model of the item-list. The model gets
119 * initialized by KItemListController::setView() and will
120 * result in calling KItemListController::onModelChanged().
121 */
122 KItemModelBase* model() const;
123
124 /**
125 * Sets the creator that creates a widget showing the
126 * content of one model-item. Usually it is sufficient
127 * to implement a custom widget X derived from KItemListWidget and
128 * set the creator by:
129 * <code>
130 * itemListView->setWidgetCreator(new KItemListWidgetCreator<X>());
131 * </code>
132 * Note that the ownership of the widget creator is not transferred to
133 * the item-list view: One instance of a widget creator might get shared
134 * by several item-list view instances.
135 **/
136 void setWidgetCreator(KItemListWidgetCreatorBase* widgetCreator);
137 KItemListWidgetCreatorBase* widgetCreator() const;
138
139 void setGroupHeaderCreator(KItemListGroupHeaderCreatorBase* groupHeaderCreator);
140 KItemListGroupHeaderCreatorBase* groupHeaderCreator() const;
141
142 void setStyleOption(const KItemListStyleOption& option);
143 const KItemListStyleOption& styleOption() const;
144
145 /** @reimp */
146 virtual void setGeometry(const QRectF& rect);
147
148 int itemAt(const QPointF& pos) const;
149 bool isAboveSelectionToggle(int index, const QPointF& pos) const;
150 bool isAboveExpansionToggle(int index, const QPointF& pos) const;
151
152 int firstVisibleIndex() const;
153 int lastVisibleIndex() const;
154
155 /**
156 * @return Required size for the item with the index \p index.
157 * Per default KItemListView::itemSize() is returned.
158 * When reimplementing this method it is recommended to
159 * also reimplement KItemListView::itemSizeHintUpdateRequired().
160 */
161 virtual QSizeF itemSizeHint(int index) const;
162
163 /**
164 * @param itemRanges Items that must be checked for getting the visible roles sizes.
165 * @return The size of each visible role in case if KItemListView::itemSize()
166 * is empty. This allows to have dynamic but equal role sizes between
167 * all items. Per default an empty hash is returned.
168 */
169 virtual QHash<QByteArray, QSizeF> visibleRolesSizes(const KItemRangeList& itemRanges) const;
170
171 /**
172 * @return True if the view supports the expanding of items. Per default false
173 * is returned. If expanding of items is supported, the methods
174 * KItemModelBase::setExpanded(), KItemModelBase::isExpanded() and
175 * KItemModelBase::isExpandable() must be reimplemented. The view-implementation
176 * has to take care itself how to visually represent the expanded items provided
177 * by the model.
178 */
179 virtual bool supportsItemExpanding() const;
180
181 /**
182 * @return The rectangle of the item relative to the top/left of
183 * the currently visible area (see KItemListView::offset()).
184 */
185 QRectF itemRect(int index) const;
186
187 /**
188 * @return The context rectangle of the item relative to the top/left of
189 * the currently visible area (see KItemListView::offset()). The
190 * context rectangle is defined by by the united rectangle of
191 * the icon rectangle and the text rectangle (see KItemListWidget::iconRect()
192 * and KItemListWidget::textRect()) and is useful as reference for e.g. aligning
193 * a tooltip or a context-menu for an item. Note that a context rectangle will
194 * only be returned for (at least partly) visible items. An empty rectangle will
195 * be returned for fully invisible items.
196 */
197 QRectF itemContextRect(int index) const;
198
199 /**
200 * Scrolls to the item with the index \a index so that the item
201 * will be fully visible.
202 */
203 void scrollToItem(int index);
204
205 void beginTransaction();
206 void endTransaction();
207 bool isTransactionActive() const;
208
209 /**
210 * Turns on the header if \p show is true. Per default the
211 * header is not shown.
212 */
213 void setHeaderShown(bool show);
214 bool isHeaderShown() const;
215
216 /**
217 * @return Pixmap that is used for a drag operation based on the
218 * items given by \a indexes. The default implementation returns
219 * a null-pixmap.
220 */
221 virtual QPixmap createDragPixmap(const QSet<int>& indexes) const;
222
223 /**
224 * @reimp
225 */
226 virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = 0);
227
228 signals:
229 void scrollOrientationChanged(Qt::Orientation current, Qt::Orientation previous);
230 void scrollOffsetChanged(qreal current, qreal previous);
231 void maximumScrollOffsetChanged(qreal current, qreal previous);
232 void itemOffsetChanged(qreal current, qreal previous);
233 void maximumItemOffsetChanged(qreal current, qreal previous);
234 void scrollTo(qreal newOffset);
235
236 /**
237 * Is emitted if the user has changed the sort order by clicking on a
238 * header item (see KItemListView::setHeaderShown()). The sort order
239 * of the model has already been adjusted to
240 * the current sort order. Note that no signal will be emitted if the
241 * sort order of the model has been changed without user interaction.
242 */
243 void sortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous);
244
245 /**
246 * Is emitted if the user has changed the sort role by clicking on a
247 * header item (see KItemListView::setHeaderShown()). The sort role
248 * of the model has already been adjusted to
249 * the current sort role. Note that no signal will be emitted if the
250 * sort role of the model has been changed without user interaction.
251 */
252 void sortRoleChanged(const QByteArray& current, const QByteArray& previous);
253
254 protected:
255 virtual void initializeItemListWidget(KItemListWidget* item);
256
257 /**
258 * @return True if at least one of the changed roles \p changedRoles might result
259 * in the need to update the item-size hint (see KItemListView::itemSizeHint()).
260 * Per default true is returned which means on each role-change of existing items
261 * the item-size hints are recalculated. For performance reasons it is recommended
262 * to return false in case if a role-change will not result in a changed
263 * item-size hint.
264 */
265 virtual bool itemSizeHintUpdateRequired(const QSet<QByteArray>& changedRoles) const;
266
267 virtual void onControllerChanged(KItemListController* current, KItemListController* previous);
268 virtual void onModelChanged(KItemModelBase* current, KItemModelBase* previous);
269
270 virtual void onScrollOrientationChanged(Qt::Orientation current, Qt::Orientation previous);
271 virtual void onItemSizeChanged(const QSizeF& current, const QSizeF& previous);
272 virtual void onScrollOffsetChanged(qreal current, qreal previous);
273 virtual void onVisibleRolesChanged(const QList<QByteArray>& current, const QList<QByteArray>& previous);
274 virtual void onStyleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous);
275
276 virtual void onTransactionBegin();
277 virtual void onTransactionEnd();
278
279 virtual bool event(QEvent* event);
280 virtual void mousePressEvent(QGraphicsSceneMouseEvent* event);
281 virtual void mouseMoveEvent(QGraphicsSceneMouseEvent* event);
282 virtual void dragEnterEvent(QGraphicsSceneDragDropEvent* event);
283 virtual void dragMoveEvent(QGraphicsSceneDragDropEvent* event);
284 virtual void dragLeaveEvent(QGraphicsSceneDragDropEvent* event);
285 virtual void dropEvent(QGraphicsSceneDragDropEvent* event);
286
287 QList<KItemListWidget*> visibleItemListWidgets() const;
288
289 protected slots:
290 virtual void slotItemsInserted(const KItemRangeList& itemRanges);
291 virtual void slotItemsRemoved(const KItemRangeList& itemRanges);
292 virtual void slotItemsMoved(const KItemRange& itemRange, const QList<int>& movedToIndexes);
293 virtual void slotItemsChanged(const KItemRangeList& itemRanges,
294 const QSet<QByteArray>& roles);
295
296 virtual void slotGroupedSortingChanged(bool current);
297 virtual void slotSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous);
298 virtual void slotSortRoleChanged(const QByteArray& current, const QByteArray& previous);
299 virtual void slotCurrentChanged(int current, int previous);
300 virtual void slotSelectionChanged(const QSet<int>& current, const QSet<int>& previous);
301
302 private slots:
303 void slotAnimationFinished(QGraphicsWidget* widget,
304 KItemListViewAnimation::AnimationType type);
305 void slotLayoutTimerFinished();
306
307 void slotRubberBandPosChanged();
308 void slotRubberBandActivationChanged(bool active);
309
310 /**
311 * Is invoked if the visible role-width of one role in the header has
312 * been changed by the user. It is remembered that the user has modified
313 * the role-width, so that it won't be changed anymore automatically to
314 * calculate an optimized width.
315 */
316 void slotVisibleRoleWidthChanged(const QByteArray& role,
317 qreal currentWidth,
318 qreal previousWidth);
319
320 /**
321 * Triggers the autoscrolling if autoScroll() is enabled by checking the
322 * current mouse position. If the mouse position is within the autoscroll
323 * margins a timer will be started that periodically triggers the autoscrolling.
324 */
325 void triggerAutoScrolling();
326
327 private:
328 enum LayoutAnimationHint
329 {
330 NoAnimation,
331 Animation
332 };
333
334 enum SizeType
335 {
336 LayouterSize,
337 ItemSize
338 };
339
340 void setController(KItemListController* controller);
341 void setModel(KItemModelBase* model);
342
343 KItemListRubberBand* rubberBand() const;
344
345 void doLayout(LayoutAnimationHint hint, int changedIndex = 0, int changedCount = 0);
346
347 /**
348 * Helper method for doLayout: Returns a list of items that can be reused for the visible
349 * area. Invisible group headers get recycled. The reusable items are items that are
350 * invisible. If the animation hint is 'Animation' then items that are currently animated
351 * won't be reused. Reusing items is faster in comparison to deleting invisible
352 * items and creating a new instance for visible items.
353 */
354 QList<int> recycleInvisibleItems(int firstVisibleIndex,
355 int lastVisibleIndex,
356 LayoutAnimationHint hint);
357
358 /**
359 * Helper method for doLayout: Starts a moving-animation for the widget to the given
360 * new position. The moving-animation is only started if the new position is within
361 * the same row or column, otherwise the create-animation is used instead.
362 * @return True if the moving-animation has been applied.
363 */
364 bool moveWidget(KItemListWidget* widget, const QRectF& itemBounds);
365
366 void emitOffsetChanges();
367
368 KItemListWidget* createWidget(int index);
369 void recycleWidget(KItemListWidget* widget);
370 void setWidgetIndex(KItemListWidget* widget, int index);
371
372 /**
373 * Helper method for prepareLayoutForIncreasedItemCount().
374 */
375 void setLayouterSize(const QSizeF& size, SizeType sizeType);
376
377 /**
378 * Helper method for createWidget() and setWidgetIndex() to update the properties
379 * of the itemlist widget.
380 */
381 void updateWidgetProperties(KItemListWidget* widget, int index);
382
383 /**
384 * Helper method for createWidget() and setWidgetIndex() to create or update
385 * the itemlist group-header.
386 */
387 void updateGroupHeaderForWidget(KItemListWidget* widget);
388
389 /**
390 * Updates the position and size of the group-header that belongs
391 * to the itemlist widget \a widget. The given widget must represent
392 * the first item of a group.
393 */
394 void updateGroupHeaderLayout(KItemListWidget* widget);
395
396 /**
397 * Recycles the group-header from the widget.
398 */
399 void recycleGroupHeaderForWidget(KItemListWidget* widget);
400
401 /**
402 * Helper method for slotGroupedSortingChanged(), slotSortOrderChanged()
403 * and slotSortRoleChanged(): Iterates through all visible items and updates
404 * the group-header widgets.
405 */
406 void updateVisibleGroupHeaders();
407
408 /**
409 * @return The widths of each visible role that is shown in the KItemListHeader.
410 */
411 QHash<QByteArray, qreal> headerRolesWidths() const;
412
413 /**
414 * Updates m_visibleRolesSizes by calling KItemListView::visibleRolesSizes().
415 * Nothing will be done if m_itemRect is not empty or custom header-widths
416 * are used (see m_useHeaderWidths). Also m_strechedVisibleRolesSizes will be adjusted
417 * to respect the available view-size.
418 */
419 void updateVisibleRolesSizes(const KItemRangeList& itemRanges);
420
421 /**
422 * Convenience method for updateVisibleRoleSizes(KItemRangeList() << KItemRange(0, m_model->count()).
423 */
424 void updateVisibleRolesSizes();
425
426 /**
427 * Updates m_stretchedVisibleRolesSizes based on m_visibleRolesSizes and the available
428 * view-size. Nothing will be done if m_itemRect is not empty or custom header-widths
429 * are used (see m_useHeaderWidths).
430 */
431 void updateStretchedVisibleRolesSizes();
432
433 /**
434 * @return Sum of the widths of all visible roles.
435 */
436 qreal visibleRolesSizesWidthSum() const;
437
438 /**
439 * @return Sum of the heights of all visible roles.
440 */
441 qreal visibleRolesSizesHeightSum() const;
442
443 /**
444 * @return Boundaries of the header. An empty rectangle is returned
445 * if no header is shown.
446 */
447 QRectF headerBoundaries() const;
448
449 /**
450 * @return True if the number of columns or rows will be changed when applying
451 * the new grid- and item-size. Used to determine whether an animation
452 * should be done when applying the new layout.
453 */
454 bool changesItemGridLayout(const QSizeF& newGridSize, const QSizeF& newItemSize) const;
455
456 /**
457 * @param changedItemCount Number of inserted or removed items.
458 * @return True if the inserting or removing of items should be animated.
459 * No animation should be done if the number of items is too large
460 * to provide a pleasant animation.
461 */
462 bool animateChangedItemCount(int changedItemCount) const;
463
464 /**
465 * Helper function for triggerAutoScrolling().
466 * @param pos Logical position of the mouse relative to the range.
467 * @param range Range of the visible area.
468 * @param oldInc Previous increment. Is used to assure that the increment
469 * increases only gradually.
470 * @return Scroll increment that should be added to the offset().
471 * As soon as \a pos is inside the autoscroll-margin a
472 * value != 0 will be returned.
473 */
474 static int calculateAutoScrollingIncrement(int pos, int range, int oldInc);
475
476 private:
477 bool m_enabledSelectionToggles;
478 bool m_grouped;
479 int m_activeTransactions; // Counter for beginTransaction()/endTransaction()
480
481 QSizeF m_itemSize;
482 KItemListController* m_controller;
483 KItemModelBase* m_model;
484 QList<QByteArray> m_visibleRoles;
485 QHash<QByteArray, QSizeF> m_visibleRolesSizes;
486 QHash<QByteArray, QSizeF> m_stretchedVisibleRolesSizes;
487 KItemListWidgetCreatorBase* m_widgetCreator;
488 KItemListGroupHeaderCreatorBase* m_groupHeaderCreator;
489 KItemListStyleOption m_styleOption;
490
491 QHash<int, KItemListWidget*> m_visibleItems;
492 QHash<KItemListWidget*, KItemListGroupHeader*> m_visibleGroups;
493
494 int m_scrollBarExtent;
495 KItemListSizeHintResolver* m_sizeHintResolver;
496 KItemListViewLayouter* m_layouter;
497 KItemListViewAnimation* m_animation;
498
499 QTimer* m_layoutTimer; // Triggers an asynchronous doLayout() call.
500 qreal m_oldScrollOffset;
501 qreal m_oldMaximumScrollOffset;
502 qreal m_oldItemOffset;
503 qreal m_oldMaximumItemOffset;
504
505 bool m_skipAutoScrollForRubberBand;
506 KItemListRubberBand* m_rubberBand;
507
508 QPointF m_mousePos;
509 int m_autoScrollIncrement;
510 QTimer* m_autoScrollTimer;
511
512 KItemListHeader* m_header;
513 bool m_useHeaderWidths;
514
515 friend class KItemListController;
516 };
517
518 /**
519 * Allows to do a fast logical creation and deletion of QGraphicsWidgets
520 * by recycling existing QGraphicsWidgets instances. Is used by
521 * KItemListWidgetCreatorBase and KItemListGroupHeaderCreatorBase.
522 * @internal
523 */
524 class LIBDOLPHINPRIVATE_EXPORT KItemListCreatorBase
525 {
526 public:
527 virtual ~KItemListCreatorBase();
528
529 protected:
530 void addCreatedWidget(QGraphicsWidget* widget);
531 void pushRecycleableWidget(QGraphicsWidget* widget);
532 QGraphicsWidget* popRecycleableWidget();
533
534 private:
535 QSet<QGraphicsWidget*> m_createdWidgets;
536 QList<QGraphicsWidget*> m_recycleableWidgets;
537 };
538
539 /**
540 * @brief Base class for creating KItemListWidgets.
541 *
542 * It is recommended that applications simply use the KItemListWidgetCreator-template class.
543 * For a custom implementation the methods create() and recyle() must be reimplemented.
544 * The intention of the widget creator is to prevent repetitive and expensive instantiations and
545 * deletions of KItemListWidgets by recycling existing widget instances.
546 */
547 class LIBDOLPHINPRIVATE_EXPORT KItemListWidgetCreatorBase : public KItemListCreatorBase
548 {
549 public:
550 virtual ~KItemListWidgetCreatorBase();
551 virtual KItemListWidget* create(KItemListView* view) = 0;
552 virtual void recycle(KItemListWidget* widget);
553 };
554
555 template <class T>
556 class KItemListWidgetCreator : public KItemListWidgetCreatorBase
557 {
558 public:
559 virtual ~KItemListWidgetCreator();
560 virtual KItemListWidget* create(KItemListView* view);
561 };
562
563 template <class T>
564 KItemListWidgetCreator<T>::~KItemListWidgetCreator()
565 {
566 }
567
568 template <class T>
569 KItemListWidget* KItemListWidgetCreator<T>::create(KItemListView* view)
570 {
571 KItemListWidget* widget = static_cast<KItemListWidget*>(popRecycleableWidget());
572 if (!widget) {
573 widget = new T(view);
574 addCreatedWidget(widget);
575 }
576 return widget;
577 }
578
579 /**
580 * @brief Base class for creating KItemListGroupHeaders.
581 *
582 * It is recommended that applications simply use the KItemListGroupHeaderCreator-template class.
583 * For a custom implementation the methods create() and recyle() must be reimplemented.
584 * The intention of the group-header creator is to prevent repetitive and expensive instantiations and
585 * deletions of KItemListGroupHeaders by recycling existing header instances.
586 */
587 class LIBDOLPHINPRIVATE_EXPORT KItemListGroupHeaderCreatorBase : public KItemListCreatorBase
588 {
589 public:
590 virtual ~KItemListGroupHeaderCreatorBase();
591 virtual KItemListGroupHeader* create(KItemListView* view) = 0;
592 virtual void recycle(KItemListGroupHeader* header);
593 };
594
595 template <class T>
596 class KItemListGroupHeaderCreator : public KItemListGroupHeaderCreatorBase
597 {
598 public:
599 virtual ~KItemListGroupHeaderCreator();
600 virtual KItemListGroupHeader* create(KItemListView* view);
601 };
602
603 template <class T>
604 KItemListGroupHeaderCreator<T>::~KItemListGroupHeaderCreator()
605 {
606 }
607
608 template <class T>
609 KItemListGroupHeader* KItemListGroupHeaderCreator<T>::create(KItemListView* view)
610 {
611 KItemListGroupHeader* widget = static_cast<KItemListGroupHeader*>(popRecycleableWidget());
612 if (!widget) {
613 widget = new T(view);
614 addCreatedWidget(widget);
615 }
616 return widget;
617 }
618
619 #endif