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