]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kitemlistcontroller.cpp
Fix scrollbar spacing when no scrollbar is visible in dolphin.
[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 QSet<int> selectedItems = m_selectionManager->selectedItems();
368 if (selectedItems.count() >= 2) {
369 emit itemsActivated(selectedItems);
370 } else if (selectedItems.count() == 1) {
371 emit itemActivated(selectedItems.toList().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 QSet<int> 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.toList().first();
387 } else if (selectedItems.count() == 1) {
388 index = selectedItems.toList().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 break;
407
408 case Qt::Key_Space:
409 if (m_selectionBehavior == MultiSelection) {
410 if (controlPressed) {
411 // Toggle the selection state of the current item.
412 m_selectionManager->endAnchoredSelection();
413 m_selectionManager->setSelected(index, 1, KItemListSelectionManager::Toggle);
414 m_selectionManager->beginAnchoredSelection(index);
415 break;
416 } else {
417 // Select the current item if it is not selected yet.
418 const int current = m_selectionManager->currentItem();
419 if (!m_selectionManager->isSelected(current)) {
420 m_selectionManager->setSelected(current);
421 break;
422 }
423 }
424 }
425 // Fall through to the default case and add the Space to the current search string.
426
427 default:
428 m_keyboardManager->addKeys(event->text());
429 // Make sure unconsumed events get propagated up the chain. #302329
430 event->ignore();
431 return false;
432 }
433
434 if (m_selectionManager->currentItem() != index) {
435 switch (m_selectionBehavior) {
436 case NoSelection:
437 m_selectionManager->setCurrentItem(index);
438 break;
439
440 case SingleSelection:
441 m_selectionManager->setCurrentItem(index);
442 m_selectionManager->clearSelection();
443 m_selectionManager->setSelected(index, 1);
444 break;
445
446 case MultiSelection:
447 if (controlPressed) {
448 m_selectionManager->endAnchoredSelection();
449 }
450
451 m_selectionManager->setCurrentItem(index);
452
453 if (!shiftOrControlPressed) {
454 m_selectionManager->clearSelection();
455 m_selectionManager->setSelected(index, 1);
456 }
457
458 if (!shiftPressed) {
459 m_selectionManager->beginAnchoredSelection(index);
460 }
461 break;
462 }
463
464 m_view->scrollToItem(index);
465 }
466 return true;
467 }
468
469 void KItemListController::slotChangeCurrentItem(const QString& text, bool searchFromNextItem)
470 {
471 if (!m_model || m_model->count() == 0) {
472 return;
473 }
474 const int currentIndex = m_selectionManager->currentItem();
475 int index;
476 if (searchFromNextItem) {
477 index = m_model->indexForKeyboardSearch(text, (currentIndex + 1) % m_model->count());
478 } else {
479 index = m_model->indexForKeyboardSearch(text, currentIndex);
480 }
481 if (index >= 0) {
482 m_selectionManager->setCurrentItem(index);
483
484 if (m_selectionBehavior != NoSelection) {
485 m_selectionManager->clearSelection();
486 m_selectionManager->setSelected(index, 1);
487 m_selectionManager->beginAnchoredSelection(index);
488 }
489
490 m_view->scrollToItem(index);
491 }
492 }
493
494 void KItemListController::slotAutoActivationTimeout()
495 {
496 if (!m_model || !m_view) {
497 return;
498 }
499
500 const int index = m_autoActivationTimer->property("index").toInt();
501 if (index < 0 || index >= m_model->count()) {
502 return;
503 }
504
505 /* m_view->isUnderMouse() fixes a bug in the Folder-View-Panel and in the
506 * Places-Panel.
507 *
508 * Bug: When you drag a file onto a Folder-View-Item or a Places-Item and
509 * then move away before the auto-activation timeout triggers, than the
510 * item still becomes activated/expanded.
511 *
512 * See Bug 293200 and 305783
513 */
514 if (m_model->supportsDropping(index) && m_view->isUnderMouse()) {
515 if (m_view->supportsItemExpanding() && m_model->isExpandable(index)) {
516 const bool expanded = m_model->isExpanded(index);
517 m_model->setExpanded(index, !expanded);
518 } else if (m_autoActivationBehavior != ExpansionOnly) {
519 emit itemActivated(index);
520 }
521 }
522 }
523
524 bool KItemListController::inputMethodEvent(QInputMethodEvent* event)
525 {
526 Q_UNUSED(event);
527 return false;
528 }
529
530 bool KItemListController::mousePressEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
531 {
532 if (!m_view) {
533 return false;
534 }
535
536 m_pressedMousePos = transform.map(event->pos());
537 m_pressedIndex = m_view->itemAt(m_pressedMousePos);
538 emit mouseButtonPressed(m_pressedIndex, event->buttons());
539
540 if ((event->buttons() & (Qt::XButton1 | Qt::XButton2)) && m_pressedIndex < 0) {
541 // Do not select items when clicking the empty part of the view with
542 // the back/forward buttons, see https://bugs.kde.org/show_bug.cgi?id=327412.
543 // Note that clicking an item with these buttons selects it, see comment in
544 // DolphinView::slotMouseButtonPressed(int, Qt::MouseButtons).
545 return true;
546 }
547
548 if (m_view->isAboveExpansionToggle(m_pressedIndex, m_pressedMousePos)) {
549 m_selectionManager->endAnchoredSelection();
550 m_selectionManager->setCurrentItem(m_pressedIndex);
551 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
552 return true;
553 }
554
555 m_selectionTogglePressed = m_view->isAboveSelectionToggle(m_pressedIndex, m_pressedMousePos);
556 if (m_selectionTogglePressed) {
557 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Toggle);
558 // The previous anchored selection has been finished already in
559 // KItemListSelectionManager::setSelected(). We can safely change
560 // the current item and start a new anchored selection now.
561 m_selectionManager->setCurrentItem(m_pressedIndex);
562 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
563 return true;
564 }
565
566 const bool shiftPressed = event->modifiers() & Qt::ShiftModifier;
567 const bool controlPressed = event->modifiers() & Qt::ControlModifier;
568
569 // The previous selection is cleared if either
570 // 1. The selection mode is SingleSelection, or
571 // 2. the selection mode is MultiSelection, and *none* of the following conditions are met:
572 // a) Shift or Control are pressed.
573 // b) The clicked item is selected already. In that case, the user might want to:
574 // - start dragging multiple items, or
575 // - open the context menu and perform an action for all selected items.
576 const bool shiftOrControlPressed = shiftPressed || controlPressed;
577 const bool pressedItemAlreadySelected = m_pressedIndex >= 0 && m_selectionManager->isSelected(m_pressedIndex);
578 const bool clearSelection = m_selectionBehavior == SingleSelection ||
579 (!shiftOrControlPressed && !pressedItemAlreadySelected);
580 if (clearSelection) {
581 m_selectionManager->clearSelection();
582 } else if (pressedItemAlreadySelected && !shiftOrControlPressed && (event->buttons() & Qt::LeftButton)) {
583 // The user might want to start dragging multiple items, but if he clicks the item
584 // in order to trigger it instead, the other selected items must be deselected.
585 // However, we do not know yet what the user is going to do.
586 // -> remember that the user pressed an item which had been selected already and
587 // clear the selection in mouseReleaseEvent(), unless the items are dragged.
588 m_clearSelectionIfItemsAreNotDragged = true;
589 }
590
591 if (!shiftPressed) {
592 // Finish the anchored selection before the current index is changed
593 m_selectionManager->endAnchoredSelection();
594 }
595
596 if (m_pressedIndex >= 0) {
597 m_selectionManager->setCurrentItem(m_pressedIndex);
598
599 switch (m_selectionBehavior) {
600 case NoSelection:
601 break;
602
603 case SingleSelection:
604 m_selectionManager->setSelected(m_pressedIndex);
605 break;
606
607 case MultiSelection:
608 if (controlPressed && !shiftPressed) {
609 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Toggle);
610 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
611 } else if (!shiftPressed || !m_selectionManager->isAnchoredSelectionActive()) {
612 // Select the pressed item and start a new anchored selection
613 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Select);
614 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
615 }
616 break;
617
618 default:
619 Q_ASSERT(false);
620 break;
621 }
622
623 if (event->buttons() & Qt::RightButton) {
624 emit itemContextMenuRequested(m_pressedIndex, event->screenPos());
625 }
626
627 return true;
628 }
629
630 if (event->buttons() & Qt::RightButton) {
631 const QRectF headerBounds = m_view->headerBoundaries();
632 if (headerBounds.contains(event->pos())) {
633 emit headerContextMenuRequested(event->screenPos());
634 } else {
635 emit viewContextMenuRequested(event->screenPos());
636 }
637 return true;
638 }
639
640 if (m_selectionBehavior == MultiSelection) {
641 QPointF startPos = m_pressedMousePos;
642 if (m_view->scrollOrientation() == Qt::Vertical) {
643 startPos.ry() += m_view->scrollOffset();
644 if (m_view->itemSize().width() < 0) {
645 // Use a special rubberband for views that have only one column and
646 // expand the rubberband to use the whole width of the view.
647 startPos.setX(0);
648 }
649 } else {
650 startPos.rx() += m_view->scrollOffset();
651 }
652
653 m_oldSelection = m_selectionManager->selectedItems();
654 KItemListRubberBand* rubberBand = m_view->rubberBand();
655 rubberBand->setStartPosition(startPos);
656 rubberBand->setEndPosition(startPos);
657 rubberBand->setActive(true);
658 connect(rubberBand, SIGNAL(endPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandChanged()));
659 m_view->setAutoScroll(true);
660 }
661
662 return false;
663 }
664
665 bool KItemListController::mouseMoveEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
666 {
667 if (!m_view) {
668 return false;
669 }
670
671 if (m_pressedIndex >= 0) {
672 // Check whether a dragging should be started
673 if (event->buttons() & Qt::LeftButton) {
674 const QPointF pos = transform.map(event->pos());
675 if ((pos - m_pressedMousePos).manhattanLength() >= QApplication::startDragDistance()) {
676 if (!m_selectionManager->isSelected(m_pressedIndex)) {
677 // Always assure that the dragged item gets selected. Usually this is already
678 // done on the mouse-press event, but when using the selection-toggle on a
679 // selected item the dragged item is not selected yet.
680 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Toggle);
681 } else {
682 // A selected item has been clicked to drag all selected items
683 // -> the selection should not be cleared when the mouse button is released.
684 m_clearSelectionIfItemsAreNotDragged = false;
685 }
686
687 startDragging();
688 }
689 }
690 } else {
691 KItemListRubberBand* rubberBand = m_view->rubberBand();
692 if (rubberBand->isActive()) {
693 QPointF endPos = transform.map(event->pos());
694
695 // Update the current item.
696 const int newCurrent = m_view->itemAt(endPos);
697 if (newCurrent >= 0) {
698 // It's expected that the new current index is also the new anchor (bug 163451).
699 m_selectionManager->endAnchoredSelection();
700 m_selectionManager->setCurrentItem(newCurrent);
701 m_selectionManager->beginAnchoredSelection(newCurrent);
702 }
703
704 if (m_view->scrollOrientation() == Qt::Vertical) {
705 endPos.ry() += m_view->scrollOffset();
706 if (m_view->itemSize().width() < 0) {
707 // Use a special rubberband for views that have only one column and
708 // expand the rubberband to use the whole width of the view.
709 endPos.setX(m_view->size().width());
710 }
711 } else {
712 endPos.rx() += m_view->scrollOffset();
713 }
714 rubberBand->setEndPosition(endPos);
715 }
716 }
717
718 return false;
719 }
720
721 bool KItemListController::mouseReleaseEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
722 {
723 if (!m_view) {
724 return false;
725 }
726
727 emit mouseButtonReleased(m_pressedIndex, event->buttons());
728
729 const bool isAboveSelectionToggle = m_view->isAboveSelectionToggle(m_pressedIndex, m_pressedMousePos);
730 if (isAboveSelectionToggle) {
731 m_selectionTogglePressed = false;
732 return true;
733 }
734
735 if (!isAboveSelectionToggle && m_selectionTogglePressed) {
736 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Toggle);
737 m_selectionTogglePressed = false;
738 return true;
739 }
740
741 const bool shiftOrControlPressed = event->modifiers() & Qt::ShiftModifier ||
742 event->modifiers() & Qt::ControlModifier;
743
744 KItemListRubberBand* rubberBand = m_view->rubberBand();
745 if (rubberBand->isActive()) {
746 disconnect(rubberBand, SIGNAL(endPositionChanged(QPointF,QPointF)), this, SLOT(slotRubberBandChanged()));
747 rubberBand->setActive(false);
748 m_oldSelection.clear();
749 m_view->setAutoScroll(false);
750 }
751
752 const QPointF pos = transform.map(event->pos());
753 const int index = m_view->itemAt(pos);
754
755 if (index >= 0 && index == m_pressedIndex) {
756 // The release event is done above the same item as the press event
757
758 if (m_clearSelectionIfItemsAreNotDragged) {
759 // A selected item has been clicked, but no drag operation has been started
760 // -> clear the rest of the selection.
761 m_selectionManager->clearSelection();
762 m_selectionManager->setSelected(m_pressedIndex, 1, KItemListSelectionManager::Select);
763 m_selectionManager->beginAnchoredSelection(m_pressedIndex);
764 }
765
766 if (event->button() & Qt::LeftButton) {
767 bool emitItemActivated = true;
768 if (m_view->isAboveExpansionToggle(index, pos)) {
769 const bool expanded = m_model->isExpanded(index);
770 m_model->setExpanded(index, !expanded);
771
772 emit itemExpansionToggleClicked(index);
773 emitItemActivated = false;
774 } else if (shiftOrControlPressed) {
775 // The mouse click should only update the selection, not trigger the item
776 emitItemActivated = false;
777 } else if (!(KGlobalSettings::singleClick() || m_singleClickActivationEnforced)) {
778 emitItemActivated = false;
779 }
780 if (emitItemActivated) {
781 emit itemActivated(index);
782 }
783 } else if (event->button() & Qt::MidButton) {
784 emit itemMiddleClicked(index);
785 }
786 }
787
788 m_pressedMousePos = QPointF();
789 m_pressedIndex = -1;
790 m_clearSelectionIfItemsAreNotDragged = false;
791 return false;
792 }
793
794 bool KItemListController::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event, const QTransform& transform)
795 {
796 const QPointF pos = transform.map(event->pos());
797 const int index = m_view->itemAt(pos);
798
799 // Expand item if desired - See Bug 295573
800 if (m_mouseDoubleClickAction != ActivateItemOnly) {
801 if (m_view && m_model && m_view->supportsItemExpanding() && m_model->isExpandable(index)) {
802 const bool expanded = m_model->isExpanded(index);
803 m_model->setExpanded(index, !expanded);
804 }
805 }
806
807 bool emitItemActivated = !(KGlobalSettings::singleClick() || m_singleClickActivationEnforced) &&
808 (event->button() & Qt::LeftButton) &&
809 index >= 0 && index < m_model->count();
810 if (emitItemActivated) {
811 emit itemActivated(index);
812 }
813 return false;
814 }
815
816 bool KItemListController::dragEnterEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
817 {
818 Q_UNUSED(event);
819 Q_UNUSED(transform);
820 return false;
821 }
822
823 bool KItemListController::dragLeaveEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
824 {
825 Q_UNUSED(event);
826 Q_UNUSED(transform);
827
828 m_view->setAutoScroll(false);
829 m_view->hideDropIndicator();
830
831 KItemListWidget* widget = hoveredWidget();
832 if (widget) {
833 widget->setHovered(false);
834 emit itemUnhovered(widget->index());
835 }
836 return false;
837 }
838
839 bool KItemListController::dragMoveEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
840 {
841 if (!m_model || !m_view) {
842 return false;
843 }
844
845 event->acceptProposedAction();
846
847 KItemListWidget* oldHoveredWidget = hoveredWidget();
848
849 const QPointF pos = transform.map(event->pos());
850 KItemListWidget* newHoveredWidget = widgetForPos(pos);
851
852 if (oldHoveredWidget != newHoveredWidget) {
853 m_autoActivationTimer->stop();
854
855 if (oldHoveredWidget) {
856 oldHoveredWidget->setHovered(false);
857 emit itemUnhovered(oldHoveredWidget->index());
858 }
859 }
860
861 if (newHoveredWidget) {
862 bool droppingBetweenItems = false;
863 if (m_model->sortRole().isEmpty()) {
864 // The model supports inserting items between other items.
865 droppingBetweenItems = (m_view->showDropIndicator(pos) >= 0);
866 }
867
868 const int index = newHoveredWidget->index();
869 if (!droppingBetweenItems) {
870 if (m_model->supportsDropping(index)) {
871 // Something has been dragged on an item.
872 m_view->hideDropIndicator();
873 if (!newHoveredWidget->isHovered()) {
874 newHoveredWidget->setHovered(true);
875 emit itemHovered(index);
876 }
877
878 if (!m_autoActivationTimer->isActive() && m_autoActivationTimer->interval() >= 0) {
879 m_autoActivationTimer->setProperty("index", index);
880 m_autoActivationTimer->start();
881 }
882 }
883 } else {
884 m_autoActivationTimer->stop();
885 if (newHoveredWidget && newHoveredWidget->isHovered()) {
886 newHoveredWidget->setHovered(false);
887 emit itemUnhovered(index);
888 }
889 }
890 } else {
891 m_view->hideDropIndicator();
892 }
893
894 return false;
895 }
896
897 bool KItemListController::dropEvent(QGraphicsSceneDragDropEvent* event, const QTransform& transform)
898 {
899 if (!m_view) {
900 return false;
901 }
902
903 m_autoActivationTimer->stop();
904 m_view->setAutoScroll(false);
905
906 const QPointF pos = transform.map(event->pos());
907
908 int dropAboveIndex = -1;
909 if (m_model->sortRole().isEmpty()) {
910 // The model supports inserting of items between other items.
911 dropAboveIndex = m_view->showDropIndicator(pos);
912 }
913
914 if (dropAboveIndex >= 0) {
915 // Something has been dropped between two items.
916 m_view->hideDropIndicator();
917 emit aboveItemDropEvent(dropAboveIndex, event);
918 } else {
919 // Something has been dropped on an item or on an empty part of the view.
920 emit itemDropEvent(m_view->itemAt(pos), event);
921 }
922
923 QAccessible::updateAccessibility(view(), 0, QAccessible::DragDropEnd);
924
925 return true;
926 }
927
928 bool KItemListController::hoverEnterEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
929 {
930 Q_UNUSED(event);
931 Q_UNUSED(transform);
932 return false;
933 }
934
935 bool KItemListController::hoverMoveEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
936 {
937 Q_UNUSED(transform);
938 if (!m_model || !m_view) {
939 return false;
940 }
941
942 KItemListWidget* oldHoveredWidget = hoveredWidget();
943 const QPointF pos = transform.map(event->pos());
944 KItemListWidget* newHoveredWidget = widgetForPos(pos);
945
946 if (oldHoveredWidget != newHoveredWidget) {
947 if (oldHoveredWidget) {
948 oldHoveredWidget->setHovered(false);
949 emit itemUnhovered(oldHoveredWidget->index());
950 }
951
952 if (newHoveredWidget) {
953 newHoveredWidget->setHovered(true);
954 emit itemHovered(newHoveredWidget->index());
955 }
956 }
957
958 return false;
959 }
960
961 bool KItemListController::hoverLeaveEvent(QGraphicsSceneHoverEvent* event, const QTransform& transform)
962 {
963 Q_UNUSED(event);
964 Q_UNUSED(transform);
965
966 if (!m_model || !m_view) {
967 return false;
968 }
969
970 foreach (KItemListWidget* widget, m_view->visibleItemListWidgets()) {
971 if (widget->isHovered()) {
972 widget->setHovered(false);
973 emit itemUnhovered(widget->index());
974 }
975 }
976 return false;
977 }
978
979 bool KItemListController::wheelEvent(QGraphicsSceneWheelEvent* event, const QTransform& transform)
980 {
981 Q_UNUSED(event);
982 Q_UNUSED(transform);
983 return false;
984 }
985
986 bool KItemListController::resizeEvent(QGraphicsSceneResizeEvent* event, const QTransform& transform)
987 {
988 Q_UNUSED(event);
989 Q_UNUSED(transform);
990 return false;
991 }
992
993 bool KItemListController::processEvent(QEvent* event, const QTransform& transform)
994 {
995 if (!event) {
996 return false;
997 }
998
999 switch (event->type()) {
1000 case QEvent::KeyPress:
1001 return keyPressEvent(static_cast<QKeyEvent*>(event));
1002 case QEvent::InputMethod:
1003 return inputMethodEvent(static_cast<QInputMethodEvent*>(event));
1004 case QEvent::GraphicsSceneMousePress:
1005 return mousePressEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
1006 case QEvent::GraphicsSceneMouseMove:
1007 return mouseMoveEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
1008 case QEvent::GraphicsSceneMouseRelease:
1009 return mouseReleaseEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
1010 case QEvent::GraphicsSceneMouseDoubleClick:
1011 return mouseDoubleClickEvent(static_cast<QGraphicsSceneMouseEvent*>(event), QTransform());
1012 case QEvent::GraphicsSceneWheel:
1013 return wheelEvent(static_cast<QGraphicsSceneWheelEvent*>(event), QTransform());
1014 case QEvent::GraphicsSceneDragEnter:
1015 return dragEnterEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
1016 case QEvent::GraphicsSceneDragLeave:
1017 return dragLeaveEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
1018 case QEvent::GraphicsSceneDragMove:
1019 return dragMoveEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
1020 case QEvent::GraphicsSceneDrop:
1021 return dropEvent(static_cast<QGraphicsSceneDragDropEvent*>(event), QTransform());
1022 case QEvent::GraphicsSceneHoverEnter:
1023 return hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
1024 case QEvent::GraphicsSceneHoverMove:
1025 return hoverMoveEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
1026 case QEvent::GraphicsSceneHoverLeave:
1027 return hoverLeaveEvent(static_cast<QGraphicsSceneHoverEvent*>(event), QTransform());
1028 case QEvent::GraphicsSceneResize:
1029 return resizeEvent(static_cast<QGraphicsSceneResizeEvent*>(event), transform);
1030 default:
1031 break;
1032 }
1033
1034 return false;
1035 }
1036
1037 void KItemListController::slotViewScrollOffsetChanged(qreal current, qreal previous)
1038 {
1039 if (!m_view) {
1040 return;
1041 }
1042
1043 KItemListRubberBand* rubberBand = m_view->rubberBand();
1044 if (rubberBand->isActive()) {
1045 const qreal diff = current - previous;
1046 // TODO: Ideally just QCursor::pos() should be used as
1047 // new end-position but it seems there is no easy way
1048 // to have something like QWidget::mapFromGlobal() for QGraphicsWidget
1049 // (... or I just missed an easy way to do the mapping)
1050 QPointF endPos = rubberBand->endPosition();
1051 if (m_view->scrollOrientation() == Qt::Vertical) {
1052 endPos.ry() += diff;
1053 } else {
1054 endPos.rx() += diff;
1055 }
1056
1057 rubberBand->setEndPosition(endPos);
1058 }
1059 }
1060
1061 void KItemListController::slotRubberBandChanged()
1062 {
1063 if (!m_view || !m_model || m_model->count() <= 0) {
1064 return;
1065 }
1066
1067 const KItemListRubberBand* rubberBand = m_view->rubberBand();
1068 const QPointF startPos = rubberBand->startPosition();
1069 const QPointF endPos = rubberBand->endPosition();
1070 QRectF rubberBandRect = QRectF(startPos, endPos).normalized();
1071
1072 const bool scrollVertical = (m_view->scrollOrientation() == Qt::Vertical);
1073 if (scrollVertical) {
1074 rubberBandRect.translate(0, -m_view->scrollOffset());
1075 } else {
1076 rubberBandRect.translate(-m_view->scrollOffset(), 0);
1077 }
1078
1079 if (!m_oldSelection.isEmpty()) {
1080 // Clear the old selection that was available before the rubberband has
1081 // been activated in case if no Shift- or Control-key are pressed
1082 const bool shiftOrControlPressed = QApplication::keyboardModifiers() & Qt::ShiftModifier ||
1083 QApplication::keyboardModifiers() & Qt::ControlModifier;
1084 if (!shiftOrControlPressed) {
1085 m_oldSelection.clear();
1086 }
1087 }
1088
1089 QSet<int> selectedItems;
1090
1091 // Select all visible items that intersect with the rubberband
1092 foreach (const KItemListWidget* widget, m_view->visibleItemListWidgets()) {
1093 const int index = widget->index();
1094
1095 const QRectF widgetRect = m_view->itemRect(index);
1096 if (widgetRect.intersects(rubberBandRect)) {
1097 const QRectF iconRect = widget->iconRect().translated(widgetRect.topLeft());
1098 const QRectF textRect = widget->textRect().translated(widgetRect.topLeft());
1099 if (iconRect.intersects(rubberBandRect) || textRect.intersects(rubberBandRect)) {
1100 selectedItems.insert(index);
1101 }
1102 }
1103 }
1104
1105 // Select all invisible items that intersect with the rubberband. Instead of
1106 // iterating all items only the area which might be touched by the rubberband
1107 // will be checked.
1108 const bool increaseIndex = scrollVertical ?
1109 startPos.y() > endPos.y(): startPos.x() > endPos.x();
1110
1111 int index = increaseIndex ? m_view->lastVisibleIndex() + 1 : m_view->firstVisibleIndex() - 1;
1112 bool selectionFinished = false;
1113 do {
1114 const QRectF widgetRect = m_view->itemRect(index);
1115 if (widgetRect.intersects(rubberBandRect)) {
1116 selectedItems.insert(index);
1117 }
1118
1119 if (increaseIndex) {
1120 ++index;
1121 selectionFinished = (index >= m_model->count()) ||
1122 ( scrollVertical && widgetRect.top() > rubberBandRect.bottom()) ||
1123 (!scrollVertical && widgetRect.left() > rubberBandRect.right());
1124 } else {
1125 --index;
1126 selectionFinished = (index < 0) ||
1127 ( scrollVertical && widgetRect.bottom() < rubberBandRect.top()) ||
1128 (!scrollVertical && widgetRect.right() < rubberBandRect.left());
1129 }
1130 } while (!selectionFinished);
1131
1132 if (QApplication::keyboardModifiers() & Qt::ControlModifier) {
1133 // If Control is pressed, the selection state of all items in the rubberband is toggled.
1134 // Therefore, the new selection contains:
1135 // 1. All previously selected items which are not inside the rubberband, and
1136 // 2. all items inside the rubberband which have not been selected previously.
1137 m_selectionManager->setSelectedItems((m_oldSelection - selectedItems) + (selectedItems - m_oldSelection));
1138 }
1139 else {
1140 m_selectionManager->setSelectedItems(selectedItems + m_oldSelection);
1141 }
1142 }
1143
1144 void KItemListController::startDragging()
1145 {
1146 if (!m_view || !m_model) {
1147 return;
1148 }
1149
1150 const QSet<int> selectedItems = m_selectionManager->selectedItems();
1151 if (selectedItems.isEmpty()) {
1152 return;
1153 }
1154
1155 QMimeData* data = m_model->createMimeData(selectedItems);
1156 if (!data) {
1157 return;
1158 }
1159
1160 // The created drag object will be owned and deleted
1161 // by QApplication::activeWindow().
1162 QDrag* drag = new QDrag(QApplication::activeWindow());
1163 drag->setMimeData(data);
1164
1165 const QPixmap pixmap = m_view->createDragPixmap(selectedItems);
1166 drag->setPixmap(pixmap);
1167
1168 const QPoint hotSpot(pixmap.width() / 2, 0);
1169 drag->setHotSpot(hotSpot);
1170
1171 drag->exec(Qt::MoveAction | Qt::CopyAction | Qt::LinkAction, Qt::CopyAction);
1172 QAccessible::updateAccessibility(view(), 0, QAccessible::DragDropStart);
1173 }
1174
1175 KItemListWidget* KItemListController::hoveredWidget() const
1176 {
1177 Q_ASSERT(m_view);
1178
1179 foreach (KItemListWidget* widget, m_view->visibleItemListWidgets()) {
1180 if (widget->isHovered()) {
1181 return widget;
1182 }
1183 }
1184
1185 return 0;
1186 }
1187
1188 KItemListWidget* KItemListController::widgetForPos(const QPointF& pos) const
1189 {
1190 Q_ASSERT(m_view);
1191
1192 foreach (KItemListWidget* widget, m_view->visibleItemListWidgets()) {
1193 const QPointF mappedPos = widget->mapFromItem(m_view, pos);
1194
1195 const bool hovered = widget->contains(mappedPos) &&
1196 !widget->expansionToggleRect().contains(mappedPos);
1197 if (hovered) {
1198 return widget;
1199 }
1200 }
1201
1202 return 0;
1203 }
1204
1205 void KItemListController::updateKeyboardAnchor()
1206 {
1207 const bool validAnchor = m_keyboardAnchorIndex >= 0 &&
1208 m_keyboardAnchorIndex < m_model->count() &&
1209 keyboardAnchorPos(m_keyboardAnchorIndex) == m_keyboardAnchorPos;
1210 if (!validAnchor) {
1211 const int index = m_selectionManager->currentItem();
1212 m_keyboardAnchorIndex = index;
1213 m_keyboardAnchorPos = keyboardAnchorPos(index);
1214 }
1215 }
1216
1217 int KItemListController::nextRowIndex(int index) const
1218 {
1219 if (m_keyboardAnchorIndex < 0) {
1220 return index;
1221 }
1222
1223 const int maxIndex = m_model->count() - 1;
1224 if (index == maxIndex) {
1225 return index;
1226 }
1227
1228 // Calculate the index of the last column inside the row of the current index
1229 int lastColumnIndex = index;
1230 while (keyboardAnchorPos(lastColumnIndex + 1) > keyboardAnchorPos(lastColumnIndex)) {
1231 ++lastColumnIndex;
1232 if (lastColumnIndex >= maxIndex) {
1233 return index;
1234 }
1235 }
1236
1237 // Based on the last column index go to the next row and calculate the nearest index
1238 // that is below the current index
1239 int nextRowIndex = lastColumnIndex + 1;
1240 int searchIndex = nextRowIndex;
1241 qreal minDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(nextRowIndex));
1242 while (searchIndex < maxIndex && keyboardAnchorPos(searchIndex + 1) > keyboardAnchorPos(searchIndex)) {
1243 ++searchIndex;
1244 const qreal searchDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(searchIndex));
1245 if (searchDiff < minDiff) {
1246 minDiff = searchDiff;
1247 nextRowIndex = searchIndex;
1248 }
1249 }
1250
1251 return nextRowIndex;
1252 }
1253
1254 int KItemListController::previousRowIndex(int index) const
1255 {
1256 if (m_keyboardAnchorIndex < 0 || index == 0) {
1257 return index;
1258 }
1259
1260 // Calculate the index of the first column inside the row of the current index
1261 int firstColumnIndex = index;
1262 while (keyboardAnchorPos(firstColumnIndex - 1) < keyboardAnchorPos(firstColumnIndex)) {
1263 --firstColumnIndex;
1264 if (firstColumnIndex <= 0) {
1265 return index;
1266 }
1267 }
1268
1269 // Based on the first column index go to the previous row and calculate the nearest index
1270 // that is above the current index
1271 int previousRowIndex = firstColumnIndex - 1;
1272 int searchIndex = previousRowIndex;
1273 qreal minDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(previousRowIndex));
1274 while (searchIndex > 0 && keyboardAnchorPos(searchIndex - 1) < keyboardAnchorPos(searchIndex)) {
1275 --searchIndex;
1276 const qreal searchDiff = qAbs(m_keyboardAnchorPos - keyboardAnchorPos(searchIndex));
1277 if (searchDiff < minDiff) {
1278 minDiff = searchDiff;
1279 previousRowIndex = searchIndex;
1280 }
1281 }
1282
1283 return previousRowIndex;
1284 }
1285
1286 qreal KItemListController::keyboardAnchorPos(int index) const
1287 {
1288 const QRectF itemRect = m_view->itemRect(index);
1289 if (!itemRect.isEmpty()) {
1290 return (m_view->scrollOrientation() == Qt::Vertical) ? itemRect.x() : itemRect.y();
1291 }
1292
1293 return 0;
1294 }
1295
1296 void KItemListController::updateExtendedSelectionRegion()
1297 {
1298 if (m_view) {
1299 const bool extend = (m_selectionBehavior != MultiSelection);
1300 KItemListStyleOption option = m_view->styleOption();
1301 if (option.extendedSelectionRegion != extend) {
1302 option.extendedSelectionRegion = extend;
1303 m_view->setStyleOption(option);
1304 }
1305 }
1306 }
1307
1308 #include "kitemlistcontroller.moc"