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