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