]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kitemlistview.h
Keep current item and selection when resorting, part 1
[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/kitemliststyleoption.h>
29 #include <kitemviews/kitemlistviewanimation_p.h>
30 #include <kitemviews/kitemlistwidget.h>
31 #include <kitemviews/kitemmodelbase.h>
32 #include <QGraphicsWidget>
33 #include <QSet>
34
35 class KItemListController;
36 class KItemListGroupHeader;
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
70 public:
71 KItemListView(QGraphicsWidget* parent = 0);
72 virtual ~KItemListView();
73
74 void setScrollOrientation(Qt::Orientation orientation);
75 Qt::Orientation scrollOrientation() const;
76
77 void setItemSize(const QSizeF& size);
78 QSizeF itemSize() const;
79
80 // TODO: add note that offset is not checked against maximumOffset, only against 0.
81 void setScrollOffset(qreal offset);
82 qreal scrollOffset() const;
83
84 qreal maximumScrollOffset() const;
85
86 void setItemOffset(qreal scrollOffset);
87 qreal itemOffset() const;
88
89 qreal maximumItemOffset() const;
90
91 void setVisibleRoles(const QList<QByteArray>& roles);
92 QList<QByteArray> visibleRoles() const;
93
94 /**
95 * If set to true an automatic scrolling is done as soon as the
96 * mouse is moved near the borders of the view. Per default
97 * the automatic scrolling is turned off.
98 */
99 void setAutoScroll(bool enabled);
100 bool autoScroll() const;
101
102 /**
103 * Turns on the header if \p show is true. Per default the
104 * header is not shown.
105 */
106 void setHeaderShown(bool show);
107 bool isHeaderShown() const;
108
109 /**
110 * @return Controller of the item-list. The controller gets
111 * initialized by KItemListController::setView() and will
112 * result in calling KItemListController::onControllerChanged().
113 */
114 KItemListController* controller() const;
115
116 /**
117 * @return Model of the item-list. The model gets
118 * initialized by KItemListController::setView() and will
119 * result in calling KItemListController::onModelChanged().
120 */
121 KItemModelBase* model() const;
122
123 /**
124 * Sets the creator that creates a widget showing the
125 * content of one model-item. Usually it is sufficient
126 * to implement a custom widget X derived from KItemListWidget and
127 * set the creator by:
128 * <code>
129 * itemListView->setWidgetCreator(new KItemListWidgetCreator<X>());
130 * </code>
131 * Note that the ownership of the widget creator is not transferred to
132 * the item-list view: One instance of a widget creator might get shared
133 * by several item-list view instances.
134 **/
135 void setWidgetCreator(KItemListWidgetCreatorBase* widgetCreator);
136 KItemListWidgetCreatorBase* widgetCreator() const;
137
138 void setGroupHeaderCreator(KItemListGroupHeaderCreatorBase* groupHeaderCreator);
139 KItemListGroupHeaderCreatorBase* groupHeaderCreator() const;
140
141 void setStyleOption(const KItemListStyleOption& option);
142 const KItemListStyleOption& styleOption() const;
143
144 /** @reimp */
145 virtual void setGeometry(const QRectF& rect);
146
147 int itemAt(const QPointF& pos) const;
148 bool isAboveSelectionToggle(int index, const QPointF& pos) const;
149 bool isAboveExpansionToggle(int index, const QPointF& pos) const;
150
151 int firstVisibleIndex() const;
152 int lastVisibleIndex() const;
153
154 /**
155 * @return Required size for the item with the index \p index.
156 * Per default KItemListView::itemSize() is returned.
157 * When reimplementing this method it is recommended to
158 * also reimplement KItemListView::itemSizeHintUpdateRequired().
159 */
160 virtual QSizeF itemSizeHint(int index) const;
161
162 /**
163 * @param itemRanges Items that must be checked for getting the visible roles sizes.
164 * @return The size of each visible role in case if KItemListView::itemSize()
165 * is empty. This allows to have dynamic but equal role sizes between
166 * all items. Per default an empty hash is returned.
167 */
168 virtual QHash<QByteArray, QSizeF> visibleRolesSizes(const KItemRangeList& itemRanges) const;
169
170 /**
171 * @return The bounding rectangle of the item relative to the top/left of
172 * the currently visible area (see KItemListView::offset()).
173 */
174 QRectF itemBoundingRect(int index) const;
175
176 /**
177 * @return The number of items that can be shown in parallel for one offset.
178 * Assuming the scrolldirection is vertical then a value of 4 means
179 * that 4 columns for items are available. Assuming the scrolldirection
180 * is horizontal then a value of 4 means that 4 lines for items are
181 * available.
182 */
183 int itemsPerOffset() const;
184
185 void beginTransaction();
186 void endTransaction();
187 bool isTransactionActive() const;
188
189 /**
190 * @return Pixmap that is used for a drag operation based on the
191 * items given by \a indexes. The default implementation returns
192 * a null-pixmap.
193 */
194 virtual QPixmap createDragPixmap(const QSet<int>& indexes) const;
195
196 /**
197 * @reimp
198 */
199 virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = 0);
200
201 signals:
202 void scrollOffsetChanged(qreal current, qreal previous);
203 void maximumScrollOffsetChanged(qreal current, qreal previous);
204 void itemOffsetChanged(qreal current, qreal previous);
205 void maximumItemOffsetChanged(qreal current, qreal previous);
206 void scrollTo(qreal newOffset);
207
208 protected:
209 virtual void initializeItemListWidget(KItemListWidget* item);
210
211 /**
212 * @return True if at least one of the changed roles \p changedRoles might result
213 * in the need to update the item-size hint (see KItemListView::itemSizeHint()).
214 * Per default true is returned which means on each role-change of existing items
215 * the item-size hints are recalculated. For performance reasons it is recommended
216 * to return false in case if a role-change will not result in a changed
217 * item-size hint.
218 */
219 virtual bool itemSizeHintUpdateRequired(const QSet<QByteArray>& changedRoles) const;
220
221 virtual void onControllerChanged(KItemListController* current, KItemListController* previous);
222 virtual void onModelChanged(KItemModelBase* current, KItemModelBase* previous);
223
224 virtual void onScrollOrientationChanged(Qt::Orientation current, Qt::Orientation previous);
225 virtual void onItemSizeChanged(const QSizeF& current, const QSizeF& previous);
226 virtual void onScrollOffsetChanged(qreal current, qreal previous);
227 virtual void onVisibleRolesChanged(const QList<QByteArray>& current, const QList<QByteArray>& previous);
228 virtual void onStyleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous);
229
230 virtual void onTransactionBegin();
231 virtual void onTransactionEnd();
232
233 virtual bool event(QEvent* event);
234 virtual void mousePressEvent(QGraphicsSceneMouseEvent* event);
235 virtual void mouseMoveEvent(QGraphicsSceneMouseEvent* event);
236 virtual void dragEnterEvent(QGraphicsSceneDragDropEvent* event);
237 virtual void dragMoveEvent(QGraphicsSceneDragDropEvent* event);
238 virtual void dragLeaveEvent(QGraphicsSceneDragDropEvent* event);
239 virtual void dropEvent(QGraphicsSceneDragDropEvent* event);
240
241 QList<KItemListWidget*> visibleItemListWidgets() const;
242
243 /** @reimp */
244 virtual void resizeEvent(QGraphicsSceneResizeEvent* event);
245
246 protected slots:
247 virtual void slotItemsInserted(const KItemRangeList& itemRanges);
248 virtual void slotItemsRemoved(const KItemRangeList& itemRanges);
249 virtual void slotItemsMoved(const KItemRange& itemRange, const QList<int>& movedToIndexes);
250 virtual void slotItemsChanged(const KItemRangeList& itemRanges,
251 const QSet<QByteArray>& roles);
252
253 private slots:
254 void slotCurrentChanged(int current, int previous);
255 void slotSelectionChanged(const QSet<int>& current, const QSet<int>& previous);
256 void slotAnimationFinished(QGraphicsWidget* widget,
257 KItemListViewAnimation::AnimationType type);
258 void slotLayoutTimerFinished();
259
260 void slotRubberBandPosChanged();
261 void slotRubberBandActivationChanged(bool active);
262
263 /**
264 * Is invoked if the visible role-width of one role in the header has
265 * been changed by the user. It is remembered that the user has modified
266 * the role-width, so that it won't be changed anymore automatically to
267 * calculate an optimized width.
268 */
269 void slotVisibleRoleWidthChanged(const QByteArray& role,
270 qreal currentWidth,
271 qreal previousWidth);
272
273 /**
274 * Triggers the autoscrolling if autoScroll() is enabled by checking the
275 * current mouse position. If the mouse position is within the autoscroll
276 * margins a timer will be started that periodically triggers the autoscrolling.
277 */
278 void triggerAutoScrolling();
279
280 private:
281 enum LayoutAnimationHint
282 {
283 NoAnimation,
284 Animation
285 };
286
287 enum SizeType
288 {
289 LayouterSize,
290 ItemSize
291 };
292
293 void setController(KItemListController* controller);
294 void setModel(KItemModelBase* model);
295
296 KItemListRubberBand* rubberBand() const;
297
298 void updateLayout();
299 void doLayout(LayoutAnimationHint hint, int changedIndex, int changedCount);
300 void doGroupHeadersLayout(LayoutAnimationHint hint, int changedIndex, int changedCount);
301 void emitOffsetChanges();
302
303 KItemListWidget* createWidget(int index);
304 void recycleWidget(KItemListWidget* widget);
305 void setWidgetIndex(KItemListWidget* widget, int index);
306
307 /**
308 * Helper method for setGeometry() and setItemSize(): Calling both methods might result
309 * in a changed number of visible items. To assure that currently invisible items can
310 * get animated from the old position to the new position prepareLayoutForIncreasedItemCount()
311 * takes care to create all item widgets that are visible with the old or the new size.
312 * @param size Size of the layouter or the item dependent on \p sizeType.
313 * @param sizeType LayouterSize: KItemListLayouter::setSize() is used.
314 * ItemSize: KItemListLayouter::setItemSize() is used.
315 */
316 void prepareLayoutForIncreasedItemCount(const QSizeF& size, SizeType sizeType);
317
318 /**
319 * Helper method for prepareLayoutForIncreasedItemCount().
320 */
321 void setLayouterSize(const QSizeF& size, SizeType sizeType);
322
323 /**
324 * Helper method for createWidget() and setWidgetIndex() to update the properties
325 * of the itemlist widget.
326 */
327 void updateWidgetProperties(KItemListWidget* widget, int index);
328
329 /**
330 * Updates the width of the KItemListHeader corresponding to the required width of
331 * the roles.
332 */
333 void updateHeaderWidth();
334
335 /**
336 * @return The widths of each visible role that is shown in the KItemListHeader.
337 */
338 QHash<QByteArray, qreal> headerRolesWidths() const;
339
340 /**
341 * Updates m_visibleRolesSizes by calling KItemListView::visibleRolesSizes().
342 * Nothing will be done if m_itemRect is not empty or custom header-widths
343 * are used (see m_useHeaderWidths). Also m_strechedVisibleRolesSizes will be adjusted
344 * to respect the available view-size.
345 */
346 void updateVisibleRolesSizes(const KItemRangeList& itemRanges);
347
348 /**
349 * Convenience method for updateVisibleRoleSizes(KItemRangeList() << KItemRange(0, m_model->count()).
350 */
351 void updateVisibleRolesSizes();
352
353 /**
354 * Updates m_stretchedVisibleRolesSizes based on m_visibleRolesSizes and the available
355 * view-size. Nothing will be done if m_itemRect is not empty or custom header-widths
356 * are used (see m_useHeaderWidths).
357 */
358 void updateStretchedVisibleRolesSizes();
359
360 /**
361 * Helper function for triggerAutoScrolling().
362 * @param pos Logical position of the mouse relative to the range.
363 * @param range Range of the visible area.
364 * @param oldInc Previous increment. Is used to assure that the increment
365 * increases only gradually.
366 * @return Scroll increment that should be added to the offset().
367 * As soon as \a pos is inside the autoscroll-margin a
368 * value != 0 will be returned.
369 */
370 static int calculateAutoScrollingIncrement(int pos, int range, int oldInc);
371
372 private:
373 bool m_grouped;
374 int m_activeTransactions; // Counter for beginTransaction()/endTransaction()
375
376 QSizeF m_itemSize;
377 KItemListController* m_controller;
378 KItemModelBase* m_model;
379 QList<QByteArray> m_visibleRoles;
380 QHash<QByteArray, QSizeF> m_visibleRolesSizes;
381 QHash<QByteArray, QSizeF> m_stretchedVisibleRolesSizes;
382 KItemListWidgetCreatorBase* m_widgetCreator;
383 KItemListGroupHeaderCreatorBase* m_groupHeaderCreator;
384 KItemListStyleOption m_styleOption;
385
386 QHash<int, KItemListWidget*> m_visibleItems;
387 QHash<KItemListWidget*, KItemListGroupHeader*> m_visibleGroups;
388
389 int m_scrollBarExtent;
390 KItemListSizeHintResolver* m_sizeHintResolver;
391 KItemListViewLayouter* m_layouter;
392 KItemListViewAnimation* m_animation;
393
394 QTimer* m_layoutTimer; // Triggers an asynchronous doLayout() call.
395 qreal m_oldScrollOffset;
396 qreal m_oldMaximumScrollOffset;
397 qreal m_oldItemOffset;
398 qreal m_oldMaximumItemOffset;
399
400 bool m_skipAutoScrollForRubberBand;
401 KItemListRubberBand* m_rubberBand;
402
403 QPointF m_mousePos;
404 int m_autoScrollIncrement;
405 QTimer* m_autoScrollTimer;
406
407 KItemListHeader* m_header;
408 bool m_useHeaderWidths;
409
410 friend class KItemListController;
411 };
412
413 /**
414 * Allows to do a fast logical creation and deletion of QGraphicsWidgets
415 * by recycling existing QGraphicsWidgets instances. Is used by
416 * KItemListWidgetCreatorBase and KItemListGroupHeaderCreatorBase.
417 * @internal
418 */
419 class LIBDOLPHINPRIVATE_EXPORT KItemListCreatorBase
420 {
421 public:
422 virtual ~KItemListCreatorBase();
423
424 protected:
425 void addCreatedWidget(QGraphicsWidget* widget);
426 void pushRecycleableWidget(QGraphicsWidget* widget);
427 QGraphicsWidget* popRecycleableWidget();
428
429 private:
430 QSet<QGraphicsWidget*> m_createdWidgets;
431 QList<QGraphicsWidget*> m_recycleableWidgets;
432 };
433
434 /**
435 * @brief Base class for creating KItemListWidgets.
436 *
437 * It is recommended that applications simply use the KItemListWidgetCreator-template class.
438 * For a custom implementation the methods create() and recyle() must be reimplemented.
439 * The intention of the widget creator is to prevent repetitive and expensive instantiations and
440 * deletions of KItemListWidgets by recycling existing widget instances.
441 */
442 class LIBDOLPHINPRIVATE_EXPORT KItemListWidgetCreatorBase : public KItemListCreatorBase
443 {
444 public:
445 virtual ~KItemListWidgetCreatorBase();
446 virtual KItemListWidget* create(KItemListView* view) = 0;
447 virtual void recycle(KItemListWidget* widget);
448 };
449
450 template <class T>
451 class LIBDOLPHINPRIVATE_EXPORT KItemListWidgetCreator : public KItemListWidgetCreatorBase
452 {
453 public:
454 virtual ~KItemListWidgetCreator();
455 virtual KItemListWidget* create(KItemListView* view);
456 };
457
458 template <class T>
459 KItemListWidgetCreator<T>::~KItemListWidgetCreator()
460 {
461 }
462
463 template <class T>
464 KItemListWidget* KItemListWidgetCreator<T>::create(KItemListView* view)
465 {
466 KItemListWidget* widget = static_cast<KItemListWidget*>(popRecycleableWidget());
467 if (!widget) {
468 widget = new T(view);
469 addCreatedWidget(widget);
470 }
471 return widget;
472 }
473
474 /**
475 * @brief Base class for creating KItemListGroupHeaders.
476 *
477 * It is recommended that applications simply use the KItemListGroupHeaderCreator-template class.
478 * For a custom implementation the methods create() and recyle() must be reimplemented.
479 * The intention of the group-header creator is to prevent repetitive and expensive instantiations and
480 * deletions of KItemListGroupHeaders by recycling existing header instances.
481 */
482 class LIBDOLPHINPRIVATE_EXPORT KItemListGroupHeaderCreatorBase : public KItemListCreatorBase
483 {
484 public:
485 virtual ~KItemListGroupHeaderCreatorBase();
486 virtual KItemListGroupHeader* create(QGraphicsWidget* parent) = 0;
487 virtual void recycle(KItemListGroupHeader* header);
488 };
489
490 template <class T>
491 class LIBDOLPHINPRIVATE_EXPORT KItemListGroupHeaderCreator : public KItemListGroupHeaderCreatorBase
492 {
493 public:
494 virtual ~KItemListGroupHeaderCreator();
495 virtual KItemListGroupHeader* create(QGraphicsWidget* parent);
496 };
497
498 template <class T>
499 KItemListGroupHeaderCreator<T>::~KItemListGroupHeaderCreator()
500 {
501 }
502
503 template <class T>
504 KItemListGroupHeader* KItemListGroupHeaderCreator<T>::create(QGraphicsWidget* parent)
505 {
506 KItemListGroupHeader* widget = static_cast<KItemListGroupHeader*>(popRecycleableWidget());
507 if (!widget) {
508 widget = new T(parent);
509 addCreatedWidget(widget);
510 }
511 return widget;
512 }
513
514 #endif