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