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