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