]> cloud.milkyroute.net Git - dolphin.git/blob - src/dolphindetailsview.cpp
fix selection regression that has been introduced by synchronizing the current index...
[dolphin.git] / src / dolphindetailsview.cpp
1 /***************************************************************************
2 * Copyright (C) 2006 by Peter Penz *
3 * peter.penz@gmx.at *
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 "dolphinsettings.h"
26 #include "dolphinsortfilterproxymodel.h"
27 #include "draganddrophelper.h"
28 #include "selectionmanager.h"
29 #include "viewproperties.h"
30
31 #include "dolphin_detailsmodesettings.h"
32 #include "dolphin_generalsettings.h"
33
34 #include <kdirmodel.h>
35 #include <klocale.h>
36 #include <kmenu.h>
37
38 #include <QAbstractProxyModel>
39 #include <QAction>
40 #include <QApplication>
41 #include <QHeaderView>
42 #include <QRubberBand>
43 #include <QPainter>
44 #include <QScrollBar>
45
46 DolphinDetailsView::DolphinDetailsView(QWidget* parent, DolphinController* controller) :
47 QTreeView(parent),
48 m_autoResize(true),
49 m_controller(controller),
50 m_font(),
51 m_decorationSize(),
52 m_showElasticBand(false),
53 m_elasticBandOrigin(),
54 m_elasticBandDestination()
55 {
56 const DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
57 Q_ASSERT(settings != 0);
58 Q_ASSERT(controller != 0);
59
60 setAcceptDrops(true);
61 setSortingEnabled(true);
62 setUniformRowHeights(true);
63 setSelectionBehavior(SelectItems);
64 setDragDropMode(QAbstractItemView::DragDrop);
65 setDropIndicatorShown(false);
66 setAlternatingRowColors(true);
67 setRootIsDecorated(settings->expandableFolders());
68 setItemsExpandable(settings->expandableFolders());
69 setEditTriggers(QAbstractItemView::NoEditTriggers);
70
71 setMouseTracking(true);
72
73 const ViewProperties props(controller->url());
74 setSortIndicatorSection(props.sorting());
75 setSortIndicatorOrder(props.sortOrder());
76
77 QHeaderView* headerView = header();
78 connect(headerView, SIGNAL(sectionClicked(int)),
79 this, SLOT(synchronizeSortingState(int)));
80 headerView->setContextMenuPolicy(Qt::CustomContextMenu);
81 connect(headerView, SIGNAL(customContextMenuRequested(const QPoint&)),
82 this, SLOT(configureColumns(const QPoint&)));
83 connect(headerView, SIGNAL(sectionResized(int, int, int)),
84 this, SLOT(slotHeaderSectionResized(int, int, int)));
85 connect(headerView, SIGNAL(sectionHandleDoubleClicked(int)),
86 this, SLOT(disableAutoResizing()));
87
88 connect(parent, SIGNAL(sortingChanged(DolphinView::Sorting)),
89 this, SLOT(setSortIndicatorSection(DolphinView::Sorting)));
90 connect(parent, SIGNAL(sortOrderChanged(Qt::SortOrder)),
91 this, SLOT(setSortIndicatorOrder(Qt::SortOrder)));
92
93 // TODO: Connecting to the signal 'activated()' is not possible, as kstyle
94 // does not forward the single vs. doubleclick to it yet (KDE 4.1?). Hence it is
95 // necessary connecting the signal 'singleClick()' or 'doubleClick' and to handle the
96 // RETURN-key in keyPressEvent().
97 if (KGlobalSettings::singleClick()) {
98 connect(this, SIGNAL(clicked(const QModelIndex&)),
99 controller, SLOT(triggerItem(const QModelIndex&)));
100 if (DolphinSettings::instance().generalSettings()->showSelectionToggle()) {
101 SelectionManager* selManager = new SelectionManager(this);
102 connect(selManager, SIGNAL(selectionChanged()),
103 this, SLOT(requestActivation()));
104 connect(m_controller, SIGNAL(urlChanged(const KUrl&)),
105 selManager, SLOT(reset()));
106 }
107 } else {
108 connect(this, SIGNAL(doubleClicked(const QModelIndex&)),
109 controller, SLOT(triggerItem(const QModelIndex&)));
110 }
111 connect(this, SIGNAL(entered(const QModelIndex&)),
112 this, SLOT(slotEntered(const QModelIndex&)));
113 connect(this, SIGNAL(viewportEntered()),
114 controller, SLOT(emitViewportEntered()));
115 connect(controller, SIGNAL(zoomIn()),
116 this, SLOT(zoomIn()));
117 connect(controller, SIGNAL(zoomOut()),
118 this, SLOT(zoomOut()));
119 connect(controller->dolphinView(), SIGNAL(additionalInfoChanged()),
120 this, SLOT(updateColumnVisibility()));
121
122 if (settings->useSystemFont()) {
123 m_font = KGlobalSettings::generalFont();
124 } else {
125 m_font = QFont(settings->fontFamily(),
126 settings->fontSize(),
127 settings->fontWeight(),
128 settings->italicFont());
129 }
130
131 setVerticalScrollMode(QTreeView::ScrollPerPixel);
132 setHorizontalScrollMode(QTreeView::ScrollPerPixel);
133
134 updateDecorationSize();
135
136 setFocus();
137
138 connect(KGlobalSettings::self(), SIGNAL(kdisplayFontChanged()),
139 this, SLOT(updateFont()));
140 }
141
142 DolphinDetailsView::~DolphinDetailsView()
143 {
144 }
145
146 bool DolphinDetailsView::event(QEvent* event)
147 {
148 if (event->type() == QEvent::Polish) {
149 QHeaderView* headerView = header();
150 headerView->setResizeMode(QHeaderView::Interactive);
151 headerView->setMovable(false);
152
153 updateColumnVisibility();
154
155 hideColumn(DolphinModel::Rating);
156 hideColumn(DolphinModel::Tags);
157 } else if (event->type() == QEvent::UpdateRequest) {
158 // a wheel movement will scroll 4 items
159 if (model()->rowCount() > 0) {
160 verticalScrollBar()->setSingleStep((sizeHintForRow(0) / 3) * 4);
161 }
162 }
163
164 return QTreeView::event(event);
165 }
166
167 QStyleOptionViewItem DolphinDetailsView::viewOptions() const
168 {
169 QStyleOptionViewItem viewOptions = QTreeView::viewOptions();
170 viewOptions.font = m_font;
171 viewOptions.showDecorationSelected = true;
172 viewOptions.decorationSize = m_decorationSize;
173 return viewOptions;
174 }
175
176 void DolphinDetailsView::contextMenuEvent(QContextMenuEvent* event)
177 {
178 QTreeView::contextMenuEvent(event);
179 m_controller->triggerContextMenuRequest(event->pos());
180 }
181
182 void DolphinDetailsView::mousePressEvent(QMouseEvent* event)
183 {
184 m_controller->requestActivation();
185
186 QTreeView::mousePressEvent(event);
187
188 const QModelIndex index = indexAt(event->pos());
189 if (!index.isValid() || (index.column() != DolphinModel::Name)) {
190 const Qt::KeyboardModifiers modifier = QApplication::keyboardModifiers();
191 if (!(modifier & Qt::ShiftModifier) && !(modifier & Qt::ControlModifier)) {
192 clearSelection();
193 }
194 }
195
196 if (event->button() == Qt::LeftButton) {
197 m_showElasticBand = true;
198
199 const QPoint pos(contentsPos());
200 m_elasticBandOrigin = event->pos();
201 m_elasticBandOrigin.setX(m_elasticBandOrigin.x() + pos.x());
202 m_elasticBandOrigin.setY(m_elasticBandOrigin.y() + pos.y());
203 m_elasticBandDestination = event->pos();
204 }
205 }
206
207 void DolphinDetailsView::mouseMoveEvent(QMouseEvent* event)
208 {
209 if (m_showElasticBand) {
210 const QPoint mousePos = event->pos();
211 const QModelIndex index = indexAt(mousePos);
212 if (!index.isValid()) {
213 // the destination of the selection rectangle is above the viewport. In this
214 // case QTreeView does no selection at all, which is not the wanted behavior
215 // in Dolphin -> select all items within the elastic band rectangle
216 clearSelection();
217
218 const int nameColumnWidth = header()->sectionSize(DolphinModel::Name);
219 QRect selRect = QRect(m_elasticBandOrigin, m_elasticBandDestination).normalized();
220 const QRect nameColumnsRect(0, 0, nameColumnWidth, viewport()->height());
221 selRect = nameColumnsRect.intersected(selRect);
222
223 setSelection(selRect, QItemSelectionModel::Select);
224 }
225
226 // TODO: enable QTreeView::mouseMoveEvent(event) again, as soon
227 // as the Qt-issue #199631 has been fixed.
228 // QTreeView::mouseMoveEvent(event);
229 QAbstractItemView::mouseMoveEvent(event);
230 updateElasticBand();
231 } else {
232 // TODO: enable QTreeView::mouseMoveEvent(event) again, as soon
233 // as the Qt-issue #199631 has been fixed.
234 // QTreeView::mouseMoveEvent(event);
235 QAbstractItemView::mouseMoveEvent(event);
236 }
237 }
238
239 void DolphinDetailsView::mouseReleaseEvent(QMouseEvent* event)
240 {
241 QTreeView::mouseReleaseEvent(event);
242 if (m_showElasticBand) {
243 updateElasticBand();
244 m_showElasticBand = false;
245 }
246 }
247
248 void DolphinDetailsView::startDrag(Qt::DropActions supportedActions)
249 {
250 DragAndDropHelper::startDrag(this, supportedActions);
251 }
252
253 void DolphinDetailsView::dragEnterEvent(QDragEnterEvent* event)
254 {
255 if (event->mimeData()->hasUrls()) {
256 event->acceptProposedAction();
257 }
258
259 if (m_showElasticBand) {
260 updateElasticBand();
261 m_showElasticBand = false;
262 }
263 }
264
265 void DolphinDetailsView::dragLeaveEvent(QDragLeaveEvent* event)
266 {
267 QTreeView::dragLeaveEvent(event);
268 setDirtyRegion(m_dropRect);
269 }
270
271 void DolphinDetailsView::dragMoveEvent(QDragMoveEvent* event)
272 {
273 QTreeView::dragMoveEvent(event);
274
275 // TODO: remove this code when the issue #160611 is solved in Qt 4.4
276 setDirtyRegion(m_dropRect);
277 const QModelIndex index = indexAt(event->pos());
278 if (index.isValid() && (index.column() == DolphinModel::Name)) {
279 const KFileItem item = m_controller->itemForIndex(index);
280 if (!item.isNull() && item.isDir()) {
281 m_dropRect = visualRect(index);
282 } else {
283 m_dropRect.setSize(QSize()); // set as invalid
284 }
285 setDirtyRegion(m_dropRect);
286 }
287
288 if (event->mimeData()->hasUrls()) {
289 // accept url drops, independently from the destination item
290 event->acceptProposedAction();
291 }
292 }
293
294 void DolphinDetailsView::dropEvent(QDropEvent* event)
295 {
296 const KUrl::List urls = KUrl::List::fromMimeData(event->mimeData());
297 if (!urls.isEmpty()) {
298 event->acceptProposedAction();
299 const QModelIndex index = indexAt(event->pos());
300 KFileItem item;
301 if (index.isValid() && (index.column() == DolphinModel::Name)) {
302 item = m_controller->itemForIndex(index);
303 }
304 m_controller->indicateDroppedUrls(urls,
305 m_controller->url(),
306 item);
307 }
308 QTreeView::dropEvent(event);
309 }
310
311 void DolphinDetailsView::paintEvent(QPaintEvent* event)
312 {
313 QTreeView::paintEvent(event);
314 if (m_showElasticBand) {
315 // The following code has been taken from QListView
316 // and adapted to DolphinDetailsView.
317 // (C) 1992-2007 Trolltech ASA
318 QStyleOptionRubberBand opt;
319 opt.initFrom(this);
320 opt.shape = QRubberBand::Rectangle;
321 opt.opaque = false;
322 opt.rect = elasticBandRect();
323
324 QPainter painter(viewport());
325 painter.save();
326 style()->drawControl(QStyle::CE_RubberBand, &opt, &painter);
327 painter.restore();
328 }
329 }
330
331 void DolphinDetailsView::keyPressEvent(QKeyEvent* event)
332 {
333 QTreeView::keyPressEvent(event);
334 m_controller->handleKeyPressEvent(event);
335 }
336
337 void DolphinDetailsView::resizeEvent(QResizeEvent* event)
338 {
339 if (m_autoResize) {
340 resizeColumns();
341 }
342 QTreeView::resizeEvent(event);
343 }
344
345 void DolphinDetailsView::wheelEvent(QWheelEvent* event)
346 {
347 // let Ctrl+wheel events propagate to the DolphinView for icon zooming
348 if (event->modifiers() & Qt::ControlModifier) {
349 event->ignore();
350 return;
351 }
352 QTreeView::wheelEvent(event);
353 }
354
355 void DolphinDetailsView::currentChanged(const QModelIndex& current, const QModelIndex& previous)
356 {
357 QTreeView::currentChanged(current, previous);
358
359 // Stay consistent with QListView: When changing the current index by key presses,
360 // also change the selection.
361 const Qt::KeyboardModifiers modifier = QApplication::keyboardModifiers();
362 const bool adjustSelection = !(modifier & Qt::ShiftModifier) &&
363 !(modifier & Qt::ControlModifier) &&
364 !m_showElasticBand;
365
366 if (adjustSelection) {
367 selectionModel()->select(current, QItemSelectionModel::ClearAndSelect);
368 }
369 }
370
371 void DolphinDetailsView::setSortIndicatorSection(DolphinView::Sorting sorting)
372 {
373 QHeaderView* headerView = header();
374 headerView->setSortIndicator(sorting, headerView->sortIndicatorOrder());
375 }
376
377 void DolphinDetailsView::setSortIndicatorOrder(Qt::SortOrder sortOrder)
378 {
379 QHeaderView* headerView = header();
380 headerView->setSortIndicator(headerView->sortIndicatorSection(), sortOrder);
381 }
382
383 void DolphinDetailsView::synchronizeSortingState(int column)
384 {
385 // The sorting has already been changed in QTreeView if this slot is
386 // invoked, but Dolphin is not informed about this.
387 DolphinView::Sorting sorting = DolphinSortFilterProxyModel::sortingForColumn(column);
388 const Qt::SortOrder sortOrder = header()->sortIndicatorOrder();
389 m_controller->indicateSortingChange(sorting);
390 m_controller->indicateSortOrderChange(sortOrder);
391 }
392
393 void DolphinDetailsView::slotEntered(const QModelIndex& index)
394 {
395 const QPoint pos = viewport()->mapFromGlobal(QCursor::pos());
396 const int nameColumnWidth = header()->sectionSize(DolphinModel::Name);
397 if (pos.x() < nameColumnWidth) {
398 m_controller->emitItemEntered(index);
399 }
400 else {
401 m_controller->emitViewportEntered();
402 }
403 }
404
405 void DolphinDetailsView::updateElasticBand()
406 {
407 if (m_showElasticBand) {
408 QRect dirtyRegion(elasticBandRect());
409 m_elasticBandDestination = viewport()->mapFromGlobal(QCursor::pos());
410 dirtyRegion = dirtyRegion.united(elasticBandRect());
411 setDirtyRegion(dirtyRegion);
412 }
413 }
414
415 QRect DolphinDetailsView::elasticBandRect() const
416 {
417 const QPoint pos(contentsPos());
418 const QPoint topLeft(m_elasticBandOrigin.x() - pos.x(), m_elasticBandOrigin.y() - pos.y());
419 return QRect(topLeft, m_elasticBandDestination).normalized();
420 }
421
422 void DolphinDetailsView::zoomIn()
423 {
424 if (isZoomInPossible()) {
425 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
426 switch (settings->iconSize()) {
427 case KIconLoader::SizeSmall: settings->setIconSize(KIconLoader::SizeMedium); break;
428 case KIconLoader::SizeMedium: settings->setIconSize(KIconLoader::SizeLarge); break;
429 default: Q_ASSERT(false); break;
430 }
431 updateDecorationSize();
432 }
433 }
434
435 void DolphinDetailsView::zoomOut()
436 {
437 if (isZoomOutPossible()) {
438 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
439 switch (settings->iconSize()) {
440 case KIconLoader::SizeLarge: settings->setIconSize(KIconLoader::SizeMedium); break;
441 case KIconLoader::SizeMedium: settings->setIconSize(KIconLoader::SizeSmall); break;
442 default: Q_ASSERT(false); break;
443 }
444 updateDecorationSize();
445 }
446 }
447
448 void DolphinDetailsView::configureColumns(const QPoint& pos)
449 {
450 KMenu popup(this);
451 popup.addTitle(i18nc("@title:menu", "Columns"));
452
453 QHeaderView* headerView = header();
454 for (int i = DolphinModel::Size; i <= DolphinModel::Type; ++i) {
455 const int logicalIndex = headerView->logicalIndex(i);
456 const QString text = model()->headerData(i, Qt::Horizontal).toString();
457 QAction* action = popup.addAction(text);
458 action->setCheckable(true);
459 action->setChecked(!headerView->isSectionHidden(logicalIndex));
460 action->setData(i);
461 }
462
463 QAction* activatedAction = popup.exec(header()->mapToGlobal(pos));
464 if (activatedAction != 0) {
465 const bool show = activatedAction->isChecked();
466 const int columnIndex = activatedAction->data().toInt();
467
468 KFileItemDelegate::InformationList list = m_controller->dolphinView()->additionalInfo();
469 const KFileItemDelegate::Information info = infoForColumn(columnIndex);
470 if (show) {
471 Q_ASSERT(!list.contains(info));
472 list.append(info);
473 } else {
474 Q_ASSERT(list.contains(info));
475 const int index = list.indexOf(info);
476 list.removeAt(index);
477 }
478
479 m_controller->indicateAdditionalInfoChange(list);
480 setColumnHidden(columnIndex, !show);
481 }
482 }
483
484 void DolphinDetailsView::updateColumnVisibility()
485 {
486 const KFileItemDelegate::InformationList list = m_controller->dolphinView()->additionalInfo();
487 for (int i = DolphinModel::Size; i <= DolphinModel::Type; ++i) {
488 const KFileItemDelegate::Information info = infoForColumn(i);
489 const bool hide = !list.contains(info);
490 if (isColumnHidden(i) != hide) {
491 setColumnHidden(i, hide);
492 }
493 }
494
495 resizeColumns();
496 }
497
498 void DolphinDetailsView::slotHeaderSectionResized(int logicalIndex, int oldSize, int newSize)
499 {
500 Q_UNUSED(logicalIndex);
501 Q_UNUSED(oldSize);
502 Q_UNUSED(newSize);
503 if (QApplication::mouseButtons() & Qt::LeftButton) {
504 disableAutoResizing();
505 }
506 }
507
508 void DolphinDetailsView::disableAutoResizing()
509 {
510 m_autoResize = false;
511 }
512
513 void DolphinDetailsView::requestActivation()
514 {
515 m_controller->requestActivation();
516 }
517
518 void DolphinDetailsView::updateFont()
519 {
520 const DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
521 Q_ASSERT(settings != 0);
522
523 if (settings->useSystemFont()) {
524 m_font = KGlobalSettings::generalFont();
525 }
526 }
527
528 bool DolphinDetailsView::isZoomInPossible() const
529 {
530 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
531 return settings->iconSize() < KIconLoader::SizeLarge;
532 }
533
534 bool DolphinDetailsView::isZoomOutPossible() const
535 {
536 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
537 return settings->iconSize() > KIconLoader::SizeSmall;
538 }
539
540 void DolphinDetailsView::updateDecorationSize()
541 {
542 DetailsModeSettings* settings = DolphinSettings::instance().detailsModeSettings();
543 const int iconSize = settings->iconSize();
544 setIconSize(QSize(iconSize, iconSize));
545 m_decorationSize = QSize(iconSize, iconSize);
546
547 m_controller->setZoomInPossible(isZoomInPossible());
548 m_controller->setZoomOutPossible(isZoomOutPossible());
549
550 doItemsLayout();
551 }
552
553 QPoint DolphinDetailsView::contentsPos() const
554 {
555 // implementation note: the horizonal position is ignored currently, as no
556 // horizontal scrolling is done anyway during a selection
557 const QScrollBar* scrollbar = verticalScrollBar();
558 Q_ASSERT(scrollbar != 0);
559
560 const int maxHeight = maximumViewportSize().height();
561 const int height = scrollbar->maximum() - scrollbar->minimum() + 1;
562 const int visibleHeight = model()->rowCount() + 1 - height;
563 if (visibleHeight <= 0) {
564 return QPoint(0, 0);
565 }
566
567 const int y = scrollbar->sliderPosition() * maxHeight / visibleHeight;
568 return QPoint(0, y);
569 }
570
571 KFileItemDelegate::Information DolphinDetailsView::infoForColumn(int columnIndex) const
572 {
573 KFileItemDelegate::Information info = KFileItemDelegate::NoInformation;
574
575 switch (columnIndex) {
576 case DolphinModel::Size: info = KFileItemDelegate::Size; break;
577 case DolphinModel::ModifiedTime: info = KFileItemDelegate::ModificationTime; break;
578 case DolphinModel::Permissions: info = KFileItemDelegate::Permissions; break;
579 case DolphinModel::Owner: info = KFileItemDelegate::Owner; break;
580 case DolphinModel::Group: info = KFileItemDelegate::OwnerAndGroup; break;
581 case DolphinModel::Type: info = KFileItemDelegate::FriendlyMimeType; break;
582 default: break;
583 }
584
585 return info;
586 }
587
588 void DolphinDetailsView::resizeColumns()
589 {
590 // Using the resize mode QHeaderView::ResizeToContents is too slow (it takes
591 // around 3 seconds for each (!) resize operation when having > 10000 items).
592 // This gets a problem especially when opening large directories, where several
593 // resize operations are received for showing the currently available items during
594 // loading (the application hangs around 20 seconds when loading > 10000 items).
595
596 QHeaderView* headerView = header();
597 QFontMetrics fontMetrics(viewport()->font());
598
599 int columnWidth[KDirModel::ColumnCount];
600 columnWidth[KDirModel::Size] = fontMetrics.width("00000 Items");
601 columnWidth[KDirModel::ModifiedTime] = fontMetrics.width("0000-00-00 00:00");
602 columnWidth[KDirModel::Permissions] = fontMetrics.width("xxxxxxxxxx");
603 columnWidth[KDirModel::Owner] = fontMetrics.width("xxxxxxxxxx");
604 columnWidth[KDirModel::Group] = fontMetrics.width("xxxxxxxxxx");
605 columnWidth[KDirModel::Type] = fontMetrics.width("XXXX Xxxxxxx");
606
607 int requiredWidth = 0;
608 for (int i = KDirModel::Size; i <= KDirModel::Type; ++i) {
609 if (!isColumnHidden(i)) {
610 columnWidth[i] += 20; // provide a default gap
611 requiredWidth += columnWidth[i];
612 headerView->resizeSection(i, columnWidth[i]);
613 }
614 }
615
616 // resize the name column in a way that the whole available width is used
617 columnWidth[KDirModel::Name] = viewport()->width() - requiredWidth;
618 if (columnWidth[KDirModel::Name] < 120) {
619 columnWidth[KDirModel::Name] = 120;
620 }
621 headerView->resizeSection(KDirModel::Name, columnWidth[KDirModel::Name]);
622 }
623
624 #include "dolphindetailsview.moc"