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