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