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