]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kitemlistcontroller.cpp
Details mode: Fix wrong required column-width calculation
[dolphin.git] / src / kitemviews / kitemlistcontroller.cpp
1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
3 * Copyright (C) 2012 by Frank Reininghaus <frank78ac@googlemail.com> *
4 * *
5 * Based on the Itemviews NG project from Trolltech Labs: *
6 * http://qt.gitorious.org/qt-labs/itemviews-ng *
7 * *
8 * This program is free software; you can redistribute it and/or modify *
9 * it under the terms of the GNU General Public License as published by *
10 * the Free Software Foundation; either version 2 of the License, or *
11 * (at your option) any later version. *
12 * *
13 * This program is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU General Public License *
19 * along with this program; if not, write to the *
20 * Free Software Foundation, Inc., *
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
22 ***************************************************************************/
23
24 #include "kitemlistcontroller.h"
25
26 #include <KGlobalSettings>
27 #include <KDebug>
28
29 #include "kitemlistview.h"
30 #include "kitemlistselectionmanager.h"
31
32 #include "private/kitemlistrubberband.h"
33 #include "private/kitemlistkeyboardsearchmanager.h"
34
35 #include <QApplication>
36 #include <QDrag>
37 #include <QEvent>
38 #include <QGraphicsScene>
39 #include <QGraphicsSceneEvent>
40 #include <QGraphicsView>
41 #include <QMimeData>
42 #include <QTimer>
43
44 KItemListController::KItemListController(KItemModelBase* model, KItemListView* view, QObject* parent) :
45 QObject(parent),
46 m_singleClickActivation(KGlobalSettings::singleClick()),
47 m_selectionTogglePressed(false),
48 m_clearSelectionIfItemsAreNotDragged(false),
49 m_selectionBehavior(NoSelection),
50 m_model(0),
51 m_view(0),
52 m_selectionManager(new KItemListSelectionManager(this)),
53 m_keyboardManager(new KItemListKeyboardSearchManager(this)),
54 m_pressedIndex(-1),
55 m_pressedMousePos(),
56 m_autoActivationTimer(0),
57 m_oldSelection(),
58 m_keyboardAnchorIndex(-1),
59 m_keyboardAnchorPos(0)
60 {
61 connect(m_keyboardManager, SIGNAL(changeCurrentItem(QString,bool)),
62 this, SLOT(slotChangeCurrentItem(QString,bool)));
63
64 m_autoActivationTimer = new QTimer(this);
65 m_autoActivationTimer->setSingleShot(true);
66 m_autoActivationTimer->setInterval(-1);
67 connect(m_autoActivationTimer, SIGNAL(timeout()), this, SLOT(slotAutoActivationTimeout()));
68
69 setModel(model);
70 setView(view);
71 }
72
73 KItemListController::~KItemListController()
74 {
75 setView(0);
76 delete m_view;
77 m_view = 0;
78
79 setModel(0);
80 delete m_model;
81 m_model = 0;
82 }
83
84 void KItemListController::setModel(KItemModelBase* model)
85 {
86 if (m_model == model) {
87 return;
88 }
89
90 KItemModelBase* oldModel = m_model;
91 m_model = model;
92 if (m_model) {
93 m_model->setParent(this);
94 }
95
96 if (m_view) {
97 m_view->setModel(m_model);
98 }
99
100 m_selectionManager->setModel(m_model);
101
102 emit modelChanged(m_model, oldModel);
103 }
104
105 KItemModelBase* KItemListController::model() const
106 {
107 return m_model;
108 }
109
110 KItemListSelectionManager* KItemListController::selectionManager() const
111 {
112 return m_selectionManager;
113 }
114
115 void KItemListController::setView(KItemListView* view)
116 {
117 if (m_view == view) {
118 return;
119 }
120
121 KItemListView* oldView = m_view;
122 if (oldView) {
123 disconnect(oldView, SIGNAL(scrollOffsetChanged(qreal,qreal)), this, SLOT(slotViewScrollOffsetChanged(qreal,qreal)));
124 }
125
126 m_view = view;
127
128 if (m_view) {
129 m_view->setController(this);
130 m_view->setModel(m_model);
131 connect(m_view, SIGNAL(scrollOffsetChanged(qreal,qreal)), this, SLOT(slotViewScrollOffsetChanged(qreal,qreal)));
132 updateExtendedSelectionRegion();
133 }
134
135 emit viewChanged(m_view, oldView);
136 }
137
138 KItemListView* KItemListController::view() const
139 {
140 return m_view;
141 }
142
143 void KItemListController::setSelectionBehavior(SelectionBehavior behavior)
144 {
145 m_selectionBehavior = behavior;
146 updateExtendedSelectionRegion();
147 }
148
149 KItemListController::SelectionBehavior KItemListController::selectionBehavior() const
150 {
151 return m_selectionBehavior;
152 }
153
154 void KItemListController::setAutoActivationDelay(int delay)
155 {
156 m_autoActivationTimer->setInterval(delay);
157 }
158
159 int KItemListController::autoActivationDelay() const
160 {
161 return m_autoActivationTimer->interval();
162 }
163
164 void KItemListController::setSingleClickActivation(bool singleClick)
165 {
166 m_singleClickActivation = singleClick;
167 }
168
169 bool KItemListController::singleClickActivation() const
170 {
171 return m_singleClickActivation;
172 }
173
174 bool KItemListController::showEvent(QShowEvent* event)
175 {
176 Q_UNUSED(event);
177 return false;
178 }
179
180 bool KItemListController::hideEvent(QHideEvent* event)
181 {
182 Q_UNUSED(event);
183 return false;
184 }
185
186 bool KItemListController::keyPressEvent(QKeyEvent* event)
187 {
188 int index = m_selectionManager->currentItem();
189 int key = event->key();
190
191 // Handle the expanding/collapsing of items
192 if (m_view->supportsItemExpanding() && m_model->isExpandable(index)) {
193 if (key == Qt::Key_Right) {
194 if (m_model->setExpanded(index, true)) {
195 return true;
196 }
197 } else if (key == Qt::Key_Left) {
198 if (m_model->setExpanded(index, false)) {
199 return true;
200 }
201 }
202 }
203
204 const bool shiftPressed = event->modifiers() & Qt::ShiftModifier;
205 const bool controlPressed = event->modifiers() & Qt::ControlModifier;
206 const bool shiftOrControlPressed = shiftPressed || controlPressed;
207
208 const int itemCount = m_model->count();
209
210 // For horizontal scroll orientation, transform
211 // the arrow keys to simplify the event handling.
212 if (m_view->scrollOrientation() == Qt::Horizontal) {
213 switch (key) {
214 case Qt::Key_Up: key = Qt::Key_Left; break;
215 case Qt::Key_Down: key = Qt::Key_Right; break;
216 case Qt::Key_Left: key = Qt::Key_Up; break;
217 case Qt::Key_Right: key = Qt::Key_Down; break;
218 default: break;
219 }
220 }
221
222 const bool selectSingleItem = m_selectionBehavior != NoSelection &&
223 itemCount == 1 &&
224 (key == Qt::Key_Home || key == Qt::Key_End ||
225 key == Qt::Key_Up || key == Qt::Key_Down ||
226 key == Qt::Key_Left || key == Qt::Key_Right);
227 if (selectSingleItem) {
228 const int current = m_selectionManager->currentItem();
229 m_selectionManager->setSelected(current);
230 return true;
231 }
232
233 switch (key) {
234 case Qt::Key_Home:
235 index = 0;
236 m_keyboardAnchorIndex = index;
237 m_keyboardAnchorPos = keyboardAnchorPos(index);
238 break;
239
240 case Qt::Key_End:
241 index = itemCount - 1;
242 m_keyboardAnchorIndex = index;
243 m_keyboardAnchorPos = keyboardAnchorPos(index);
244 break;
245
246 case Qt::Key_Left:
247 if (index > 0) {
248 --index;
249 m_keyboardAnchorIndex = index;
250 m_keyboardAnchorPos = keyboardAnchorPos(index);
251 }
252 break;
253
254 case Qt::Key_Right:
255 if (index < itemCount - 1) {
256 ++index;
257 m_keyboardAnchorIndex = index;
258 m_keyboardAnchorPos = keyboardAnchorPos(index);
259 }
260 break;
261
262 case Qt::Key_Up:
263 updateKeyboardAnchor();
264 index = previousRowIndex(index);
265 break;
266
267 case Qt::Key_Down:
268 updateKeyboardAnchor();
269 index = nextRowIndex(index);
270 break;
271
272 case Qt::Key_PageUp:
273 if (m_view->scrollOrientation() == Qt::Horizontal) {
274 // The new current index should correspond to the first item in the current column.
275 int newIndex = qMax(index - 1, 0);
276 while (newIndex != index && m_view->itemRect(newIndex).topLeft().y() < m_view->itemRect(index).topLeft().y()) {
277 index = newIndex;
278 newIndex = qMax(index - 1, 0);
279 }
280 m_keyboardAnchorIndex = index;
281 m_keyboardAnchorPos = keyboardAnchorPos(index);
282 } else {
283 const qreal currentItemBottom = m_view->itemRect(index).bottomLeft().y();
284 const qreal height = m_view->geometry().height();
285
286 // The new current item should be the first item in the current
287 // column whose itemRect's top coordinate is larger than targetY.
288 const qreal targetY = currentItemBottom - height;
289
290 updateKeyboardAnchor();
291 int newIndex = previousRowIndex(index);
292 do {
293 index = newIndex;
294 updateKeyboardAnchor();
295 newIndex = previousRowIndex(index);
296 } while (m_view->itemRect(newIndex).topLeft().y() > targetY && newIndex != index);
297 }
298 break;
299
300 case Qt::Key_PageDown:
301 if (m_view->scrollOrientation() == Qt::Horizontal) {
302 // The new current index should correspond to the last item in the current column.
303 int newIndex = qMin(index + 1, m_model->count() - 1);
304 while (newIndex != index && m_view->itemRect(newIndex).topLeft().y() > m_view->itemRect(index).topLeft().y()) {
305 index = newIndex;
306 newIndex = qMin(index + 1, m_model->count() - 1);
307 }
308 m_keyboardAnchorIndex = index;
309 m_keyboardAnchorPos = keyboardAnchorPos(index);
310 } else {
311 const qreal currentItemTop = m_view->itemRect(index).topLeft().y();
312 const qreal height = m_view->geometry().height();
313
314 // The new current item should be the last item in the current
315 // column whose itemRect's bottom coordinate is smaller than targetY.
316 const qreal targetY = currentItemTop + height;
317
318 updateKeyboardAnchor();
319 int newIndex = nextRowIndex(index);
320 do {
321 index = newIndex;
322 updateKeyboardAnchor();
323 newIndex = nextRowIndex(index);
324 } while (m_view->itemRect(newIndex).bottomLeft().y() < targetY && newIndex != index);
325 }
326 break;
327
328 case Qt::Key_Enter:
329 case Qt::Key_Return: {
330 const QSet<int> selectedItems = m_selectionManager->selectedItems();
331 if (selectedItems.count() >= 2) {
332 emit itemsActivated(selectedItems);
333 } else if (selectedItems.count() == 1) {
334 emit itemActivated(selectedItems.toList().first());
335 } else {
336 emit itemActivated(index);
337 }
338 break;
339 }
340
341 case Qt::Key_Space:
342 if (m_selectionBehavior == MultiSelection) {
343 if (controlPressed) {
344 m_selectionManager->endAnchoredSelection();
345 m_selectionManager->setSelected(index, 1, KItemListSelectionManager::Toggle);
346 m_selectionManager->beginAnchoredSelection(index);
347 } else {
348 const int current = m_selectionManager->currentItem();
349 m_selectionManager->setSelected(current);
350 }
351 }
352 break;
353
354 case Qt::Key_Menu: {
355 // Emit the signal itemContextMenuRequested() in case if at least one
356 // item is selected. Otherwise the signal viewContextMenuRequested() will be emitted.
357 const QSet<int> selectedItems = m_selectionManager->selectedItems();
358 int index = -1;
359 if (selectedItems.count() >= 2) {
360 const int currentItemIndex = m_selectionManager->currentItem();
361 index = selectedItems.contains(currentItemIndex)
362 ? currentItemIndex : selectedItems.toList().first();
363 } else if (selectedItems.count() == 1) {
364 index = selectedItems.toList().first();
365 }
366
367 if (index >= 0) {
368 const QRectF contextRect = m_view->itemContextRect(index);
369 const QPointF pos(m_view->scene()->views().first()->mapToGlobal(contextRect.bottomRight().toPoint()));
370 emit itemContextMenuRequested(index, pos);
371 } else {
372 emit viewContextMenuRequested(QCursor::pos());
373 }
374 break;
375 }
376
377 default:
378 m_keyboardManager->addKeys(event->text());
379 return false;
380 }
381
382 if (m_selectionManager->currentItem() != index) {
383 switch (m_selectionBehavior) {
384 case NoSelection:
385 m_selectionManager->setCurrentItem(index);
386 break;
387
388 case SingleSelection:
389 m_selectionManager->setCurrentItem(index);
390 m_selectionManager->clearSelection();
391 m_selectionManager->setSelected(index, 1);
392 break;
393
394 case MultiSelection:
395 if (controlPressed) {
396 m_selectionManager->endAnchoredSelection();
397 }
398
399 m_selectionManager->setCurrentItem(index);
400
401 if (!shiftOrControlPressed) {
402 m_selectionManager->clearSelection();
403 m_selectionManager->setSelected(index, 1);
404 }
405
406 if (!shiftPressed) {
407 m_selectionManager->beginAnchoredSelection(index);
408 }
409 break;
410 }
411
412 m_view->scrollToItem(index);
413 }
414 return true;
415 }
416
417 void KItemListController::slotChangeCurrentItem(const QString& text, bool searchFromNextItem)
418 {
419 if (!m_model || m_model->count() == 0) {
420 return;
421 }
422 const int currentIndex = m_selectionManager->currentItem();
423 int index;
424 if (searchFromNextItem) {
425 index = m_model->indexForKeyboardSearch(text, (currentIndex + 1) % m_model->count());
426 } else {
427 index = m_model->indexForKeyboardSearch(text, currentIndex);
428 }
429 if (index >= 0) {
430 m_selectionManager->setCurrentItem(index);
431 m_selectionManager->clearSelection();
432 m_selectionManager->setSelected(index, 1);
433 m_selectionManager->beginAnchoredSelection(index);
434 m_view->scrollToItem(index);
435 }
436 }
437
438 void KItemListController::slotAutoActivationTimeout()
439 {
440 if (!m_model || !m_view) {
441 return;
442 }
443
444 const int index = m_autoActivationTimer->property("index").toInt();
445 if (index < 0 || index >= m_model->count()) {
446 return;
447 }
448
449 if (m_model->supportsDropping(index)) {
450 if (m_view->supportsItemExpanding() && m_model->isExpandable(index)) {
451 const bool expanded = m_model->isExpanded(index);
452 m_model->setExpanded(index, !expanded);
453 } else {
454 emit itemActivated(index);
455 }
456 }
457 }
458
459 bool KItemListController::inputMethodEvent(QInputMethodEvent* event)
460 {
461 Q_UNUSED(event);
462 return false;
463 }
464
465 bool KItemListController::mousePressEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
466 {
467 if (!m_view) {
468 return false;
469 }
470
471 m_pressedMousePos = transform.map(event->pos());
472 m_pressedIndex = m_view->itemAt(m_pressedMousePos);
473 emit mouseButtonPressed(m_pressedIndex, event->buttons());
474
475 if (m_view->isAboveExpansionToggle(m_pressedIndex, m_pressedMousePos)) {
476 m_selectionManager->endAnchoredSelection();
477 m_selectionManager->setCurrentItem(m_pressedIndex);
478 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
479 return true;
480 }
481
482 m_selectionTogglePressed = m_view->isAboveSelectionToggle(m_pressedIndex, m_pressedMousePos);
483 if (m_selectionTogglePressed) {
484 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Toggle);
485 // The previous anchored selection has been finished already in
486 // KItemListSelectionManager::setSelected(). We can safely change
487 // the current item and start a new anchored selection now.
488 m_selectionManager->setCurrentItem(m_pressedIndex);
489 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
490 return true;
491 }
492
493 const bool shiftPressed = event->modifiers() & Qt::ShiftModifier;
494 const bool controlPressed = event->modifiers() & Qt::ControlModifier;
495
496 // The previous selection is cleared if either
497 // 1. The selection mode is SingleSelection, or
498 // 2. the selection mode is MultiSelection, and *none* of the following conditions are met:
499 // a) Shift or Control are pressed.
500 // b) The clicked item is selected already. In that case, the user might want to:
501 // - start dragging multiple items, or
502 // - open the context menu and perform an action for all selected items.
503 const bool shiftOrControlPressed = shiftPressed || controlPressed;
504 const bool pressedItemAlreadySelected = m_pressedIndex >= 0 && m_selectionManager->isSelected(m_pressedIndex);
505 const bool clearSelection = m_selectionBehavior == SingleSelection ||
506 (!shiftOrControlPressed && !pressedItemAlreadySelected);
507 if (clearSelection) {
508 m_selectionManager->clearSelection();
509 } else if (pressedItemAlreadySelected && !shiftOrControlPressed && (event->buttons() & Qt::LeftButton)) {
510 // The user might want to start dragging multiple items, but if he clicks the item
511 // in order to trigger it instead, the other selected items must be deselected.
512 // However, we do not know yet what the user is going to do.
513 // -> remember that the user pressed an item which had been selected already and
514 // clear the selection in mouseReleaseEvent(), unless the items are dragged.
515 m_clearSelectionIfItemsAreNotDragged = true;
516 }
517
518 if (!shiftPressed) {
519 // Finish the anchored selection before the current index is changed
520 m_selectionManager->endAnchoredSelection();
521 }
522
523 if (m_pressedIndex >= 0) {
524 m_selectionManager->setCurrentItem(m_pressedIndex);
525
526 switch (m_selectionBehavior) {
527 case NoSelection:
528 break;
529
530 case SingleSelection:
531 m_selectionManager->setSelected(m_pressedIndex);
532 break;
533
534 case MultiSelection:
535 if (controlPressed) {
536 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Toggle);
537 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
538 } else if (!shiftPressed || !m_selectionManager->isAnchoredSelectionActive()) {
539 // Select the pressed item and start a new anchored selection
540 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Select);
541 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
542 }
543 break;
544
545 default:
546 Q_ASSERT(false);
547 break;
548 }
549
550 if (event->buttons() & Qt::RightButton) {
551 emit itemContextMenuRequested(m_pressedIndex, event->screenPos());
552 }
553
554 return true;
555 }
556
557 if (event->buttons() & Qt::RightButton) {
558 const QRectF headerBounds = m_view->headerBoundaries();
559 if (headerBounds.contains(event->pos())) {
560 emit headerContextMenuRequested(event->screenPos());
561 } else {
562 emit viewContextMenuRequested(event->screenPos());
563 }
564 return true;
565 }
566
567 if (m_selectionBehavior == MultiSelection) {
568 QPointF startPos = m_pressedMousePos;
569 if (m_view->scrollOrientation() == Qt::Vertical) {
570 startPos.ry() += m_view->scrollOffset();
571 if (m_view->itemSize().width() < 0) {
572 // Use a special rubberband for views that have only one column and
573 // expand the rubberband to use the whole width of the view.
574 startPos.setX(0);
575 }
576 } else {
577 startPos.rx() += m_view->scrollOffset();
578 }
579
580 m_oldSelection = m_selectionManager->selectedItems();
581 KItemListRubberBand* rubberBand = m_view->rubberBand();
582 rubberBand->setStartPosition(startPos);
583 rubberBand->setEndPosition(startPos);
584 rubberBand->setActive(true);
585 connect(rubberBand, SIGNAL(endPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandChanged()));
586 m_view->setAutoScroll(true);
587 }
588
589 return false;
590 }
591
592 bool KItemListController::mouseMoveEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
593 {
594 if (!m_view) {
595 return false;
596 }
597
598 if (m_pressedIndex >= 0) {
599 // Check whether a dragging should be started
600 if (event->buttons() & Qt::LeftButton) {
601 const QPointF pos = transform.map(event->pos());
602 if ((pos - m_pressedMousePos).manhattanLength() >= QApplication::startDragDistance()) {
603 if (!m_selectionManager->isSelected(m_pressedIndex)) {
604 // Always assure that the dragged item gets selected. Usually this is already
605 // done on the mouse-press event, but when using the selection-toggle on a
606 // selected item the dragged item is not selected yet.
607 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Toggle);
608 } else {
609 // A selected item has been clicked to drag all selected items
610 // -> the selection should not be cleared when the mouse button is released.
611 m_clearSelectionIfItemsAreNotDragged = false;
612 }
613
614 startDragging();
615 }
616 }
617 } else {
618 KItemListRubberBand* rubberBand = m_view->rubberBand();
619 if (rubberBand->isActive()) {
620 QPointF endPos = transform.map(event->pos());
621
622 // Update the current item.
623 const int newCurrent = m_view->itemAt(endPos);
624 if (newCurrent >= 0) {
625 // It's expected that the new current index is also the new anchor (bug 163451).
626 m_selectionManager->endAnchoredSelection();
627 m_selectionManager->setCurrentItem(newCurrent);
628 m_selectionManager->beginAnchoredSelection(newCurrent);
629 }
630
631 if (m_view->scrollOrientation() == Qt::Vertical) {
632 endPos.ry() += m_view->scrollOffset();
633 if (m_view->itemSize().width() < 0) {
634 // Use a special rubberband for views that have only one column and
635 // expand the rubberband to use the whole width of the view.
636 endPos.setX(m_view->size().width());
637 }
638 } else {
639 endPos.rx() += m_view->scrollOffset();
640 }
641 rubberBand->setEndPosition(endPos);
642 }
643 }
644
645 return false;
646 }
647
648 bool KItemListController::mouseReleaseEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
649 {
650 if (!m_view) {
651 return false;
652 }
653
654 emit mouseButtonReleased(m_pressedIndex, event->buttons());
655
656 const bool isAboveSelectionToggle = m_view->isAboveSelectionToggle(m_pressedIndex, m_pressedMousePos);
657 if (isAboveSelectionToggle) {
658 m_selectionTogglePressed = false;
659 return true;
660 }
661
662 if (!isAboveSelectionToggle && m_selectionTogglePressed) {
663 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Toggle);
664 m_selectionTogglePressed = false;
665 return true;
666 }
667
668 const bool shiftOrControlPressed = event->modifiers() & Qt::ShiftModifier ||
669 event->modifiers() & Qt::ControlModifier;
670
671 KItemListRubberBand* rubberBand = m_view->rubberBand();
672 if (rubberBand->isActive()) {
673 disconnect(rubberBand, SIGNAL(endPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandChanged()));
674 rubberBand->setActive(false);
675 m_oldSelection.clear();
676 m_view->setAutoScroll(false);
677 }
678
679 const QPointF pos = transform.map(event->pos());
680 const int index = m_view->itemAt(pos);
681
682 if (index >= 0 && index == m_pressedIndex) {
683 // The release event is done above the same item as the press event
684
685 if (m_clearSelectionIfItemsAreNotDragged) {
686 // A selected item has been clicked, but no drag operation has been started
687 // -> clear the rest of the selection.
688 m_selectionManager->clearSelection();
689 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Select);
690 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
691 }
692
693 if (event->button() & Qt::LeftButton) {
694 bool emitItemActivated = true;
695 if (m_view->isAboveExpansionToggle(index, pos)) {
696 const bool expanded = m_model->isExpanded(index);
697 m_model->setExpanded(index, !expanded);
698
699 emit itemExpansionToggleClicked(index);
700 emitItemActivated = false;
701 } else if (shiftOrControlPressed) {
702 // The mouse click should only update the selection, not trigger the item
703 emitItemActivated = false;
704 } else if (!m_singleClickActivation) {
705 emitItemActivated = false;
706 }
707 if (emitItemActivated) {
708 emit itemActivated(index);
709 }
710 } else if (event->button() & Qt::MidButton) {
711 emit itemMiddleClicked(index);
712 }
713 }
714
715 m_pressedMousePos = QPointF();
716 m_pressedIndex = -1;
717 m_clearSelectionIfItemsAreNotDragged = false;
718 return false;
719 }
720
721 bool KItemListController::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
722 {
723 const QPointF pos = transform.map(event->pos());
724 const int index = m_view->itemAt(pos);
725
726 bool emitItemActivated = !m_singleClickActivation &&
727 (event->button() & Qt::LeftButton) &&
728 index >= 0 && index < m_model->count();
729 if (emitItemActivated) {
730 emit itemActivated(index);
731 }
732 return false;
733 }
734
735 bool KItemListController::dragEnterEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
736 {
737 Q_UNUSED(event);
738 Q_UNUSED(transform);
739 return false;
740 }
741
742 bool KItemListController::dragLeaveEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
743 {
744 Q_UNUSED(event);
745 Q_UNUSED(transform);
746
747 m_view->setAutoScroll(false);
748
749 KItemListWidget* widget = hoveredWidget();
750 if (widget) {
751 widget->setHovered(false);
752 emit itemUnhovered(widget->index());
753 }
754 return false;
755 }
756
757 bool KItemListController::dragMoveEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
758 {
759 Q_UNUSED(transform);
760 if (!m_model || !m_view) {
761 return false;
762 }
763
764 event->acceptProposedAction();
765
766 KItemListWidget* oldHoveredWidget = hoveredWidget();
767
768 const QPointF pos = transform.map(event->pos());
769 KItemListWidget* newHoveredWidget = widgetForPos(pos);
770
771 if (oldHoveredWidget != newHoveredWidget) {
772 m_autoActivationTimer->stop();
773
774 if (oldHoveredWidget) {
775 oldHoveredWidget->setHovered(false);
776 emit itemUnhovered(oldHoveredWidget->index());
777 }
778
779 if (newHoveredWidget) {
780 const int index = newHoveredWidget->index();
781 if (m_model->supportsDropping(index)) {
782 newHoveredWidget->setHovered(true);
783 }
784 emit itemHovered(index);
785
786 if (m_autoActivationTimer->interval() >= 0) {
787 m_autoActivationTimer->setProperty("index", index);
788 m_autoActivationTimer->start();
789 }
790 }
791 }
792
793 return false;
794 }
795
796 bool KItemListController::dropEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
797 {
798 Q_UNUSED(transform)
799 if (!m_view) {
800 return false;
801 }
802
803 m_autoActivationTimer->stop();
804 m_view->setAutoScroll(false);
805
806 const QPointF pos = transform.map(event->pos());
807 const int index = m_view->itemAt(pos);
808 emit itemDropEvent(index, event);
809
810 return true;
811 }
812
813 bool KItemListController::hoverEnterEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
814 {
815 Q_UNUSED(event);
816 Q_UNUSED(transform);
817 return false;
818 }
819
820 bool KItemListController::hoverMoveEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
821 {
822 Q_UNUSED(transform);
823 if (!m_model || !m_view) {
824 return false;
825 }
826
827 KItemListWidget* oldHoveredWidget = hoveredWidget();
828 const QPointF pos = transform.map(event->pos());
829 KItemListWidget* newHoveredWidget = widgetForPos(pos);
830
831 if (oldHoveredWidget != newHoveredWidget) {
832 if (oldHoveredWidget) {
833 oldHoveredWidget->setHovered(false);
834 emit itemUnhovered(oldHoveredWidget->index());
835 }
836
837 if (newHoveredWidget) {
838 newHoveredWidget->setHovered(true);
839 emit itemHovered(newHoveredWidget->index());
840 }
841 }
842
843 return false;
844 }
845
846 bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
847 {
848 Q_UNUSED(event);
849 Q_UNUSED(transform);
850
851 if (!m_model || !m_view) {
852 return false;
853 }
854
855 foreach (KItemListWidget* widget, m_view->visibleItemListWidgets()) {
856 if (widget->isHovered()) {
857 widget->setHovered(false);
858 emit itemUnhovered(widget->index());
859 }
860 }
861 return false;
862 }
863
864 bool KItemListController::wheelEvent(QGraphicsSceneWheelEvent* event, const QTransform& transform)
865 {
866 Q_UNUSED(event);
867 Q_UNUSED(transform);
868 return false;
869 }
870
871 bool KItemListController::resizeEvent(QGraphicsSceneResizeEvent* event, const QTransform& transform)
872 {
873 Q_UNUSED(event);
874 Q_UNUSED(transform);
875 return false;
876 }
877
878 bool KItemListController::processEvent(QEvent* event, const QTransform& transform)
879 {
880 if (!event) {
881 return false;
882 }
883
884 switch (event->type()) {
885 case QEvent::KeyPress:
886 return keyPressEvent(static_cast<QKeyEvent*>(event));
887 case QEvent::InputMethod:
888 return inputMethodEvent(static_cast<QInputMethodEvent*>(event));
889 case QEvent::GraphicsSceneMousePress:
890 return mousePressEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
891 case QEvent::GraphicsSceneMouseMove:
892 return mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
893 case QEvent::GraphicsSceneMouseRelease:
894 return mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
895 case QEvent::GraphicsSceneMouseDoubleClick:
896 return mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
897 case QEvent::GraphicsSceneWheel:
898 return wheelEvent(static_cast<QGraphicsSceneWheelEvent*>(event), QTransform());
899 case QEvent::GraphicsSceneDragEnter:
900 return dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
901 case QEvent::GraphicsSceneDragLeave:
902 return dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
903 case QEvent::GraphicsSceneDragMove:
904 return dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
905 case QEvent::GraphicsSceneDrop:
906 return dropEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
907 case QEvent::GraphicsSceneHoverEnter:
908 return hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
909 case QEvent::GraphicsSceneHoverMove:
910 return hoverMoveEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
911 case QEvent::GraphicsSceneHoverLeave:
912 return hoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
913 case QEvent::GraphicsSceneResize:
914 return resizeEvent(static_cast<QGraphicsSceneResizeEvent*>(event), transform);
915 default:
916 break;
917 }
918
919 return false;
920 }
921
922 void KItemListController::slotViewScrollOffsetChanged(qreal current, qreal previous)
923 {
924 if (!m_view) {
925 return;
926 }
927
928 KItemListRubberBand* rubberBand = m_view->rubberBand();
929 if (rubberBand->isActive()) {
930 const qreal diff = current - previous;
931 // TODO: Ideally just QCursor::pos() should be used as
932 // new end-position but it seems there is no easy way
933 // to have something like QWidget::mapFromGlobal() for QGraphicsWidget
934 // (... or I just missed an easy way to do the mapping)
935 QPointF endPos = rubberBand->endPosition();
936 if (m_view->scrollOrientation() == Qt::Vertical) {
937 endPos.ry() += diff;
938 } else {
939 endPos.rx() += diff;
940 }
941
942 rubberBand->setEndPosition(endPos);
943 }
944 }
945
946 void KItemListController::slotRubberBandChanged()
947 {
948 if (!m_view || !m_model || m_model->count() <= 0) {
949 return;
950 }
951
952 const KItemListRubberBand* rubberBand = m_view->rubberBand();
953 const QPointF startPos = rubberBand->startPosition();
954 const QPointF endPos = rubberBand->endPosition();
955 QRectF rubberBandRect = QRectF(startPos, endPos).normalized();
956
957 const bool scrollVertical = (m_view->scrollOrientation() == Qt::Vertical);
958 if (scrollVertical) {
959 rubberBandRect.translate(0, -m_view->scrollOffset());
960 } else {
961 rubberBandRect.translate(-m_view->scrollOffset(), 0);
962 }
963
964 if (!m_oldSelection.isEmpty()) {
965 // Clear the old selection that was available before the rubberband has
966 // been activated in case if no Shift- or Control-key are pressed
967 const bool shiftOrControlPressed = QApplication::keyboardModifiers() & Qt::ShiftModifier ||
968 QApplication::keyboardModifiers() & Qt::ControlModifier;
969 if (!shiftOrControlPressed) {
970 m_oldSelection.clear();
971 }
972 }
973
974 QSet<int> selectedItems;
975
976 // Select all visible items that intersect with the rubberband
977 foreach (const KItemListWidget* widget, m_view->visibleItemListWidgets()) {
978 const int index = widget->index();
979
980 const QRectF widgetRect = m_view->itemRect(index);
981 if (widgetRect.intersects(rubberBandRect)) {
982 const QRectF iconRect = widget->iconRect().translated(widgetRect.topLeft());
983 const QRectF textRect = widget->textRect().translated(widgetRect.topLeft());
984 if (iconRect.intersects(rubberBandRect) || textRect.intersects(rubberBandRect)) {
985 selectedItems.insert(index);
986 }
987 }
988 }
989
990 // Select all invisible items that intersect with the rubberband. Instead of
991 // iterating all items only the area which might be touched by the rubberband
992 // will be checked.
993 const bool increaseIndex = scrollVertical ?
994 startPos.y() > endPos.y(): startPos.x() > endPos.x();
995
996 int index = increaseIndex ? m_view->lastVisibleIndex() + 1 : m_view->firstVisibleIndex() - 1;
997 bool selectionFinished = false;
998 do {
999 const QRectF widgetRect = m_view->itemRect(index);
1000 if (widgetRect.intersects(rubberBandRect)) {
1001 selectedItems.insert(index);
1002 }
1003
1004 if (increaseIndex) {
1005 ++index;
1006 selectionFinished = (index >= m_model->count()) ||
1007 ( scrollVertical && widgetRect.top() > rubberBandRect.bottom()) ||
1008 (!scrollVertical && widgetRect.left() > rubberBandRect.right());
1009 } else {
1010 --index;
1011 selectionFinished = (index < 0) ||
1012 ( scrollVertical && widgetRect.bottom() < rubberBandRect.top()) ||
1013 (!scrollVertical && widgetRect.right() < rubberBandRect.left());
1014 }
1015 } while (!selectionFinished);
1016
1017 if (QApplication::keyboardModifiers() & Qt::ControlModifier) {
1018 // If Control is pressed, the selection state of all items in the rubberband is toggled.
1019 // Therefore, the new selection contains:
1020 // 1. All previously selected items which are not inside the rubberband, and
1021 // 2. all items inside the rubberband which have not been selected previously.
1022 m_selectionManager->setSelectedItems((m_oldSelection - selectedItems) + (selectedItems - m_oldSelection));
1023 }
1024 else {
1025 m_selectionManager->setSelectedItems(selectedItems + m_oldSelection);
1026 }
1027 }
1028
1029 void KItemListController::startDragging()
1030 {
1031 if (!m_view || !m_model) {
1032 return;
1033 }
1034
1035 const QSet<int> selectedItems = m_selectionManager->selectedItems();
1036 if (selectedItems.isEmpty()) {
1037 return;
1038 }
1039
1040 QMimeData* data = m_model->createMimeData(selectedItems);
1041 if (!data) {
1042 return;
1043 }
1044
1045 // The created drag object will be owned and deleted
1046 // by QApplication::activeWindow().
1047 QDrag* drag = new QDrag(QApplication::activeWindow());
1048 drag->setMimeData(data);
1049
1050 const QPixmap pixmap = m_view->createDragPixmap(selectedItems);
1051 drag->setPixmap(pixmap);
1052
1053 drag->exec(Qt::MoveAction | Qt::CopyAction | Qt::LinkAction, Qt::CopyAction);
1054 }
1055
1056 KItemListWidget* KItemListController::hoveredWidget() const
1057 {
1058 Q_ASSERT(m_view);
1059
1060 foreach (KItemListWidget* widget, m_view->visibleItemListWidgets()) {
1061 if (widget->isHovered()) {
1062 return widget;
1063 }
1064 }
1065
1066 return 0;
1067 }
1068
1069 KItemListWidget* KItemListController::widgetForPos(const QPointF& pos) const
1070 {
1071 Q_ASSERT(m_view);
1072
1073 foreach (KItemListWidget* widget, m_view->visibleItemListWidgets()) {
1074 const QPointF mappedPos = widget->mapFromItem(m_view, pos);
1075
1076 const bool hovered = widget->contains(mappedPos) &&
1077 !widget->expansionToggleRect().contains(mappedPos);
1078 if (hovered) {
1079 return widget;
1080 }
1081 }
1082
1083 return 0;
1084 }
1085
1086 void KItemListController::updateKeyboardAnchor()
1087 {
1088 const bool validAnchor = m_keyboardAnchorIndex >= 0 &&
1089 m_keyboardAnchorIndex < m_model->count() &&
1090 keyboardAnchorPos(m_keyboardAnchorIndex) == m_keyboardAnchorPos;
1091 if (!validAnchor) {
1092 const int index = m_selectionManager->currentItem();
1093 m_keyboardAnchorIndex = index;
1094 m_keyboardAnchorPos = keyboardAnchorPos(index);
1095 }
1096 }
1097
1098 int KItemListController::nextRowIndex(int index) const
1099 {
1100 if (m_keyboardAnchorIndex < 0) {
1101 return index;
1102 }
1103
1104 const int maxIndex = m_model->count() - 1;
1105 if (index == maxIndex) {
1106 return index;
1107 }
1108
1109 // Calculate the index of the last column inside the row of the current index
1110 int lastColumnIndex = index;
1111 while (keyboardAnchorPos(lastColumnIndex + 1) > keyboardAnchorPos(lastColumnIndex)) {
1112 ++lastColumnIndex;
1113 if (lastColumnIndex >= maxIndex) {
1114 return index;
1115 }
1116 }
1117
1118 // Based on the last column index go to the next row and calculate the nearest index
1119 // that is below the current index
1120 int nextRowIndex = lastColumnIndex + 1;
1121 int searchIndex = nextRowIndex;
1122 qreal minDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(nextRowIndex));
1123 while (searchIndex < maxIndex && keyboardAnchorPos(searchIndex + 1) > keyboardAnchorPos(searchIndex)) {
1124 ++searchIndex;
1125 const qreal searchDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(searchIndex));
1126 if (searchDiff < minDiff) {
1127 minDiff = searchDiff;
1128 nextRowIndex = searchIndex;
1129 }
1130 }
1131
1132 return nextRowIndex;
1133 }
1134
1135 int KItemListController::previousRowIndex(int index) const
1136 {
1137 if (m_keyboardAnchorIndex < 0 || index == 0) {
1138 return index;
1139 }
1140
1141 // Calculate the index of the first column inside the row of the current index
1142 int firstColumnIndex = index;
1143 while (keyboardAnchorPos(firstColumnIndex - 1) < keyboardAnchorPos(firstColumnIndex)) {
1144 --firstColumnIndex;
1145 if (firstColumnIndex <= 0) {
1146 return index;
1147 }
1148 }
1149
1150 // Based on the first column index go to the previous row and calculate the nearest index
1151 // that is above the current index
1152 int previousRowIndex = firstColumnIndex - 1;
1153 int searchIndex = previousRowIndex;
1154 qreal minDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(previousRowIndex));
1155 while (searchIndex > 0 && keyboardAnchorPos(searchIndex - 1) < keyboardAnchorPos(searchIndex)) {
1156 --searchIndex;
1157 const qreal searchDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(searchIndex));
1158 if (searchDiff < minDiff) {
1159 minDiff = searchDiff;
1160 previousRowIndex = searchIndex;
1161 }
1162 }
1163
1164 return previousRowIndex;
1165 }
1166
1167 qreal KItemListController::keyboardAnchorPos(int index) const
1168 {
1169 const QRectF itemRect = m_view->itemRect(index);
1170 if (!itemRect.isEmpty()) {
1171 return (m_view->scrollOrientation() == Qt::Vertical) ? itemRect.x() : itemRect.y();
1172 }
1173
1174 return 0;
1175 }
1176
1177 void KItemListController::updateExtendedSelectionRegion()
1178 {
1179 if (m_view) {
1180 const bool extend = (m_selectionBehavior != MultiSelection);
1181 KItemListStyleOption option = m_view->styleOption();
1182 if (option.extendedSelectionRegion != extend) {
1183 option.extendedSelectionRegion = extend;
1184 m_view->setStyleOption(option);
1185 }
1186 }
1187 }
1188
1189 #include "kitemlistcontroller.moc"