]> cloud.milkyroute.net Git - dolphin.git/blob - src/views/dolphinview.cpp
SVN_SILENT made messages (.desktop file)
[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(itemHovered(int)), this, SLOT(slotItemHovered(int)));
145 connect(controller, SIGNAL(itemUnhovered(int)), this, SLOT(slotItemUnhovered(int)));
146 connect(controller, SIGNAL(itemDropEvent(int,QGraphicsSceneDragDropEvent*)), this, SLOT(slotItemDropEvent(int,QGraphicsSceneDragDropEvent*)));
147 connect(controller, SIGNAL(modelChanged(KItemModelBase*,KItemModelBase*)), this, SLOT(slotModelChanged(KItemModelBase*,KItemModelBase*)));
148
149 KFileItemModel* model = fileItemModel();
150 if (model) {
151 connect(model, SIGNAL(loadingCompleted()), this, SLOT(slotLoadingCompleted()));
152 }
153
154 KItemListSelectionManager* selectionManager = controller->selectionManager();
155 connect(selectionManager, SIGNAL(selectionChanged(QSet<int>,QSet<int>)),
156 this, SLOT(slotSelectionChanged(QSet<int>,QSet<int>)));
157
158 m_toolTipManager = new ToolTipManager(this);
159
160 m_versionControlObserver = new VersionControlObserver(this);
161 m_versionControlObserver->setModel(model);
162 connect(m_versionControlObserver, SIGNAL(infoMessage(QString)), this, SIGNAL(infoMessage(QString)));
163 connect(m_versionControlObserver, SIGNAL(errorMessage(QString)), this, SIGNAL(errorMessage(QString)));
164 connect(m_versionControlObserver, SIGNAL(operationCompletedMessage(QString)), this, SIGNAL(operationCompletedMessage(QString)));
165
166 applyViewProperties();
167 m_topLayout->addWidget(m_container);
168
169 loadDirectory(url);
170 }
171
172 DolphinView::~DolphinView()
173 {
174 }
175
176 KUrl DolphinView::url() const
177 {
178 return m_url;
179 }
180
181 void DolphinView::setActive(bool active)
182 {
183 if (active == m_active) {
184 return;
185 }
186
187 m_active = active;
188
189 QColor color = KColorScheme(QPalette::Active, KColorScheme::View).background().color();
190 if (!active) {
191 color.setAlpha(150);
192 }
193
194 QWidget* viewport = m_container->viewport();
195 if (viewport) {
196 QPalette palette;
197 palette.setColor(viewport->backgroundRole(), color);
198 viewport->setPalette(palette);
199 }
200
201 update();
202
203 if (active) {
204 m_container->setFocus();
205 emit activated();
206 emit writeStateChanged(m_isFolderWritable);
207 }
208 }
209
210 bool DolphinView::isActive() const
211 {
212 return m_active;
213 }
214
215 void DolphinView::setMode(Mode mode)
216 {
217 if (mode != m_mode) {
218 ViewProperties props(url());
219 props.setViewMode(mode);
220 props.save();
221
222 applyViewProperties();
223 }
224 }
225
226 DolphinView::Mode DolphinView::mode() const
227 {
228 return m_mode;
229 }
230
231 void DolphinView::setPreviewsShown(bool show)
232 {
233 if (previewsShown() == show) {
234 return;
235 }
236
237 ViewProperties props(url());
238 props.setPreviewsShown(show);
239
240 m_container->setPreviewsShown(show);
241 emit previewsShownChanged(show);
242 }
243
244 bool DolphinView::previewsShown() const
245 {
246 return m_container->previewsShown();
247 }
248
249 void DolphinView::setHiddenFilesShown(bool show)
250 {
251 if (m_dirLister->showingDotFiles() == show) {
252 return;
253 }
254
255 const KFileItemList itemList = selectedItems();
256 m_selectedUrls.clear();
257 m_selectedUrls = itemList.urlList();
258
259 ViewProperties props(url());
260 props.setHiddenFilesShown(show);
261
262 m_dirLister->setShowingDotFiles(show);
263 m_dirLister->emitChanges();
264 emit hiddenFilesShownChanged(show);
265 }
266
267 bool DolphinView::hiddenFilesShown() const
268 {
269 return m_dirLister->showingDotFiles();
270 }
271
272 void DolphinView::setGroupedSorting(bool grouped)
273 {
274 if (grouped == groupedSorting()) {
275 return;
276 }
277
278 ViewProperties props(url());
279 props.setGroupedSorting(grouped);
280 props.save();
281
282 m_container->controller()->model()->setGroupedSorting(grouped);
283
284 emit groupedSortingChanged(grouped);
285 }
286
287 bool DolphinView::groupedSorting() const
288 {
289 return fileItemModel()->groupedSorting();
290 }
291
292 KFileItemList DolphinView::items() const
293 {
294 return m_dirLister->items();
295 }
296
297 KFileItemList DolphinView::selectedItems() const
298 {
299 const KFileItemModel* model = fileItemModel();
300 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
301 const QSet<int> selectedIndexes = selectionManager->selectedItems();
302
303 QList<int> sortedIndexes = selectedIndexes.toList();
304 qSort(sortedIndexes);
305
306 KFileItemList selectedItems;
307 QListIterator<int> it(sortedIndexes);
308 while (it.hasNext()) {
309 const int index = it.next();
310 selectedItems.append(model->fileItem(index));
311 }
312 return selectedItems;
313 }
314
315 int DolphinView::selectedItemsCount() const
316 {
317 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
318 return selectionManager->selectedItems().count();
319 }
320
321 void DolphinView::markUrlsAsSelected(const QList<KUrl>& urls)
322 {
323 m_selectedUrls = urls;
324 }
325
326 void DolphinView::markUrlAsCurrent(const KUrl& url)
327 {
328 m_currentItemUrl = url;
329 }
330
331 void DolphinView::setItemSelectionEnabled(const QRegExp& pattern, bool enabled)
332 {
333 const KItemListSelectionManager::SelectionMode mode = enabled
334 ? KItemListSelectionManager::Select
335 : KItemListSelectionManager::Deselect;
336 const KFileItemModel* model = fileItemModel();
337 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
338
339 for (int index = 0; index < model->count(); index++) {
340 const KFileItem item = model->fileItem(index);
341 if (pattern.exactMatch(item.text())) {
342 // An alternative approach would be to store the matching items in a QSet<int> and
343 // select them in one go after the loop, but we'd need a new function
344 // KItemListSelectionManager::setSelected(QSet<int>, SelectionMode mode)
345 // for that.
346 selectionManager->setSelected(index, 1, mode);
347 }
348 }
349 }
350
351 void DolphinView::setZoomLevel(int level)
352 {
353 const int oldZoomLevel = zoomLevel();
354 m_container->setZoomLevel(level);
355 if (zoomLevel() != oldZoomLevel) {
356 emit zoomLevelChanged(zoomLevel(), oldZoomLevel);
357 }
358 }
359
360 int DolphinView::zoomLevel() const
361 {
362 return m_container->zoomLevel();
363 }
364
365 void DolphinView::setSorting(Sorting sorting)
366 {
367 if (sorting != this->sorting()) {
368 updateSorting(sorting);
369 }
370 }
371
372 DolphinView::Sorting DolphinView::sorting() const
373 {
374 KItemModelBase* model = m_container->controller()->model();
375 return sortingForSortRole(model->sortRole());
376 }
377
378 void DolphinView::setSortOrder(Qt::SortOrder order)
379 {
380 if (sortOrder() != order) {
381 updateSortOrder(order);
382 }
383 }
384
385 Qt::SortOrder DolphinView::sortOrder() const
386 {
387 KItemModelBase* model = fileItemModel();
388 return model->sortOrder();
389 }
390
391 void DolphinView::setSortFoldersFirst(bool foldersFirst)
392 {
393 if (sortFoldersFirst() != foldersFirst) {
394 updateSortFoldersFirst(foldersFirst);
395 }
396 }
397
398 bool DolphinView::sortFoldersFirst() const
399 {
400 KFileItemModel* model = fileItemModel();
401 return model->sortFoldersFirst();
402 }
403
404 void DolphinView::setAdditionalInfoList(const QList<AdditionalInfo>& info)
405 {
406 const QList<AdditionalInfo> previousList = info;
407
408 ViewProperties props(url());
409 props.setAdditionalInfoList(info);
410
411 m_additionalInfoList = info;
412 applyAdditionalInfoListToView();
413
414 emit additionalInfoListChanged(m_additionalInfoList, previousList);
415 }
416
417 QList<DolphinView::AdditionalInfo> DolphinView::additionalInfoList() const
418 {
419 return m_additionalInfoList;
420 }
421
422 void DolphinView::reload()
423 {
424 QByteArray viewState;
425 QDataStream saveStream(&viewState, QIODevice::WriteOnly);
426 saveState(saveStream);
427
428 const KFileItemList itemList = selectedItems();
429 m_selectedUrls.clear();
430 m_selectedUrls = itemList.urlList();
431
432 setUrl(url());
433 loadDirectory(url(), true);
434
435 QDataStream restoreStream(viewState);
436 restoreState(restoreStream);
437 }
438
439 void DolphinView::stopLoading()
440 {
441 m_dirLister->stop();
442 }
443
444 void DolphinView::refresh()
445 {
446 const bool oldActivationState = m_active;
447 const int oldZoomLevel = zoomLevel();
448 m_active = true;
449
450 applyViewProperties();
451 reload();
452
453 setActive(oldActivationState);
454 updateZoomLevel(oldZoomLevel);
455 }
456
457 void DolphinView::setNameFilter(const QString& nameFilter)
458 {
459 Q_UNUSED(nameFilter);
460 //m_viewModeController->setNameFilter(nameFilter);
461 }
462
463 QString DolphinView::nameFilter() const
464 {
465 return QString(); //m_viewModeController->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 Q_UNUSED(index);
696
697 const KFileItemList items = selectedItems();
698 if (items.isEmpty()) {
699 return;
700 }
701
702 if (items.count() == 1) {
703 emit itemActivated(items.at(0)); // caught by DolphinViewContainer or DolphinPart
704 } else {
705 foreach (const KFileItem& item, items) {
706 if (item.isDir()) {
707 emit tabRequested(item.url());
708 } else {
709 emit itemActivated(item);
710 }
711 }
712 }
713 }
714
715 void DolphinView::slotItemMiddleClicked(int index)
716 {
717 const KFileItem item = fileItemModel()->fileItem(index);
718 if (item.isDir() || isTabsForFilesEnabled()) {
719 emit tabRequested(item.url());
720 }
721 }
722
723 void DolphinView::slotItemContextMenuRequested(int index, const QPointF& pos)
724 {
725 if (GeneralSettings::showToolTips()) {
726 m_toolTipManager->hideToolTip();
727 }
728 const KFileItem item = fileItemModel()->fileItem(index);
729 emit requestContextMenu(pos.toPoint(), item, url(), QList<QAction*>());
730 }
731
732 void DolphinView::slotViewContextMenuRequested(const QPointF& pos)
733 {
734 if (GeneralSettings::showToolTips()) {
735 m_toolTipManager->hideToolTip();
736 }
737 emit requestContextMenu(pos.toPoint(), KFileItem(), url(), QList<QAction*>());
738 }
739
740 void DolphinView::slotHeaderContextMenuRequested(const QPointF& pos)
741 {
742 QWeakPointer<KMenu> menu = new KMenu(QApplication::activeWindow());
743
744 KItemListView* view = m_container->controller()->view();
745 const QSet<QByteArray> visibleRolesSet = view->visibleRoles().toSet();
746
747 // Add all roles to the menu that can be shown or hidden by the user
748 const AdditionalInfoAccessor& infoAccessor = AdditionalInfoAccessor::instance();
749 const QList<DolphinView::AdditionalInfo> keys = infoAccessor.keys();
750 foreach (const DolphinView::AdditionalInfo info, keys) {
751 const QByteArray& role = infoAccessor.role(info);
752 if (role != "name") {
753 const QString text = fileItemModel()->roleDescription(role);
754
755 QAction* action = menu.data()->addAction(text);
756 action->setCheckable(true);
757 action->setChecked(visibleRolesSet.contains(role));
758 action->setData(info);
759 }
760 }
761
762 QAction* action = menu.data()->exec(pos.toPoint());
763 if (action) {
764 // Show or hide the selected role
765 const DolphinView::AdditionalInfo info =
766 static_cast<DolphinView::AdditionalInfo>(action->data().toInt());
767
768 ViewProperties props(url());
769 QList<DolphinView::AdditionalInfo> infoList = props.additionalInfoList();
770
771 const QByteArray selectedRole = infoAccessor.role(info);
772 QList<QByteArray> visibleRoles = view->visibleRoles();
773
774 if (action->isChecked()) {
775 const int index = keys.indexOf(info) + 1;
776 visibleRoles.insert(index, selectedRole);
777 infoList.insert(index, info);
778 } else {
779 visibleRoles.removeOne(selectedRole);
780 infoList.removeOne(info);
781 }
782
783 view->setVisibleRoles(visibleRoles);
784 props.setAdditionalInfoList(infoList);
785 }
786
787 delete menu.data();
788 }
789
790 void DolphinView::slotItemHovered(int index)
791 {
792 const KFileItem item = fileItemModel()->fileItem(index);
793
794 if (GeneralSettings::showToolTips()) {
795 QRectF itemRect = m_container->controller()->view()->itemRect(index);
796 const QPoint pos = m_container->mapToGlobal(itemRect.topLeft().toPoint());
797 itemRect.moveTo(pos);
798
799 m_toolTipManager->showToolTip(item, itemRect);
800 }
801
802 emit requestItemInfo(item);
803 }
804
805 void DolphinView::slotItemUnhovered(int index)
806 {
807 Q_UNUSED(index);
808 if (GeneralSettings::showToolTips()) {
809 m_toolTipManager->hideToolTip();
810 }
811 emit requestItemInfo(KFileItem());
812 }
813
814 void DolphinView::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* event)
815 {
816 const KFileItem destItem = fileItemModel()->fileItem(index);
817
818 QDropEvent dropEvent(event->pos().toPoint(),
819 event->possibleActions(),
820 event->mimeData(),
821 event->buttons(),
822 event->modifiers());
823
824 DragAndDropHelper::dropUrls(destItem, url(), &dropEvent, this);
825 }
826
827 void DolphinView::slotModelChanged(KItemModelBase* current, KItemModelBase* previous)
828 {
829 if (previous != 0) {
830 disconnect(previous, SIGNAL(loadingCompleted()), this, SLOT(slotLoadingCompleted()));
831 }
832
833 Q_ASSERT(qobject_cast<KFileItemModel*>(current));
834 connect(current, SIGNAL(loadingCompleted()), this, SLOT(slotLoadingCompleted()));
835
836 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(current);
837 m_versionControlObserver->setModel(fileItemModel);
838 }
839
840 void DolphinView::slotSelectionChanged(const QSet<int>& current, const QSet<int>& previous)
841 {
842 const int currentCount = current.count();
843 const int previousCount = previous.count();
844 const bool selectionStateChanged = (currentCount == 0 && previousCount > 0) ||
845 (currentCount > 0 && previousCount == 0);
846
847 // If nothing has been selected before and something got selected (or if something
848 // was selected before and now nothing is selected) the selectionChangedSignal must
849 // be emitted asynchronously as fast as possible to update the edit-actions.
850 m_selectionChangedTimer->setInterval(selectionStateChanged ? 0 : 300);
851 m_selectionChangedTimer->start();
852 }
853
854 void DolphinView::emitSelectionChangedSignal()
855 {
856 m_selectionChangedTimer->stop();
857 emit selectionChanged(selectedItems());
858 }
859
860 void DolphinView::dropUrls(const KFileItem& destItem,
861 const KUrl& destPath,
862 QDropEvent* event)
863 {
864 Q_UNUSED(destItem);
865 Q_UNUSED(destPath);
866 markPastedUrlsAsSelected(event->mimeData());
867 //DragAndDropHelper::instance().dropUrls(destItem, destPath, event, this);
868 }
869
870 void DolphinView::updateSorting(DolphinView::Sorting sorting)
871 {
872 ViewProperties props(url());
873 props.setSorting(sorting);
874
875 KItemModelBase* model = m_container->controller()->model();
876 model->setSortRole(sortRoleForSorting(sorting));
877
878 emit sortingChanged(sorting);
879 }
880
881 void DolphinView::updateSortOrder(Qt::SortOrder order)
882 {
883 ViewProperties props(url());
884 props.setSortOrder(order);
885
886 KItemModelBase* model = fileItemModel();
887 model->setSortOrder(order);
888
889 emit sortOrderChanged(order);
890 }
891
892 void DolphinView::updateSortFoldersFirst(bool foldersFirst)
893 {
894 ViewProperties props(url());
895 props.setSortFoldersFirst(foldersFirst);
896
897 KFileItemModel* model = fileItemModel();
898 model->setSortFoldersFirst(foldersFirst);
899
900 emit sortFoldersFirstChanged(foldersFirst);
901 }
902
903 QPair<bool, QString> DolphinView::pasteInfo() const
904 {
905 return KonqOperations::pasteInfo(url());
906 }
907
908 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles)
909 {
910 m_tabsForFiles = tabsForFiles;
911 }
912
913 bool DolphinView::isTabsForFilesEnabled() const
914 {
915 return m_tabsForFiles;
916 }
917
918 bool DolphinView::itemsExpandable() const
919 {
920 return m_mode == DetailsView;
921 }
922
923 void DolphinView::restoreState(QDataStream& stream)
924 {
925 // Restore the current item that had the keyboard focus
926 stream >> m_currentItemUrl;
927
928 // Restore the view position
929 stream >> m_restoredContentsPosition;
930
931 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
932 QSet<KUrl> urls;
933 stream >> urls;
934 fileItemModel()->restoreExpandedUrls(urls);
935 }
936
937 void DolphinView::saveState(QDataStream& stream)
938 {
939 // Save the current item that has the keyboard focus
940 const int currentIndex = m_container->controller()->selectionManager()->currentItem();
941 if (currentIndex != -1) {
942 KFileItem item = fileItemModel()->fileItem(currentIndex);
943 KUrl currentItemUrl = item.url();
944 stream << currentItemUrl;
945 } else {
946 stream << KUrl();
947 }
948
949 // Save view position
950 const qreal x = m_container->horizontalScrollBar()->value();
951 const qreal y = m_container->verticalScrollBar()->value();
952 stream << QPoint(x, y);
953
954 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
955 stream << fileItemModel()->expandedUrls();
956 }
957
958 bool DolphinView::hasSelection() const
959 {
960 return m_container->controller()->selectionManager()->hasSelection();
961 }
962
963 KFileItem DolphinView::rootItem() const
964 {
965 return m_dirLister->rootItem();
966 }
967
968 void DolphinView::observeCreatedItem(const KUrl& url)
969 {
970 m_createdItemUrl = url;
971 //connect(m_dirModel, SIGNAL(rowsInserted(QModelIndex,int,int)),
972 // this, SLOT(selectAndScrollToCreatedItem()));
973 }
974
975 void DolphinView::selectAndScrollToCreatedItem()
976 {
977 /*const QModelIndex dirIndex = m_viewAccessor.dirModel()->indexForUrl(m_createdItemUrl);
978 if (dirIndex.isValid()) {
979 const QModelIndex proxyIndex = m_viewAccessor.proxyModel()->mapFromSource(dirIndex);
980 QAbstractItemView* view = m_viewAccessor.itemView();
981 if (view) {
982 view->setCurrentIndex(proxyIndex);
983 }
984 }
985
986 disconnect(m_viewAccessor.dirModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
987 this, SLOT(selectAndScrollToCreatedItem()));*/
988 m_createdItemUrl = KUrl();
989 }
990
991 void DolphinView::slotRedirection(const KUrl& oldUrl, const KUrl& newUrl)
992 {
993 if (oldUrl.equals(url(), KUrl::CompareWithoutTrailingSlash)) {
994 emit redirection(oldUrl, newUrl);
995 m_url = newUrl; // #186947
996 }
997 }
998
999 void DolphinView::updateViewState()
1000 {
1001 if (m_currentItemUrl != KUrl()) {
1002 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1003 const int currentIndex = fileItemModel()->index(m_currentItemUrl);
1004 if (currentIndex != -1) {
1005 selectionManager->setCurrentItem(currentIndex);
1006 } else {
1007 selectionManager->setCurrentItem(0);
1008 }
1009 m_currentItemUrl = KUrl();
1010 }
1011
1012 if (!m_restoredContentsPosition.isNull()) {
1013 const int x = m_restoredContentsPosition.x();
1014 const int y = m_restoredContentsPosition.y();
1015 m_restoredContentsPosition = QPoint();
1016
1017 m_container->horizontalScrollBar()->setValue(x);
1018 m_container->verticalScrollBar()->setValue(y);
1019 }
1020
1021 if (!m_selectedUrls.isEmpty()) {
1022 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1023 QSet<int> selectedItems = selectionManager->selectedItems();
1024 const KFileItemModel* model = fileItemModel();
1025
1026 foreach (const KUrl& url, m_selectedUrls) {
1027 const int index = model->index(url);
1028 if (index >= 0) {
1029 selectedItems.insert(index);
1030 }
1031 }
1032
1033 selectionManager->setSelectedItems(selectedItems);
1034 m_selectedUrls.clear();
1035 }
1036 }
1037
1038 void DolphinView::showHoverInformation(const KFileItem& item)
1039 {
1040 emit requestItemInfo(item);
1041 }
1042
1043 void DolphinView::clearHoverInformation()
1044 {
1045 emit requestItemInfo(KFileItem());
1046 }
1047
1048 void DolphinView::slotDeleteFileFinished(KJob* job)
1049 {
1050 if (job->error() == 0) {
1051 emit operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1052 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1053 emit errorMessage(job->errorString());
1054 }
1055 }
1056
1057 void DolphinView::slotDirListerStarted(const KUrl& url)
1058 {
1059 // Disable the writestate temporary until it can be determined in a fast way
1060 // in DolphinView::slotLoadingCompleted()
1061 if (m_isFolderWritable) {
1062 m_isFolderWritable = false;
1063 emit writeStateChanged(m_isFolderWritable);
1064 }
1065
1066 emit startedPathLoading(url);
1067 }
1068
1069 void DolphinView::slotLoadingCompleted()
1070 {
1071 // Update the view-state. This has to be done using a Qt::QueuedConnection
1072 // because the view might not be in its final state yet (the view also
1073 // listens to the completed()-signal from KDirLister and the order of
1074 // of slots is undefined).
1075 QTimer::singleShot(0, this, SLOT(updateViewState()));
1076
1077 emit finishedPathLoading(url());
1078
1079 updateWritableState();
1080 }
1081
1082 void DolphinView::slotRefreshItems()
1083 {
1084 if (m_assureVisibleCurrentIndex) {
1085 m_assureVisibleCurrentIndex = false;
1086 //QAbstractItemView* view = m_viewAccessor.itemView();
1087 //if (view) {
1088 // m_viewAccessor.itemView()->scrollTo(m_viewAccessor.itemView()->currentIndex());
1089 //}
1090 }
1091 }
1092
1093 KFileItemModel* DolphinView::fileItemModel() const
1094 {
1095 return static_cast<KFileItemModel*>(m_container->controller()->model());
1096 }
1097
1098 void DolphinView::loadDirectory(const KUrl& url, bool reload)
1099 {
1100 if (!url.isValid()) {
1101 const QString location(url.pathOrUrl());
1102 if (location.isEmpty()) {
1103 emit errorMessage(i18nc("@info:status", "The location is empty."));
1104 } else {
1105 emit errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location));
1106 }
1107 return;
1108 }
1109
1110 m_dirLister->openUrl(url, reload ? KDirLister::Reload : KDirLister::NoFlags);
1111 }
1112
1113 void DolphinView::applyViewProperties()
1114 {
1115 m_container->beginTransaction();
1116
1117 const ViewProperties props(url());
1118
1119 const Mode mode = props.viewMode();
1120 if (m_mode != mode) {
1121 const Mode previousMode = m_mode;
1122 m_mode = mode;
1123
1124 // Changing the mode might result in changing
1125 // the zoom level. Remember the old zoom level so
1126 // that zoomLevelChanged() can get emitted.
1127 const int oldZoomLevel = m_container->zoomLevel();
1128
1129 switch (m_mode) {
1130 case IconsView: m_container->setItemLayout(KFileItemListView::IconsLayout); break;
1131 case CompactView: m_container->setItemLayout(KFileItemListView::CompactLayout); break;
1132 case DetailsView: m_container->setItemLayout(KFileItemListView::DetailsLayout); break;
1133 default: Q_ASSERT(false); break;
1134 }
1135
1136 emit modeChanged(m_mode, previousMode);
1137
1138 if (m_container->zoomLevel() != oldZoomLevel) {
1139 emit zoomLevelChanged(m_container->zoomLevel(), oldZoomLevel);
1140 }
1141 }
1142
1143 const bool hiddenFilesShown = props.hiddenFilesShown();
1144 if (hiddenFilesShown != m_dirLister->showingDotFiles()) {
1145 m_dirLister->setShowingDotFiles(hiddenFilesShown);
1146 m_dirLister->emitChanges();
1147 emit hiddenFilesShownChanged(hiddenFilesShown);
1148 }
1149
1150 KFileItemModel* model = fileItemModel();
1151
1152 const bool groupedSorting = props.groupedSorting();
1153 if (groupedSorting != model->groupedSorting()) {
1154 model->setGroupedSorting(groupedSorting);
1155 emit groupedSortingChanged(groupedSorting);
1156 }
1157
1158 const DolphinView::Sorting sorting = props.sorting();
1159 const QByteArray newSortRole = sortRoleForSorting(sorting);
1160 if (newSortRole != model->sortRole()) {
1161 model->setSortRole(newSortRole);
1162 emit sortingChanged(sorting);
1163 }
1164
1165 const Qt::SortOrder sortOrder = props.sortOrder();
1166 if (sortOrder != model->sortOrder()) {
1167 model->setSortOrder(sortOrder);
1168 emit sortOrderChanged(sortOrder);
1169 }
1170
1171 const bool sortFoldersFirst = props.sortFoldersFirst();
1172 if (sortFoldersFirst != model->sortFoldersFirst()) {
1173 model->setSortFoldersFirst(sortFoldersFirst);
1174 emit sortFoldersFirstChanged(sortFoldersFirst);
1175 }
1176
1177 const QList<DolphinView::AdditionalInfo> infoList = props.additionalInfoList();
1178 if (infoList != m_additionalInfoList) {
1179 const QList<DolphinView::AdditionalInfo> previousList = m_additionalInfoList;
1180 m_additionalInfoList = infoList;
1181 applyAdditionalInfoListToView();
1182 emit additionalInfoListChanged(m_additionalInfoList, previousList);
1183 }
1184
1185 const bool previewsShown = props.previewsShown();
1186 if (previewsShown != m_container->previewsShown()) {
1187 const int oldZoomLevel = zoomLevel();
1188
1189 m_container->setPreviewsShown(previewsShown);
1190 emit previewsShownChanged(previewsShown);
1191
1192 // Changing the preview-state might result in a changed zoom-level
1193 if (oldZoomLevel != zoomLevel()) {
1194 emit zoomLevelChanged(zoomLevel(), oldZoomLevel);
1195 }
1196 }
1197
1198 m_container->endTransaction();
1199 }
1200
1201 void DolphinView::applyAdditionalInfoListToView()
1202 {
1203 const AdditionalInfoAccessor& infoAccessor = AdditionalInfoAccessor::instance();
1204
1205 QList<QByteArray> visibleRoles;
1206 visibleRoles.reserve(m_additionalInfoList.count() + 1);
1207 visibleRoles.append("name");
1208
1209 foreach (AdditionalInfo info, m_additionalInfoList) {
1210 visibleRoles.append(infoAccessor.role(info));
1211 }
1212
1213 m_container->setVisibleRoles(visibleRoles);
1214 }
1215
1216 void DolphinView::pasteToUrl(const KUrl& url)
1217 {
1218 markPastedUrlsAsSelected(QApplication::clipboard()->mimeData());
1219 KonqOperations::doPaste(this, url);
1220 }
1221
1222 void DolphinView::updateZoomLevel(int oldZoomLevel)
1223 {
1224 Q_UNUSED(oldZoomLevel);
1225 /* const int newZoomLevel = ZoomLevelInfo::zoomLevelForIconSize(m_viewAccessor.itemView()->iconSize());
1226 if (oldZoomLevel != newZoomLevel) {
1227 m_viewModeController->setZoomLevel(newZoomLevel);
1228 emit zoomLevelChanged(newZoomLevel);
1229 }*/
1230 }
1231
1232 KUrl::List DolphinView::simplifiedSelectedUrls() const
1233 {
1234 KUrl::List urls;
1235
1236 const KFileItemList items = selectedItems();
1237 foreach (const KFileItem &item, items) {
1238 urls.append(item.url());
1239 }
1240
1241 if (itemsExpandable()) {
1242 // TODO: Check if we still need KDirModel for this in KDE 5.0
1243 urls = KDirModel::simplifiedUrlList(urls);
1244 }
1245
1246 return urls;
1247 }
1248
1249 QMimeData* DolphinView::selectionMimeData() const
1250 {
1251 const KFileItemModel* model = fileItemModel();
1252 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1253 const QSet<int> selectedIndexes = selectionManager->selectedItems();
1254
1255 return model->createMimeData(selectedIndexes);
1256 }
1257
1258 void DolphinView::markPastedUrlsAsSelected(const QMimeData* mimeData)
1259 {
1260 const KUrl::List urls = KUrl::List::fromMimeData(mimeData);
1261 markUrlsAsSelected(urls);
1262 }
1263
1264 void DolphinView::updateWritableState()
1265 {
1266 const bool wasFolderWritable = m_isFolderWritable;
1267 m_isFolderWritable = true;
1268
1269 const KFileItem item = m_dirLister->rootItem();
1270 if (!item.isNull()) {
1271 KFileItemListProperties capabilities(KFileItemList() << item);
1272 m_isFolderWritable = capabilities.supportsWriting();
1273 }
1274 if (m_isFolderWritable != wasFolderWritable) {
1275 emit writeStateChanged(m_isFolderWritable);
1276 }
1277 }
1278
1279 QByteArray DolphinView::sortRoleForSorting(Sorting sorting) const
1280 {
1281 switch (sorting) {
1282 case SortByName: return "name";
1283 case SortBySize: return "size";
1284 case SortByDate: return "date";
1285 case SortByPermissions: return "permissions";
1286 case SortByOwner: return "owner";
1287 case SortByGroup: return "group";
1288 case SortByType: return "type";
1289 case SortByDestination: return "destination";
1290 case SortByPath: return "path";
1291 default: break;
1292 }
1293
1294 return QByteArray();
1295 }
1296
1297 DolphinView::Sorting DolphinView::sortingForSortRole(const QByteArray& sortRole) const
1298 {
1299 static QHash<QByteArray, DolphinView::Sorting> sortHash;
1300 if (sortHash.isEmpty()) {
1301 sortHash.insert("name", SortByName);
1302 sortHash.insert("size", SortBySize);
1303 sortHash.insert("date", SortByDate);
1304 sortHash.insert("permissions", SortByPermissions);
1305 sortHash.insert("owner", SortByOwner);
1306 sortHash.insert("group", SortByGroup);
1307 sortHash.insert("type", SortByType);
1308 sortHash.insert("destination", SortByDestination);
1309 sortHash.insert("path", SortByPath);
1310 }
1311 return sortHash.value(sortRole);
1312 }
1313
1314 QString DolphinView::fileSizeText(KIO::filesize_t fileSize)
1315 {
1316 const KLocale* locale = KGlobal::locale();
1317 const unsigned int multiplier = (locale->binaryUnitDialect() == KLocale::MetricBinaryDialect)
1318 ? 1000 : 1024;
1319
1320 QString text;
1321 if (fileSize < multiplier) {
1322 // Show the size in bytes
1323 text = locale->formatByteSize(fileSize, 0, KLocale::DefaultBinaryDialect, KLocale::UnitByte);
1324 } else if (fileSize < multiplier * multiplier) {
1325 // Show the size in kilobytes and always round up. This is done
1326 // for consistency with the values shown e.g. in the "Size" column
1327 // of the details-view.
1328 fileSize += (multiplier / 2) - 1;
1329 text = locale->formatByteSize(fileSize, 0, KLocale::DefaultBinaryDialect, KLocale::UnitKiloByte);
1330 } else {
1331 // Show the size in the best fitting unit having one decimal
1332 text = locale->formatByteSize(fileSize, 1);
1333 }
1334 return text;
1335 }
1336
1337 #include "dolphinview.moc"