]> cloud.milkyroute.net Git - dolphin.git/blob - src/dolphindetailsview.cpp
Fix wrong fontMetrics when using custom fonts
[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 height = m_decorationSize.height();
430 const int step = (height >= KIconLoader::SizeHuge) ? height / 10 : (KIconLoader::SizeHuge - height) / 2;
431 verticalScrollBar()->setSingleStep(step);
432 QTreeView::wheelEvent(event);
433 }
434
435 void DolphinDetailsView::currentChanged(const QModelIndex& current, const QModelIndex& previous)
436 {
437 QTreeView::currentChanged(current, previous);
438 m_extensionsFactory->handleCurrentIndexChange(current, previous);
439
440 // Stay consistent with QListView: When changing the current index by key presses,
441 // also change the selection.
442 if (m_keyPressed) {
443 setCurrentIndex(current);
444 }
445 }
446
447 bool DolphinDetailsView::eventFilter(QObject* watched, QEvent* event)
448 {
449 if ((watched == viewport()) && (event->type() == QEvent::Leave)) {
450 // if the mouse is above an item and moved very fast outside the widget,
451 // no viewportEntered() signal might be emitted although the mouse has been moved
452 // above the viewport
453 m_controller->emitViewportEntered();
454 }
455
456 return QTreeView::eventFilter(watched, event);
457 }
458
459 QModelIndex DolphinDetailsView::indexAt(const QPoint& point) const
460 {
461 // the blank portion of the name column counts as empty space
462 const QModelIndex index = QTreeView::indexAt(point);
463 const bool isAboveEmptySpace = !m_useDefaultIndexAt &&
464 (index.column() == KDirModel::Name) && !visualRect(index).contains(point);
465 return isAboveEmptySpace ? QModelIndex() : index;
466 }
467
468 QRect DolphinDetailsView::visualRect(const QModelIndex& index) const
469 {
470 QRect rect = QTreeView::visualRect(index);
471 const KFileItem item = m_controller->itemForIndex(index);
472 if (!item.isNull()) {
473 const int width = DolphinFileItemDelegate::nameColumnWidth(item.text(), viewOptions());
474 rect.setWidth(width);
475 }
476
477 return rect;
478 }
479
480 void DolphinDetailsView::setSelection(const QRect& rect, QItemSelectionModel::SelectionFlags command)
481 {
482 // We must override setSelection() as Qt calls it internally and when this happens
483 // we must ensure that the default indexAt() is used.
484 if (!m_band.show) {
485 m_useDefaultIndexAt = true;
486 QTreeView::setSelection(rect, command);
487 m_useDefaultIndexAt = false;
488 } else {
489 // Use our own elastic band selection algorithm
490 updateElasticBandSelection();
491 }
492 }
493
494 void DolphinDetailsView::scrollTo(const QModelIndex & index, ScrollHint hint)
495 {
496 if (!m_ignoreScrollTo) {
497 QTreeView::scrollTo(index, hint);
498 }
499 }
500
501 void DolphinDetailsView::setSortIndicatorSection(DolphinView::Sorting sorting)
502 {
503 header()->setSortIndicator(sorting, header()->sortIndicatorOrder());
504 }
505
506 void DolphinDetailsView::setSortIndicatorOrder(Qt::SortOrder sortOrder)
507 {
508 header()->setSortIndicator(header()->sortIndicatorSection(), sortOrder);
509 }
510
511 void DolphinDetailsView::synchronizeSortingState(int column)
512 {
513 // The sorting has already been changed in QTreeView if this slot is
514 // invoked, but Dolphin is not informed about this.
515 DolphinView::Sorting sorting = DolphinSortFilterProxyModel::sortingForColumn(column);
516 const Qt::SortOrder sortOrder = header()->sortIndicatorOrder();
517 m_controller->indicateSortingChange(sorting);
518 m_controller->indicateSortOrderChange(sortOrder);
519 }
520
521 void DolphinDetailsView::slotEntered(const QModelIndex& index)
522 {
523 if (index.column() == DolphinModel::Name) {
524 m_controller->emitItemEntered(index);
525 } else {
526 m_controller->emitViewportEntered();
527 }
528 }
529
530 void DolphinDetailsView::updateElasticBand()
531 {
532 if (m_band.show) {
533 QRect dirtyRegion(elasticBandRect());
534 const QPoint scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
535 m_band.destination = viewport()->mapFromGlobal(QCursor::pos()) + scrollPos;
536 // Going above the (logical) top-left of the view causes complications during selection;
537 // we may as well prevent it.
538 if (m_band.destination.y() < 0) {
539 m_band.destination.setY(0);
540 }
541 if (m_band.destination.x() < 0) {
542 m_band.destination.setX(0);
543 }
544 dirtyRegion = dirtyRegion.united(elasticBandRect());
545 setDirtyRegion(dirtyRegion);
546 }
547 }
548
549 QRect DolphinDetailsView::elasticBandRect() const
550 {
551 const QPoint scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
552
553 const QPoint topLeft = m_band.origin - scrollPos;
554 const QPoint bottomRight = m_band.destination - scrollPos;
555 return QRect(topLeft, bottomRight).normalized();
556 }
557
558 void DolphinDetailsView::setZoomLevel(int level)
559 {
560 const int size = ZoomLevelInfo::iconSizeForZoomLevel(level);
561 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
562
563 const bool showPreview = m_controller->dolphinView()->showPreview();
564 if (showPreview) {
565 settings->setPreviewSize(size);
566 } else {
567 settings->setIconSize(size);
568 }
569
570 updateDecorationSize(showPreview);
571 }
572
573 void DolphinDetailsView::slotShowPreviewChanged()
574 {
575 const DolphinView* view = m_controller->dolphinView();
576 updateDecorationSize(view->showPreview());
577 }
578
579 void DolphinDetailsView::configureSettings(const QPoint& pos)
580 {
581 KMenu popup(this);
582 popup.addTitle(i18nc("@title:menu", "Columns"));
583
584 // add checkbox items for each column
585 QHeaderView* headerView = header();
586 const int columns = model()->columnCount();
587 for (int i = 0; i < columns; ++i) {
588 const int logicalIndex = headerView->logicalIndex(i);
589 const QString text = model()->headerData(logicalIndex, Qt::Horizontal).toString();
590 QAction* action = popup.addAction(text);
591 action->setCheckable(true);
592 action->setChecked(!headerView->isSectionHidden(logicalIndex));
593 action->setData(logicalIndex);
594 action->setEnabled(logicalIndex != DolphinModel::Name);
595 }
596 popup.addSeparator();
597
598 QAction* activatedAction = popup.exec(header()->mapToGlobal(pos));
599 if (activatedAction != 0) {
600 const bool show = activatedAction->isChecked();
601 const int columnIndex = activatedAction->data().toInt();
602
603 KFileItemDelegate::InformationList list = m_controller->dolphinView()->additionalInfo();
604 const KFileItemDelegate::Information info = infoForColumn(columnIndex);
605 if (show) {
606 Q_ASSERT(!list.contains(info));
607 list.append(info);
608 } else {
609 Q_ASSERT(list.contains(info));
610 const int index = list.indexOf(info);
611 list.removeAt(index);
612 }
613
614 m_controller->indicateAdditionalInfoChange(list);
615 setColumnHidden(columnIndex, !show);
616 resizeColumns();
617 }
618 }
619
620 void DolphinDetailsView::updateColumnVisibility()
621 {
622 QHeaderView* headerView = header();
623 disconnect(headerView, SIGNAL(sectionMoved(int, int, int)),
624 this, SLOT(saveColumnPositions()));
625
626 const DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
627 const QList<int> columnPositions = settings->columnPositions();
628
629 const KFileItemDelegate::InformationList list = m_controller->dolphinView()->additionalInfo();
630 for (int i = DolphinModel::Name; i <= DolphinModel::Version; ++i) {
631 const KFileItemDelegate::Information info = infoForColumn(i);
632 const bool hide = !list.contains(info) && (i != DolphinModel::Name);
633 if (isColumnHidden(i) != hide) {
634 setColumnHidden(i, hide);
635 }
636
637 const int from = headerView->visualIndex(i);
638 headerView->moveSection(from, columnPositions[i]);
639 }
640
641 resizeColumns();
642
643 connect(headerView, SIGNAL(sectionMoved(int, int, int)),
644 this, SLOT(saveColumnPositions()));
645
646 }
647
648 void DolphinDetailsView::saveColumnPositions()
649 {
650 QList<int> columnPositions;
651 for (int i = DolphinModel::Name; i <= DolphinModel::Version; ++i) {
652 columnPositions.append(header()->visualIndex(i));
653 }
654
655 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
656 settings->setColumnPositions(columnPositions);
657 }
658
659 void DolphinDetailsView::slotHeaderSectionResized(int logicalIndex, int oldSize, int newSize)
660 {
661 Q_UNUSED(logicalIndex);
662 Q_UNUSED(oldSize);
663 Q_UNUSED(newSize);
664 // If the user changes the size of the headers, the autoresize feature should be
665 // turned off. As there is no dedicated interface to find out whether the header
666 // section has been resized by the user or by a resize event, another approach is used.
667 // Attention: Take care when changing the if-condition to verify that there is no
668 // regression in combination with bug 178630 (see fix in comment #8).
669 if ((QApplication::mouseButtons() & Qt::LeftButton) && header()->underMouse()) {
670 disableAutoResizing();
671 }
672 }
673
674 void DolphinDetailsView::slotActivationChanged(bool active)
675 {
676 setAlternatingRowColors(active);
677 }
678
679 void DolphinDetailsView::disableAutoResizing()
680 {
681 m_autoResize = false;
682 }
683
684 void DolphinDetailsView::requestActivation()
685 {
686 m_controller->requestActivation();
687 }
688
689 void DolphinDetailsView::slotGlobalSettingsChanged(int category)
690 {
691 Q_UNUSED(category);
692
693 const DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
694 Q_ASSERT(settings != 0);
695 if (settings->useSystemFont()) {
696 m_font = KGlobalSettings::generalFont();
697 }
698 //Disconnect then reconnect, since the settings have been changed, the connection requirements may have also.
699 disconnect(this, SIGNAL(clicked(QModelIndex)), m_controller, SLOT(triggerItem(QModelIndex)));
700 disconnect(this, SIGNAL(doubleClicked(QModelIndex)), m_controller, SLOT(triggerItem(QModelIndex)));
701 if (KGlobalSettings::singleClick()) {
702 connect(this, SIGNAL(clicked(QModelIndex)), m_controller, SLOT(triggerItem(QModelIndex)));
703 } else {
704 connect(this, SIGNAL(doubleClicked(QModelIndex)), m_controller, SLOT(triggerItem(QModelIndex)));
705 }
706 }
707
708 void DolphinDetailsView::updateElasticBandSelection()
709 {
710 if (!m_band.show) {
711 return;
712 }
713
714 // Ensure the elastic band itself is up-to-date, in
715 // case we are being called due to e.g. a drag event.
716 updateElasticBand();
717
718 // Clip horizontally to the name column, as some filenames will be
719 // longer than the column. We don't clip vertically as origin
720 // may be above or below the current viewport area.
721 const int nameColumnX = header()->sectionPosition(DolphinModel::Name);
722 const int nameColumnWidth = header()->sectionSize(DolphinModel::Name);
723 QRect selRect = elasticBandRect().normalized();
724 QRect nameColumnArea(nameColumnX, selRect.y(), nameColumnWidth, selRect.height());
725 selRect = nameColumnArea.intersect(selRect).normalized();
726 // Get the last elastic band rectangle, expressed in viewpoint coordinates.
727 const QPoint scrollPos(horizontalScrollBar()->value(), verticalScrollBar()->value());
728 QRect oldSelRect = QRect(m_band.lastSelectionOrigin - scrollPos, m_band.lastSelectionDestination - scrollPos).normalized();
729
730 if (selRect.isNull()) {
731 selectionModel()->select(m_band.originalSelection, QItemSelectionModel::ClearAndSelect);
732 m_band.ignoreOldInfo = true;
733 return;
734 }
735
736 if (!m_band.ignoreOldInfo) {
737 // Do some quick checks to see if we can rule out the need to
738 // update the selection.
739 Q_ASSERT(uniformRowHeights());
740 QModelIndex dummyIndex = model()->index(0, 0);
741 if (!dummyIndex.isValid()) {
742 // No items in the model presumably.
743 return;
744 }
745
746 // If the elastic band does not cover the same rows as before, we'll
747 // need to re-check, and also invalidate the old item distances.
748 const int rowHeight = QTreeView::rowHeight(dummyIndex);
749 const bool coveringSameRows =
750 (selRect.top() / rowHeight == oldSelRect.top() / rowHeight) &&
751 (selRect.bottom() / rowHeight == oldSelRect.bottom() / rowHeight);
752 if (coveringSameRows) {
753 // Covering the same rows, but have we moved far enough horizontally
754 // that we might have (de)selected some other items?
755 const bool itemSelectionChanged =
756 ((selRect.left() > oldSelRect.left()) &&
757 (selRect.left() > m_band.insideNearestLeftEdge)) ||
758 ((selRect.left() < oldSelRect.left()) &&
759 (selRect.left() <= m_band.outsideNearestLeftEdge)) ||
760 ((selRect.right() < oldSelRect.right()) &&
761 (selRect.left() >= m_band.insideNearestRightEdge)) ||
762 ((selRect.right() > oldSelRect.right()) &&
763 (selRect.right() >= m_band.outsideNearestRightEdge));
764
765 if (!itemSelectionChanged) {
766 return;
767 }
768 }
769 }
770 else {
771 // This is the only piece of optimization data that needs to be explicitly
772 // discarded.
773 m_band.lastSelectionOrigin = QPoint();
774 m_band.lastSelectionDestination = QPoint();
775 oldSelRect = selRect;
776 }
777
778 // Do the selection from scratch. Force a update of the horizontal distances info.
779 m_band.insideNearestLeftEdge = nameColumnX + nameColumnWidth + 1;
780 m_band.insideNearestRightEdge = nameColumnX - 1;
781 m_band.outsideNearestLeftEdge = nameColumnX - 1;
782 m_band.outsideNearestRightEdge = nameColumnX + nameColumnWidth + 1;
783
784 // Include the old selection rect as well, so we can deselect
785 // items that were inside it but not in the new selRect.
786 const QRect boundingRect = selRect.united(oldSelRect).normalized();
787 if (boundingRect.isNull()) {
788 return;
789 }
790
791 // Get the index of the item in this row in the name column.
792 // TODO - would this still work if the columns could be re-ordered?
793 QModelIndex startIndex = QTreeView::indexAt(boundingRect.topLeft());
794 if (startIndex.parent().isValid()) {
795 startIndex = startIndex.parent().child(startIndex.row(), KDirModel::Name);
796 } else {
797 startIndex = model()->index(startIndex.row(), KDirModel::Name);
798 }
799 if (!startIndex.isValid()) {
800 selectionModel()->select(m_band.originalSelection, QItemSelectionModel::ClearAndSelect);
801 m_band.ignoreOldInfo = true;
802 return;
803 }
804
805 // Go through all indexes between the top and bottom of boundingRect, and
806 // update the selection.
807 const int verticalCutoff = boundingRect.bottom();
808 QModelIndex currIndex = startIndex;
809 QModelIndex lastIndex;
810 bool allItemsInBoundDone = false;
811
812 // Calling selectionModel()->select(...) for each item that needs to be
813 // toggled is slow as each call emits selectionChanged(...) so store them
814 // and do the selection toggle in one batch.
815 QItemSelection itemsToToggle;
816 // QItemSelection's deal with continuous ranges of indexes better than
817 // single indexes, so try to portion items that need to be toggled into ranges.
818 bool formingToggleIndexRange = false;
819 QModelIndex toggleIndexRangeBegin = QModelIndex();
820
821 do {
822 QRect currIndexRect = visualRect(currIndex);
823
824 // Update some optimization info as we go.
825 const int cr = currIndexRect.right();
826 const int cl = currIndexRect.left();
827 const int sl = selRect.left();
828 const int sr = selRect.right();
829 // "The right edge of the name is outside of the rect but nearer than m_outsideNearestLeft", etc
830 if ((cr < sl && cr > m_band.outsideNearestLeftEdge)) {
831 m_band.outsideNearestLeftEdge = cr;
832 }
833 if ((cl > sr && cl < m_band.outsideNearestRightEdge)) {
834 m_band.outsideNearestRightEdge = cl;
835 }
836 if ((cl >= sl && cl <= sr && cl > m_band.insideNearestRightEdge)) {
837 m_band.insideNearestRightEdge = cl;
838 }
839 if ((cr >= sl && cr <= sr && cr < m_band.insideNearestLeftEdge)) {
840 m_band.insideNearestLeftEdge = cr;
841 }
842
843 bool currentlySelected = selectionModel()->isSelected(currIndex);
844 bool originallySelected = m_band.originalSelection.contains(currIndex);
845 bool intersectsSelectedRect = currIndexRect.intersects(selRect);
846 bool shouldBeSelected = (intersectsSelectedRect && !originallySelected) || (!intersectsSelectedRect && originallySelected);
847 bool needToToggleItem = (currentlySelected && !shouldBeSelected) || (!currentlySelected && shouldBeSelected);
848 if (needToToggleItem && !formingToggleIndexRange) {
849 toggleIndexRangeBegin = currIndex;
850 formingToggleIndexRange = true;
851 }
852
853 // NOTE: indexBelow actually walks up and down expanded trees for us.
854 QModelIndex nextIndex = indexBelow(currIndex);
855 allItemsInBoundDone = !nextIndex.isValid() || currIndexRect.top() > verticalCutoff;
856
857 const bool commitToggleIndexRange = formingToggleIndexRange &&
858 (!needToToggleItem ||
859 allItemsInBoundDone ||
860 currIndex.parent() != toggleIndexRangeBegin.parent());
861 if (commitToggleIndexRange) {
862 formingToggleIndexRange = false;
863 // If this is the last item in the bounds and it is also the beginning of a range,
864 // don't toggle lastIndex - it will already have been dealt with.
865 if (!allItemsInBoundDone || toggleIndexRangeBegin != currIndex) {
866 itemsToToggle.select(toggleIndexRangeBegin, lastIndex);
867 }
868 // Need to start a new range immediately with currIndex?
869 if (needToToggleItem) {
870 toggleIndexRangeBegin = currIndex;
871 formingToggleIndexRange = true;
872 }
873 if (allItemsInBoundDone && needToToggleItem) {
874 // Toggle the very last item in the bounds.
875 itemsToToggle.select(currIndex, currIndex);
876 }
877 }
878
879 // next item
880 lastIndex = currIndex;
881 currIndex = nextIndex;
882 } while (!allItemsInBoundDone);
883
884 selectionModel()->select(itemsToToggle, QItemSelectionModel::Toggle);
885
886 m_band.lastSelectionOrigin = m_band.origin;
887 m_band.lastSelectionDestination = m_band.destination;
888 m_band.ignoreOldInfo = false;
889 }
890
891 void DolphinDetailsView::setFoldersExpandable(bool expandable)
892 {
893 if (!expandable) {
894 // collapse all expanded folders, as QTreeView::setItemsExpandable(false)
895 // does not do this task
896 const int rowCount = model()->rowCount();
897 for (int row = 0; row < rowCount; ++row) {
898 setExpanded(model()->index(row, 0), false);
899 }
900 }
901 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
902 settings->setExpandableFolders(expandable);
903 setRootIsDecorated(expandable);
904 setItemsExpandable(expandable);
905 }
906
907 void DolphinDetailsView::slotExpanded(const QModelIndex& index)
908 {
909 KFileItem item = m_controller->itemForIndex(index);
910 if (!item.isNull()) {
911 m_expandedUrls.insert(item.url());
912 }
913 }
914
915 void DolphinDetailsView::slotCollapsed(const QModelIndex& index)
916 {
917 KFileItem item = m_controller->itemForIndex(index);
918 if (!item.isNull()) {
919 m_expandedUrls.remove(item.url());
920 }
921 }
922
923 void DolphinDetailsView::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
924 {
925 removeExpandedIndexes(parent, start, end);
926 QTreeView::rowsAboutToBeRemoved(parent, start, end);
927 }
928
929 void DolphinDetailsView::removeExpandedIndexes(const QModelIndex& parent, int start, int end)
930 {
931 if (m_expandedUrls.isEmpty()) {
932 return;
933 }
934
935 for (int row = start; row <= end; row++) {
936 const QModelIndex index = model()->index(row, 0, parent);
937 if (isExpanded(index)) {
938 slotCollapsed(index);
939 removeExpandedIndexes(index, 0, model()->rowCount(index) - 1);
940 }
941 }
942 }
943
944 void DolphinDetailsView::updateDecorationSize(bool showPreview)
945 {
946 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
947 const int iconSize = showPreview ? settings->previewSize() : settings->iconSize();
948 setIconSize(QSize(iconSize, iconSize));
949 m_decorationSize = QSize(iconSize, iconSize);
950
951 doItemsLayout();
952 }
953
954 KFileItemDelegate::Information DolphinDetailsView::infoForColumn(int columnIndex) const
955 {
956 KFileItemDelegate::Information info = KFileItemDelegate::NoInformation;
957
958 switch (columnIndex) {
959 case DolphinModel::Size: info = KFileItemDelegate::Size; break;
960 case DolphinModel::ModifiedTime: info = KFileItemDelegate::ModificationTime; break;
961 case DolphinModel::Permissions: info = KFileItemDelegate::Permissions; break;
962 case DolphinModel::Owner: info = KFileItemDelegate::Owner; break;
963 case DolphinModel::Group: info = KFileItemDelegate::OwnerAndGroup; break;
964 case DolphinModel::Type: info = KFileItemDelegate::FriendlyMimeType; break;
965 default: break;
966 }
967
968 return info;
969 }
970
971 void DolphinDetailsView::resizeColumns()
972 {
973 // Using the resize mode QHeaderView::ResizeToContents is too slow (it takes
974 // around 3 seconds for each (!) resize operation when having > 10000 items).
975 // This gets a problem especially when opening large directories, where several
976 // resize operations are received for showing the currently available items during
977 // loading (the application hangs around 20 seconds when loading > 10000 items).
978
979 QHeaderView* headerView = header();
980 QFontMetrics fontMetrics(viewport()->font());
981
982 int columnWidth[DolphinModel::Version + 1];
983 columnWidth[DolphinModel::Size] = fontMetrics.width("00000 Items");
984 columnWidth[DolphinModel::ModifiedTime] = fontMetrics.width("0000-00-00 00:00");
985 columnWidth[DolphinModel::Permissions] = fontMetrics.width("xxxxxxxxxx");
986 columnWidth[DolphinModel::Owner] = fontMetrics.width("xxxxxxxxxx");
987 columnWidth[DolphinModel::Group] = fontMetrics.width("xxxxxxxxxx");
988 columnWidth[DolphinModel::Type] = fontMetrics.width("XXXX Xxxxxxx");
989 columnWidth[DolphinModel::Version] = fontMetrics.width("xxxxxxxx");
990
991 int requiredWidth = 0;
992 for (int i = KDirModel::Size; i <= KDirModel::Type; ++i) {
993 if (!isColumnHidden(i)) {
994 columnWidth[i] += 20; // provide a default gap
995 requiredWidth += columnWidth[i];
996 headerView->resizeSection(i, columnWidth[i]);
997 }
998 }
999
1000 // resize the name column in a way that the whole available width is used
1001 columnWidth[KDirModel::Name] = viewport()->width() - requiredWidth;
1002
1003 const int minNameWidth = 300;
1004 if (columnWidth[KDirModel::Name] < minNameWidth) {
1005 columnWidth[KDirModel::Name] = minNameWidth;
1006
1007 // It might be possible that the name column width can be
1008 // decreased without clipping any text. For performance
1009 // reasons the exact necessary width for full visible names is
1010 // only checked for up to 200 items:
1011 const int rowCount = model()->rowCount();
1012 if (rowCount > 0 && rowCount < 200) {
1013 const int nameWidth = sizeHintForColumn(DolphinModel::Name);
1014 if (nameWidth + requiredWidth <= viewport()->width()) {
1015 columnWidth[KDirModel::Name] = viewport()->width() - requiredWidth;
1016 } else if (nameWidth < minNameWidth) {
1017 columnWidth[KDirModel::Name] = nameWidth;
1018 }
1019 }
1020 }
1021
1022 headerView->resizeSection(KDirModel::Name, columnWidth[KDirModel::Name]);
1023 }
1024
1025 bool DolphinDetailsView::isAboveExpandingToggle(const QPoint& pos) const
1026 {
1027 // QTreeView offers no public API to get the information whether an index has an
1028 // expanding toggle and what boundaries the toggle has. The following approach
1029 // also assumes a toggle for file items.
1030 if (itemsExpandable()) {
1031 const QModelIndex index = QTreeView::indexAt(pos);
1032 if (index.isValid() && (index.column() == KDirModel::Name)) {
1033 QRect rect = visualRect(index);
1034 const int toggleSize = rect.height();
1035 if (isRightToLeft()) {
1036 rect.moveRight(rect.right());
1037 } else {
1038 rect.moveLeft(rect.x() - toggleSize);
1039 }
1040 rect.setWidth(toggleSize);
1041
1042 QStyleOption opt;
1043 opt.initFrom(this);
1044 opt.rect = rect;
1045 rect = style()->subElementRect(QStyle::SE_TreeViewDisclosureItem, &opt, this);
1046
1047 return rect.contains(pos);
1048 }
1049 }
1050 return false;
1051 }
1052
1053 DolphinDetailsView::ElasticBand::ElasticBand() :
1054 show(false),
1055 origin(),
1056 destination(),
1057 lastSelectionOrigin(),
1058 lastSelectionDestination(),
1059 ignoreOldInfo(true),
1060 outsideNearestLeftEdge(0),
1061 outsideNearestRightEdge(0),
1062 insideNearestLeftEdge(0),
1063 insideNearestRightEdge(0)
1064 {
1065 }
1066
1067 #include "dolphindetailsview.moc"