]> cloud.milkyroute.net Git - dolphin.git/blob - src/views/dolphinview.cpp
Context menu cleanups
[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 "settings/dolphinsettings.h"
68 #include "versioncontrol/versioncontrolobserver.h"
69 #include "viewmodecontroller.h"
70 #include "viewproperties.h"
71 #include "views/tooltips/tooltipmanager.h"
72 #include "zoomlevelinfo.h"
73
74 namespace {
75 const int MaxModeEnum = DolphinView::CompactView;
76 const int MaxSortingEnum = DolphinView::SortByPath;
77 };
78
79 DolphinView::DolphinView(const KUrl& url, QWidget* parent) :
80 QWidget(parent),
81 m_active(true),
82 m_tabsForFiles(false),
83 m_assureVisibleCurrentIndex(false),
84 m_isFolderWritable(true),
85 m_url(url),
86 m_mode(DolphinView::IconsView),
87 m_additionalInfoList(),
88 m_topLayout(0),
89 m_dirLister(0),
90 m_container(0),
91 m_toolTipManager(0),
92 m_selectionChangedTimer(0),
93 m_currentItemUrl(),
94 m_restoredContentsPosition(),
95 m_createdItemUrl(),
96 m_selectedUrls(),
97 m_versionControlObserver(0)
98 {
99 m_topLayout = new QVBoxLayout(this);
100 m_topLayout->setSpacing(0);
101 m_topLayout->setMargin(0);
102
103 //m_dolphinViewController = new DolphinViewController(this);
104
105 //m_viewModeController = new ViewModeController(this);
106 //m_viewModeController->setUrl(url);
107
108 /*connect(m_viewModeController, SIGNAL(urlChanged(KUrl)),
109 this, SIGNAL(urlChanged(KUrl)));
110
111 connect(m_dolphinViewController, SIGNAL(requestContextMenu(QPoint,QList<QAction*>)),
112 this, SLOT(openContextMenu(QPoint,QList<QAction*>)));
113 connect(m_dolphinViewController, SIGNAL(urlsDropped(KFileItem,KUrl,QDropEvent*)),
114 this, SLOT(dropUrls(KFileItem,KUrl,QDropEvent*)));
115 connect(m_dolphinViewController, SIGNAL(sortingChanged(DolphinView::Sorting)),
116 this, SLOT(updateSorting(DolphinView::Sorting)));
117 connect(m_dolphinViewController, SIGNAL(sortOrderChanged(Qt::SortOrder)),
118 this, SLOT(updateSortOrder(Qt::SortOrder)));
119 connect(m_dolphinViewController, SIGNAL(sortFoldersFirstChanged(bool)),
120 this, SLOT(updateSortFoldersFirst(bool)));
121 connect(m_dolphinViewController, SIGNAL(additionalInfoChanged(QList<DolphinView::AdditionalInfo>)),
122 this, SLOT(updateAdditionalInfo(QList<DolphinView::AdditionalInfo>)));*/
123 //connect(m_dolphinViewController, SIGNAL(itemActivated(KFileItem)),
124 // this, SLOT(triggerItem(KFileItem)));
125 //connect(m_dolphinViewController, SIGNAL(tabRequested(KUrl)),
126 // this, SIGNAL(tabRequested(KUrl)));
127 /*connect(m_dolphinViewController, SIGNAL(activated()),
128 this, SLOT(activate()));
129 connect(m_dolphinViewController, SIGNAL(itemEntered(KFileItem)),
130 this, SLOT(showHoverInformation(KFileItem)));
131 connect(m_dolphinViewController, SIGNAL(viewportEntered()),
132 this, SLOT(clearHoverInformation()));
133 connect(m_dolphinViewController, SIGNAL(urlChangeRequested(KUrl)),
134 this, SLOT(slotUrlChangeRequested(KUrl)));*/
135
136 // When a new item has been created by the "Create New..." menu, the item should
137 // get selected and it must be assured that the item will get visible. As the
138 // creation is done asynchronously, several signals must be checked:
139 connect(&DolphinNewFileMenuObserver::instance(), SIGNAL(itemCreated(KUrl)),
140 this, SLOT(observeCreatedItem(KUrl)));
141
142 m_selectionChangedTimer = new QTimer(this);
143 m_selectionChangedTimer->setSingleShot(true);
144 m_selectionChangedTimer->setInterval(300);
145 connect(m_selectionChangedTimer, SIGNAL(timeout()),
146 this, SLOT(emitSelectionChangedSignal()));
147
148 m_dirLister = new DolphinDirLister(this);
149 m_dirLister->setAutoUpdate(true);
150 m_dirLister->setDelayedMimeTypes(true);
151
152 connect(m_dirLister, SIGNAL(redirection(KUrl,KUrl)), this, SLOT(slotRedirection(KUrl,KUrl)));
153 connect(m_dirLister, SIGNAL(started(KUrl)), this, SLOT(slotDirListerStarted(KUrl)));
154 connect(m_dirLister, SIGNAL(refreshItems(QList<QPair<KFileItem,KFileItem> >)),
155 this, SLOT(slotRefreshItems()));
156
157 connect(m_dirLister, SIGNAL(clear()), this, SIGNAL(itemCountChanged()));
158 connect(m_dirLister, SIGNAL(newItems(KFileItemList)), this, SIGNAL(itemCountChanged()));
159 connect(m_dirLister, SIGNAL(infoMessage(QString)), this, SIGNAL(infoMessage(QString)));
160 connect(m_dirLister, SIGNAL(errorMessage(QString)), this, SIGNAL(infoMessage(QString)));
161 connect(m_dirLister, SIGNAL(percent(int)), this, SIGNAL(pathLoadingProgress(int)));
162 connect(m_dirLister, SIGNAL(urlIsFileError(KUrl)), this, SIGNAL(urlIsFileError(KUrl)));
163 connect(m_dirLister, SIGNAL(itemsDeleted(KFileItemList)), this, SIGNAL(itemCountChanged()));
164
165 m_container = new DolphinItemListContainer(m_dirLister, this);
166 m_container->setVisibleRoles(QList<QByteArray>() << "name");
167
168 KItemListController* controller = m_container->controller();
169 controller->setSelectionBehavior(KItemListController::MultiSelection);
170 connect(controller, SIGNAL(itemActivated(int)),
171 this, SLOT(slotItemActivated(int)));
172 connect(controller, SIGNAL(itemMiddleClicked(int)), this, SLOT(slotItemMiddleClicked(int)));
173 connect(controller, SIGNAL(itemContextMenuRequested(int,QPointF)), this, SLOT(slotItemContextMenuRequested(int,QPointF)));
174 connect(controller, SIGNAL(viewContextMenuRequested(QPointF)), this, SLOT(slotViewContextMenuRequested(QPointF)));
175 connect(controller, SIGNAL(headerContextMenuRequested(QPointF)), this, SLOT(slotHeaderContextMenuRequested(QPointF)));
176 connect(controller, SIGNAL(itemExpansionToggleClicked(int)), this, SLOT(slotItemExpansionToggleClicked(int)));
177 connect(controller, SIGNAL(itemHovered(int)), this, SLOT(slotItemHovered(int)));
178 connect(controller, SIGNAL(itemUnhovered(int)), this, SLOT(slotItemUnhovered(int)));
179 connect(controller, SIGNAL(itemDropEvent(int,QGraphicsSceneDragDropEvent*)), this, SLOT(slotItemDropEvent(int,QGraphicsSceneDragDropEvent*)));
180 connect(controller, SIGNAL(modelChanged(KItemModelBase*,KItemModelBase*)), this, SLOT(slotModelChanged(KItemModelBase*,KItemModelBase*)));
181
182 KFileItemModel* model = fileItemModel();
183 if (model) {
184 connect(model, SIGNAL(loadingCompleted()), this, SLOT(slotLoadingCompleted()));
185 }
186
187 KItemListSelectionManager* selectionManager = controller->selectionManager();
188 connect(selectionManager, SIGNAL(selectionChanged(QSet<int>,QSet<int>)),
189 this, SLOT(slotSelectionChanged(QSet<int>,QSet<int>)));
190
191 m_toolTipManager = new ToolTipManager(this);
192
193 m_versionControlObserver = new VersionControlObserver(this);
194 m_versionControlObserver->setModel(model);
195 connect(m_versionControlObserver, SIGNAL(infoMessage(QString)), this, SIGNAL(infoMessage(QString)));
196 connect(m_versionControlObserver, SIGNAL(errorMessage(QString)), this, SIGNAL(errorMessage(QString)));
197 connect(m_versionControlObserver, SIGNAL(operationCompletedMessage(QString)), this, SIGNAL(operationCompletedMessage(QString)));
198
199 applyViewProperties();
200 m_topLayout->addWidget(m_container);
201
202 loadDirectory(url);
203 }
204
205 DolphinView::~DolphinView()
206 {
207 }
208
209 KUrl DolphinView::url() const
210 {
211 return m_url;
212 }
213
214 void DolphinView::setActive(bool active)
215 {
216 if (active == m_active) {
217 return;
218 }
219
220 m_active = active;
221
222 QColor color = KColorScheme(QPalette::Active, KColorScheme::View).background().color();
223 if (!active) {
224 color.setAlpha(150);
225 }
226
227 /*QAbstractItemView* view = m_viewAccessor.itemView();
228 QWidget* viewport = view ? view->viewport() : 0;
229 if (viewport) {
230 QPalette palette;
231 palette.setColor(viewport->backgroundRole(), color);
232 viewport->setPalette(palette);
233 }*/
234
235 update();
236
237 if (active) {
238 //if (view) {
239 // view->setFocus();
240 //}
241 emit activated();
242 emit writeStateChanged(m_isFolderWritable);
243 }
244
245 //m_viewModeController->indicateActivationChange(active);
246 }
247
248 bool DolphinView::isActive() const
249 {
250 return m_active;
251 }
252
253 void DolphinView::setMode(Mode mode)
254 {
255 if (mode != m_mode) {
256 ViewProperties props(url());
257 props.setViewMode(mode);
258 props.save();
259
260 applyViewProperties();
261 }
262 }
263
264 DolphinView::Mode DolphinView::mode() const
265 {
266 return m_mode;
267 }
268
269 bool DolphinView::previewsShown() const
270 {
271 return m_container->previewsShown();
272 }
273
274 bool DolphinView::hiddenFilesShown() const
275 {
276 return m_dirLister->showingDotFiles();
277 }
278
279 bool DolphinView::categorizedSorting() const
280 {
281 return false; //m_storedCategorizedSorting;
282 }
283
284 KFileItemList DolphinView::items() const
285 {
286 return m_dirLister->items();
287 }
288
289 KFileItemList DolphinView::selectedItems() const
290 {
291 const KFileItemModel* model = fileItemModel();
292 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
293 const QSet<int> selectedIndexes = selectionManager->selectedItems();
294
295 KFileItemList selectedItems;
296 QSetIterator<int> it(selectedIndexes);
297 while (it.hasNext()) {
298 const int index = it.next();
299 selectedItems.append(model->fileItem(index));
300 }
301 return selectedItems;
302 }
303
304 int DolphinView::selectedItemsCount() const
305 {
306 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
307 return selectionManager->selectedItems().count();
308 }
309
310 void DolphinView::markUrlsAsSelected(const QList<KUrl>& urls)
311 {
312 m_selectedUrls = urls;
313 }
314
315 void DolphinView::setItemSelectionEnabled(const QRegExp& pattern, bool enabled)
316 {
317 const KItemListSelectionManager::SelectionMode mode = enabled
318 ? KItemListSelectionManager::Select
319 : KItemListSelectionManager::Deselect;
320 const KFileItemModel* model = fileItemModel();
321 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
322
323 for (int index = 0; index < model->count(); index++) {
324 const KFileItem item = model->fileItem(index);
325 if (pattern.exactMatch(item.name())) {
326 // An alternative approach would be to store the matching items in a QSet<int> and
327 // select them in one go after the loop, but we'd need a new function
328 // KItemListSelectionManager::setSelected(QSet<int>, SelectionMode mode)
329 // for that.
330 selectionManager->setSelected(index, 1, mode);
331 }
332 }
333 }
334
335 void DolphinView::setZoomLevel(int level)
336 {
337 const int oldZoomLevel = zoomLevel();
338 m_container->setZoomLevel(level);
339 if (zoomLevel() != oldZoomLevel) {
340 emit zoomLevelChanged(zoomLevel(), oldZoomLevel);
341 }
342 }
343
344 int DolphinView::zoomLevel() const
345 {
346 return m_container->zoomLevel();
347 }
348
349 void DolphinView::setSorting(Sorting sorting)
350 {
351 if (sorting != this->sorting()) {
352 updateSorting(sorting);
353 }
354 }
355
356 DolphinView::Sorting DolphinView::sorting() const
357 {
358 KItemModelBase* model = m_container->controller()->model();
359 return sortingForSortRole(model->sortRole());
360 }
361
362 void DolphinView::setSortOrder(Qt::SortOrder order)
363 {
364 if (sortOrder() != order) {
365 updateSortOrder(order);
366 }
367 }
368
369 Qt::SortOrder DolphinView::sortOrder() const
370 {
371 KItemModelBase* model = fileItemModel();
372 return model->sortOrder();
373 }
374
375 void DolphinView::setSortFoldersFirst(bool foldersFirst)
376 {
377 if (sortFoldersFirst() != foldersFirst) {
378 updateSortFoldersFirst(foldersFirst);
379 }
380 }
381
382 bool DolphinView::sortFoldersFirst() const
383 {
384 KFileItemModel* model = fileItemModel();
385 return model->sortFoldersFirst();
386 }
387
388 void DolphinView::setAdditionalInfoList(const QList<AdditionalInfo>& info)
389 {
390 const QList<AdditionalInfo> previousList = info;
391
392 ViewProperties props(url());
393 props.setAdditionalInfoList(info);
394
395 m_additionalInfoList = info;
396 applyAdditionalInfoListToView();
397
398 emit additionalInfoListChanged(m_additionalInfoList, previousList);
399 }
400
401 QList<DolphinView::AdditionalInfo> DolphinView::additionalInfoList() const
402 {
403 return m_additionalInfoList;
404 }
405
406 void DolphinView::reload()
407 {
408 QByteArray viewState;
409 QDataStream saveStream(&viewState, QIODevice::WriteOnly);
410 saveState(saveStream);
411
412 const KFileItemList itemList = selectedItems();
413 m_selectedUrls.clear();
414 m_selectedUrls = itemList.urlList();
415
416 setUrl(url());
417 loadDirectory(url(), true);
418
419 QDataStream restoreStream(viewState);
420 restoreState(restoreStream);
421 }
422
423 void DolphinView::stopLoading()
424 {
425 m_dirLister->stop();
426 }
427
428 void DolphinView::refresh()
429 {
430 const bool oldActivationState = m_active;
431 const int oldZoomLevel = zoomLevel();
432 m_active = true;
433
434 applyViewProperties();
435 reload();
436
437 setActive(oldActivationState);
438 updateZoomLevel(oldZoomLevel);
439 }
440
441 void DolphinView::setNameFilter(const QString& nameFilter)
442 {
443 Q_UNUSED(nameFilter);
444 //m_viewModeController->setNameFilter(nameFilter);
445 }
446
447 QString DolphinView::nameFilter() const
448 {
449 return QString(); //m_viewModeController->nameFilter();
450 }
451
452 void DolphinView::calculateItemCount(int& fileCount,
453 int& folderCount,
454 KIO::filesize_t& totalFileSize) const
455 {
456 foreach (const KFileItem& item, m_dirLister->items()) {
457 if (item.isDir()) {
458 ++folderCount;
459 } else {
460 ++fileCount;
461 totalFileSize += item.size();
462 }
463 }
464 }
465
466 QString DolphinView::statusBarText() const
467 {
468 QString text;
469 int folderCount = 0;
470 int fileCount = 0;
471 KIO::filesize_t totalFileSize = 0;
472
473 if (hasSelection()) {
474 // give a summary of the status of the selected files
475 const KFileItemList list = selectedItems();
476 if (list.isEmpty()) {
477 // when an item is triggered, it is temporary selected but selectedItems()
478 // will return an empty list
479 return text;
480 }
481
482 KFileItemList::const_iterator it = list.begin();
483 const KFileItemList::const_iterator end = list.end();
484 while (it != end) {
485 const KFileItem& item = *it;
486 if (item.isDir()) {
487 ++folderCount;
488 } else {
489 ++fileCount;
490 totalFileSize += item.size();
491 }
492 ++it;
493 }
494
495 if (folderCount + fileCount == 1) {
496 // if only one item is selected, show the filename
497 const QString name = list.first().text();
498 text = (folderCount == 1) ? i18nc("@info:status", "<filename>%1</filename> selected", name) :
499 i18nc("@info:status", "<filename>%1</filename> selected (%2)",
500 name, KIO::convertSize(totalFileSize));
501 } else {
502 // at least 2 items are selected
503 const QString foldersText = i18ncp("@info:status", "1 Folder selected", "%1 Folders selected", folderCount);
504 const QString filesText = i18ncp("@info:status", "1 File selected", "%1 Files selected", fileCount);
505 if ((folderCount > 0) && (fileCount > 0)) {
506 text = i18nc("@info:status folders, files (size)", "%1, %2 (%3)",
507 foldersText, filesText, KIO::convertSize(totalFileSize));
508 } else if (fileCount > 0) {
509 text = i18nc("@info:status files (size)", "%1 (%2)", filesText, KIO::convertSize(totalFileSize));
510 } else {
511 Q_ASSERT(folderCount > 0);
512 text = foldersText;
513 }
514 }
515 } else {
516 calculateItemCount(fileCount, folderCount, totalFileSize);
517 text = KIO::itemsSummaryString(fileCount + folderCount,
518 fileCount, folderCount,
519 totalFileSize, true);
520 }
521
522 return text;
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 /*if ((itemCount == 1) && DolphinSettings::instance().generalSettings()->renameInline()) {
589 const QModelIndex dirIndex = m_viewAccessor.dirModel()->indexForItem(items.first());
590 const QModelIndex proxyIndex = m_viewAccessor.proxyModel()->mapFromSource(dirIndex);
591 m_viewAccessor.itemView()->edit(proxyIndex);
592 } else {*/
593 RenameDialog* dialog = new RenameDialog(this, items);
594 dialog->setAttribute(Qt::WA_DeleteOnClose);
595 dialog->show();
596 dialog->raise();
597 dialog->activateWindow();
598 //}
599
600 // assure that the current index remains visible when KDirLister
601 // will notify the view about changed items
602 m_assureVisibleCurrentIndex = true;
603 }
604
605 void DolphinView::trashSelectedItems()
606 {
607 const KUrl::List list = simplifiedSelectedUrls();
608 KonqOperations::del(this, KonqOperations::TRASH, list);
609 }
610
611 void DolphinView::deleteSelectedItems()
612 {
613 const KUrl::List list = simplifiedSelectedUrls();
614 const bool del = KonqOperations::askDeleteConfirmation(list,
615 KonqOperations::DEL,
616 KonqOperations::DEFAULT_CONFIRMATION,
617 this);
618
619 if (del) {
620 KIO::Job* job = KIO::del(list);
621 connect(job, SIGNAL(result(KJob*)),
622 this, SLOT(slotDeleteFileFinished(KJob*)));
623 }
624 }
625
626 void DolphinView::cutSelectedItems()
627 {
628 QMimeData* mimeData = selectionMimeData();
629 KonqMimeData::addIsCutSelection(mimeData, true);
630 QApplication::clipboard()->setMimeData(mimeData);
631 }
632
633 void DolphinView::copySelectedItems()
634 {
635 QMimeData* mimeData = selectionMimeData();
636 QApplication::clipboard()->setMimeData(mimeData);
637 }
638
639 void DolphinView::paste()
640 {
641 pasteToUrl(url());
642 }
643
644 void DolphinView::pasteIntoFolder()
645 {
646 const KFileItemList items = selectedItems();
647 if ((items.count() == 1) && items.first().isDir()) {
648 pasteToUrl(items.first().url());
649 }
650 }
651
652 void DolphinView::setPreviewsShown(bool show)
653 {
654 if (previewsShown() == show) {
655 return;
656 }
657
658 ViewProperties props(url());
659 props.setPreviewsShown(show);
660
661 m_container->setPreviewsShown(show);
662 emit previewsShownChanged(show);
663 }
664
665 void DolphinView::setHiddenFilesShown(bool show)
666 {
667 if (m_dirLister->showingDotFiles() == show) {
668 return;
669 }
670
671 const KFileItemList itemList = selectedItems();
672 m_selectedUrls.clear();
673 m_selectedUrls = itemList.urlList();
674
675 ViewProperties props(url());
676 props.setHiddenFilesShown(show);
677
678 m_dirLister->setShowingDotFiles(show);
679 m_dirLister->emitChanges();
680 emit hiddenFilesShownChanged(show);
681 }
682
683 void DolphinView::setCategorizedSorting(bool categorized)
684 {
685 if (categorized == categorizedSorting()) {
686 return;
687 }
688
689 ViewProperties props(url());
690 props.setCategorizedSorting(categorized);
691 props.save();
692
693 //m_viewAccessor.proxyModel()->setCategorizedModel(categorized);
694
695 emit categorizedSortingChanged(categorized);
696 }
697
698 void DolphinView::mouseReleaseEvent(QMouseEvent* event)
699 {
700 QWidget::mouseReleaseEvent(event);
701 setActive(true);
702 }
703
704 void DolphinView::activate()
705 {
706 setActive(true);
707 }
708
709 void DolphinView::slotItemActivated(int index)
710 {
711 Q_UNUSED(index);
712
713 const KFileItemList items = selectedItems();
714 if (items.isEmpty()) {
715 return;
716 }
717
718 if (items.count() == 1) {
719 emit itemActivated(items.at(0)); // caught by DolphinViewContainer or DolphinPart
720 } else {
721 foreach (const KFileItem& item, items) {
722 if (item.isDir()) {
723 emit tabRequested(item.url());
724 } else {
725 emit itemActivated(item);
726 }
727 }
728 }
729 }
730
731 void DolphinView::slotItemMiddleClicked(int index)
732 {
733 const KFileItem item = fileItemModel()->fileItem(index);
734 if (item.isDir() || isTabsForFilesEnabled()) {
735 emit tabRequested(item.url());
736 }
737 }
738
739 void DolphinView::slotItemContextMenuRequested(int index, const QPointF& pos)
740 {
741 if (GeneralSettings::showToolTips()) {
742 m_toolTipManager->hideToolTip();
743 }
744 const KFileItem item = fileItemModel()->fileItem(index);
745 emit requestContextMenu(pos.toPoint(), item, url(), QList<QAction*>());
746 }
747
748 void DolphinView::slotViewContextMenuRequested(const QPointF& pos)
749 {
750 if (GeneralSettings::showToolTips()) {
751 m_toolTipManager->hideToolTip();
752 }
753 emit requestContextMenu(pos.toPoint(), KFileItem(), url(), QList<QAction*>());
754 }
755
756 void DolphinView::slotHeaderContextMenuRequested(const QPointF& pos)
757 {
758 QWeakPointer<KMenu> menu = new KMenu(QApplication::activeWindow());
759
760 KItemListView* view = m_container->controller()->view();
761 const QSet<QByteArray> visibleRolesSet = view->visibleRoles().toSet();
762
763 // Add all roles to the menu that can be shown or hidden by the user
764 const AdditionalInfoAccessor& infoAccessor = AdditionalInfoAccessor::instance();
765 const QList<DolphinView::AdditionalInfo> keys = infoAccessor.keys();
766 foreach (const DolphinView::AdditionalInfo info, keys) {
767 const QByteArray& role = infoAccessor.role(info);
768 if (role != "name") {
769 const QString text = fileItemModel()->roleDescription(role);
770
771 QAction* action = menu.data()->addAction(text);
772 action->setCheckable(true);
773 action->setChecked(visibleRolesSet.contains(role));
774 action->setData(info);
775 }
776 }
777
778 QAction* action = menu.data()->exec(pos.toPoint());
779 if (action) {
780 // Show or hide the selected role
781 const DolphinView::AdditionalInfo info =
782 static_cast<DolphinView::AdditionalInfo>(action->data().toInt());
783
784 const QByteArray selectedRole = infoAccessor.role(info);
785 QList<QByteArray> visibleRoles = view->visibleRoles();
786 if (action->isChecked()) {
787 const int index = keys.indexOf(info);
788 visibleRoles.insert(index + 1, selectedRole);
789 } else {
790 visibleRoles.removeOne(selectedRole);
791 }
792 view->setVisibleRoles(visibleRoles);
793 }
794
795 delete menu.data();
796 }
797
798 void DolphinView::slotItemExpansionToggleClicked(int index)
799 {
800 // TODO: When doing a model->setExpanded(false) it should
801 // be checked here whether the current index is part of the
802 // closed sub-tree. If this is the case, the current index
803 // should be adjusted to the parent index.
804 KFileItemModel* model = fileItemModel();
805 const bool expanded = model->isExpanded(index);
806 model->setExpanded(index, !expanded);
807 }
808
809 void DolphinView::slotItemHovered(int index)
810 {
811 const KFileItem item = fileItemModel()->fileItem(index);
812
813 if (GeneralSettings::showToolTips()) {
814 QRectF itemRect = m_container->controller()->view()->itemBoundingRect(index);
815 const QPoint pos = m_container->mapToGlobal(itemRect.topLeft().toPoint());
816 itemRect.moveTo(pos);
817
818 m_toolTipManager->showToolTip(item, itemRect);
819 }
820
821 emit requestItemInfo(item);
822 }
823
824 void DolphinView::slotItemUnhovered(int index)
825 {
826 Q_UNUSED(index);
827 if (GeneralSettings::showToolTips()) {
828 m_toolTipManager->hideToolTip();
829 }
830 emit requestItemInfo(KFileItem());
831 }
832
833 void DolphinView::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* event)
834 {
835 const KFileItem destItem = fileItemModel()->fileItem(index);
836
837 QDropEvent dropEvent(event->pos().toPoint(),
838 event->possibleActions(),
839 event->mimeData(),
840 event->buttons(),
841 event->modifiers());
842
843 DragAndDropHelper::dropUrls(destItem, url(), &dropEvent, this);
844 }
845
846 void DolphinView::slotModelChanged(KItemModelBase* current, KItemModelBase* previous)
847 {
848 if (previous != 0) {
849 disconnect(previous, SIGNAL(loadingCompleted()), this, SLOT(slotLoadingCompleted()));
850 }
851
852 Q_ASSERT(qobject_cast<KFileItemModel*>(current));
853 connect(current, SIGNAL(loadingCompleted()), this, SLOT(slotLoadingCompleted()));
854
855 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(current);
856 m_versionControlObserver->setModel(fileItemModel);
857 }
858
859 void DolphinView::slotSelectionChanged(const QSet<int>& current, const QSet<int>& previous)
860 {
861 const int currentCount = current.count();
862 const int previousCount = previous.count();
863 const bool selectionStateChanged = (currentCount == 0 && previousCount > 0) ||
864 (currentCount > 0 && previousCount == 0);
865
866 // If nothing has been selected before and something got selected (or if something
867 // was selected before and now nothing is selected) the selectionChangedSignal must
868 // be emitted asynchronously as fast as possible to update the edit-actions.
869 m_selectionChangedTimer->setInterval(selectionStateChanged ? 0 : 300);
870 m_selectionChangedTimer->start();
871 }
872
873 void DolphinView::emitSelectionChangedSignal()
874 {
875 m_selectionChangedTimer->stop();
876 emit selectionChanged(selectedItems());
877 }
878
879 void DolphinView::dropUrls(const KFileItem& destItem,
880 const KUrl& destPath,
881 QDropEvent* event)
882 {
883 Q_UNUSED(destItem);
884 Q_UNUSED(destPath);
885 markPastedUrlsAsSelected(event->mimeData());
886 //DragAndDropHelper::instance().dropUrls(destItem, destPath, event, this);
887 }
888
889 void DolphinView::updateSorting(DolphinView::Sorting sorting)
890 {
891 ViewProperties props(url());
892 props.setSorting(sorting);
893
894 KItemModelBase* model = m_container->controller()->model();
895 model->setSortRole(sortRoleForSorting(sorting));
896
897 emit sortingChanged(sorting);
898 }
899
900 void DolphinView::updateSortOrder(Qt::SortOrder order)
901 {
902 ViewProperties props(url());
903 props.setSortOrder(order);
904
905 KItemModelBase* model = fileItemModel();
906 model->setSortOrder(order);
907
908 emit sortOrderChanged(order);
909 }
910
911 void DolphinView::updateSortFoldersFirst(bool foldersFirst)
912 {
913 ViewProperties props(url());
914 props.setSortFoldersFirst(foldersFirst);
915
916 KFileItemModel* model = fileItemModel();
917 model->setSortFoldersFirst(foldersFirst);
918
919 emit sortFoldersFirstChanged(foldersFirst);
920 }
921
922 QPair<bool, QString> DolphinView::pasteInfo() const
923 {
924 return KonqOperations::pasteInfo(url());
925 }
926
927 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles)
928 {
929 m_tabsForFiles = tabsForFiles;
930 }
931
932 bool DolphinView::isTabsForFilesEnabled() const
933 {
934 return m_tabsForFiles;
935 }
936
937 bool DolphinView::itemsExpandable() const
938 {
939 return m_mode == DetailsView;
940 }
941
942 void DolphinView::restoreState(QDataStream& stream)
943 {
944 // Restore the current item that had the keyboard focus
945 stream >> m_currentItemUrl;
946
947 // Restore the view position
948 stream >> m_restoredContentsPosition;
949
950 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
951 QSet<KUrl> urls;
952 stream >> urls;
953 fileItemModel()->restoreExpandedUrls(urls);
954 }
955
956 void DolphinView::saveState(QDataStream& stream)
957 {
958 // Save the current item that has the keyboard focus
959 const int currentIndex = m_container->controller()->selectionManager()->currentItem();
960 if (currentIndex != -1) {
961 KFileItem item = fileItemModel()->fileItem(currentIndex);
962 KUrl currentItemUrl = item.url();
963 stream << currentItemUrl;
964 } else {
965 stream << KUrl();
966 }
967
968 // Save view position
969 const qreal x = m_container->horizontalScrollBar()->value();
970 const qreal y = m_container->verticalScrollBar()->value();
971 stream << QPoint(x, y);
972
973 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
974 stream << fileItemModel()->expandedUrls();
975 }
976
977 bool DolphinView::hasSelection() const
978 {
979 return m_container->controller()->selectionManager()->hasSelection();
980 }
981
982 KFileItem DolphinView::rootItem() const
983 {
984 return m_dirLister->rootItem();
985 }
986
987 void DolphinView::observeCreatedItem(const KUrl& url)
988 {
989 m_createdItemUrl = url;
990 //connect(m_dirModel, SIGNAL(rowsInserted(QModelIndex,int,int)),
991 // this, SLOT(selectAndScrollToCreatedItem()));
992 }
993
994 void DolphinView::selectAndScrollToCreatedItem()
995 {
996 /*const QModelIndex dirIndex = m_viewAccessor.dirModel()->indexForUrl(m_createdItemUrl);
997 if (dirIndex.isValid()) {
998 const QModelIndex proxyIndex = m_viewAccessor.proxyModel()->mapFromSource(dirIndex);
999 QAbstractItemView* view = m_viewAccessor.itemView();
1000 if (view) {
1001 view->setCurrentIndex(proxyIndex);
1002 }
1003 }
1004
1005 disconnect(m_viewAccessor.dirModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
1006 this, SLOT(selectAndScrollToCreatedItem()));*/
1007 m_createdItemUrl = KUrl();
1008 }
1009
1010 void DolphinView::slotRedirection(const KUrl& oldUrl, const KUrl& newUrl)
1011 {
1012 if (oldUrl.equals(url(), KUrl::CompareWithoutTrailingSlash)) {
1013 emit redirection(oldUrl, newUrl);
1014 m_url = newUrl; // #186947
1015 }
1016 }
1017
1018 void DolphinView::updateViewState()
1019 {
1020 if (m_currentItemUrl != KUrl()) {
1021 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1022 const int currentIndex = fileItemModel()->index(m_currentItemUrl);
1023 if (currentIndex != -1) {
1024 selectionManager->setCurrentItem(currentIndex);
1025 } else {
1026 selectionManager->setCurrentItem(0);
1027 }
1028 m_currentItemUrl = KUrl();
1029 }
1030
1031 if (!m_restoredContentsPosition.isNull()) {
1032 const int x = m_restoredContentsPosition.x();
1033 const int y = m_restoredContentsPosition.y();
1034 m_restoredContentsPosition = QPoint();
1035
1036 m_container->horizontalScrollBar()->setValue(x);
1037 m_container->verticalScrollBar()->setValue(y);
1038 }
1039
1040 if (!m_selectedUrls.isEmpty()) {
1041 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1042 QSet<int> selectedItems = selectionManager->selectedItems();
1043 const KFileItemModel* model = fileItemModel();
1044
1045 foreach (const KUrl& url, m_selectedUrls) {
1046 const int index = model->index(url);
1047 if (index >= 0) {
1048 selectedItems.insert(index);
1049 }
1050 }
1051
1052 selectionManager->setSelectedItems(selectedItems);
1053 m_selectedUrls.clear();
1054 }
1055 }
1056
1057 void DolphinView::showHoverInformation(const KFileItem& item)
1058 {
1059 emit requestItemInfo(item);
1060 }
1061
1062 void DolphinView::clearHoverInformation()
1063 {
1064 emit requestItemInfo(KFileItem());
1065 }
1066
1067 void DolphinView::slotDeleteFileFinished(KJob* job)
1068 {
1069 if (job->error() == 0) {
1070 emit operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1071 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1072 emit errorMessage(job->errorString());
1073 }
1074 }
1075
1076 void DolphinView::slotDirListerStarted(const KUrl& url)
1077 {
1078 // Disable the writestate temporary until it can be determined in a fast way
1079 // in DolphinView::slotLoadingCompleted()
1080 if (m_isFolderWritable) {
1081 m_isFolderWritable = false;
1082 emit writeStateChanged(m_isFolderWritable);
1083 }
1084
1085 emit startedPathLoading(url);
1086 }
1087
1088 void DolphinView::slotLoadingCompleted()
1089 {
1090 // Update the view-state. This has to be done using a Qt::QueuedConnection
1091 // because the view might not be in its final state yet (the view also
1092 // listens to the completed()-signal from KDirLister and the order of
1093 // of slots is undefined).
1094 QTimer::singleShot(0, this, SLOT(updateViewState()));
1095
1096 emit finishedPathLoading(url());
1097
1098 updateWritableState();
1099 }
1100
1101 void DolphinView::slotRefreshItems()
1102 {
1103 if (m_assureVisibleCurrentIndex) {
1104 m_assureVisibleCurrentIndex = false;
1105 //QAbstractItemView* view = m_viewAccessor.itemView();
1106 //if (view) {
1107 // m_viewAccessor.itemView()->scrollTo(m_viewAccessor.itemView()->currentIndex());
1108 //}
1109 }
1110 }
1111
1112 KFileItemModel* DolphinView::fileItemModel() const
1113 {
1114 return static_cast<KFileItemModel*>(m_container->controller()->model());
1115 }
1116
1117 void DolphinView::loadDirectory(const KUrl& url, bool reload)
1118 {
1119 if (!url.isValid()) {
1120 const QString location(url.pathOrUrl());
1121 if (location.isEmpty()) {
1122 emit errorMessage(i18nc("@info:status", "The location is empty."));
1123 } else {
1124 emit errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location));
1125 }
1126 return;
1127 }
1128
1129 m_dirLister->openUrl(url, reload ? KDirLister::Reload : KDirLister::NoFlags);
1130 }
1131
1132 void DolphinView::applyViewProperties()
1133 {
1134 m_container->beginTransaction();
1135
1136 const ViewProperties props(url());
1137
1138 const Mode mode = props.viewMode();
1139 if (m_mode != mode) {
1140 const Mode previousMode = m_mode;
1141 m_mode = mode;
1142
1143 // Changing the mode might result in changing
1144 // the zoom level. Remember the old zoom level so
1145 // that zoomLevelChanged() can get emitted.
1146 const int oldZoomLevel = m_container->zoomLevel();
1147
1148 switch (m_mode) {
1149 case IconsView: m_container->setItemLayout(KFileItemListView::IconsLayout); break;
1150 case CompactView: m_container->setItemLayout(KFileItemListView::CompactLayout); break;
1151 case DetailsView: m_container->setItemLayout(KFileItemListView::DetailsLayout); break;
1152 default: Q_ASSERT(false); break;
1153 }
1154
1155 emit modeChanged(m_mode, previousMode);
1156
1157 if (m_container->zoomLevel() != oldZoomLevel) {
1158 emit zoomLevelChanged(m_container->zoomLevel(), oldZoomLevel);
1159 }
1160 }
1161
1162 const bool hiddenFilesShown = props.hiddenFilesShown();
1163 if (hiddenFilesShown != m_dirLister->showingDotFiles()) {
1164 m_dirLister->setShowingDotFiles(hiddenFilesShown);
1165 m_dirLister->emitChanges();
1166 emit hiddenFilesShownChanged(hiddenFilesShown);
1167 }
1168
1169 /* m_storedCategorizedSorting = props.categorizedSorting();
1170 const bool categorized = m_storedCategorizedSorting && supportsCategorizedSorting();
1171 if (categorized != m_viewAccessor.proxyModel()->isCategorizedModel()) {
1172 m_viewAccessor.proxyModel()->setCategorizedModel(categorized);
1173 emit categorizedSortingChanged();
1174 }*/
1175
1176 const DolphinView::Sorting sorting = props.sorting();
1177 KFileItemModel* model = fileItemModel();
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 void DolphinView::updateZoomLevel(int oldZoomLevel)
1242 {
1243 Q_UNUSED(oldZoomLevel);
1244 /* const int newZoomLevel = ZoomLevelInfo::zoomLevelForIconSize(m_viewAccessor.itemView()->iconSize());
1245 if (oldZoomLevel != newZoomLevel) {
1246 m_viewModeController->setZoomLevel(newZoomLevel);
1247 emit zoomLevelChanged(newZoomLevel);
1248 }*/
1249 }
1250
1251 KUrl::List DolphinView::simplifiedSelectedUrls() const
1252 {
1253 KUrl::List urls;
1254
1255 const KFileItemList items = selectedItems();
1256 foreach (const KFileItem &item, items) {
1257 urls.append(item.url());
1258 }
1259
1260 if (itemsExpandable()) {
1261 // TODO: Check if we still need KDirModel for this in KDE 5.0
1262 urls = KDirModel::simplifiedUrlList(urls);
1263 }
1264
1265 return urls;
1266 }
1267
1268 QMimeData* DolphinView::selectionMimeData() const
1269 {
1270 const KFileItemModel* model = fileItemModel();
1271 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1272 const QSet<int> selectedIndexes = selectionManager->selectedItems();
1273
1274 return model->createMimeData(selectedIndexes);
1275 }
1276
1277 void DolphinView::markPastedUrlsAsSelected(const QMimeData* mimeData)
1278 {
1279 const KUrl::List urls = KUrl::List::fromMimeData(mimeData);
1280 markUrlsAsSelected(urls);
1281 }
1282
1283 void DolphinView::updateWritableState()
1284 {
1285 const bool wasFolderWritable = m_isFolderWritable;
1286 m_isFolderWritable = true;
1287
1288 const KFileItem item = m_dirLister->rootItem();
1289 if (!item.isNull()) {
1290 KFileItemListProperties capabilities(KFileItemList() << item);
1291 m_isFolderWritable = capabilities.supportsWriting();
1292 }
1293 if (m_isFolderWritable != wasFolderWritable) {
1294 emit writeStateChanged(m_isFolderWritable);
1295 }
1296 }
1297
1298 QByteArray DolphinView::sortRoleForSorting(Sorting sorting) const
1299 {
1300 switch (sorting) {
1301 case SortByName: return "name";
1302 case SortBySize: return "size";
1303 case SortByDate: return "date";
1304 case SortByPermissions: return "permissions";
1305 case SortByOwner: return "owner";
1306 case SortByGroup: return "group";
1307 case SortByType: return "type";
1308 case SortByDestination: return "destination";
1309 case SortByPath: return "path";
1310 default: break;
1311 }
1312
1313 return QByteArray();
1314 }
1315
1316 DolphinView::Sorting DolphinView::sortingForSortRole(const QByteArray& sortRole) const
1317 {
1318 static QHash<QByteArray, DolphinView::Sorting> sortHash;
1319 if (sortHash.isEmpty()) {
1320 sortHash.insert("name", SortByName);
1321 sortHash.insert("size", SortBySize);
1322 sortHash.insert("date", SortByDate);
1323 sortHash.insert("permissions", SortByPermissions);
1324 sortHash.insert("owner", SortByOwner);
1325 sortHash.insert("group", SortByGroup);
1326 sortHash.insert("type", SortByType);
1327 sortHash.insert("destination", SortByDestination);
1328 sortHash.insert("path", SortByPath);
1329 }
1330 return sortHash.value(sortRole);
1331 }
1332
1333 void DolphinView::markUrlAsCurrent(const KUrl& url)
1334 {
1335 m_currentItemUrl = url;
1336 }
1337
1338 #include "dolphinview.moc"