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