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