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