]> cloud.milkyroute.net Git - dolphin.git/blob - src/views/dolphinview.cpp
Remove RolesInfoAccessor
[dolphin.git] / src / views / dolphinview.cpp
1 /***************************************************************************
2 * Copyright (C) 2006-2009 by Peter Penz <peter.penz19@gmail.com> *
3 * Copyright (C) 2006 by Gregor Kališnik <gregor@podnapisi.net> *
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 "dolphinview.h"
22
23 #include <QAbstractItemView>
24 #include <QApplication>
25 #include <QBoxLayout>
26 #include <QClipboard>
27 #include <QDropEvent>
28 #include <QGraphicsSceneDragDropEvent>
29 #include <QKeyEvent>
30 #include <QItemSelection>
31 #include <QTimer>
32 #include <QScrollBar>
33
34 #include <KActionCollection>
35 #include <KColorScheme>
36 #include <KDirLister>
37 #include <KDirModel>
38 #include <KIconEffect>
39 #include <KFileItem>
40 #include <KFileItemListProperties>
41 #include <KLocale>
42 #include <kitemviews/kfileitemmodel.h>
43 #include <kitemviews/kfileitemlistview.h>
44 #include <kitemviews/kitemlistselectionmanager.h>
45 #include <kitemviews/kitemlistview.h>
46 #include <kitemviews/kitemlistcontroller.h>
47 #include <KIO/DeleteJob>
48 #include <KIO/NetAccess>
49 #include <KIO/PreviewJob>
50 #include <KJob>
51 #include <KMenu>
52 #include <KMessageBox>
53 #include <konq_fileitemcapabilities.h>
54 #include <konq_operations.h>
55 #include <konqmimedata.h>
56 #include <KToggleAction>
57 #include <KUrl>
58
59 #include "dolphindirlister.h"
60 #include "dolphinnewfilemenuobserver.h"
61 #include "dolphin_detailsmodesettings.h"
62 #include "dolphin_generalsettings.h"
63 #include "dolphinitemlistcontainer.h"
64 #include "draganddrophelper.h"
65 #include "renamedialog.h"
66 #include "versioncontrol/versioncontrolobserver.h"
67 #include "viewmodecontroller.h"
68 #include "viewproperties.h"
69 #include "views/tooltips/tooltipmanager.h"
70 #include "zoomlevelinfo.h"
71
72 namespace {
73 const int MaxModeEnum = DolphinView::CompactView;
74 };
75
76 DolphinView::DolphinView(const KUrl& url, QWidget* parent) :
77 QWidget(parent),
78 m_active(true),
79 m_tabsForFiles(false),
80 m_assureVisibleCurrentIndex(false),
81 m_isFolderWritable(true),
82 m_dragging(false),
83 m_url(url),
84 m_mode(DolphinView::IconsView),
85 m_visibleRoles(),
86 m_topLayout(0),
87 m_dirLister(0),
88 m_container(0),
89 m_toolTipManager(0),
90 m_selectionChangedTimer(0),
91 m_currentItemUrl(),
92 m_restoredContentsPosition(),
93 m_createdItemUrl(),
94 m_selectedUrls(),
95 m_versionControlObserver(0)
96 {
97 m_topLayout = new QVBoxLayout(this);
98 m_topLayout->setSpacing(0);
99 m_topLayout->setMargin(0);
100
101 // When a new item has been created by the "Create New..." menu, the item should
102 // get selected and it must be assured that the item will get visible. As the
103 // creation is done asynchronously, several signals must be checked:
104 connect(&DolphinNewFileMenuObserver::instance(), SIGNAL(itemCreated(KUrl)),
105 this, SLOT(observeCreatedItem(KUrl)));
106
107 m_selectionChangedTimer = new QTimer(this);
108 m_selectionChangedTimer->setSingleShot(true);
109 m_selectionChangedTimer->setInterval(300);
110 connect(m_selectionChangedTimer, SIGNAL(timeout()),
111 this, SLOT(emitSelectionChangedSignal()));
112
113 m_dirLister = new DolphinDirLister(this);
114 m_dirLister->setAutoUpdate(true);
115 m_dirLister->setDelayedMimeTypes(true);
116
117 connect(m_dirLister, SIGNAL(redirection(KUrl,KUrl)), this, SLOT(slotRedirection(KUrl,KUrl)));
118 connect(m_dirLister, SIGNAL(started(KUrl)), this, SLOT(slotDirListerStarted(KUrl)));
119 connect(m_dirLister, SIGNAL(refreshItems(QList<QPair<KFileItem,KFileItem> >)),
120 this, SLOT(slotRefreshItems()));
121
122 connect(m_dirLister, SIGNAL(clear()), this, SIGNAL(itemCountChanged()));
123 connect(m_dirLister, SIGNAL(newItems(KFileItemList)), this, SIGNAL(itemCountChanged()));
124 connect(m_dirLister, SIGNAL(infoMessage(QString)), this, SIGNAL(infoMessage(QString)));
125 connect(m_dirLister, SIGNAL(errorMessage(QString)), this, SIGNAL(infoMessage(QString)));
126 connect(m_dirLister, SIGNAL(percent(int)), this, SIGNAL(pathLoadingProgress(int)));
127 connect(m_dirLister, SIGNAL(urlIsFileError(KUrl)), this, SIGNAL(urlIsFileError(KUrl)));
128 connect(m_dirLister, SIGNAL(itemsDeleted(KFileItemList)), this, SIGNAL(itemCountChanged()));
129
130 m_container = new DolphinItemListContainer(m_dirLister, this);
131 m_container->setVisibleRoles(QList<QByteArray>() << "name");
132 m_container->installEventFilter(this);
133 setFocusProxy(m_container);
134 connect(m_container->horizontalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(hideToolTip()));
135 connect(m_container->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(hideToolTip()));
136
137 KItemListController* controller = m_container->controller();
138 controller->setSelectionBehavior(KItemListController::MultiSelection);
139 connect(controller, SIGNAL(itemActivated(int)), this, SLOT(slotItemActivated(int)));
140 connect(controller, SIGNAL(itemsActivated(QSet<int>)), this, SLOT(slotItemsActivated(QSet<int>)));
141 connect(controller, SIGNAL(itemMiddleClicked(int)), this, SLOT(slotItemMiddleClicked(int)));
142 connect(controller, SIGNAL(itemContextMenuRequested(int,QPointF)), this, SLOT(slotItemContextMenuRequested(int,QPointF)));
143 connect(controller, SIGNAL(viewContextMenuRequested(QPointF)), this, SLOT(slotViewContextMenuRequested(QPointF)));
144 connect(controller, SIGNAL(headerContextMenuRequested(QPointF)), this, SLOT(slotHeaderContextMenuRequested(QPointF)));
145 connect(controller, SIGNAL(itemPressed(int,Qt::MouseButton)), this, SLOT(hideToolTip()));
146 connect(controller, SIGNAL(itemHovered(int)), this, SLOT(slotItemHovered(int)));
147 connect(controller, SIGNAL(itemUnhovered(int)), this, SLOT(slotItemUnhovered(int)));
148 connect(controller, SIGNAL(itemDropEvent(int,QGraphicsSceneDragDropEvent*)), this, SLOT(slotItemDropEvent(int,QGraphicsSceneDragDropEvent*)));
149 connect(controller, SIGNAL(modelChanged(KItemModelBase*,KItemModelBase*)), this, SLOT(slotModelChanged(KItemModelBase*,KItemModelBase*)));
150
151 KFileItemModel* model = fileItemModel();
152 if (model) {
153 connect(model, SIGNAL(loadingCompleted()), this, SLOT(slotLoadingCompleted()));
154 }
155
156 KItemListView* view = controller->view();
157 view->installEventFilter(this);
158 connect(view, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
159 this, SLOT(slotSortOrderChangedByHeader(Qt::SortOrder,Qt::SortOrder)));
160 connect(view, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
161 this, SLOT(slotSortRoleChangedByHeader(QByteArray,QByteArray)));
162 connect(view, SIGNAL(visibleRolesChanged(QList<QByteArray>,QList<QByteArray>)),
163 this, SLOT(slotVisibleRolesChangedByHeader(QList<QByteArray>,QList<QByteArray>)));
164
165 KItemListSelectionManager* selectionManager = controller->selectionManager();
166 connect(selectionManager, SIGNAL(selectionChanged(QSet<int>,QSet<int>)),
167 this, SLOT(slotSelectionChanged(QSet<int>,QSet<int>)));
168
169 m_toolTipManager = new ToolTipManager(this);
170
171 m_versionControlObserver = new VersionControlObserver(this);
172 m_versionControlObserver->setModel(model);
173 connect(m_versionControlObserver, SIGNAL(infoMessage(QString)), this, SIGNAL(infoMessage(QString)));
174 connect(m_versionControlObserver, SIGNAL(errorMessage(QString)), this, SIGNAL(errorMessage(QString)));
175 connect(m_versionControlObserver, SIGNAL(operationCompletedMessage(QString)), this, SIGNAL(operationCompletedMessage(QString)));
176
177 applyViewProperties();
178 m_topLayout->addWidget(m_container);
179
180 loadDirectory(url);
181 }
182
183 DolphinView::~DolphinView()
184 {
185 }
186
187 KUrl DolphinView::url() const
188 {
189 return m_url;
190 }
191
192 void DolphinView::setActive(bool active)
193 {
194 if (active == m_active) {
195 return;
196 }
197
198 m_active = active;
199
200 QColor color = KColorScheme(QPalette::Active, KColorScheme::View).background().color();
201 if (!active) {
202 color.setAlpha(150);
203 }
204
205 QWidget* viewport = m_container->viewport();
206 if (viewport) {
207 QPalette palette;
208 palette.setColor(viewport->backgroundRole(), color);
209 viewport->setPalette(palette);
210 }
211
212 update();
213
214 if (active) {
215 m_container->setFocus();
216 emit activated();
217 emit writeStateChanged(m_isFolderWritable);
218 }
219 }
220
221 bool DolphinView::isActive() const
222 {
223 return m_active;
224 }
225
226 void DolphinView::setMode(Mode mode)
227 {
228 if (mode != m_mode) {
229 ViewProperties props(url());
230 props.setViewMode(mode);
231 props.save();
232
233 applyViewProperties();
234 }
235 }
236
237 DolphinView::Mode DolphinView::mode() const
238 {
239 return m_mode;
240 }
241
242 void DolphinView::setPreviewsShown(bool show)
243 {
244 if (previewsShown() == show) {
245 return;
246 }
247
248 ViewProperties props(url());
249 props.setPreviewsShown(show);
250
251 m_container->setPreviewsShown(show);
252 emit previewsShownChanged(show);
253 }
254
255 bool DolphinView::previewsShown() const
256 {
257 return m_container->previewsShown();
258 }
259
260 void DolphinView::setHiddenFilesShown(bool show)
261 {
262 if (m_dirLister->showingDotFiles() == show) {
263 return;
264 }
265
266 const KFileItemList itemList = selectedItems();
267 m_selectedUrls.clear();
268 m_selectedUrls = itemList.urlList();
269
270 ViewProperties props(url());
271 props.setHiddenFilesShown(show);
272
273 fileItemModel()->setShowHiddenFiles(show);
274 emit hiddenFilesShownChanged(show);
275 }
276
277 bool DolphinView::hiddenFilesShown() const
278 {
279 return m_dirLister->showingDotFiles();
280 }
281
282 void DolphinView::setGroupedSorting(bool grouped)
283 {
284 if (grouped == groupedSorting()) {
285 return;
286 }
287
288 ViewProperties props(url());
289 props.setGroupedSorting(grouped);
290 props.save();
291
292 m_container->controller()->model()->setGroupedSorting(grouped);
293
294 emit groupedSortingChanged(grouped);
295 }
296
297 bool DolphinView::groupedSorting() const
298 {
299 return fileItemModel()->groupedSorting();
300 }
301
302 KFileItemList DolphinView::items() const
303 {
304 return m_dirLister->items();
305 }
306
307 KFileItemList DolphinView::selectedItems() const
308 {
309 const KFileItemModel* model = fileItemModel();
310 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
311 const QSet<int> selectedIndexes = selectionManager->selectedItems();
312
313 KFileItemList selectedItems;
314 QSetIterator<int> it(selectedIndexes);
315 while (it.hasNext()) {
316 const int index = it.next();
317 selectedItems.append(model->fileItem(index));
318 }
319 return selectedItems;
320 }
321
322 int DolphinView::selectedItemsCount() const
323 {
324 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
325 return selectionManager->selectedItems().count();
326 }
327
328 void DolphinView::markUrlsAsSelected(const QList<KUrl>& urls)
329 {
330 m_selectedUrls = urls;
331 }
332
333 void DolphinView::markUrlAsCurrent(const KUrl& url)
334 {
335 m_currentItemUrl = url;
336 }
337
338 void DolphinView::setItemSelectionEnabled(const QRegExp& pattern, bool enabled)
339 {
340 const KItemListSelectionManager::SelectionMode mode = enabled
341 ? KItemListSelectionManager::Select
342 : KItemListSelectionManager::Deselect;
343 const KFileItemModel* model = fileItemModel();
344 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
345
346 for (int index = 0; index < model->count(); index++) {
347 const KFileItem item = model->fileItem(index);
348 if (pattern.exactMatch(item.text())) {
349 // An alternative approach would be to store the matching items in a QSet<int> and
350 // select them in one go after the loop, but we'd need a new function
351 // KItemListSelectionManager::setSelected(QSet<int>, SelectionMode mode)
352 // for that.
353 selectionManager->setSelected(index, 1, mode);
354 }
355 }
356 }
357
358 void DolphinView::setZoomLevel(int level)
359 {
360 const int oldZoomLevel = zoomLevel();
361 m_container->setZoomLevel(level);
362 if (zoomLevel() != oldZoomLevel) {
363 emit zoomLevelChanged(zoomLevel(), oldZoomLevel);
364 }
365 }
366
367 int DolphinView::zoomLevel() const
368 {
369 return m_container->zoomLevel();
370 }
371
372 void DolphinView::setSortRole(const QByteArray& role)
373 {
374 if (role != sortRole()) {
375 updateSortRole(role);
376 }
377 }
378
379 QByteArray DolphinView::sortRole() const
380 {
381 const KItemModelBase* model = m_container->controller()->model();
382 return model->sortRole();
383 }
384
385 void DolphinView::setSortOrder(Qt::SortOrder order)
386 {
387 if (sortOrder() != order) {
388 updateSortOrder(order);
389 }
390 }
391
392 Qt::SortOrder DolphinView::sortOrder() const
393 {
394 KItemModelBase* model = fileItemModel();
395 return model->sortOrder();
396 }
397
398 void DolphinView::setSortFoldersFirst(bool foldersFirst)
399 {
400 if (sortFoldersFirst() != foldersFirst) {
401 updateSortFoldersFirst(foldersFirst);
402 }
403 }
404
405 bool DolphinView::sortFoldersFirst() const
406 {
407 KFileItemModel* model = fileItemModel();
408 return model->sortFoldersFirst();
409 }
410
411 void DolphinView::setVisibleRoles(const QList<QByteArray>& roles)
412 {
413 const QList<QByteArray> previousRoles = roles;
414
415 ViewProperties props(url());
416 props.setVisibleRoles(roles);
417
418 m_visibleRoles = roles;
419 m_container->setVisibleRoles(roles);
420
421 emit visibleRolesChanged(m_visibleRoles, previousRoles);
422 }
423
424 QList<QByteArray> DolphinView::visibleRoles() const
425 {
426 return m_visibleRoles;
427 }
428
429 void DolphinView::reload()
430 {
431 QByteArray viewState;
432 QDataStream saveStream(&viewState, QIODevice::WriteOnly);
433 saveState(saveStream);
434
435 const KFileItemList itemList = selectedItems();
436 m_selectedUrls.clear();
437 m_selectedUrls = itemList.urlList();
438
439 setUrl(url());
440 loadDirectory(url(), true);
441
442 QDataStream restoreStream(viewState);
443 restoreState(restoreStream);
444 }
445
446 void DolphinView::stopLoading()
447 {
448 m_dirLister->stop();
449 }
450
451 void DolphinView::readSettings()
452 {
453 const int oldZoomLevel = m_container->zoomLevel();
454
455 GeneralSettings::self()->readConfig();
456 m_container->readSettings();
457 applyViewProperties();
458
459 const int newZoomLevel = m_container->zoomLevel();
460 if (newZoomLevel != oldZoomLevel) {
461 emit zoomLevelChanged(newZoomLevel, oldZoomLevel);
462 }
463 }
464
465 void DolphinView::writeSettings()
466 {
467 GeneralSettings::self()->writeConfig();
468 m_container->writeSettings();
469 }
470
471 void DolphinView::setNameFilter(const QString& nameFilter)
472 {
473 fileItemModel()->setNameFilter(nameFilter);
474 }
475
476 QString DolphinView::nameFilter() const
477 {
478 return fileItemModel()->nameFilter();
479 }
480
481 void DolphinView::calculateItemCount(int& fileCount,
482 int& folderCount,
483 KIO::filesize_t& totalFileSize) const
484 {
485 foreach (const KFileItem& item, m_dirLister->items()) {
486 if (item.isDir()) {
487 ++folderCount;
488 } else {
489 ++fileCount;
490 totalFileSize += item.size();
491 }
492 }
493 }
494
495 QString DolphinView::statusBarText() const
496 {
497 QString summary;
498 QString foldersText;
499 QString filesText;
500
501 int folderCount = 0;
502 int fileCount = 0;
503 KIO::filesize_t totalFileSize = 0;
504
505 if (hasSelection()) {
506 // Give a summary of the status of the selected files
507 const KFileItemList list = selectedItems();
508 foreach (const KFileItem& item, list) {
509 if (item.isDir()) {
510 ++folderCount;
511 } else {
512 ++fileCount;
513 totalFileSize += item.size();
514 }
515 }
516
517 if (folderCount + fileCount == 1) {
518 // If only one item is selected, show the filename
519 filesText = i18nc("@info:status", "<filename>%1</filename> selected", list.first().text());
520 } else {
521 // At least 2 items are selected
522 foldersText = i18ncp("@info:status", "1 Folder selected", "%1 Folders selected", folderCount);
523 filesText = i18ncp("@info:status", "1 File selected", "%1 Files selected", fileCount);
524 }
525 } else {
526 calculateItemCount(fileCount, folderCount, totalFileSize);
527 foldersText = i18ncp("@info:status", "1 Folder", "%1 Folders", folderCount);
528 filesText = i18ncp("@info:status", "1 File", "%1 Files", fileCount);
529 }
530
531 if (fileCount > 0 && folderCount > 0) {
532 summary = i18nc("@info:status folders, files (size)", "%1, %2 (%3)",
533 foldersText, filesText, fileSizeText(totalFileSize));
534 } else if (fileCount > 0) {
535 summary = i18nc("@info:status files (size)", "%1 (%2)", filesText, fileSizeText(totalFileSize));
536 } else if (folderCount > 0) {
537 summary = foldersText;
538 }
539
540 return summary;
541 }
542
543 QList<QAction*> DolphinView::versionControlActions(const KFileItemList& items) const
544 {
545 QList<QAction*> actions;
546
547 if (items.isEmpty()) {
548 const KFileItem item = fileItemModel()->rootItem();
549 actions = m_versionControlObserver->actions(KFileItemList() << item);
550 } else {
551 actions = m_versionControlObserver->actions(items);
552 }
553
554 return actions;
555 }
556
557 void DolphinView::setUrl(const KUrl& url)
558 {
559 if (url == m_url) {
560 return;
561 }
562
563 emit urlAboutToBeChanged(url);
564 m_url = url;
565
566 hideToolTip();
567
568 // It is important to clear the items from the model before
569 // applying the view properties, otherwise expensive operations
570 // might be done on the existing items although they get cleared
571 // anyhow afterwards by loadDirectory().
572 fileItemModel()->clear();
573 applyViewProperties();
574 loadDirectory(url);
575
576 emit urlChanged(url);
577 }
578
579 void DolphinView::selectAll()
580 {
581 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
582 selectionManager->setSelected(0, fileItemModel()->count());
583 }
584
585 void DolphinView::invertSelection()
586 {
587 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
588 selectionManager->setSelected(0, fileItemModel()->count(), KItemListSelectionManager::Toggle);
589 }
590
591 void DolphinView::clearSelection()
592 {
593 m_container->controller()->selectionManager()->clearSelection();
594 }
595
596 void DolphinView::renameSelectedItems()
597 {
598 KFileItemList items = selectedItems();
599 const int itemCount = items.count();
600 if (itemCount < 1) {
601 return;
602 }
603
604 // TODO: The new view-engine introduced with Dolphin 2.0 does not support inline
605 // renaming yet.
606 /*if ((itemCount == 1) && DolphinSettings::instance().generalSettings()->renameInline()) {
607 const QModelIndex dirIndex = m_viewAccessor.dirModel()->indexForItem(items.first());
608 const QModelIndex proxyIndex = m_viewAccessor.proxyModel()->mapFromSource(dirIndex);
609 m_viewAccessor.itemView()->edit(proxyIndex);
610 } else {*/
611 RenameDialog* dialog = new RenameDialog(this, items);
612 dialog->setAttribute(Qt::WA_DeleteOnClose);
613 dialog->show();
614 dialog->raise();
615 dialog->activateWindow();
616 //}
617
618 // assure that the current index remains visible when KDirLister
619 // will notify the view about changed items
620 m_assureVisibleCurrentIndex = true;
621 }
622
623 void DolphinView::trashSelectedItems()
624 {
625 const KUrl::List list = simplifiedSelectedUrls();
626 KonqOperations::del(this, KonqOperations::TRASH, list);
627 }
628
629 void DolphinView::deleteSelectedItems()
630 {
631 const KUrl::List list = simplifiedSelectedUrls();
632 const bool del = KonqOperations::askDeleteConfirmation(list,
633 KonqOperations::DEL,
634 KonqOperations::DEFAULT_CONFIRMATION,
635 this);
636
637 if (del) {
638 KIO::Job* job = KIO::del(list);
639 connect(job, SIGNAL(result(KJob*)),
640 this, SLOT(slotDeleteFileFinished(KJob*)));
641 }
642 }
643
644 void DolphinView::cutSelectedItems()
645 {
646 QMimeData* mimeData = selectionMimeData();
647 KonqMimeData::addIsCutSelection(mimeData, true);
648 QApplication::clipboard()->setMimeData(mimeData);
649 }
650
651 void DolphinView::copySelectedItems()
652 {
653 QMimeData* mimeData = selectionMimeData();
654 QApplication::clipboard()->setMimeData(mimeData);
655 }
656
657 void DolphinView::paste()
658 {
659 pasteToUrl(url());
660 }
661
662 void DolphinView::pasteIntoFolder()
663 {
664 const KFileItemList items = selectedItems();
665 if ((items.count() == 1) && items.first().isDir()) {
666 pasteToUrl(items.first().url());
667 }
668 }
669
670 bool DolphinView::eventFilter(QObject* watched, QEvent* event)
671 {
672 switch (event->type()) {
673 case QEvent::FocusIn:
674 if (watched == m_container) {
675 setActive(true);
676 }
677 break;
678
679 case QEvent::GraphicsSceneDragEnter:
680 if (watched == m_container->controller()->view()) {
681 m_dragging = true;
682 }
683 break;
684
685 case QEvent::GraphicsSceneDragLeave:
686 if (watched == m_container->controller()->view()) {
687 m_dragging = false;
688 }
689 break;
690
691 case QEvent::GraphicsSceneDrop:
692 if (watched == m_container->controller()->view()) {
693 m_dragging = false;
694 }
695 default:
696 break;
697 }
698
699 return QWidget::eventFilter(watched, event);
700 }
701
702 void DolphinView::wheelEvent(QWheelEvent* event)
703 {
704 if (event->modifiers().testFlag(Qt::ControlModifier)) {
705 const int numDegrees = event->delta() / 8;
706 const int numSteps = numDegrees / 15;
707
708 setZoomLevel(zoomLevel() + numSteps);
709 event->accept();
710 } else {
711 event->ignore();
712 }
713 }
714
715 void DolphinView::hideEvent(QHideEvent* event)
716 {
717 hideToolTip();
718 QWidget::hideEvent(event);
719 }
720
721 void DolphinView::activate()
722 {
723 setActive(true);
724 }
725
726 void DolphinView::slotItemActivated(int index)
727 {
728 const KFileItem item = fileItemModel()->fileItem(index);
729 if (!item.isNull()) {
730 emit itemActivated(item);
731 }
732 }
733
734 void DolphinView::slotItemsActivated(const QSet<int>& indexes)
735 {
736 Q_ASSERT(indexes.count() >= 2);
737
738 KFileItemList items;
739
740 KFileItemModel* model = fileItemModel();
741 QSetIterator<int> it(indexes);
742 while (it.hasNext()) {
743 const int index = it.next();
744 items.append(model->fileItem(index));
745 }
746
747 foreach (const KFileItem& item, items) {
748 if (item.isDir()) {
749 emit tabRequested(item.url());
750 } else {
751 emit itemActivated(item);
752 }
753 }
754 }
755
756 void DolphinView::slotItemMiddleClicked(int index)
757 {
758 const KFileItem item = fileItemModel()->fileItem(index);
759 if (item.isDir() || isTabsForFilesEnabled()) {
760 emit tabRequested(item.url());
761 }
762 }
763
764 void DolphinView::slotItemContextMenuRequested(int index, const QPointF& pos)
765 {
766 const KFileItem item = fileItemModel()->fileItem(index);
767 emit requestContextMenu(pos.toPoint(), item, url(), QList<QAction*>());
768 }
769
770 void DolphinView::slotViewContextMenuRequested(const QPointF& pos)
771 {
772 emit requestContextMenu(pos.toPoint(), KFileItem(), url(), QList<QAction*>());
773 }
774
775 void DolphinView::slotHeaderContextMenuRequested(const QPointF& pos)
776 {
777 QWeakPointer<KMenu> menu = new KMenu(QApplication::activeWindow());
778
779 KItemListView* view = m_container->controller()->view();
780 const QSet<QByteArray> visibleRolesSet = view->visibleRoles().toSet();
781
782 // Add all roles to the menu that can be shown or hidden by the user
783 const QList<KFileItemModel::RoleInfo> rolesInfo = KFileItemModel::rolesInformation();
784 foreach (const KFileItemModel::RoleInfo& info, rolesInfo) {
785 if (info.role != "name") {
786 const QString text = fileItemModel()->roleDescription(info.role);
787
788 QAction* action = menu.data()->addAction(text);
789 action->setCheckable(true);
790 action->setChecked(visibleRolesSet.contains(info.role));
791 action->setData(info.role);
792 }
793 }
794
795 QAction* action = menu.data()->exec(pos.toPoint());
796 if (action) {
797 // Show or hide the selected role
798 const QByteArray selectedRole = action->data().toByteArray();
799
800 ViewProperties props(url());
801 QList<QByteArray> visibleRoles = view->visibleRoles();
802 if (action->isChecked()) {
803 visibleRoles.append(selectedRole);
804 } else {
805 visibleRoles.removeOne(selectedRole);
806 }
807
808 view->setVisibleRoles(visibleRoles);
809 props.setVisibleRoles(visibleRoles);
810 }
811
812 delete menu.data();
813 }
814
815 void DolphinView::slotItemHovered(int index)
816 {
817 const KFileItem item = fileItemModel()->fileItem(index);
818
819 if (GeneralSettings::showToolTips() && !m_dragging) {
820 QRectF itemRect = m_container->controller()->view()->itemContextRect(index);
821 const QPoint pos = m_container->mapToGlobal(itemRect.topLeft().toPoint());
822 itemRect.moveTo(pos);
823
824 m_toolTipManager->showToolTip(item, itemRect);
825 }
826
827 emit requestItemInfo(item);
828 }
829
830 void DolphinView::slotItemUnhovered(int index)
831 {
832 Q_UNUSED(index);
833 hideToolTip();
834 emit requestItemInfo(KFileItem());
835 }
836
837 void DolphinView::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* event)
838 {
839 KUrl destUrl;
840 KFileItem destItem = fileItemModel()->fileItem(index);
841 if (destItem.isNull() || (!destItem.isDir() && !destItem.isDesktopFile())) {
842 // Use the URL of the view as drop target if the item is no directory
843 // or desktop-file
844 destItem = fileItemModel()->rootItem();
845 destUrl = url();
846 } else {
847 // The item represents a directory or desktop-file
848 destUrl = destItem.url();
849 }
850
851 QDropEvent dropEvent(event->pos().toPoint(),
852 event->possibleActions(),
853 event->mimeData(),
854 event->buttons(),
855 event->modifiers());
856
857 const QString error = DragAndDropHelper::dropUrls(destItem, destUrl, &dropEvent);
858 if (!error.isEmpty()) {
859 emit errorMessage(error);
860 }
861 }
862
863 void DolphinView::slotModelChanged(KItemModelBase* current, KItemModelBase* previous)
864 {
865 if (previous != 0) {
866 disconnect(previous, SIGNAL(loadingCompleted()), this, SLOT(slotLoadingCompleted()));
867 }
868
869 Q_ASSERT(qobject_cast<KFileItemModel*>(current));
870 connect(current, SIGNAL(loadingCompleted()), this, SLOT(slotLoadingCompleted()));
871
872 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(current);
873 m_versionControlObserver->setModel(fileItemModel);
874 }
875
876 void DolphinView::slotSelectionChanged(const QSet<int>& current, const QSet<int>& previous)
877 {
878 const int currentCount = current.count();
879 const int previousCount = previous.count();
880 const bool selectionStateChanged = (currentCount == 0 && previousCount > 0) ||
881 (currentCount > 0 && previousCount == 0);
882
883 // If nothing has been selected before and something got selected (or if something
884 // was selected before and now nothing is selected) the selectionChangedSignal must
885 // be emitted asynchronously as fast as possible to update the edit-actions.
886 m_selectionChangedTimer->setInterval(selectionStateChanged ? 0 : 300);
887 m_selectionChangedTimer->start();
888 }
889
890 void DolphinView::emitSelectionChangedSignal()
891 {
892 m_selectionChangedTimer->stop();
893 emit selectionChanged(selectedItems());
894 }
895
896 void DolphinView::updateSortRole(const QByteArray& role)
897 {
898 ViewProperties props(url());
899 props.setSortRole(role);
900
901 KItemModelBase* model = m_container->controller()->model();
902 model->setSortRole(role);
903
904 emit sortRoleChanged(role);
905 }
906
907 void DolphinView::updateSortOrder(Qt::SortOrder order)
908 {
909 ViewProperties props(url());
910 props.setSortOrder(order);
911
912 KItemModelBase* model = fileItemModel();
913 model->setSortOrder(order);
914
915 emit sortOrderChanged(order);
916 }
917
918 void DolphinView::updateSortFoldersFirst(bool foldersFirst)
919 {
920 ViewProperties props(url());
921 props.setSortFoldersFirst(foldersFirst);
922
923 KFileItemModel* model = fileItemModel();
924 model->setSortFoldersFirst(foldersFirst);
925
926 emit sortFoldersFirstChanged(foldersFirst);
927 }
928
929 QPair<bool, QString> DolphinView::pasteInfo() const
930 {
931 return KonqOperations::pasteInfo(url());
932 }
933
934 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles)
935 {
936 m_tabsForFiles = tabsForFiles;
937 }
938
939 bool DolphinView::isTabsForFilesEnabled() const
940 {
941 return m_tabsForFiles;
942 }
943
944 bool DolphinView::itemsExpandable() const
945 {
946 return m_mode == DetailsView;
947 }
948
949 void DolphinView::restoreState(QDataStream& stream)
950 {
951 // Restore the current item that had the keyboard focus
952 stream >> m_currentItemUrl;
953
954 // Restore the view position
955 stream >> m_restoredContentsPosition;
956
957 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
958 QSet<KUrl> urls;
959 stream >> urls;
960 fileItemModel()->restoreExpandedUrls(urls);
961 }
962
963 void DolphinView::saveState(QDataStream& stream)
964 {
965 // Save the current item that has the keyboard focus
966 const int currentIndex = m_container->controller()->selectionManager()->currentItem();
967 if (currentIndex != -1) {
968 KFileItem item = fileItemModel()->fileItem(currentIndex);
969 Q_ASSERT(!item.isNull()); // If the current index is valid a item must exist
970 KUrl currentItemUrl = item.url();
971 stream << currentItemUrl;
972 } else {
973 stream << KUrl();
974 }
975
976 // Save view position
977 const qreal x = m_container->horizontalScrollBar()->value();
978 const qreal y = m_container->verticalScrollBar()->value();
979 stream << QPoint(x, y);
980
981 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
982 stream << fileItemModel()->expandedUrls();
983 }
984
985 bool DolphinView::hasSelection() const
986 {
987 return m_container->controller()->selectionManager()->hasSelection();
988 }
989
990 KFileItem DolphinView::rootItem() const
991 {
992 return m_dirLister->rootItem();
993 }
994
995 void DolphinView::observeCreatedItem(const KUrl& url)
996 {
997 m_createdItemUrl = url;
998 //connect(m_dirModel, SIGNAL(rowsInserted(QModelIndex,int,int)),
999 // this, SLOT(selectAndScrollToCreatedItem()));
1000 }
1001
1002 void DolphinView::selectAndScrollToCreatedItem()
1003 {
1004 /*const QModelIndex dirIndex = m_viewAccessor.dirModel()->indexForUrl(m_createdItemUrl);
1005 if (dirIndex.isValid()) {
1006 const QModelIndex proxyIndex = m_viewAccessor.proxyModel()->mapFromSource(dirIndex);
1007 QAbstractItemView* view = m_viewAccessor.itemView();
1008 if (view) {
1009 view->setCurrentIndex(proxyIndex);
1010 }
1011 }
1012
1013 disconnect(m_viewAccessor.dirModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
1014 this, SLOT(selectAndScrollToCreatedItem()));*/
1015 m_createdItemUrl = KUrl();
1016 }
1017
1018 void DolphinView::slotRedirection(const KUrl& oldUrl, const KUrl& newUrl)
1019 {
1020 if (oldUrl.equals(url(), KUrl::CompareWithoutTrailingSlash)) {
1021 emit redirection(oldUrl, newUrl);
1022 m_url = newUrl; // #186947
1023 }
1024 }
1025
1026 void DolphinView::updateViewState()
1027 {
1028 if (m_currentItemUrl != KUrl()) {
1029 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1030 const int currentIndex = fileItemModel()->index(m_currentItemUrl);
1031 if (currentIndex != -1) {
1032 selectionManager->setCurrentItem(currentIndex);
1033 } else {
1034 selectionManager->setCurrentItem(0);
1035 }
1036 m_currentItemUrl = KUrl();
1037 }
1038
1039 if (!m_restoredContentsPosition.isNull()) {
1040 const int x = m_restoredContentsPosition.x();
1041 const int y = m_restoredContentsPosition.y();
1042 m_restoredContentsPosition = QPoint();
1043
1044 m_container->horizontalScrollBar()->setValue(x);
1045 m_container->verticalScrollBar()->setValue(y);
1046 }
1047
1048 if (!m_selectedUrls.isEmpty()) {
1049 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1050 QSet<int> selectedItems = selectionManager->selectedItems();
1051 const KFileItemModel* model = fileItemModel();
1052
1053 foreach (const KUrl& url, m_selectedUrls) {
1054 const int index = model->index(url);
1055 if (index >= 0) {
1056 selectedItems.insert(index);
1057 }
1058 }
1059
1060 selectionManager->setSelectedItems(selectedItems);
1061 m_selectedUrls.clear();
1062 }
1063 }
1064
1065 void DolphinView::hideToolTip()
1066 {
1067 if (GeneralSettings::showToolTips()) {
1068 m_toolTipManager->hideToolTip();
1069 }
1070 }
1071
1072 void DolphinView::showHoverInformation(const KFileItem& item)
1073 {
1074 emit requestItemInfo(item);
1075 }
1076
1077 void DolphinView::clearHoverInformation()
1078 {
1079 emit requestItemInfo(KFileItem());
1080 }
1081
1082 void DolphinView::slotDeleteFileFinished(KJob* job)
1083 {
1084 if (job->error() == 0) {
1085 emit operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1086 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1087 emit errorMessage(job->errorString());
1088 }
1089 }
1090
1091 void DolphinView::slotDirListerStarted(const KUrl& url)
1092 {
1093 // Disable the writestate temporary until it can be determined in a fast way
1094 // in DolphinView::slotLoadingCompleted()
1095 if (m_isFolderWritable) {
1096 m_isFolderWritable = false;
1097 emit writeStateChanged(m_isFolderWritable);
1098 }
1099
1100 emit startedPathLoading(url);
1101 }
1102
1103 void DolphinView::slotLoadingCompleted()
1104 {
1105 // Update the view-state. This has to be done using a Qt::QueuedConnection
1106 // because the view might not be in its final state yet (the view also
1107 // listens to the completed()-signal from KDirLister and the order of
1108 // of slots is undefined).
1109 QTimer::singleShot(0, this, SLOT(updateViewState()));
1110
1111 emit finishedPathLoading(url());
1112
1113 updateWritableState();
1114 }
1115
1116 void DolphinView::slotRefreshItems()
1117 {
1118 if (m_assureVisibleCurrentIndex) {
1119 m_assureVisibleCurrentIndex = false;
1120 //QAbstractItemView* view = m_viewAccessor.itemView();
1121 //if (view) {
1122 // m_viewAccessor.itemView()->scrollTo(m_viewAccessor.itemView()->currentIndex());
1123 //}
1124 }
1125 }
1126
1127 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current, Qt::SortOrder previous)
1128 {
1129 Q_UNUSED(previous);
1130 Q_ASSERT(fileItemModel()->sortOrder() == current);
1131
1132 ViewProperties props(url());
1133 props.setSortOrder(current);
1134
1135 emit sortOrderChanged(current);
1136 }
1137
1138 void DolphinView::slotSortRoleChangedByHeader(const QByteArray& current, const QByteArray& previous)
1139 {
1140 Q_UNUSED(previous);
1141 Q_ASSERT(fileItemModel()->sortRole() == current);
1142
1143 ViewProperties props(url());
1144 props.setSortRole(current);
1145
1146 emit sortRoleChanged(current);
1147 }
1148
1149 void DolphinView::slotVisibleRolesChangedByHeader(const QList<QByteArray>& current,
1150 const QList<QByteArray>& previous)
1151 {
1152 Q_UNUSED(previous);
1153 Q_ASSERT(m_container->controller()->view()->visibleRoles() == current);
1154
1155 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1156
1157 m_visibleRoles = current;
1158
1159 ViewProperties props(url());
1160 props.setVisibleRoles(m_visibleRoles);
1161
1162 emit visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1163 }
1164
1165 KFileItemModel* DolphinView::fileItemModel() const
1166 {
1167 return static_cast<KFileItemModel*>(m_container->controller()->model());
1168 }
1169
1170 void DolphinView::loadDirectory(const KUrl& url, bool reload)
1171 {
1172 if (!url.isValid()) {
1173 const QString location(url.pathOrUrl());
1174 if (location.isEmpty()) {
1175 emit errorMessage(i18nc("@info:status", "The location is empty."));
1176 } else {
1177 emit errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location));
1178 }
1179 return;
1180 }
1181
1182 m_dirLister->openUrl(url, reload ? KDirLister::Reload : KDirLister::NoFlags);
1183 }
1184
1185 void DolphinView::applyViewProperties()
1186 {
1187 m_container->beginTransaction();
1188
1189 const ViewProperties props(url());
1190 KFileItemModel* model = fileItemModel();
1191
1192 const Mode mode = props.viewMode();
1193 if (m_mode != mode) {
1194 const Mode previousMode = m_mode;
1195 m_mode = mode;
1196
1197 // Changing the mode might result in changing
1198 // the zoom level. Remember the old zoom level so
1199 // that zoomLevelChanged() can get emitted.
1200 const int oldZoomLevel = m_container->zoomLevel();
1201
1202 switch (m_mode) {
1203 case IconsView: m_container->setItemLayout(KFileItemListView::IconsLayout); break;
1204 case CompactView: m_container->setItemLayout(KFileItemListView::CompactLayout); break;
1205 case DetailsView: m_container->setItemLayout(KFileItemListView::DetailsLayout); break;
1206 default: Q_ASSERT(false); break;
1207 }
1208
1209 emit modeChanged(m_mode, previousMode);
1210
1211 if (m_container->zoomLevel() != oldZoomLevel) {
1212 emit zoomLevelChanged(m_container->zoomLevel(), oldZoomLevel);
1213 }
1214 }
1215
1216 const bool hiddenFilesShown = props.hiddenFilesShown();
1217 if (hiddenFilesShown != model->showHiddenFiles()) {
1218 model->setShowHiddenFiles(hiddenFilesShown);
1219 emit hiddenFilesShownChanged(hiddenFilesShown);
1220 }
1221
1222 const bool groupedSorting = props.groupedSorting();
1223 if (groupedSorting != model->groupedSorting()) {
1224 model->setGroupedSorting(groupedSorting);
1225 emit groupedSortingChanged(groupedSorting);
1226 }
1227
1228 const QByteArray sortRole = props.sortRole();
1229 if (sortRole != model->sortRole()) {
1230 model->setSortRole(sortRole);
1231 emit sortRoleChanged(sortRole);
1232 }
1233
1234 const Qt::SortOrder sortOrder = props.sortOrder();
1235 if (sortOrder != model->sortOrder()) {
1236 model->setSortOrder(sortOrder);
1237 emit sortOrderChanged(sortOrder);
1238 }
1239
1240 const bool sortFoldersFirst = props.sortFoldersFirst();
1241 if (sortFoldersFirst != model->sortFoldersFirst()) {
1242 model->setSortFoldersFirst(sortFoldersFirst);
1243 emit sortFoldersFirstChanged(sortFoldersFirst);
1244 }
1245
1246 const QList<QByteArray> visibleRoles = props.visibleRoles();
1247 if (visibleRoles != m_visibleRoles) {
1248 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1249 m_visibleRoles = visibleRoles;
1250 m_container->setVisibleRoles(visibleRoles);
1251 emit visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1252 }
1253
1254 const bool previewsShown = props.previewsShown();
1255 if (previewsShown != m_container->previewsShown()) {
1256 const int oldZoomLevel = zoomLevel();
1257
1258 m_container->setPreviewsShown(previewsShown);
1259 emit previewsShownChanged(previewsShown);
1260
1261 // Changing the preview-state might result in a changed zoom-level
1262 if (oldZoomLevel != zoomLevel()) {
1263 emit zoomLevelChanged(zoomLevel(), oldZoomLevel);
1264 }
1265 }
1266
1267 m_container->endTransaction();
1268 }
1269
1270 void DolphinView::pasteToUrl(const KUrl& url)
1271 {
1272 markPastedUrlsAsSelected(QApplication::clipboard()->mimeData());
1273 KonqOperations::doPaste(this, url);
1274 }
1275
1276 KUrl::List DolphinView::simplifiedSelectedUrls() const
1277 {
1278 KUrl::List urls;
1279
1280 const KFileItemList items = selectedItems();
1281 foreach (const KFileItem &item, items) {
1282 urls.append(item.url());
1283 }
1284
1285 if (itemsExpandable()) {
1286 // TODO: Check if we still need KDirModel for this in KDE 5.0
1287 urls = KDirModel::simplifiedUrlList(urls);
1288 }
1289
1290 return urls;
1291 }
1292
1293 QMimeData* DolphinView::selectionMimeData() const
1294 {
1295 const KFileItemModel* model = fileItemModel();
1296 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1297 const QSet<int> selectedIndexes = selectionManager->selectedItems();
1298
1299 return model->createMimeData(selectedIndexes);
1300 }
1301
1302 void DolphinView::markPastedUrlsAsSelected(const QMimeData* mimeData)
1303 {
1304 const KUrl::List urls = KUrl::List::fromMimeData(mimeData);
1305 markUrlsAsSelected(urls);
1306 }
1307
1308 void DolphinView::updateWritableState()
1309 {
1310 const bool wasFolderWritable = m_isFolderWritable;
1311 m_isFolderWritable = true;
1312
1313 const KFileItem item = m_dirLister->rootItem();
1314 if (!item.isNull()) {
1315 KFileItemListProperties capabilities(KFileItemList() << item);
1316 m_isFolderWritable = capabilities.supportsWriting();
1317 }
1318 if (m_isFolderWritable != wasFolderWritable) {
1319 emit writeStateChanged(m_isFolderWritable);
1320 }
1321 }
1322
1323 QString DolphinView::fileSizeText(KIO::filesize_t fileSize)
1324 {
1325 const KLocale* locale = KGlobal::locale();
1326 const unsigned int multiplier = (locale->binaryUnitDialect() == KLocale::MetricBinaryDialect)
1327 ? 1000 : 1024;
1328
1329 QString text;
1330 if (fileSize < multiplier) {
1331 // Show the size in bytes
1332 text = locale->formatByteSize(fileSize, 0, KLocale::DefaultBinaryDialect, KLocale::UnitByte);
1333 } else if (fileSize < multiplier * multiplier) {
1334 // Show the size in kilobytes and always round up. This is done
1335 // for consistency with the values shown e.g. in the "Size" column
1336 // of the details-view.
1337 fileSize += (multiplier / 2) - 1;
1338 text = locale->formatByteSize(fileSize, 0, KLocale::DefaultBinaryDialect, KLocale::UnitKiloByte);
1339 } else {
1340 // Show the size in the best fitting unit having one decimal
1341 text = locale->formatByteSize(fileSize, 1);
1342 }
1343 return text;
1344 }
1345
1346 #include "dolphinview.moc"