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