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