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