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