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