]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kitemlistview.h
Minor layout and coding style cleanups
[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 /**
206 * @return The number of items that can be shown in parallel for one offset.
207 * Assuming the scrolldirection is vertical then a value of 4 means
208 * that 4 columns for items are available. Assuming the scrolldirection
209 * is horizontal then a value of 4 means that 4 lines for items are
210 * available.
211 */
212 int itemsPerOffset() const;
213
214 void beginTransaction();
215 void endTransaction();
216 bool isTransactionActive() const;
217
218 /**
219 * Turns on the header if \p show is true. Per default the
220 * header is not shown.
221 */
222 void setHeaderShown(bool show);
223 bool isHeaderShown() const;
224
225 /**
226 * @return Pixmap that is used for a drag operation based on the
227 * items given by \a indexes. The default implementation returns
228 * a null-pixmap.
229 */
230 virtual QPixmap createDragPixmap(const QSet<int>& indexes) const;
231
232 /**
233 * @reimp
234 */
235 virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = 0);
236
237 signals:
238 void scrollOrientationChanged(Qt::Orientation current, Qt::Orientation previous);
239 void scrollOffsetChanged(qreal current, qreal previous);
240 void maximumScrollOffsetChanged(qreal current, qreal previous);
241 void itemOffsetChanged(qreal current, qreal previous);
242 void maximumItemOffsetChanged(qreal current, qreal previous);
243 void scrollTo(qreal newOffset);
244
245 /**
246 * Is emitted if the user has changed the sort order by clicking on a
247 * header item (see KItemListView::setHeaderShown()). The sort order
248 * of the model has already been adjusted to
249 * the current sort order. Note that no signal will be emitted if the
250 * sort order of the model has been changed without user interaction.
251 */
252 void sortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous);
253
254 /**
255 * Is emitted if the user has changed the sort role by clicking on a
256 * header item (see KItemListView::setHeaderShown()). The sort role
257 * of the model has already been adjusted to
258 * the current sort role. Note that no signal will be emitted if the
259 * sort role of the model has been changed without user interaction.
260 */
261 void sortRoleChanged(const QByteArray& current, const QByteArray& previous);
262
263 protected:
264 virtual void initializeItemListWidget(KItemListWidget* item);
265
266 /**
267 * @return True if at least one of the changed roles \p changedRoles might result
268 * in the need to update the item-size hint (see KItemListView::itemSizeHint()).
269 * Per default true is returned which means on each role-change of existing items
270 * the item-size hints are recalculated. For performance reasons it is recommended
271 * to return false in case if a role-change will not result in a changed
272 * item-size hint.
273 */
274 virtual bool itemSizeHintUpdateRequired(const QSet<QByteArray>& changedRoles) const;
275
276 virtual void onControllerChanged(KItemListController* current, KItemListController* previous);
277 virtual void onModelChanged(KItemModelBase* current, KItemModelBase* previous);
278
279 virtual void onScrollOrientationChanged(Qt::Orientation current, Qt::Orientation previous);
280 virtual void onItemSizeChanged(const QSizeF& current, const QSizeF& previous);
281 virtual void onScrollOffsetChanged(qreal current, qreal previous);
282 virtual void onVisibleRolesChanged(const QList<QByteArray>& current, const QList<QByteArray>& previous);
283 virtual void onStyleOptionChanged(const KItemListStyleOption& current, const KItemListStyleOption& previous);
284
285 virtual void onTransactionBegin();
286 virtual void onTransactionEnd();
287
288 virtual bool event(QEvent* event);
289 virtual void mousePressEvent(QGraphicsSceneMouseEvent* event);
290 virtual void mouseMoveEvent(QGraphicsSceneMouseEvent* event);
291 virtual void dragEnterEvent(QGraphicsSceneDragDropEvent* event);
292 virtual void dragMoveEvent(QGraphicsSceneDragDropEvent* event);
293 virtual void dragLeaveEvent(QGraphicsSceneDragDropEvent* event);
294 virtual void dropEvent(QGraphicsSceneDragDropEvent* event);
295
296 QList<KItemListWidget*> visibleItemListWidgets() const;
297
298 /** @reimp */
299 virtual void resizeEvent(QGraphicsSceneResizeEvent* event);
300
301 protected slots:
302 virtual void slotItemsInserted(const KItemRangeList& itemRanges);
303 virtual void slotItemsRemoved(const KItemRangeList& itemRanges);
304 virtual void slotItemsMoved(const KItemRange& itemRange, const QList<int>& movedToIndexes);
305 virtual void slotItemsChanged(const KItemRangeList& itemRanges,
306 const QSet<QByteArray>& roles);
307
308 virtual void slotGroupedSortingChanged(bool current);
309 virtual void slotSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous);
310 virtual void slotSortRoleChanged(const QByteArray& current, const QByteArray& previous);
311 virtual void slotCurrentChanged(int current, int previous);
312 virtual void slotSelectionChanged(const QSet<int>& current, const QSet<int>& previous);
313
314 private slots:
315 void slotAnimationFinished(QGraphicsWidget* widget,
316 KItemListViewAnimation::AnimationType type);
317 void slotLayoutTimerFinished();
318
319 void slotRubberBandPosChanged();
320 void slotRubberBandActivationChanged(bool active);
321
322 /**
323 * Is invoked if the visible role-width of one role in the header has
324 * been changed by the user. It is remembered that the user has modified
325 * the role-width, so that it won't be changed anymore automatically to
326 * calculate an optimized width.
327 */
328 void slotVisibleRoleWidthChanged(const QByteArray& role,
329 qreal currentWidth,
330 qreal previousWidth);
331
332 /**
333 * Triggers the autoscrolling if autoScroll() is enabled by checking the
334 * current mouse position. If the mouse position is within the autoscroll
335 * margins a timer will be started that periodically triggers the autoscrolling.
336 */
337 void triggerAutoScrolling();
338
339 private:
340 enum LayoutAnimationHint
341 {
342 NoAnimation,
343 Animation
344 };
345
346 enum SizeType
347 {
348 LayouterSize,
349 ItemSize
350 };
351
352 void setController(KItemListController* controller);
353 void setModel(KItemModelBase* model);
354
355 KItemListRubberBand* rubberBand() const;
356
357 void doLayout(LayoutAnimationHint hint, int changedIndex = 0, int changedCount = 0);
358
359 void emitOffsetChanges();
360
361 KItemListWidget* createWidget(int index);
362 void recycleWidget(KItemListWidget* widget);
363 void setWidgetIndex(KItemListWidget* widget, int index);
364
365 /**
366 * Helper method for setGeometry() and setItemSize(): Calling both methods might result
367 * in a changed number of visible items. To assure that currently invisible items can
368 * get animated from the old position to the new position prepareLayoutForIncreasedItemCount()
369 * takes care to create all item widgets that are visible with the old or the new size.
370 * @param size Size of the layouter or the item dependent on \p sizeType.
371 * @param sizeType LayouterSize: KItemListLayouter::setSize() is used.
372 * ItemSize: KItemListLayouter::setItemSize() is used.
373 */
374 void prepareLayoutForIncreasedItemCount(const QSizeF& size, SizeType sizeType);
375
376 /**
377 * Helper method for prepareLayoutForIncreasedItemCount().
378 */
379 void setLayouterSize(const QSizeF& size, SizeType sizeType);
380
381 /**
382 * Helper method for createWidget() and setWidgetIndex() to update the properties
383 * of the itemlist widget.
384 */
385 void updateWidgetProperties(KItemListWidget* widget, int index);
386
387 /**
388 * Helper method for createWidget() and setWidgetIndex() to create or update
389 * the itemlist group-header.
390 */
391 void updateGroupHeaderForWidget(KItemListWidget* widget);
392
393 /**
394 * Updates the position and size of the group-header that belongs
395 * to the itemlist widget \a widget. The given widget must represent
396 * the first item of a group.
397 */
398 void updateGroupHeaderLayout(KItemListWidget* widget);
399
400 /**
401 * Recycles the group-header from the widget.
402 */
403 void recycleGroupHeaderForWidget(KItemListWidget* widget);
404
405 /**
406 * Helper method for slotGroupedSortingChanged(), slotSortOrderChanged()
407 * and slotSortRoleChanged(): Iterates through all visible items and updates
408 * the group-header widgets.
409 */
410 void updateVisibleGroupHeaders();
411
412 /**
413 * @return The widths of each visible role that is shown in the KItemListHeader.
414 */
415 QHash<QByteArray, qreal> headerRolesWidths() const;
416
417 /**
418 * Updates m_visibleRolesSizes by calling KItemListView::visibleRolesSizes().
419 * Nothing will be done if m_itemRect is not empty or custom header-widths
420 * are used (see m_useHeaderWidths). Also m_strechedVisibleRolesSizes will be adjusted
421 * to respect the available view-size.
422 */
423 void updateVisibleRolesSizes(const KItemRangeList& itemRanges);
424
425 /**
426 * Convenience method for updateVisibleRoleSizes(KItemRangeList() << KItemRange(0, m_model->count()).
427 */
428 void updateVisibleRolesSizes();
429
430 /**
431 * Updates m_stretchedVisibleRolesSizes based on m_visibleRolesSizes and the available
432 * view-size. Nothing will be done if m_itemRect is not empty or custom header-widths
433 * are used (see m_useHeaderWidths).
434 */
435 void updateStretchedVisibleRolesSizes();
436
437 /**
438 * @return Sum of the widths of all visible roles.
439 */
440 qreal visibleRolesSizesWidthSum() const;
441
442 /**
443 * @return Sum of the heights of all visible roles.
444 */
445 qreal visibleRolesSizesHeightSum() const;
446
447 /**
448 * @return Boundaries of the header. An empty rectangle is returned
449 * if no header is shown.
450 */
451 QRectF headerBoundaries() const;
452
453 /**
454 * Helper function for triggerAutoScrolling().
455 * @param pos Logical position of the mouse relative to the range.
456 * @param range Range of the visible area.
457 * @param oldInc Previous increment. Is used to assure that the increment
458 * increases only gradually.
459 * @return Scroll increment that should be added to the offset().
460 * As soon as \a pos is inside the autoscroll-margin a
461 * value != 0 will be returned.
462 */
463 static int calculateAutoScrollingIncrement(int pos, int range, int oldInc);
464
465 private:
466 bool m_enabledSelectionToggles;
467 bool m_grouped;
468 int m_activeTransactions; // Counter for beginTransaction()/endTransaction()
469
470 QSizeF m_itemSize;
471 KItemListController* m_controller;
472 KItemModelBase* m_model;
473 QList<QByteArray> m_visibleRoles;
474 QHash<QByteArray, QSizeF> m_visibleRolesSizes;
475 QHash<QByteArray, QSizeF> m_stretchedVisibleRolesSizes;
476 KItemListWidgetCreatorBase* m_widgetCreator;
477 KItemListGroupHeaderCreatorBase* m_groupHeaderCreator;
478 KItemListStyleOption m_styleOption;
479
480 QHash<int, KItemListWidget*> m_visibleItems;
481 QHash<KItemListWidget*, KItemListGroupHeader*> m_visibleGroups;
482
483 int m_scrollBarExtent;
484 KItemListSizeHintResolver* m_sizeHintResolver;
485 KItemListViewLayouter* m_layouter;
486 KItemListViewAnimation* m_animation;
487
488 QTimer* m_layoutTimer; // Triggers an asynchronous doLayout() call.
489 qreal m_oldScrollOffset;
490 qreal m_oldMaximumScrollOffset;
491 qreal m_oldItemOffset;
492 qreal m_oldMaximumItemOffset;
493
494 bool m_skipAutoScrollForRubberBand;
495 KItemListRubberBand* m_rubberBand;
496
497 QPointF m_mousePos;
498 int m_autoScrollIncrement;
499 QTimer* m_autoScrollTimer;
500
501 KItemListHeader* m_header;
502 bool m_useHeaderWidths;
503
504 friend class KItemListController;
505 };
506
507 /**
508 * Allows to do a fast logical creation and deletion of QGraphicsWidgets
509 * by recycling existing QGraphicsWidgets instances. Is used by
510 * KItemListWidgetCreatorBase and KItemListGroupHeaderCreatorBase.
511 * @internal
512 */
513 class LIBDOLPHINPRIVATE_EXPORT KItemListCreatorBase
514 {
515 public:
516 virtual ~KItemListCreatorBase();
517
518 protected:
519 void addCreatedWidget(QGraphicsWidget* widget);
520 void pushRecycleableWidget(QGraphicsWidget* widget);
521 QGraphicsWidget* popRecycleableWidget();
522
523 private:
524 QSet<QGraphicsWidget*> m_createdWidgets;
525 QList<QGraphicsWidget*> m_recycleableWidgets;
526 };
527
528 /**
529 * @brief Base class for creating KItemListWidgets.
530 *
531 * It is recommended that applications simply use the KItemListWidgetCreator-template class.
532 * For a custom implementation the methods create() and recyle() must be reimplemented.
533 * The intention of the widget creator is to prevent repetitive and expensive instantiations and
534 * deletions of KItemListWidgets by recycling existing widget instances.
535 */
536 class LIBDOLPHINPRIVATE_EXPORT KItemListWidgetCreatorBase : public KItemListCreatorBase
537 {
538 public:
539 virtual ~KItemListWidgetCreatorBase();
540 virtual KItemListWidget* create(KItemListView* view) = 0;
541 virtual void recycle(KItemListWidget* widget);
542 };
543
544 template <class T>
545 class KItemListWidgetCreator : public KItemListWidgetCreatorBase
546 {
547 public:
548 virtual ~KItemListWidgetCreator();
549 virtual KItemListWidget* create(KItemListView* view);
550 };
551
552 template <class T>
553 KItemListWidgetCreator<T>::~KItemListWidgetCreator()
554 {
555 }
556
557 template <class T>
558 KItemListWidget* KItemListWidgetCreator<T>::create(KItemListView* view)
559 {
560 KItemListWidget* widget = static_cast<KItemListWidget*>(popRecycleableWidget());
561 if (!widget) {
562 widget = new T(view);
563 addCreatedWidget(widget);
564 }
565 return widget;
566 }
567
568 /**
569 * @brief Base class for creating KItemListGroupHeaders.
570 *
571 * It is recommended that applications simply use the KItemListGroupHeaderCreator-template class.
572 * For a custom implementation the methods create() and recyle() must be reimplemented.
573 * The intention of the group-header creator is to prevent repetitive and expensive instantiations and
574 * deletions of KItemListGroupHeaders by recycling existing header instances.
575 */
576 class LIBDOLPHINPRIVATE_EXPORT KItemListGroupHeaderCreatorBase : public KItemListCreatorBase
577 {
578 public:
579 virtual ~KItemListGroupHeaderCreatorBase();
580 virtual KItemListGroupHeader* create(KItemListView* view) = 0;
581 virtual void recycle(KItemListGroupHeader* header);
582 };
583
584 template <class T>
585 class KItemListGroupHeaderCreator : public KItemListGroupHeaderCreatorBase
586 {
587 public:
588 virtual ~KItemListGroupHeaderCreator();
589 virtual KItemListGroupHeader* create(KItemListView* view);
590 };
591
592 template <class T>
593 KItemListGroupHeaderCreator<T>::~KItemListGroupHeaderCreator()
594 {
595 }
596
597 template <class T>
598 KItemListGroupHeader* KItemListGroupHeaderCreator<T>::create(KItemListView* view)
599 {
600 KItemListGroupHeader* widget = static_cast<KItemListGroupHeader*>(popRecycleableWidget());
601 if (!widget) {
602 widget = new T(view);
603 addCreatedWidget(widget);
604 }
605 return widget;
606 }
607
608 #endif