]> cloud.milkyroute.net Git - dolphin.git/blob - src/views/dolphinview.cpp
Bug 196035 - middle clicking on archive files in dolphin does not open them in a...
[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 <config-nepomuk.h>
24
25 #include <QAbstractItemView>
26 #include <QApplication>
27 #include <QBoxLayout>
28 #include <QClipboard>
29 #include <QDropEvent>
30 #include <QGraphicsSceneDragDropEvent>
31 #include <QKeyEvent>
32 #include <QItemSelection>
33 #include <QTimer>
34 #include <QScrollBar>
35
36 #include <KDesktopFile>
37 #include <KProtocolManager>
38 #include <KActionCollection>
39 #include <KColorScheme>
40 #include <KDirModel>
41 #include <KIconEffect>
42 #include <KFileItem>
43 #include <KFileItemListProperties>
44 #include <KLocale>
45 #include <kitemviews/kfileitemmodel.h>
46 #include <kitemviews/kfileitemlistview.h>
47 #include <kitemviews/kitemlistcontainer.h>
48 #include <kitemviews/kitemlistheader.h>
49 #include <kitemviews/kitemlistselectionmanager.h>
50 #include <kitemviews/kitemlistview.h>
51 #include <kitemviews/kitemlistcontroller.h>
52 #include <KIO/DeleteJob>
53 #include <KIO/JobUiDelegate>
54 #include <KIO/NetAccess>
55 #include <KIO/PreviewJob>
56 #include <KJob>
57 #include <KMenu>
58 #include <KMessageBox>
59 #include <konq_fileitemcapabilities.h>
60 #include <konq_operations.h>
61 #include <konqmimedata.h>
62 #include <KToggleAction>
63 #include <KUrl>
64
65 #include "dolphinnewfilemenuobserver.h"
66 #include "dolphin_detailsmodesettings.h"
67 #include "dolphin_generalsettings.h"
68 #include "dolphinitemlistview.h"
69 #include "draganddrophelper.h"
70 #include "renamedialog.h"
71 #include "versioncontrol/versioncontrolobserver.h"
72 #include "viewmodecontroller.h"
73 #include "viewproperties.h"
74 #include "views/tooltips/tooltipmanager.h"
75 #include "zoomlevelinfo.h"
76
77 #ifdef HAVE_NEPOMUK
78 #include <Nepomuk2/ResourceManager>
79 #endif
80
81 namespace {
82 const int MaxModeEnum = DolphinView::CompactView;
83 };
84
85 DolphinView::DolphinView(const KUrl& url, QWidget* parent) :
86 QWidget(parent),
87 m_active(true),
88 m_tabsForFiles(false),
89 m_assureVisibleCurrentIndex(false),
90 m_isFolderWritable(true),
91 m_dragging(false),
92 m_url(url),
93 m_viewPropertiesContext(),
94 m_mode(DolphinView::IconsView),
95 m_visibleRoles(),
96 m_topLayout(0),
97 m_model(0),
98 m_view(0),
99 m_container(0),
100 m_toolTipManager(0),
101 m_selectionChangedTimer(0),
102 m_currentItemUrl(),
103 m_scrollToCurrentItem(false),
104 m_restoredContentsPosition(),
105 m_selectedUrls(),
106 m_clearSelectionBeforeSelectingNewItems(false),
107 m_markFirstNewlySelectedItemAsCurrent(false),
108 m_versionControlObserver(0)
109 {
110 m_topLayout = new QVBoxLayout(this);
111 m_topLayout->setSpacing(0);
112 m_topLayout->setMargin(0);
113
114 // When a new item has been created by the "Create New..." menu, the item should
115 // get selected and it must be assured that the item will get visible. As the
116 // creation is done asynchronously, several signals must be checked:
117 connect(&DolphinNewFileMenuObserver::instance(), SIGNAL(itemCreated(KUrl)),
118 this, SLOT(observeCreatedItem(KUrl)));
119
120 m_selectionChangedTimer = new QTimer(this);
121 m_selectionChangedTimer->setSingleShot(true);
122 m_selectionChangedTimer->setInterval(300);
123 connect(m_selectionChangedTimer, SIGNAL(timeout()),
124 this, SLOT(emitSelectionChangedSignal()));
125
126 m_model = new KFileItemModel(this);
127 m_view = new DolphinItemListView();
128 m_view->setEnabledSelectionToggles(GeneralSettings::showSelectionToggle());
129 m_view->setVisibleRoles(QList<QByteArray>() << "text");
130 applyModeToView();
131
132 KItemListController* controller = new KItemListController(m_model, m_view, this);
133 const int delay = GeneralSettings::autoExpandFolders() ? 750 : -1;
134 controller->setAutoActivationDelay(delay);
135
136 // The EnlargeSmallPreviews setting can only be changed after the model
137 // has been set in the view by KItemListController.
138 m_view->setEnlargeSmallPreviews(GeneralSettings::enlargeSmallPreviews());
139
140 m_container = new KItemListContainer(controller, this);
141 m_container->installEventFilter(this);
142 setFocusProxy(m_container);
143 connect(m_container->horizontalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(hideToolTip()));
144 connect(m_container->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(hideToolTip()));
145
146 controller->setSelectionBehavior(KItemListController::MultiSelection);
147 connect(controller, SIGNAL(itemActivated(int)), this, SLOT(slotItemActivated(int)));
148 connect(controller, SIGNAL(itemsActivated(QSet<int>)), this, SLOT(slotItemsActivated(QSet<int>)));
149 connect(controller, SIGNAL(itemMiddleClicked(int)), this, SLOT(slotItemMiddleClicked(int)));
150 connect(controller, SIGNAL(itemContextMenuRequested(int,QPointF)), this, SLOT(slotItemContextMenuRequested(int,QPointF)));
151 connect(controller, SIGNAL(viewContextMenuRequested(QPointF)), this, SLOT(slotViewContextMenuRequested(QPointF)));
152 connect(controller, SIGNAL(headerContextMenuRequested(QPointF)), this, SLOT(slotHeaderContextMenuRequested(QPointF)));
153 connect(controller, SIGNAL(mouseButtonPressed(int,Qt::MouseButtons)), this, SLOT(slotMouseButtonPressed(int,Qt::MouseButtons)));
154 connect(controller, SIGNAL(itemHovered(int)), this, SLOT(slotItemHovered(int)));
155 connect(controller, SIGNAL(itemUnhovered(int)), this, SLOT(slotItemUnhovered(int)));
156 connect(controller, SIGNAL(itemDropEvent(int,QGraphicsSceneDragDropEvent*)), this, SLOT(slotItemDropEvent(int,QGraphicsSceneDragDropEvent*)));
157 connect(controller, SIGNAL(modelChanged(KItemModelBase*,KItemModelBase*)), this, SLOT(slotModelChanged(KItemModelBase*,KItemModelBase*)));
158
159 connect(m_model, SIGNAL(directoryLoadingStarted()), this, SLOT(slotDirectoryLoadingStarted()));
160 connect(m_model, SIGNAL(directoryLoadingCompleted()), this, SLOT(slotDirectoryLoadingCompleted()));
161 connect(m_model, SIGNAL(directoryLoadingCanceled()), this, SIGNAL(directoryLoadingCanceled()));
162 connect(m_model, SIGNAL(directoryLoadingProgress(int)), this, SIGNAL(directoryLoadingProgress(int)));
163 connect(m_model, SIGNAL(directorySortingProgress(int)), this, SIGNAL(directorySortingProgress(int)));
164 connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
165 this, SLOT(slotItemsChanged()));
166 connect(m_model, SIGNAL(itemsRemoved(KItemRangeList)), this, SIGNAL(itemCountChanged()));
167 connect(m_model, SIGNAL(itemsInserted(KItemRangeList)), this, SIGNAL(itemCountChanged()));
168 connect(m_model, SIGNAL(infoMessage(QString)), this, SIGNAL(infoMessage(QString)));
169 connect(m_model, SIGNAL(errorMessage(QString)), this, SIGNAL(errorMessage(QString)));
170 connect(m_model, SIGNAL(directoryRedirection(KUrl,KUrl)), this, SLOT(slotDirectoryRedirection(KUrl,KUrl)));
171 connect(m_model, SIGNAL(urlIsFileError(KUrl)), this, SIGNAL(urlIsFileError(KUrl)));
172
173 m_view->installEventFilter(this);
174 connect(m_view, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
175 this, SLOT(slotSortOrderChangedByHeader(Qt::SortOrder,Qt::SortOrder)));
176 connect(m_view, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
177 this, SLOT(slotSortRoleChangedByHeader(QByteArray,QByteArray)));
178 connect(m_view, SIGNAL(visibleRolesChanged(QList<QByteArray>,QList<QByteArray>)),
179 this, SLOT(slotVisibleRolesChangedByHeader(QList<QByteArray>,QList<QByteArray>)));
180 connect(m_view, SIGNAL(roleEditingFinished(int,QByteArray,QVariant)),
181 this, SLOT(slotRoleEditingFinished(int,QByteArray,QVariant)));
182 connect(m_view->header(), SIGNAL(columnWidthChanged(QByteArray,qreal,qreal)),
183 this, SLOT(slotHeaderColumnWidthChanged(QByteArray,qreal,qreal)));
184
185 KItemListSelectionManager* selectionManager = controller->selectionManager();
186 connect(selectionManager, SIGNAL(selectionChanged(QSet<int>,QSet<int>)),
187 this, SLOT(slotSelectionChanged(QSet<int>,QSet<int>)));
188
189 m_toolTipManager = new ToolTipManager(this);
190
191 m_versionControlObserver = new VersionControlObserver(this);
192 m_versionControlObserver->setModel(m_model);
193 connect(m_versionControlObserver, SIGNAL(infoMessage(QString)), this, SIGNAL(infoMessage(QString)));
194 connect(m_versionControlObserver, SIGNAL(errorMessage(QString)), this, SIGNAL(errorMessage(QString)));
195 connect(m_versionControlObserver, SIGNAL(operationCompletedMessage(QString)), this, SIGNAL(operationCompletedMessage(QString)));
196
197 applyViewProperties();
198 m_topLayout->addWidget(m_container);
199
200 loadDirectory(url);
201 }
202
203 DolphinView::~DolphinView()
204 {
205 }
206
207 KUrl DolphinView::url() const
208 {
209 return m_url;
210 }
211
212 void DolphinView::setActive(bool active)
213 {
214 if (active == m_active) {
215 return;
216 }
217
218 m_active = active;
219
220 QColor color = KColorScheme(QPalette::Active, KColorScheme::View).background().color();
221 if (!active) {
222 color.setAlpha(150);
223 }
224
225 QWidget* viewport = m_container->viewport();
226 if (viewport) {
227 QPalette palette;
228 palette.setColor(viewport->backgroundRole(), color);
229 viewport->setPalette(palette);
230 }
231
232 update();
233
234 if (active) {
235 m_container->setFocus();
236 emit activated();
237 emit writeStateChanged(m_isFolderWritable);
238 }
239 }
240
241 bool DolphinView::isActive() const
242 {
243 return m_active;
244 }
245
246 void DolphinView::setMode(Mode mode)
247 {
248 if (mode != m_mode) {
249 ViewProperties props(viewPropertiesUrl());
250 props.setViewMode(mode);
251 props.save();
252
253 applyViewProperties();
254 }
255 }
256
257 DolphinView::Mode DolphinView::mode() const
258 {
259 return m_mode;
260 }
261
262 void DolphinView::setPreviewsShown(bool show)
263 {
264 if (previewsShown() == show) {
265 return;
266 }
267
268 ViewProperties props(viewPropertiesUrl());
269 props.setPreviewsShown(show);
270
271 const int oldZoomLevel = m_view->zoomLevel();
272 m_view->setPreviewsShown(show);
273 emit previewsShownChanged(show);
274
275 const int newZoomLevel = m_view->zoomLevel();
276 if (newZoomLevel != oldZoomLevel) {
277 emit zoomLevelChanged(newZoomLevel, oldZoomLevel);
278 }
279 }
280
281 bool DolphinView::previewsShown() const
282 {
283 return m_view->previewsShown();
284 }
285
286 void DolphinView::setHiddenFilesShown(bool show)
287 {
288 if (m_model->showHiddenFiles() == show) {
289 return;
290 }
291
292 const KFileItemList itemList = selectedItems();
293 m_selectedUrls.clear();
294 m_selectedUrls = itemList.urlList();
295
296 ViewProperties props(viewPropertiesUrl());
297 props.setHiddenFilesShown(show);
298
299 m_model->setShowHiddenFiles(show);
300 emit hiddenFilesShownChanged(show);
301 }
302
303 bool DolphinView::hiddenFilesShown() const
304 {
305 return m_model->showHiddenFiles();
306 }
307
308 void DolphinView::setGroupedSorting(bool grouped)
309 {
310 if (grouped == groupedSorting()) {
311 return;
312 }
313
314 ViewProperties props(viewPropertiesUrl());
315 props.setGroupedSorting(grouped);
316 props.save();
317
318 m_container->controller()->model()->setGroupedSorting(grouped);
319
320 emit groupedSortingChanged(grouped);
321 }
322
323 bool DolphinView::groupedSorting() const
324 {
325 return m_model->groupedSorting();
326 }
327
328 KFileItemList DolphinView::items() const
329 {
330 KFileItemList list;
331 const int itemCount = m_model->count();
332 list.reserve(itemCount);
333
334 for (int i = 0; i < itemCount; ++i) {
335 list.append(m_model->fileItem(i));
336 }
337
338 return list;
339 }
340
341 int DolphinView::itemsCount() const
342 {
343 return m_model->count();
344 }
345
346 KFileItemList DolphinView::selectedItems() const
347 {
348 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
349 QList<int> selectedIndexes = selectionManager->selectedItems().toList();
350
351 qSort(selectedIndexes);
352
353 KFileItemList selectedItems;
354 QListIterator<int> it(selectedIndexes);
355 while (it.hasNext()) {
356 const int index = it.next();
357 selectedItems.append(m_model->fileItem(index));
358 }
359 return selectedItems;
360 }
361
362 int DolphinView::selectedItemsCount() const
363 {
364 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
365 return selectionManager->selectedItems().count();
366 }
367
368 void DolphinView::markUrlsAsSelected(const QList<KUrl>& urls)
369 {
370 m_selectedUrls = urls;
371 }
372
373 void DolphinView::markUrlAsCurrent(const KUrl& url)
374 {
375 m_currentItemUrl = url;
376 m_scrollToCurrentItem = true;
377 }
378
379 void DolphinView::selectItems(const QRegExp& pattern, bool enabled)
380 {
381 const KItemListSelectionManager::SelectionMode mode = enabled
382 ? KItemListSelectionManager::Select
383 : KItemListSelectionManager::Deselect;
384 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
385
386 for (int index = 0; index < m_model->count(); index++) {
387 const KFileItem item = m_model->fileItem(index);
388 if (pattern.exactMatch(item.text())) {
389 // An alternative approach would be to store the matching items in a QSet<int> and
390 // select them in one go after the loop, but we'd need a new function
391 // KItemListSelectionManager::setSelected(QSet<int>, SelectionMode mode)
392 // for that.
393 selectionManager->setSelected(index, 1, mode);
394 }
395 }
396 }
397
398 void DolphinView::setZoomLevel(int level)
399 {
400 const int oldZoomLevel = zoomLevel();
401 m_view->setZoomLevel(level);
402 if (zoomLevel() != oldZoomLevel) {
403 hideToolTip();
404 emit zoomLevelChanged(zoomLevel(), oldZoomLevel);
405 }
406 }
407
408 int DolphinView::zoomLevel() const
409 {
410 return m_view->zoomLevel();
411 }
412
413 void DolphinView::setSortRole(const QByteArray& role)
414 {
415 if (role != sortRole()) {
416 updateSortRole(role);
417 }
418 }
419
420 QByteArray DolphinView::sortRole() const
421 {
422 const KItemModelBase* model = m_container->controller()->model();
423 return model->sortRole();
424 }
425
426 void DolphinView::setSortOrder(Qt::SortOrder order)
427 {
428 if (sortOrder() != order) {
429 updateSortOrder(order);
430 }
431 }
432
433 Qt::SortOrder DolphinView::sortOrder() const
434 {
435 return m_model->sortOrder();
436 }
437
438 void DolphinView::setSortFoldersFirst(bool foldersFirst)
439 {
440 if (sortFoldersFirst() != foldersFirst) {
441 updateSortFoldersFirst(foldersFirst);
442 }
443 }
444
445 bool DolphinView::sortFoldersFirst() const
446 {
447 return m_model->sortDirectoriesFirst();
448 }
449
450 void DolphinView::setVisibleRoles(const QList<QByteArray>& roles)
451 {
452 const QList<QByteArray> previousRoles = roles;
453
454 ViewProperties props(viewPropertiesUrl());
455 props.setVisibleRoles(roles);
456
457 m_visibleRoles = roles;
458 m_view->setVisibleRoles(roles);
459
460 emit visibleRolesChanged(m_visibleRoles, previousRoles);
461 }
462
463 QList<QByteArray> DolphinView::visibleRoles() const
464 {
465 return m_visibleRoles;
466 }
467
468 void DolphinView::reload()
469 {
470 QByteArray viewState;
471 QDataStream saveStream(&viewState, QIODevice::WriteOnly);
472 saveState(saveStream);
473
474 const KFileItemList itemList = selectedItems();
475 m_selectedUrls.clear();
476 m_selectedUrls = itemList.urlList();
477
478 setUrl(url());
479 loadDirectory(url(), true);
480
481 QDataStream restoreStream(viewState);
482 restoreState(restoreStream);
483 }
484
485 void DolphinView::stopLoading()
486 {
487 m_model->cancelDirectoryLoading();
488 }
489
490 void DolphinView::readSettings()
491 {
492 const int oldZoomLevel = m_view->zoomLevel();
493
494 GeneralSettings::self()->readConfig();
495 m_view->readSettings();
496 applyViewProperties();
497
498 const int delay = GeneralSettings::autoExpandFolders() ? 750 : -1;
499 m_container->controller()->setAutoActivationDelay(delay);
500
501 const int newZoomLevel = m_view->zoomLevel();
502 if (newZoomLevel != oldZoomLevel) {
503 emit zoomLevelChanged(newZoomLevel, oldZoomLevel);
504 }
505 }
506
507 void DolphinView::writeSettings()
508 {
509 GeneralSettings::self()->writeConfig();
510 m_view->writeSettings();
511 }
512
513 void DolphinView::setNameFilter(const QString& nameFilter)
514 {
515 m_model->setNameFilter(nameFilter);
516 }
517
518 QString DolphinView::nameFilter() const
519 {
520 return m_model->nameFilter();
521 }
522
523 void DolphinView::setMimeTypeFilters(const QStringList& filters)
524 {
525 return m_model->setMimeTypeFilters(filters);
526 }
527
528 QStringList DolphinView::mimeTypeFilters() const
529 {
530 return m_model->mimeTypeFilters();
531 }
532
533 QString DolphinView::statusBarText() const
534 {
535 QString summary;
536 QString foldersText;
537 QString filesText;
538
539 int folderCount = 0;
540 int fileCount = 0;
541 KIO::filesize_t totalFileSize = 0;
542
543 if (m_container->controller()->selectionManager()->hasSelection()) {
544 // Give a summary of the status of the selected files
545 const KFileItemList list = selectedItems();
546 foreach (const KFileItem& item, list) {
547 if (item.isDir()) {
548 ++folderCount;
549 } else {
550 ++fileCount;
551 totalFileSize += item.size();
552 }
553 }
554
555 if (folderCount + fileCount == 1) {
556 // If only one item is selected, show the filename
557 filesText = i18nc("@info:status", "<filename>%1</filename> selected", list.first().text());
558 } else {
559 // At least 2 items are selected
560 foldersText = i18ncp("@info:status", "1 Folder selected", "%1 Folders selected", folderCount);
561 filesText = i18ncp("@info:status", "1 File selected", "%1 Files selected", fileCount);
562 }
563 } else {
564 calculateItemCount(fileCount, folderCount, totalFileSize);
565 foldersText = i18ncp("@info:status", "1 Folder", "%1 Folders", folderCount);
566 filesText = i18ncp("@info:status", "1 File", "%1 Files", fileCount);
567 }
568
569 if (fileCount > 0 && folderCount > 0) {
570 summary = i18nc("@info:status folders, files (size)", "%1, %2 (%3)",
571 foldersText, filesText,
572 KGlobal::locale()->formatByteSize(totalFileSize));
573 } else if (fileCount > 0) {
574 summary = i18nc("@info:status files (size)", "%1 (%2)",
575 filesText,
576 KGlobal::locale()->formatByteSize(totalFileSize));
577 } else if (folderCount > 0) {
578 summary = foldersText;
579 } else {
580 summary = i18nc("@info:status", "0 Folders, 0 Files");
581 }
582
583 return summary;
584 }
585
586 QList<QAction*> DolphinView::versionControlActions(const KFileItemList& items) const
587 {
588 QList<QAction*> actions;
589
590 if (items.isEmpty()) {
591 const KFileItem item = m_model->rootItem();
592 if (!item.isNull()) {
593 actions = m_versionControlObserver->actions(KFileItemList() << item);
594 }
595 } else {
596 actions = m_versionControlObserver->actions(items);
597 }
598
599 return actions;
600 }
601
602 void DolphinView::setUrl(const KUrl& url)
603 {
604 if (url == m_url) {
605 return;
606 }
607
608 clearSelection();
609
610 emit urlAboutToBeChanged(url);
611 m_url = url;
612
613 hideToolTip();
614
615 // It is important to clear the items from the model before
616 // applying the view properties, otherwise expensive operations
617 // might be done on the existing items although they get cleared
618 // anyhow afterwards by loadDirectory().
619 m_model->clear();
620 applyViewProperties();
621 loadDirectory(url);
622
623 emit urlChanged(url);
624 }
625
626 void DolphinView::selectAll()
627 {
628 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
629 selectionManager->setSelected(0, m_model->count());
630 }
631
632 void DolphinView::invertSelection()
633 {
634 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
635 selectionManager->setSelected(0, m_model->count(), KItemListSelectionManager::Toggle);
636 }
637
638 void DolphinView::clearSelection()
639 {
640 m_selectedUrls.clear();
641 m_container->controller()->selectionManager()->clearSelection();
642 }
643
644 void DolphinView::renameSelectedItems()
645 {
646 const KFileItemList items = selectedItems();
647 if (items.isEmpty()) {
648 return;
649 }
650
651 if (items.count() == 1 && GeneralSettings::renameInline()) {
652 const int index = m_model->index(items.first());
653 m_view->editRole(index, "text");
654 } else {
655 RenameDialog* dialog = new RenameDialog(this, items);
656 dialog->setAttribute(Qt::WA_DeleteOnClose);
657 dialog->show();
658 dialog->raise();
659 dialog->activateWindow();
660 }
661
662 // Assure that the current index remains visible when KFileItemModel
663 // will notify the view about changed items (which might result in
664 // a changed sorting).
665 m_assureVisibleCurrentIndex = true;
666 }
667
668 void DolphinView::trashSelectedItems()
669 {
670 const KUrl::List list = simplifiedSelectedUrls();
671 KonqOperations::del(this, KonqOperations::TRASH, list);
672 }
673
674 void DolphinView::deleteSelectedItems()
675 {
676 const KUrl::List list = simplifiedSelectedUrls();
677 const bool del = KonqOperations::askDeleteConfirmation(list,
678 KonqOperations::DEL,
679 KonqOperations::DEFAULT_CONFIRMATION,
680 this);
681
682 if (del) {
683 KIO::Job* job = KIO::del(list);
684 if (job->ui()) {
685 job->ui()->setWindow(this);
686 }
687 connect(job, SIGNAL(result(KJob*)),
688 this, SLOT(slotDeleteFileFinished(KJob*)));
689 }
690 }
691
692 void DolphinView::cutSelectedItems()
693 {
694 QMimeData* mimeData = selectionMimeData();
695 KonqMimeData::addIsCutSelection(mimeData, true);
696 QApplication::clipboard()->setMimeData(mimeData);
697 }
698
699 void DolphinView::copySelectedItems()
700 {
701 QMimeData* mimeData = selectionMimeData();
702 QApplication::clipboard()->setMimeData(mimeData);
703 }
704
705 void DolphinView::paste()
706 {
707 pasteToUrl(url());
708 }
709
710 void DolphinView::pasteIntoFolder()
711 {
712 const KFileItemList items = selectedItems();
713 if ((items.count() == 1) && items.first().isDir()) {
714 pasteToUrl(items.first().url());
715 }
716 }
717
718 bool DolphinView::eventFilter(QObject* watched, QEvent* event)
719 {
720 switch (event->type()) {
721 case QEvent::FocusIn:
722 if (watched == m_container) {
723 setActive(true);
724 }
725 break;
726
727 case QEvent::GraphicsSceneDragEnter:
728 if (watched == m_view) {
729 m_dragging = true;
730 }
731 break;
732
733 case QEvent::GraphicsSceneDragLeave:
734 if (watched == m_view) {
735 m_dragging = false;
736 }
737 break;
738
739 case QEvent::GraphicsSceneDrop:
740 if (watched == m_view) {
741 m_dragging = false;
742 }
743 default:
744 break;
745 }
746
747 return QWidget::eventFilter(watched, event);
748 }
749
750 void DolphinView::wheelEvent(QWheelEvent* event)
751 {
752 if (event->modifiers().testFlag(Qt::ControlModifier)) {
753 const int numDegrees = event->delta() / 8;
754 const int numSteps = numDegrees / 15;
755
756 setZoomLevel(zoomLevel() + numSteps);
757 event->accept();
758 } else {
759 event->ignore();
760 }
761 }
762
763 void DolphinView::hideEvent(QHideEvent* event)
764 {
765 hideToolTip();
766 QWidget::hideEvent(event);
767 }
768
769 bool DolphinView::event(QEvent* event)
770 {
771 /* See Bug 297355
772 * Dolphin leaves file preview tooltips open even when is not visible.
773 *
774 * Hide tool-tip when Dolphin loses focus.
775 */
776 if (event->type() == QEvent::WindowDeactivate) {
777 hideToolTip();
778 }
779
780 return QWidget::event(event);
781 }
782
783 void DolphinView::activate()
784 {
785 setActive(true);
786 }
787
788 void DolphinView::slotItemActivated(int index)
789 {
790 const KFileItem item = m_model->fileItem(index);
791 if (!item.isNull()) {
792 emit itemActivated(item);
793 }
794 }
795
796 void DolphinView::slotItemsActivated(const QSet<int>& indexes)
797 {
798 Q_ASSERT(indexes.count() >= 2);
799
800 if (indexes.count() > 5) {
801 QString question = i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes.count());
802 const int answer = KMessageBox::warningYesNo(this, question);
803 if (answer != KMessageBox::Yes) {
804 return;
805 }
806 }
807
808 KFileItemList items;
809 items.reserve(indexes.count());
810
811 QSetIterator<int> it(indexes);
812 while (it.hasNext()) {
813 const int index = it.next();
814 KFileItem item = m_model->fileItem(index);
815 const KUrl& url = openItemAsFolderUrl(item);
816
817 if (!url.isEmpty()) { // Open folders in new tabs
818 emit tabRequested(url);
819 } else {
820 items.append(item);
821 }
822 }
823
824 if (items.count() == 1) {
825 emit itemActivated(items.first());
826 } else if (items.count() > 1) {
827 emit itemsActivated(items);
828 }
829 }
830
831 void DolphinView::slotItemMiddleClicked(int index)
832 {
833 const KFileItem& item = m_model->fileItem(index);
834 const KUrl& url = openItemAsFolderUrl(item);
835 if (!url.isEmpty()) {
836 emit tabRequested(url);
837 } else if (isTabsForFilesEnabled()) {
838 emit tabRequested(item.url());
839 }
840 }
841
842 void DolphinView::slotItemContextMenuRequested(int index, const QPointF& pos)
843 {
844 const KFileItem item = m_model->fileItem(index);
845 emit requestContextMenu(pos.toPoint(), item, url(), QList<QAction*>());
846 }
847
848 void DolphinView::slotViewContextMenuRequested(const QPointF& pos)
849 {
850 emit requestContextMenu(pos.toPoint(), KFileItem(), url(), QList<QAction*>());
851 }
852
853 void DolphinView::slotHeaderContextMenuRequested(const QPointF& pos)
854 {
855 ViewProperties props(viewPropertiesUrl());
856
857 QPointer<KMenu> menu = new KMenu(QApplication::activeWindow());
858
859 KItemListView* view = m_container->controller()->view();
860 const QSet<QByteArray> visibleRolesSet = view->visibleRoles().toSet();
861
862 bool nepomukRunning = false;
863 bool indexingEnabled = false;
864 #ifdef HAVE_NEPOMUK
865 nepomukRunning = (Nepomuk2::ResourceManager::instance()->initialized());
866 if (nepomukRunning) {
867 KConfig config("nepomukserverrc");
868 indexingEnabled = config.group("Service-nepomukfileindexer").readEntry("autostart", true);
869 }
870 #endif
871
872 QString groupName;
873 QMenu* groupMenu = 0;
874
875 // Add all roles to the menu that can be shown or hidden by the user
876 const QList<KFileItemModel::RoleInfo> rolesInfo = KFileItemModel::rolesInformation();
877 foreach (const KFileItemModel::RoleInfo& info, rolesInfo) {
878 if (info.role == "text") {
879 // It should not be possible to hide the "text" role
880 continue;
881 }
882
883 const QString text = m_model->roleDescription(info.role);
884 QAction* action = 0;
885 if (info.group.isEmpty()) {
886 action = menu->addAction(text);
887 } else {
888 if (!groupMenu || info.group != groupName) {
889 groupName = info.group;
890 groupMenu = menu->addMenu(groupName);
891 }
892
893 action = groupMenu->addAction(text);
894 }
895
896 action->setCheckable(true);
897 action->setChecked(visibleRolesSet.contains(info.role));
898 action->setData(info.role);
899
900 const bool enable = (!info.requiresNepomuk && !info.requiresIndexer) ||
901 (info.requiresNepomuk && nepomukRunning) ||
902 (info.requiresIndexer && indexingEnabled);
903 action->setEnabled(enable);
904 }
905
906 menu->addSeparator();
907
908 QActionGroup* widthsGroup = new QActionGroup(menu);
909 const bool autoColumnWidths = props.headerColumnWidths().isEmpty();
910
911 QAction* autoAdjustWidthsAction = menu->addAction(i18nc("@action:inmenu", "Automatic Column Widths"));
912 autoAdjustWidthsAction->setCheckable(true);
913 autoAdjustWidthsAction->setChecked(autoColumnWidths);
914 autoAdjustWidthsAction->setActionGroup(widthsGroup);
915
916 QAction* customWidthsAction = menu->addAction(i18nc("@action:inmenu", "Custom Column Widths"));
917 customWidthsAction->setCheckable(true);
918 customWidthsAction->setChecked(!autoColumnWidths);
919 customWidthsAction->setActionGroup(widthsGroup);
920
921 QAction* action = menu->exec(pos.toPoint());
922 if (menu && action) {
923 KItemListHeader* header = view->header();
924
925 if (action == autoAdjustWidthsAction) {
926 // Clear the column-widths from the viewproperties and turn on
927 // the automatic resizing of the columns
928 props.setHeaderColumnWidths(QList<int>());
929 header->setAutomaticColumnResizing(true);
930 } else if (action == customWidthsAction) {
931 // Apply the current column-widths as custom column-widths and turn
932 // off the automatic resizing of the columns
933 QList<int> columnWidths;
934 foreach (const QByteArray& role, view->visibleRoles()) {
935 columnWidths.append(header->columnWidth(role));
936 }
937 props.setHeaderColumnWidths(columnWidths);
938 header->setAutomaticColumnResizing(false);
939 } else {
940 // Show or hide the selected role
941 const QByteArray selectedRole = action->data().toByteArray();
942
943 QList<QByteArray> visibleRoles = view->visibleRoles();
944 if (action->isChecked()) {
945 visibleRoles.append(selectedRole);
946 } else {
947 visibleRoles.removeOne(selectedRole);
948 }
949
950 view->setVisibleRoles(visibleRoles);
951 props.setVisibleRoles(visibleRoles);
952
953 QList<int> columnWidths;
954 if (!header->automaticColumnResizing()) {
955 foreach (const QByteArray& role, view->visibleRoles()) {
956 columnWidths.append(header->columnWidth(role));
957 }
958 }
959 props.setHeaderColumnWidths(columnWidths);
960 }
961 }
962
963 delete menu;
964 }
965
966 void DolphinView::slotHeaderColumnWidthChanged(const QByteArray& role, qreal current, qreal previous)
967 {
968 Q_UNUSED(previous);
969
970 const QList<QByteArray> visibleRoles = m_view->visibleRoles();
971
972 ViewProperties props(viewPropertiesUrl());
973 QList<int> columnWidths = props.headerColumnWidths();
974 if (columnWidths.count() != visibleRoles.count()) {
975 columnWidths.clear();
976 columnWidths.reserve(visibleRoles.count());
977 const KItemListHeader* header = m_view->header();
978 foreach (const QByteArray& role, visibleRoles) {
979 const int width = header->columnWidth(role);
980 columnWidths.append(width);
981 }
982 }
983
984 const int roleIndex = visibleRoles.indexOf(role);
985 Q_ASSERT(roleIndex >= 0 && roleIndex < columnWidths.count());
986 columnWidths[roleIndex] = current;
987
988 props.setHeaderColumnWidths(columnWidths);
989 }
990
991 void DolphinView::slotItemHovered(int index)
992 {
993 const KFileItem item = m_model->fileItem(index);
994
995 if (GeneralSettings::showToolTips() && !m_dragging) {
996 QRectF itemRect = m_container->controller()->view()->itemContextRect(index);
997 const QPoint pos = m_container->mapToGlobal(itemRect.topLeft().toPoint());
998 itemRect.moveTo(pos);
999
1000 m_toolTipManager->showToolTip(item, itemRect);
1001 }
1002
1003 emit requestItemInfo(item);
1004 }
1005
1006 void DolphinView::slotItemUnhovered(int index)
1007 {
1008 Q_UNUSED(index);
1009 hideToolTip();
1010 emit requestItemInfo(KFileItem());
1011 }
1012
1013 void DolphinView::slotItemDropEvent(int index, QGraphicsSceneDragDropEvent* event)
1014 {
1015 KUrl destUrl;
1016 KFileItem destItem = m_model->fileItem(index);
1017 if (destItem.isNull() || (!destItem.isDir() && !destItem.isDesktopFile())) {
1018 // Use the URL of the view as drop target if the item is no directory
1019 // or desktop-file
1020 destItem = m_model->rootItem();
1021 destUrl = url();
1022 } else {
1023 // The item represents a directory or desktop-file
1024 destUrl = destItem.url();
1025 }
1026
1027 QDropEvent dropEvent(event->pos().toPoint(),
1028 event->possibleActions(),
1029 event->mimeData(),
1030 event->buttons(),
1031 event->modifiers());
1032
1033 QString error;
1034 KonqOperations* op = DragAndDropHelper::dropUrls(destItem, destUrl, &dropEvent, error);
1035 if (!error.isEmpty()) {
1036 emit infoMessage(error);
1037 }
1038
1039 if (op && destUrl == url()) {
1040 // Mark the dropped urls as selected.
1041 m_clearSelectionBeforeSelectingNewItems = true;
1042 connect(op, SIGNAL(urlPasted(KUrl)), this, SLOT(slotUrlPasted(KUrl)));
1043 }
1044 }
1045
1046 void DolphinView::slotModelChanged(KItemModelBase* current, KItemModelBase* previous)
1047 {
1048 if (previous != 0) {
1049 disconnect(previous, SIGNAL(directoryLoadingCompleted()), this, SLOT(slotDirectoryLoadingCompleted()));
1050 m_versionControlObserver->setModel(0);
1051 }
1052
1053 if (current) {
1054 Q_ASSERT(qobject_cast<KFileItemModel*>(current));
1055 connect(current, SIGNAL(loadingCompleted()), this, SLOT(slotDirectoryLoadingCompleted()));
1056
1057 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(current);
1058 m_versionControlObserver->setModel(fileItemModel);
1059 }
1060 }
1061
1062 void DolphinView::slotMouseButtonPressed(int itemIndex, Qt::MouseButtons buttons)
1063 {
1064 hideToolTip();
1065
1066 if (itemIndex < 0) {
1067 // Trigger the history navigation only when clicking on the viewport:
1068 // Above an item the XButtons provide a simple way to select items in
1069 // the singleClick mode.
1070 if (buttons & Qt::XButton1) {
1071 emit goBackRequested();
1072 } else if (buttons & Qt::XButton2) {
1073 emit goForwardRequested();
1074 }
1075 }
1076 }
1077
1078 void DolphinView::slotAboutToCreate(const KUrl::List& urls)
1079 {
1080 if (!urls.isEmpty()) {
1081 if (m_markFirstNewlySelectedItemAsCurrent) {
1082 markUrlAsCurrent(urls.first());
1083 m_markFirstNewlySelectedItemAsCurrent = false;
1084 }
1085 m_selectedUrls << urls;
1086 }
1087 }
1088
1089 void DolphinView::slotSelectionChanged(const QSet<int>& current, const QSet<int>& previous)
1090 {
1091 const int currentCount = current.count();
1092 const int previousCount = previous.count();
1093 const bool selectionStateChanged = (currentCount == 0 && previousCount > 0) ||
1094 (currentCount > 0 && previousCount == 0);
1095
1096 // If nothing has been selected before and something got selected (or if something
1097 // was selected before and now nothing is selected) the selectionChangedSignal must
1098 // be emitted asynchronously as fast as possible to update the edit-actions.
1099 m_selectionChangedTimer->setInterval(selectionStateChanged ? 0 : 300);
1100 m_selectionChangedTimer->start();
1101 }
1102
1103 void DolphinView::emitSelectionChangedSignal()
1104 {
1105 m_selectionChangedTimer->stop();
1106 emit selectionChanged(selectedItems());
1107 }
1108
1109 void DolphinView::updateSortRole(const QByteArray& role)
1110 {
1111 ViewProperties props(viewPropertiesUrl());
1112 props.setSortRole(role);
1113
1114 KItemModelBase* model = m_container->controller()->model();
1115 model->setSortRole(role);
1116
1117 emit sortRoleChanged(role);
1118 }
1119
1120 void DolphinView::updateSortOrder(Qt::SortOrder order)
1121 {
1122 ViewProperties props(viewPropertiesUrl());
1123 props.setSortOrder(order);
1124
1125 m_model->setSortOrder(order);
1126
1127 emit sortOrderChanged(order);
1128 }
1129
1130 void DolphinView::updateSortFoldersFirst(bool foldersFirst)
1131 {
1132 ViewProperties props(viewPropertiesUrl());
1133 props.setSortFoldersFirst(foldersFirst);
1134
1135 m_model->setSortDirectoriesFirst(foldersFirst);
1136
1137 emit sortFoldersFirstChanged(foldersFirst);
1138 }
1139
1140 QPair<bool, QString> DolphinView::pasteInfo() const
1141 {
1142 return KonqOperations::pasteInfo(url());
1143 }
1144
1145 void DolphinView::setTabsForFilesEnabled(bool tabsForFiles)
1146 {
1147 m_tabsForFiles = tabsForFiles;
1148 }
1149
1150 bool DolphinView::isTabsForFilesEnabled() const
1151 {
1152 return m_tabsForFiles;
1153 }
1154
1155 bool DolphinView::itemsExpandable() const
1156 {
1157 return m_mode == DetailsView;
1158 }
1159
1160 void DolphinView::restoreState(QDataStream& stream)
1161 {
1162 // Restore the current item that had the keyboard focus
1163 stream >> m_currentItemUrl;
1164
1165 // Restore the view position
1166 stream >> m_restoredContentsPosition;
1167
1168 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1169 QSet<KUrl> urls;
1170 stream >> urls;
1171 m_model->restoreExpandedDirectories(urls);
1172 }
1173
1174 void DolphinView::saveState(QDataStream& stream)
1175 {
1176 // Save the current item that has the keyboard focus
1177 const int currentIndex = m_container->controller()->selectionManager()->currentItem();
1178 if (currentIndex != -1) {
1179 KFileItem item = m_model->fileItem(currentIndex);
1180 Q_ASSERT(!item.isNull()); // If the current index is valid a item must exist
1181 KUrl currentItemUrl = item.url();
1182 stream << currentItemUrl;
1183 } else {
1184 stream << KUrl();
1185 }
1186
1187 // Save view position
1188 const qreal x = m_container->horizontalScrollBar()->value();
1189 const qreal y = m_container->verticalScrollBar()->value();
1190 stream << QPoint(x, y);
1191
1192 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1193 stream << m_model->expandedDirectories();
1194 }
1195
1196 KFileItem DolphinView::rootItem() const
1197 {
1198 return m_model->rootItem();
1199 }
1200
1201 void DolphinView::setViewPropertiesContext(const QString& context)
1202 {
1203 m_viewPropertiesContext = context;
1204 }
1205
1206 QString DolphinView::viewPropertiesContext() const
1207 {
1208 return m_viewPropertiesContext;
1209 }
1210
1211 KUrl DolphinView::openItemAsFolderUrl(const KFileItem& item, const bool browseThroughArchives)
1212 {
1213 if (item.isNull()) {
1214 return KUrl();
1215 }
1216
1217 KUrl url = item.targetUrl();
1218
1219 if (item.isDir()) {
1220 return url;
1221 }
1222
1223 if (item.isMimeTypeKnown()) {
1224 const QString& mimetype = item.mimetype();
1225
1226 if (browseThroughArchives && item.isFile() && url.isLocalFile()) {
1227 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1228 // zip:/<path>/ when clicking on a zip file, etc.
1229 // The .protocol file specifies the mimetype that the kioslave handles.
1230 // Note that we don't use mimetype inheritance since we don't want to
1231 // open OpenDocument files as zip folders...
1232 const QString& protocol = KProtocolManager::protocolForArchiveMimetype(mimetype);
1233 if (!protocol.isEmpty()) {
1234 url.setProtocol(protocol);
1235 return url;
1236 }
1237 }
1238
1239 if (mimetype == QLatin1String("application/x-desktop")) {
1240 // Redirect to the URL in Type=Link desktop files
1241 KDesktopFile desktopFile(url.toLocalFile());
1242 if (desktopFile.hasLinkType()) {
1243 return desktopFile.readUrl();
1244 }
1245 }
1246 }
1247
1248 return KUrl();
1249 }
1250
1251 void DolphinView::observeCreatedItem(const KUrl& url)
1252 {
1253 if (m_active) {
1254 clearSelection();
1255 markUrlAsCurrent(url);
1256 markUrlsAsSelected(QList<KUrl>() << url);
1257 }
1258 }
1259
1260 void DolphinView::slotDirectoryRedirection(const KUrl& oldUrl, const KUrl& newUrl)
1261 {
1262 if (oldUrl.equals(url(), KUrl::CompareWithoutTrailingSlash)) {
1263 emit redirection(oldUrl, newUrl);
1264 m_url = newUrl; // #186947
1265 }
1266 }
1267
1268 void DolphinView::updateViewState()
1269 {
1270 if (m_currentItemUrl != KUrl()) {
1271 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1272 const int currentIndex = m_model->index(m_currentItemUrl);
1273 if (currentIndex != -1) {
1274 selectionManager->setCurrentItem(currentIndex);
1275
1276 // scroll to current item and reset the state
1277 if (m_scrollToCurrentItem) {
1278 m_view->scrollToItem(currentIndex);
1279 m_scrollToCurrentItem = false;
1280 }
1281
1282 m_currentItemUrl = KUrl();
1283 } else {
1284 selectionManager->setCurrentItem(0);
1285 }
1286 }
1287
1288 if (!m_restoredContentsPosition.isNull()) {
1289 const int x = m_restoredContentsPosition.x();
1290 const int y = m_restoredContentsPosition.y();
1291 m_restoredContentsPosition = QPoint();
1292
1293 m_container->horizontalScrollBar()->setValue(x);
1294 m_container->verticalScrollBar()->setValue(y);
1295 }
1296
1297 if (!m_selectedUrls.isEmpty()) {
1298 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1299
1300 if (m_clearSelectionBeforeSelectingNewItems) {
1301 selectionManager->clearSelection();
1302 m_clearSelectionBeforeSelectingNewItems = false;
1303 }
1304
1305 QSet<int> selectedItems = selectionManager->selectedItems();
1306
1307 QList<KUrl>::iterator it = m_selectedUrls.begin();
1308 while (it != m_selectedUrls.end()) {
1309 const int index = m_model->index(*it);
1310 if (index >= 0) {
1311 selectedItems.insert(index);
1312 it = m_selectedUrls.erase(it);
1313 } else {
1314 ++it;
1315 }
1316 }
1317
1318 selectionManager->setSelectedItems(selectedItems);
1319 }
1320 }
1321
1322 void DolphinView::hideToolTip()
1323 {
1324 if (GeneralSettings::showToolTips()) {
1325 m_toolTipManager->hideToolTip();
1326 }
1327 }
1328
1329 void DolphinView::calculateItemCount(int& fileCount,
1330 int& folderCount,
1331 KIO::filesize_t& totalFileSize) const
1332 {
1333 const int itemCount = m_model->count();
1334 for (int i = 0; i < itemCount; ++i) {
1335 const KFileItem item = m_model->fileItem(i);
1336 if (item.isDir()) {
1337 ++folderCount;
1338 } else {
1339 ++fileCount;
1340 totalFileSize += item.size();
1341 }
1342 }
1343 }
1344
1345 void DolphinView::showHoverInformation(const KFileItem& item)
1346 {
1347 emit requestItemInfo(item);
1348 }
1349
1350 void DolphinView::clearHoverInformation()
1351 {
1352 emit requestItemInfo(KFileItem());
1353 }
1354
1355 void DolphinView::slotDeleteFileFinished(KJob* job)
1356 {
1357 if (job->error() == 0) {
1358 emit operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1359 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1360 emit errorMessage(job->errorString());
1361 }
1362 }
1363
1364 void DolphinView::slotDirectoryLoadingStarted()
1365 {
1366 // Disable the writestate temporary until it can be determined in a fast way
1367 // in DolphinView::slotLoadingCompleted()
1368 if (m_isFolderWritable) {
1369 m_isFolderWritable = false;
1370 emit writeStateChanged(m_isFolderWritable);
1371 }
1372
1373 emit directoryLoadingStarted();
1374 }
1375
1376 void DolphinView::slotDirectoryLoadingCompleted()
1377 {
1378 // Update the view-state. This has to be done asynchronously
1379 // because the view might not be in its final state yet.
1380 QTimer::singleShot(0, this, SLOT(updateViewState()));
1381
1382 emit directoryLoadingCompleted();
1383
1384 updateWritableState();
1385 }
1386
1387 void DolphinView::slotItemsChanged()
1388 {
1389 m_assureVisibleCurrentIndex = false;
1390 }
1391
1392 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current, Qt::SortOrder previous)
1393 {
1394 Q_UNUSED(previous);
1395 Q_ASSERT(m_model->sortOrder() == current);
1396
1397 ViewProperties props(viewPropertiesUrl());
1398 props.setSortOrder(current);
1399
1400 emit sortOrderChanged(current);
1401 }
1402
1403 void DolphinView::slotSortRoleChangedByHeader(const QByteArray& current, const QByteArray& previous)
1404 {
1405 Q_UNUSED(previous);
1406 Q_ASSERT(m_model->sortRole() == current);
1407
1408 ViewProperties props(viewPropertiesUrl());
1409 props.setSortRole(current);
1410
1411 emit sortRoleChanged(current);
1412 }
1413
1414 void DolphinView::slotVisibleRolesChangedByHeader(const QList<QByteArray>& current,
1415 const QList<QByteArray>& previous)
1416 {
1417 Q_UNUSED(previous);
1418 Q_ASSERT(m_container->controller()->view()->visibleRoles() == current);
1419
1420 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1421
1422 m_visibleRoles = current;
1423
1424 ViewProperties props(viewPropertiesUrl());
1425 props.setVisibleRoles(m_visibleRoles);
1426
1427 emit visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1428 }
1429
1430 void DolphinView::slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value)
1431 {
1432 if (index < 0 || index >= m_model->count()) {
1433 return;
1434 }
1435
1436 if (role == "text") {
1437 const KFileItem oldItem = m_model->fileItem(index);
1438 const QString newName = value.toString();
1439 if (!newName.isEmpty() && newName != oldItem.text() && newName != QLatin1String(".") && newName != QLatin1String("..")) {
1440 const KUrl oldUrl = oldItem.url();
1441
1442 const KUrl newUrl(url().path(KUrl::AddTrailingSlash) + newName);
1443 const bool newNameExistsAlready = (m_model->index(newUrl) >= 0);
1444 if (!newNameExistsAlready) {
1445 // Only change the data in the model if no item with the new name
1446 // is in the model yet. If there is an item with the new name
1447 // already, calling KonqOperations::rename() will open a dialog
1448 // asking for a new name, and KFileItemModel will update the
1449 // data when the dir lister signals that the file name has changed.
1450 QHash<QByteArray, QVariant> data;
1451 data.insert(role, value);
1452 m_model->setData(index, data);
1453 }
1454
1455 KonqOperations::rename(this, oldUrl, newName);
1456 }
1457 }
1458 }
1459
1460 void DolphinView::loadDirectory(const KUrl& url, bool reload)
1461 {
1462 if (!url.isValid()) {
1463 const QString location(url.pathOrUrl());
1464 if (location.isEmpty()) {
1465 emit errorMessage(i18nc("@info:status", "The location is empty."));
1466 } else {
1467 emit errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location));
1468 }
1469 return;
1470 }
1471
1472 if (reload) {
1473 m_model->refreshDirectory(url);
1474 } else {
1475 m_model->loadDirectory(url);
1476 }
1477 }
1478
1479 void DolphinView::applyViewProperties()
1480 {
1481 m_view->beginTransaction();
1482
1483 const ViewProperties props(viewPropertiesUrl());
1484
1485 const Mode mode = props.viewMode();
1486 if (m_mode != mode) {
1487 const Mode previousMode = m_mode;
1488 m_mode = mode;
1489
1490 // Changing the mode might result in changing
1491 // the zoom level. Remember the old zoom level so
1492 // that zoomLevelChanged() can get emitted.
1493 const int oldZoomLevel = m_view->zoomLevel();
1494 applyModeToView();
1495
1496 emit modeChanged(m_mode, previousMode);
1497
1498 if (m_view->zoomLevel() != oldZoomLevel) {
1499 emit zoomLevelChanged(m_view->zoomLevel(), oldZoomLevel);
1500 }
1501 }
1502
1503 const bool hiddenFilesShown = props.hiddenFilesShown();
1504 if (hiddenFilesShown != m_model->showHiddenFiles()) {
1505 m_model->setShowHiddenFiles(hiddenFilesShown);
1506 emit hiddenFilesShownChanged(hiddenFilesShown);
1507 }
1508
1509 const bool groupedSorting = props.groupedSorting();
1510 if (groupedSorting != m_model->groupedSorting()) {
1511 m_model->setGroupedSorting(groupedSorting);
1512 emit groupedSortingChanged(groupedSorting);
1513 }
1514
1515 const QByteArray sortRole = props.sortRole();
1516 if (sortRole != m_model->sortRole()) {
1517 m_model->setSortRole(sortRole);
1518 emit sortRoleChanged(sortRole);
1519 }
1520
1521 const Qt::SortOrder sortOrder = props.sortOrder();
1522 if (sortOrder != m_model->sortOrder()) {
1523 m_model->setSortOrder(sortOrder);
1524 emit sortOrderChanged(sortOrder);
1525 }
1526
1527 const bool sortFoldersFirst = props.sortFoldersFirst();
1528 if (sortFoldersFirst != m_model->sortDirectoriesFirst()) {
1529 m_model->setSortDirectoriesFirst(sortFoldersFirst);
1530 emit sortFoldersFirstChanged(sortFoldersFirst);
1531 }
1532
1533 const QList<QByteArray> visibleRoles = props.visibleRoles();
1534 if (visibleRoles != m_visibleRoles) {
1535 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1536 m_visibleRoles = visibleRoles;
1537 m_view->setVisibleRoles(visibleRoles);
1538 emit visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1539 }
1540
1541 const bool previewsShown = props.previewsShown();
1542 if (previewsShown != m_view->previewsShown()) {
1543 const int oldZoomLevel = zoomLevel();
1544
1545 m_view->setPreviewsShown(previewsShown);
1546 emit previewsShownChanged(previewsShown);
1547
1548 // Changing the preview-state might result in a changed zoom-level
1549 if (oldZoomLevel != zoomLevel()) {
1550 emit zoomLevelChanged(zoomLevel(), oldZoomLevel);
1551 }
1552 }
1553
1554 KItemListView* itemListView = m_container->controller()->view();
1555 if (itemListView->isHeaderVisible()) {
1556 KItemListHeader* header = itemListView->header();
1557 const QList<int> headerColumnWidths = props.headerColumnWidths();
1558 const int rolesCount = m_visibleRoles.count();
1559 if (headerColumnWidths.count() == rolesCount) {
1560 header->setAutomaticColumnResizing(false);
1561
1562 QHash<QByteArray, qreal> columnWidths;
1563 for (int i = 0; i < rolesCount; ++i) {
1564 columnWidths.insert(m_visibleRoles[i], headerColumnWidths[i]);
1565 }
1566 header->setColumnWidths(columnWidths);
1567 } else {
1568 header->setAutomaticColumnResizing(true);
1569 }
1570 }
1571
1572 m_view->endTransaction();
1573 }
1574
1575 void DolphinView::applyModeToView()
1576 {
1577 switch (m_mode) {
1578 case IconsView: m_view->setItemLayout(KFileItemListView::IconsLayout); break;
1579 case CompactView: m_view->setItemLayout(KFileItemListView::CompactLayout); break;
1580 case DetailsView: m_view->setItemLayout(KFileItemListView::DetailsLayout); break;
1581 default: Q_ASSERT(false); break;
1582 }
1583 }
1584
1585 void DolphinView::pasteToUrl(const KUrl& url)
1586 {
1587 KonqOperations* op = KonqOperations::doPasteV2(this, url);
1588 if (op) {
1589 m_clearSelectionBeforeSelectingNewItems = true;
1590 m_markFirstNewlySelectedItemAsCurrent = true;
1591 connect(op, SIGNAL(aboutToCreate(KUrl::List)), this, SLOT(slotAboutToCreate(KUrl::List)));
1592 }
1593 }
1594
1595 KUrl::List DolphinView::simplifiedSelectedUrls() const
1596 {
1597 KUrl::List urls;
1598
1599 const KFileItemList items = selectedItems();
1600 foreach (const KFileItem& item, items) {
1601 urls.append(item.url());
1602 }
1603
1604 if (itemsExpandable()) {
1605 // TODO: Check if we still need KDirModel for this in KDE 5.0
1606 urls = KDirModel::simplifiedUrlList(urls);
1607 }
1608
1609 return urls;
1610 }
1611
1612 QMimeData* DolphinView::selectionMimeData() const
1613 {
1614 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1615 const QSet<int> selectedIndexes = selectionManager->selectedItems();
1616
1617 return m_model->createMimeData(selectedIndexes);
1618 }
1619
1620 void DolphinView::updateWritableState()
1621 {
1622 const bool wasFolderWritable = m_isFolderWritable;
1623 m_isFolderWritable = true;
1624
1625 const KFileItem item = m_model->rootItem();
1626 if (!item.isNull()) {
1627 KFileItemListProperties capabilities(KFileItemList() << item);
1628 m_isFolderWritable = capabilities.supportsWriting();
1629 }
1630 if (m_isFolderWritable != wasFolderWritable) {
1631 emit writeStateChanged(m_isFolderWritable);
1632 }
1633 }
1634
1635 KUrl DolphinView::viewPropertiesUrl() const
1636 {
1637 if (m_viewPropertiesContext.isEmpty()) {
1638 return m_url;
1639 }
1640
1641 KUrl url;
1642 url.setProtocol(m_url.protocol());
1643 url.setPath(m_viewPropertiesContext);
1644 return url;
1645 }
1646
1647 #include "dolphinview.moc"