]> cloud.milkyroute.net Git - dolphin.git/blob - src/dolphindetailsview.cpp
Revert http://websvn.kde.org/?view=rev&revision=876107 - it introduced a massive...
[dolphin.git] / src / dolphindetailsview.cpp
1 /***************************************************************************
2 * Copyright (C) 2006 by Peter Penz (peter.penz@gmx.at) *
3 * Copyright (C) 2008 by Simon St. James (kdedevel@etotheipiplusone.com) *
4 * *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
9 * *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
14 * *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
19 ***************************************************************************/
20
21 #include "dolphindetailsview.h"
22
23 #include "dolphinmodel.h"
24 #include "dolphincontroller.h"
25 #include "dolphinfileitemdelegate.h"
26 #include "dolphinsettings.h"
27 #include "dolphinsortfilterproxymodel.h"
28 #include "draganddrophelper.h"
29 #include "selectionmanager.h"
30 #include "viewproperties.h"
31 #include "zoomlevelinfo.h"
32
33 #include "dolphin_detailsmodesettings.h"
34 #include "dolphin_generalsettings.h"
35
36 #include <kdirmodel.h>
37 #include <klocale.h>
38 #include <kmenu.h>
39
40 #include <QAbstractProxyModel>
41 #include <QAction>
42 #include <QApplication>
43 #include <QHeaderView>
44 #include <QRubberBand>
45 #include <QPainter>
46 #include <QScrollBar>
47
48 DolphinDetailsView::DolphinDetailsView(QWidget* parent, DolphinController* controller) :
49 QTreeView(parent),
50 m_autoResize(true),
51 m_expandingTogglePressed(false),
52 m_keyPressed(false),
53 m_useDefaultIndexAt(true),
54 m_controller(controller),
55 m_selectionManager(0),
56 m_font(),
57 m_decorationSize(),
58 m_band()
59 {
60 const DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
61 Q_ASSERT(settings != 0);
62 Q_ASSERT(controller != 0);
63
64 setLayoutDirection(Qt::LeftToRight);
65 setAcceptDrops(true);
66 setSortingEnabled(true);
67 setUniformRowHeights(true);
68 setSelectionBehavior(SelectItems);
69 setDragDropMode(QAbstractItemView::DragDrop);
70 setDropIndicatorShown(false);
71 setAlternatingRowColors(true);
72 setRootIsDecorated(settings->expandableFolders());
73 setItemsExpandable(settings->expandableFolders());
74 setEditTriggers(QAbstractItemView::NoEditTriggers);
75
76 setMouseTracking(true);
77
78 const ViewProperties props(controller->url());
79 setSortIndicatorSection(props.sorting());
80 setSortIndicatorOrder(props.sortOrder());
81
82 QHeaderView* headerView = header();
83 connect(headerView, SIGNAL(sectionClicked(int)),
84 this, SLOT(synchronizeSortingState(int)));
85 headerView->setContextMenuPolicy(Qt::CustomContextMenu);
86 connect(headerView, SIGNAL(customContextMenuRequested(const QPoint&)),
87 this, SLOT(configureColumns(const QPoint&)));
88 connect(headerView, SIGNAL(sectionResized(int, int, int)),
89 this, SLOT(slotHeaderSectionResized(int, int, int)));
90 connect(headerView, SIGNAL(sectionHandleDoubleClicked(int)),
91 this, SLOT(disableAutoResizing()));
92
93 connect(parent, SIGNAL(sortingChanged(DolphinView::Sorting)),
94 this, SLOT(setSortIndicatorSection(DolphinView::Sorting)));
95 connect(parent, SIGNAL(sortOrderChanged(Qt::SortOrder)),
96 this, SLOT(setSortIndicatorOrder(Qt::SortOrder)));
97
98 // TODO: Connecting to the signal 'activated()' is not possible, as kstyle
99 // does not forward the single vs. doubleclick to it yet (KDE 4.1?). Hence it is
100 // necessary connecting the signal 'singleClick()' or 'doubleClick' and to handle the
101 // RETURN-key in keyPressEvent().
102 if (KGlobalSettings::singleClick()) {
103 connect(this, SIGNAL(clicked(const QModelIndex&)),
104 controller, SLOT(triggerItem(const QModelIndex&)));
105 } else {
106 connect(this, SIGNAL(doubleClicked(const QModelIndex&)),
107 controller, SLOT(triggerItem(const QModelIndex&)));
108 }
109
110 if (DolphinSettings::instance().generalSettings()->showSelectionToggle()) {
111 m_selectionManager = new SelectionManager(this);
112 connect(m_selectionManager, SIGNAL(selectionChanged()),
113 this, SLOT(requestActivation()));
114 connect(m_controller, SIGNAL(urlChanged(const KUrl&)),
115 m_selectionManager, SLOT(reset()));
116 }
117
118 connect(this, SIGNAL(entered(const QModelIndex&)),
119 this, SLOT(slotEntered(const QModelIndex&)));
120 connect(this, SIGNAL(viewportEntered()),
121 controller, SLOT(emitViewportEntered()));
122 connect(controller, SIGNAL(zoomLevelChanged(int)),
123 this, SLOT(setZoomLevel(int)));
124 connect(controller->dolphinView(), SIGNAL(additionalInfoChanged()),
125 this, SLOT(updateColumnVisibility()));
126 connect(controller, SIGNAL(activationChanged(bool)),
127 this, SLOT(slotActivationChanged(bool)));
128
129 if (settings->useSystemFont()) {
130 m_font = KGlobalSettings::generalFont();
131 } else {
132 m_font = QFont(settings->fontFamily(),
133 settings->fontSize(),
134 settings->fontWeight(),
135 settings->italicFont());
136 }
137
138 setVerticalScrollMode(QTreeView::ScrollPerPixel);
139 setHorizontalScrollMode(QTreeView::ScrollPerPixel);
140
141 const DolphinView* view = controller->dolphinView();
142 connect(view, SIGNAL(showPreviewChanged()),
143 this, SLOT(slotShowPreviewChanged()));
144
145 updateDecorationSize(view->showPreview());
146
147 setFocus();
148 viewport()->installEventFilter(this);
149
150 connect(KGlobalSettings::self(), SIGNAL(kdisplayFontChanged()),
151 this, SLOT(updateFont()));
152
153 m_useDefaultIndexAt = false;
154 }
155
156 DolphinDetailsView::~DolphinDetailsView()
157 {
158 }
159
160 bool DolphinDetailsView::event(QEvent* event)
161 {
162 if (event->type() == QEvent::Polish) {
163 QHeaderView* headerView = header();
164 headerView->setResizeMode(QHeaderView::Interactive);
165 headerView->setMovable(false);
166
167 updateColumnVisibility();
168
169 hideColumn(DolphinModel::Rating);
170 hideColumn(DolphinModel::Tags);
171 } else if (event->type() == QEvent::UpdateRequest) {
172 // a wheel movement will scroll 4 items
173 if (model()->rowCount() > 0) {
174 verticalScrollBar()->setSingleStep((sizeHintForRow(0) / 3) * 4);
175 }
176 }
177
178 return QTreeView::event(event);
179 }
180
181 QStyleOptionViewItem DolphinDetailsView::viewOptions() const
182 {
183 QStyleOptionViewItem viewOptions = QTreeView::viewOptions();
184 viewOptions.font = m_font;
185 viewOptions.showDecorationSelected = true;
186 viewOptions.decorationSize = m_decorationSize;
187 return viewOptions;
188 }
189
190 void DolphinDetailsView::contextMenuEvent(QContextMenuEvent* event)
191 {
192 QTreeView::contextMenuEvent(event);
193 m_controller->triggerContextMenuRequest(event->pos());
194 }
195
196 void DolphinDetailsView::mousePressEvent(QMouseEvent* event)
197 {
198 m_controller->requestActivation();
199
200 const QModelIndex current = currentIndex();
201 QTreeView::mousePressEvent(event);
202
203 m_expandingTogglePressed = false;
204 const QModelIndex index = indexAt(event->pos());
205 const bool updateState = index.isValid() &&
206 (index.column() == DolphinModel::Name) &&
207 (event->button() == Qt::LeftButton);
208 if (updateState) {
209 // TODO: See comment in DolphinIconsView::mousePressEvent(). Only update
210 // the state if no expanding/collapsing area has been hit:
211 const QRect rect = visualRect(index);
212 if (event->pos().x() >= rect.x() + indentation()) {
213 setState(QAbstractItemView::DraggingState);
214 } else {
215 m_expandingTogglePressed = true;
216 kDebug() << "m_expandingTogglePressed " << m_expandingTogglePressed;
217 }
218 }
219
220 if (!index.isValid() || (index.column() != DolphinModel::Name)) {
221 // the mouse press is done somewhere outside the filename column
222 if (QApplication::mouseButtons() & Qt::MidButton) {
223 m_controller->replaceUrlByClipboard();
224 }
225
226 const Qt::KeyboardModifiers modifier = QApplication::keyboardModifiers();
227 if (!(modifier & Qt::ShiftModifier) && !(modifier & Qt::ControlModifier)) {
228 clearSelection();
229 }
230
231 // restore the current index, other columns are handled as viewport area
232 selectionModel()->setCurrentIndex(current, QItemSelectionModel::Current);
233
234
235 if ((event->button() == Qt::LeftButton) && !m_expandingTogglePressed) {
236 // Inform Qt about what we are doing - otherwise it starts dragging items around!
237 setState(DragSelectingState);
238 m_band.show = true;
239 // Incremental update data will not be useful - start from scratch.
240 m_band.ignoreOldInfo = true;
241 const QPoint pos = contentsPos();
242 const QPoint scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
243 m_band.origin = event->pos() + pos + scrollPos;
244 m_band.destination = m_band.origin;
245 }
246 }
247 }
248
249 void DolphinDetailsView::mouseMoveEvent(QMouseEvent* event)
250 {
251 if (m_band.show) {
252 const QPoint mousePos = event->pos();
253 const QModelIndex index = indexAt(mousePos);
254 if (!index.isValid()) {
255 // the destination of the selection rectangle is above the viewport. In this
256 // case QTreeView does no selection at all, which is not the wanted behavior
257 // in Dolphin -> select all items within the elastic band rectangle
258 updateElasticBandSelection();
259 }
260
261 // TODO: enable QTreeView::mouseMoveEvent(event) again, as soon
262 // as the Qt-issue #199631 has been fixed.
263 // QTreeView::mouseMoveEvent(event);
264 QAbstractItemView::mouseMoveEvent(event);
265 updateElasticBand();
266 } else {
267 // TODO: enable QTreeView::mouseMoveEvent(event) again, as soon
268 // as the Qt-issue #199631 has been fixed.
269 // QTreeView::mouseMoveEvent(event);
270 QAbstractItemView::mouseMoveEvent(event);
271 }
272
273 if (m_expandingTogglePressed) {
274 // Per default QTreeView starts either a selection or a drag operation when dragging
275 // the expanding toggle button (Qt-issue - see TODO comment in DolphinIconsView::mousePressEvent()).
276 // Turn off this behavior in Dolphin to stay predictable:
277 clearSelection();
278 setState(QAbstractItemView::NoState);
279 }
280 }
281
282 void DolphinDetailsView::mouseReleaseEvent(QMouseEvent* event)
283 {
284 const QModelIndex index = indexAt(event->pos());
285 if (index.isValid() && (index.column() == DolphinModel::Name)) {
286 QTreeView::mouseReleaseEvent(event);
287 } else {
288 // don't change the current index if the cursor is released
289 // above any other column than the name column, as the other
290 // columns act as viewport
291 const QModelIndex current = currentIndex();
292 QTreeView::mouseReleaseEvent(event);
293 selectionModel()->setCurrentIndex(current, QItemSelectionModel::Current);
294 }
295
296 m_expandingTogglePressed = false;
297 if (m_band.show) {
298 setState(NoState);
299 updateElasticBand();
300 m_band.show = false;
301 }
302 }
303
304 void DolphinDetailsView::startDrag(Qt::DropActions supportedActions)
305 {
306 DragAndDropHelper::startDrag(this, supportedActions, m_controller);
307 m_band.show = false;
308 }
309
310 void DolphinDetailsView::dragEnterEvent(QDragEnterEvent* event)
311 {
312 if (DragAndDropHelper::isMimeDataSupported(event->mimeData())) {
313 event->acceptProposedAction();
314 }
315
316 if (m_band.show) {
317 updateElasticBand();
318 m_band.show = false;
319 }
320 }
321
322 void DolphinDetailsView::dragLeaveEvent(QDragLeaveEvent* event)
323 {
324 QTreeView::dragLeaveEvent(event);
325 setDirtyRegion(m_dropRect);
326 }
327
328 void DolphinDetailsView::dragMoveEvent(QDragMoveEvent* event)
329 {
330 QTreeView::dragMoveEvent(event);
331
332 // TODO: remove this code when the issue #160611 is solved in Qt 4.4
333 setDirtyRegion(m_dropRect);
334 const QModelIndex index = indexAt(event->pos());
335 if (index.isValid() && (index.column() == DolphinModel::Name)) {
336 const KFileItem item = m_controller->itemForIndex(index);
337 if (!item.isNull() && item.isDir()) {
338 m_dropRect = visualRect(index);
339 } else {
340 m_dropRect.setSize(QSize()); // set as invalid
341 }
342 setDirtyRegion(m_dropRect);
343 }
344
345 if (DragAndDropHelper::isMimeDataSupported(event->mimeData())) {
346 // accept url drops, independently from the destination item
347 event->acceptProposedAction();
348 }
349 }
350
351 void DolphinDetailsView::dropEvent(QDropEvent* event)
352 {
353 const QModelIndex index = indexAt(event->pos());
354 KFileItem item;
355 if (index.isValid() && (index.column() == DolphinModel::Name)) {
356 item = m_controller->itemForIndex(index);
357 }
358 m_controller->indicateDroppedUrls(item, m_controller->url(), event);
359 QTreeView::dropEvent(event);
360 }
361
362 void DolphinDetailsView::paintEvent(QPaintEvent* event)
363 {
364 QTreeView::paintEvent(event);
365 if (m_band.show) {
366 // The following code has been taken from QListView
367 // and adapted to DolphinDetailsView.
368 // (C) 1992-2007 Trolltech ASA
369 QStyleOptionRubberBand opt;
370 opt.initFrom(this);
371 opt.shape = QRubberBand::Rectangle;
372 opt.opaque = false;
373 opt.rect = elasticBandRect();
374
375 QPainter painter(viewport());
376 painter.save();
377 style()->drawControl(QStyle::CE_RubberBand, &opt, &painter);
378 painter.restore();
379 }
380 }
381
382 void DolphinDetailsView::keyPressEvent(QKeyEvent* event)
383 {
384 // If the Control modifier is pressed, a multiple selection
385 // is done and DolphinDetailsView::currentChanged() may not
386 // not change the selection in a custom way.
387 m_keyPressed = !(event->modifiers() & Qt::ControlModifier);
388
389 QTreeView::keyPressEvent(event);
390 m_controller->handleKeyPressEvent(event);
391 }
392
393 void DolphinDetailsView::keyReleaseEvent(QKeyEvent* event)
394 {
395 QTreeView::keyReleaseEvent(event);
396 m_keyPressed = false;
397 }
398
399 void DolphinDetailsView::resizeEvent(QResizeEvent* event)
400 {
401 if (m_autoResize) {
402 resizeColumns();
403 }
404 QTreeView::resizeEvent(event);
405 }
406
407 void DolphinDetailsView::wheelEvent(QWheelEvent* event)
408 {
409 if (m_selectionManager != 0) {
410 m_selectionManager->reset();
411 }
412
413 // let Ctrl+wheel events propagate to the DolphinView for icon zooming
414 if (event->modifiers() & Qt::ControlModifier) {
415 event->ignore();
416 return;
417 }
418
419 QTreeView::wheelEvent(event);
420 }
421
422 void DolphinDetailsView::currentChanged(const QModelIndex& current, const QModelIndex& previous)
423 {
424 QTreeView::currentChanged(current, previous);
425
426 // Stay consistent with QListView: When changing the current index by key presses,
427 // also change the selection.
428 if (m_keyPressed) {
429 selectionModel()->select(current, QItemSelectionModel::ClearAndSelect);
430 }
431 }
432
433 bool DolphinDetailsView::eventFilter(QObject* watched, QEvent* event)
434 {
435 if ((watched == viewport()) && (event->type() == QEvent::Leave)) {
436 // if the mouse is above an item and moved very fast outside the widget,
437 // no viewportEntered() signal might be emitted although the mouse has been moved
438 // above the viewport
439 m_controller->emitViewportEntered();
440 }
441
442 return QTreeView::eventFilter(watched, event);
443 }
444
445 QModelIndex DolphinDetailsView::indexAt(const QPoint& point) const
446 {
447 // the blank portion of the name column counts as empty space
448 const QModelIndex index = QTreeView::indexAt(point);
449 const bool isAboveEmptySpace = !m_useDefaultIndexAt &&
450 (index.column() == KDirModel::Name) && !nameColumnRect(index).contains(point);
451 return isAboveEmptySpace ? QModelIndex() : index;
452 }
453
454 void DolphinDetailsView::setSelection(const QRect &rect, QItemSelectionModel::SelectionFlags command)
455 {
456 // We must override setSelection() as Qt calls it internally and when this happens
457 // we must ensure that the default indexAt() is used.
458 if (!m_band.show) {
459 m_useDefaultIndexAt = true;
460 QTreeView::setSelection(rect, command);
461 m_useDefaultIndexAt = false;
462 } else {
463
464 // Use our own elastic band selection algorithm
465 updateElasticBandSelection();
466 }
467 }
468
469 void DolphinDetailsView::setSortIndicatorSection(DolphinView::Sorting sorting)
470 {
471 QHeaderView* headerView = header();
472 headerView->setSortIndicator(sorting, headerView->sortIndicatorOrder());
473 }
474
475 void DolphinDetailsView::setSortIndicatorOrder(Qt::SortOrder sortOrder)
476 {
477 QHeaderView* headerView = header();
478 headerView->setSortIndicator(headerView->sortIndicatorSection(), sortOrder);
479 }
480
481 void DolphinDetailsView::synchronizeSortingState(int column)
482 {
483 // The sorting has already been changed in QTreeView if this slot is
484 // invoked, but Dolphin is not informed about this.
485 DolphinView::Sorting sorting = DolphinSortFilterProxyModel::sortingForColumn(column);
486 const Qt::SortOrder sortOrder = header()->sortIndicatorOrder();
487 m_controller->indicateSortingChange(sorting);
488 m_controller->indicateSortOrderChange(sortOrder);
489 }
490
491 void DolphinDetailsView::slotEntered(const QModelIndex& index)
492 {
493 if (index.column() == DolphinModel::Name) {
494 m_controller->emitItemEntered(index);
495 } else {
496 m_controller->emitViewportEntered();
497 }
498 }
499
500 void DolphinDetailsView::updateElasticBand()
501 {
502 if (m_band.show) {
503 QRect dirtyRegion(elasticBandRect());
504 const QPoint scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
505 m_band.destination = viewport()->mapFromGlobal(QCursor::pos()) + scrollPos;
506 dirtyRegion = dirtyRegion.united(elasticBandRect());
507 setDirtyRegion(dirtyRegion);
508 }
509 }
510
511 QRect DolphinDetailsView::elasticBandRect() const
512 {
513 const QPoint pos(contentsPos());
514 const QPoint scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
515
516 const QPoint topLeft = m_band.origin - pos - scrollPos;
517 const QPoint bottomRight = m_band.destination - pos - scrollPos;
518 return QRect(topLeft, bottomRight).normalized();
519 }
520
521 void DolphinDetailsView::setZoomLevel(int level)
522 {
523 const int size = ZoomLevelInfo::iconSizeForZoomLevel(level);
524 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
525
526 const bool showPreview = m_controller->dolphinView()->showPreview();
527 if (showPreview) {
528 settings->setPreviewSize(size);
529 } else {
530 settings->setIconSize(size);
531 }
532
533 updateDecorationSize(showPreview);
534 }
535
536
537 void DolphinDetailsView::slotShowPreviewChanged()
538 {
539 const DolphinView* view = m_controller->dolphinView();
540 updateDecorationSize(view->showPreview());
541 }
542
543 void DolphinDetailsView::configureColumns(const QPoint& pos)
544 {
545 KMenu popup(this);
546 popup.addTitle(i18nc("@title:menu", "Columns"));
547
548 QHeaderView* headerView = header();
549 for (int i = DolphinModel::Size; i <= DolphinModel::Type; ++i) {
550 const int logicalIndex = headerView->logicalIndex(i);
551 const QString text = model()->headerData(i, Qt::Horizontal).toString();
552 QAction* action = popup.addAction(text);
553 action->setCheckable(true);
554 action->setChecked(!headerView->isSectionHidden(logicalIndex));
555 action->setData(i);
556 }
557
558 QAction* activatedAction = popup.exec(header()->mapToGlobal(pos));
559 if (activatedAction != 0) {
560 const bool show = activatedAction->isChecked();
561 const int columnIndex = activatedAction->data().toInt();
562
563 KFileItemDelegate::InformationList list = m_controller->dolphinView()->additionalInfo();
564 const KFileItemDelegate::Information info = infoForColumn(columnIndex);
565 if (show) {
566 Q_ASSERT(!list.contains(info));
567 list.append(info);
568 } else {
569 Q_ASSERT(list.contains(info));
570 const int index = list.indexOf(info);
571 list.removeAt(index);
572 }
573
574 m_controller->indicateAdditionalInfoChange(list);
575 setColumnHidden(columnIndex, !show);
576 }
577 }
578
579 void DolphinDetailsView::updateColumnVisibility()
580 {
581 const KFileItemDelegate::InformationList list = m_controller->dolphinView()->additionalInfo();
582 for (int i = DolphinModel::Size; i <= DolphinModel::Type; ++i) {
583 const KFileItemDelegate::Information info = infoForColumn(i);
584 const bool hide = !list.contains(info);
585 if (isColumnHidden(i) != hide) {
586 setColumnHidden(i, hide);
587 }
588 }
589
590 resizeColumns();
591 }
592
593 void DolphinDetailsView::slotHeaderSectionResized(int logicalIndex, int oldSize, int newSize)
594 {
595 Q_UNUSED(logicalIndex);
596 Q_UNUSED(oldSize);
597 Q_UNUSED(newSize);
598 if (QApplication::mouseButtons() & Qt::LeftButton) {
599 disableAutoResizing();
600 }
601 }
602
603 void DolphinDetailsView::slotActivationChanged(bool active)
604 {
605 setAlternatingRowColors(active);
606 }
607
608 void DolphinDetailsView::disableAutoResizing()
609 {
610 m_autoResize = false;
611 }
612
613 void DolphinDetailsView::requestActivation()
614 {
615 m_controller->requestActivation();
616 }
617
618 void DolphinDetailsView::updateFont()
619 {
620 const DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
621 Q_ASSERT(settings != 0);
622
623 if (settings->useSystemFont()) {
624 m_font = KGlobalSettings::generalFont();
625 }
626 }
627
628 void DolphinDetailsView::updateElasticBandSelection()
629 {
630 if (!m_band.show) {
631 return;
632 }
633
634 // Ensure the elastic band itself is up-to-date, in
635 // case we are being called due to e.g. a drag event.
636 updateElasticBand();
637
638 // Clip horizontally to the name column, as some filenames will be
639 // longer than the column. We don't clip vertically as origin
640 // may be above or below the current viewport area.
641 const int nameColumnX = header()->sectionPosition(DolphinModel::Name);
642 const int nameColumnWidth = header()->sectionSize(DolphinModel::Name);
643 QRect selRect = elasticBandRect().normalized();
644 QRect nameColumnRect(nameColumnX, selRect.y(), nameColumnWidth, selRect.height());
645 selRect = nameColumnRect.intersect(selRect).normalized();
646
647 if (selRect.isNull()) {
648 clearSelection();
649 m_band.ignoreOldInfo = true;
650 return;
651 }
652
653 if (!m_band.ignoreOldInfo) {
654 // Do some quick checks to see if we can rule out the need to
655 // update the selection.
656 Q_ASSERT(uniformRowHeights());
657 QModelIndex dummyIndex = model()->index(0, 0);
658 if (!dummyIndex.isValid()) {
659 // No items in the model presumably.
660 return;
661 }
662
663 // If the elastic band does not cover the same rows as before, we'll
664 // need to re-check, and also invalidate the old item distances.
665 const int rowHeight = QTreeView::rowHeight(dummyIndex);
666 const bool coveringSameRows =
667 (selRect.top() / rowHeight == m_band.oldSelectionRect.top() / rowHeight) &&
668 (selRect.bottom() / rowHeight == m_band.oldSelectionRect.bottom() / rowHeight);
669 if (coveringSameRows) {
670 // Covering the same rows, but have we moved far enough horizontally
671 // that we might have (de)selected some other items?
672 const QRect oldSelRect = m_band.oldSelectionRect;
673 const bool itemSelectionChanged =
674 ((selRect.left() > oldSelRect.left()) &&
675 (selRect.left() > m_band.insideNearestLeftEdge)) ||
676 ((selRect.left() < oldSelRect.left()) &&
677 (selRect.left() <= m_band.outsideNearestLeftEdge)) ||
678 ((selRect.right() < oldSelRect.right()) &&
679 (selRect.left() >= m_band.insideNearestRightEdge)) ||
680 ((selRect.right() > oldSelRect.right()) &&
681 (selRect.right() >= m_band.outsideNearestRightEdge));
682
683 if (!itemSelectionChanged) {
684 return;
685 }
686 }
687 }
688
689 // Do the selection from scratch. Force a update of the horizontal distances info.
690 m_band.insideNearestLeftEdge = nameColumnX + nameColumnWidth + 1;
691 m_band.insideNearestRightEdge = nameColumnX - 1;
692 m_band.outsideNearestLeftEdge = nameColumnX - 1;
693 m_band.outsideNearestRightEdge = nameColumnX + nameColumnWidth + 1;
694
695 // Include the old selection rect as well, so we can deselect
696 // items that were inside it but not in the new selRect.
697 const QRect boundingRect = selRect.united(m_band.oldSelectionRect).normalized();
698 if (boundingRect.isNull()) {
699 return;
700 }
701
702 // Get the index of the item in this row in the name column.
703 // TODO - would this still work if the columns could be re-ordered?
704 QModelIndex startIndex = QTreeView::indexAt(boundingRect.topLeft());
705 if (startIndex.parent().isValid()) {
706 startIndex = startIndex.parent().child(startIndex.row(), KDirModel::Name);
707 } else {
708 startIndex = model()->index(startIndex.row(), KDirModel::Name);
709 }
710
711 // Go through all indexes between the top and bottom of boundingRect, and
712 // update the selection.
713 const int verticalCutoff = boundingRect.bottom();
714 QModelIndex currIndex = startIndex;
715 QModelIndex lastIndex;
716 bool allItemsInBoundDone = false;
717
718 // Calling selectionModel()->select(...) for each item that needs to be
719 // toggled is slow as each call emits selectionChanged(...) so store them
720 // and do the selection toggle in one batch.
721 QItemSelection itemsToToggle;
722 // QItemSelection's deal with continuous ranges of indexes better than
723 // single indexes, so try to portion items that need to be toggled into ranges.
724 bool formingToggleIndexRange = false;
725 QModelIndex toggleIndexRangeBegin = QModelIndex();
726
727 do {
728 QRect currIndexRect = visualRect(currIndex);
729 const QString name = m_controller->itemForIndex(currIndex).name();
730 currIndexRect.setWidth(DolphinFileItemDelegate::nameColumnWidth(name, viewOptions()));
731
732 // Update some optimisation info as we go.
733 const int cr = currIndexRect.right();
734 const int cl = currIndexRect.left();
735 const int sl = selRect.left();
736 const int sr = selRect.right();
737 // "The right edge of the name is outside of the rect but nearer than m_outsideNearestLeft", etc
738 if ((cr < sl && cr > m_band.outsideNearestLeftEdge)) {
739 m_band.outsideNearestLeftEdge = cr;
740 }
741 if ((cl > sr && cl < m_band.outsideNearestRightEdge)) {
742 m_band.outsideNearestRightEdge = cl;
743 }
744 if ((cl >= sl && cl <= sr && cl > m_band.insideNearestRightEdge)) {
745 m_band.insideNearestRightEdge = cl;
746 }
747 if ((cr >= sl && cr <= sr && cr < m_band.insideNearestLeftEdge)) {
748 m_band.insideNearestLeftEdge = cr;
749 }
750
751 bool currentlySelected = selectionModel()->isSelected(currIndex);
752 bool intersectsSelectedRect = currIndexRect.intersects(selRect);
753 bool needToToggleItem = (currentlySelected && !intersectsSelectedRect) || (!currentlySelected && intersectsSelectedRect);
754 if (needToToggleItem && !formingToggleIndexRange) {
755 toggleIndexRangeBegin = currIndex;
756 formingToggleIndexRange = true;
757 }
758
759 // NOTE: indexBelow actually walks up and down expanded trees for us.
760 QModelIndex nextIndex = indexBelow(currIndex);
761 allItemsInBoundDone = !nextIndex.isValid() || currIndexRect.top() > verticalCutoff;
762
763 const bool commitToggleIndexRange = formingToggleIndexRange &&
764 (!needToToggleItem ||
765 allItemsInBoundDone ||
766 currIndex.parent() != toggleIndexRangeBegin.parent());
767 if (commitToggleIndexRange) {
768 itemsToToggle.select(toggleIndexRangeBegin, lastIndex );
769 formingToggleIndexRange = false;
770 }
771
772 // next item
773 lastIndex = currIndex;
774 currIndex = nextIndex;
775 } while (!allItemsInBoundDone);
776
777 selectionModel()->select(itemsToToggle, QItemSelectionModel::Toggle);
778
779 m_band.oldSelectionRect = selRect;
780 m_band.ignoreOldInfo = false;
781 }
782
783 void DolphinDetailsView::updateDecorationSize(bool showPreview)
784 {
785 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
786 const int iconSize = showPreview ? settings->previewSize() : settings->iconSize();
787 setIconSize(QSize(iconSize, iconSize));
788 m_decorationSize = QSize(iconSize, iconSize);
789
790 if (m_selectionManager != 0) {
791 m_selectionManager->reset();
792 }
793
794 doItemsLayout();
795 }
796
797 QPoint DolphinDetailsView::contentsPos() const
798 {
799 // implementation note: the horizonal position is ignored currently, as no
800 // horizontal scrolling is done anyway during a selection
801 const QScrollBar* scrollbar = verticalScrollBar();
802 Q_ASSERT(scrollbar != 0);
803
804 const int maxHeight = maximumViewportSize().height();
805 const int height = scrollbar->maximum() - scrollbar->minimum() + 1;
806 const int visibleHeight = model()->rowCount() + 1 - height;
807 if (visibleHeight <= 0) {
808 return QPoint(0, 0);
809 }
810
811 const int y = scrollbar->sliderPosition() * maxHeight / visibleHeight;
812 return QPoint(0, y);
813 }
814
815 KFileItemDelegate::Information DolphinDetailsView::infoForColumn(int columnIndex) const
816 {
817 KFileItemDelegate::Information info = KFileItemDelegate::NoInformation;
818
819 switch (columnIndex) {
820 case DolphinModel::Size: info = KFileItemDelegate::Size; break;
821 case DolphinModel::ModifiedTime: info = KFileItemDelegate::ModificationTime; break;
822 case DolphinModel::Permissions: info = KFileItemDelegate::Permissions; break;
823 case DolphinModel::Owner: info = KFileItemDelegate::Owner; break;
824 case DolphinModel::Group: info = KFileItemDelegate::OwnerAndGroup; break;
825 case DolphinModel::Type: info = KFileItemDelegate::FriendlyMimeType; break;
826 default: break;
827 }
828
829 return info;
830 }
831
832 void DolphinDetailsView::resizeColumns()
833 {
834 // Using the resize mode QHeaderView::ResizeToContents is too slow (it takes
835 // around 3 seconds for each (!) resize operation when having > 10000 items).
836 // This gets a problem especially when opening large directories, where several
837 // resize operations are received for showing the currently available items during
838 // loading (the application hangs around 20 seconds when loading > 10000 items).
839
840 QHeaderView* headerView = header();
841 QFontMetrics fontMetrics(viewport()->font());
842
843 int columnWidth[KDirModel::ColumnCount];
844 columnWidth[KDirModel::Size] = fontMetrics.width("00000 Items");
845 columnWidth[KDirModel::ModifiedTime] = fontMetrics.width("0000-00-00 00:00");
846 columnWidth[KDirModel::Permissions] = fontMetrics.width("xxxxxxxxxx");
847 columnWidth[KDirModel::Owner] = fontMetrics.width("xxxxxxxxxx");
848 columnWidth[KDirModel::Group] = fontMetrics.width("xxxxxxxxxx");
849 columnWidth[KDirModel::Type] = fontMetrics.width("XXXX Xxxxxxx");
850
851 int requiredWidth = 0;
852 for (int i = KDirModel::Size; i <= KDirModel::Type; ++i) {
853 if (!isColumnHidden(i)) {
854 columnWidth[i] += 20; // provide a default gap
855 requiredWidth += columnWidth[i];
856 headerView->resizeSection(i, columnWidth[i]);
857 }
858 }
859
860 // resize the name column in a way that the whole available width is used
861 columnWidth[KDirModel::Name] = viewport()->width() - requiredWidth;
862 if (columnWidth[KDirModel::Name] < 120) {
863 columnWidth[KDirModel::Name] = 120;
864 }
865 headerView->resizeSection(KDirModel::Name, columnWidth[KDirModel::Name]);
866 }
867
868 QRect DolphinDetailsView::nameColumnRect(const QModelIndex& index) const
869 {
870 QRect rect = visualRect(index);
871 const KFileItem item = m_controller->itemForIndex(index);
872 if (!item.isNull()) {
873 const int width = DolphinFileItemDelegate::nameColumnWidth(item.name(), viewOptions());
874 rect.setWidth(width);
875 }
876
877 return rect;
878 }
879
880 DolphinDetailsView::ElasticBand::ElasticBand() :
881 show(false),
882 origin(),
883 destination(),
884 oldSelectionRect(),
885 ignoreOldInfo(true),
886 outsideNearestLeftEdge(0),
887 outsideNearestRightEdge(0),
888 insideNearestLeftEdge(0),
889 insideNearestRightEdge(0)
890 {
891 }
892
893 #include "dolphindetailsview.moc"