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