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