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