]> cloud.milkyroute.net Git - dolphin.git/blob - src/views/dolphinview.cpp
Merge remote-tracking branch 'origin/KDE/4.10'
[dolphin.git] / src / views / dolphinview.cpp
1 /***************************************************************************
2 * Copyright (C) 2006-2009 by Peter Penz <peter.penz19@gmail.com> *
3 * Copyright (C) 2006 by Gregor Kališnik <gregor@podnapisi.net> *
4 * *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) any later version. *
9 * *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
14 * *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
19 ***************************************************************************/
20
21 #include "dolphinview.h"
22
23 #include <config-nepomuk.h>
24
25 #include <QAbstractItemView>
26 #include <QApplication>
27 #include <QBoxLayout>
28 #include <QClipboard>
29 #include <QDropEvent>
30 #include <QGraphicsSceneDragDropEvent>
31 #include <QKeyEvent>
32 #include <QItemSelection>
33 #include <QTimer>
34 #include <QScrollBar>
35
36 #include <KDesktopFile>
37 #include <KProtocolManager>
38 #include <KActionCollection>
39 #include <KColorScheme>
40 #include <KDirModel>
41 #include <KIconEffect>
42 #include <KFileItem>
43 #include <KFileItemListProperties>
44 #include <KLocale>
45 #include <kitemviews/kfileitemmodel.h>
46 #include <kitemviews/kfileitemlistview.h>
47 #include <kitemviews/kitemlistcontainer.h>
48 #include <kitemviews/kitemlistheader.h>
49 #include <kitemviews/kitemlistselectionmanager.h>
50 #include <kitemviews/kitemlistview.h>
51 #include <kitemviews/kitemlistcontroller.h>
52 #include <KIO/DeleteJob>
53 #include <KIO/JobUiDelegate>
54 #include <KIO/NetAccess>
55 #include <KIO/PreviewJob>
56 #include <KJob>
57 #include <KMenu>
58 #include <KMessageBox>
59 #include <konq_fileitemcapabilities.h>
60 #include <konq_operations.h>
61 #include <konqmimedata.h>
62 #include <KToggleAction>
63 #include <KUrl>
64
65 #include "dolphinnewfilemenuobserver.h"
66 #include "dolphin_detailsmodesettings.h"
67 #include "dolphin_generalsettings.h"
68 #include "dolphinitemlistview.h"
69 #include "draganddrophelper.h"
70 #include "renamedialog.h"
71 #include "versioncontrol/versioncontrolobserver.h"
72 #include "viewmodecontroller.h"
73 #include "viewproperties.h"
74 #include "views/tooltips/tooltipmanager.h"
75 #include "zoomlevelinfo.h"
76
77 #ifdef HAVE_NEPOMUK
78 #include <Nepomuk2/ResourceManager>
79 #endif
80
81 namespace {
82 const int MaxModeEnum = DolphinView::CompactView;
83 };
84
85 DolphinView::DolphinView(const KUrl& url, QWidget* parent) :
86 QWidget(parent),
87 m_active(true),
88 m_tabsForFiles(false),
89 m_assureVisibleCurrentIndex(false),
90 m_isFolderWritable(true),
91 m_dragging(false),
92 m_url(url),
93 m_viewPropertiesContext(),
94 m_mode(DolphinView::IconsView),
95 m_visibleRoles(),
96 m_topLayout(0),
97 m_model(0),
98 m_view(0),
99 m_container(0),
100 m_toolTipManager(0),
101 m_selectionChangedTimer(0),
102 m_currentItemUrl(),
103 m_scrollToCurrentItem(false),
104 m_restoredContentsPosition(),
105 m_selectedUrls(),
106 m_clearSelectionBeforeSelectingNewItems(false),
107 m_markFirstNewlySelectedItemAsCurrent(false),
108 m_versionControlObserver(0)
109 {
110 m_topLayout = new QVBoxLayout(this);
111 m_topLayout->setSpacing(0);
112 m_topLayout->setMargin(0);
113
114 // When a new item has been created by the "Create New..." menu, the item should
115 // get selected and it must be assured that the item will get visible. As the
116 // creation is done asynchronously, several signals must be checked:
117 connect(&DolphinNewFileMenuObserver::instance(), SIGNAL(itemCreated(KUrl)),
118 this, SLOT(observeCreatedItem(KUrl)));
119
120 m_selectionChangedTimer = new QTimer(this);
121 m_selectionChangedTimer->setSingleShot(true);
122 m_selectionChangedTimer->setInterval(300);
123 connect(m_selectionChangedTimer, SIGNAL(timeout()),
124 this, SLOT(emitSelectionChangedSignal()));
125
126 m_model = new KFileItemModel(this);
127 m_view = new DolphinItemListView();
128 m_view->setEnabledSelectionToggles(GeneralSettings::showSelectionToggle());
129 m_view->setVisibleRoles(QList<QByteArray>() << "text");
130 applyModeToView();
131
132 KItemListController* controller = new KItemListController(m_model, m_view, this);
133 const int delay = GeneralSettings::autoExpandFolders() ? 750 : -1;
134 controller->setAutoActivationDelay(delay);
135
136 // The EnlargeSmallPreviews setting can only be changed after the model
137 // has been set in the view by KItemListController.
138 m_view->setEnlargeSmallPreviews(GeneralSettings::enlargeSmallPreviews());
139
140 m_container = new KItemListContainer(controller, this);
141 m_container->installEventFilter(this);
142 setFocusProxy(m_container);
143 connect(m_container->horizontalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(hideToolTip()));
144 connect(m_container->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(hideToolTip()));
145
146 controller->setSelectionBehavior(KItemListController::MultiSelection);
147 connect(controller, SIGNAL(itemActivated(int)), this, SLOT(slotItemActivated(int)));
148 connect(controller, SIGNAL(itemsActivated(QSet<int>)), this, SLOT(slotItemsActivated(QSet<int>)));
149 connect(controller, SIGNAL(itemMiddleClicked(int)), this, SLOT(slotItemMiddleClicked(int)));
150 connect(controller, SIGNAL(itemContextMenuRequested(int,QPointF)), this, SLOT(slotItemContextMenuRequested(int,QPointF)));
151 connect(controller, SIGNAL(viewContextMenuRequested(QPointF)), this, SLOT(slotViewContextMenuRequested(QPointF)));
152 connect(controller, SIGNAL(headerContextMenuRequested(QPointF)), this, SLOT(slotHeaderContextMenuRequested(QPointF)));
153 connect(controller, SIGNAL(mouseButtonPressed(int,Qt::MouseButtons)), this, SLOT(slotMouseButtonPressed(int,Qt::MouseButtons)));
154 connect(controller, SIGNAL(itemHovered(int)), this, SLOT(slotItemHovered(int)));
155 connect(controller, SIGNAL(itemUnhovered(int)), this, SLOT(slotItemUnhovered(int)));
156 connect(controller, SIGNAL(itemDropEvent(int,QGraphicsSceneDragDropEvent*)), this, SLOT(slotItemDropEvent(int,QGraphicsSceneDragDropEvent*)));
157 connect(controller, SIGNAL(modelChanged(KItemModelBase*,KItemModelBase*)), this, SLOT(slotModelChanged(KItemModelBase*,KItemModelBase*)));
158
159 connect(m_model, SIGNAL(directoryLoadingStarted()), this, SLOT(slotDirectoryLoadingStarted()));
160 connect(m_model, SIGNAL(directoryLoadingCompleted()), this, SLOT(slotDirectoryLoadingCompleted()));
161 connect(m_model, SIGNAL(directoryLoadingCanceled()), this, SIGNAL(directoryLoadingCanceled()));
162 connect(m_model, SIGNAL(directoryLoadingProgress(int)), this, SIGNAL(directoryLoadingProgress(int)));
163 connect(m_model, SIGNAL(directorySortingProgress(int)), this, SIGNAL(directorySortingProgress(int)));
164 connect(m_model, SIGNAL(itemsChanged(KItemRangeList,QSet<QByteArray>)),
165 this, SLOT(slotItemsChanged()));
166 connect(m_model, SIGNAL(itemsRemoved(KItemRangeList)), this, SIGNAL(itemCountChanged()));
167 connect(m_model, SIGNAL(itemsInserted(KItemRangeList)), this, SIGNAL(itemCountChanged()));
168 connect(m_model, SIGNAL(infoMessage(QString)), this, SIGNAL(infoMessage(QString)));
169 connect(m_model, SIGNAL(errorMessage(QString)), this, SIGNAL(errorMessage(QString)));
170 connect(m_model, SIGNAL(directoryRedirection(KUrl,KUrl)), this, SLOT(slotDirectoryRedirection(KUrl,KUrl)));
171 connect(m_model, SIGNAL(urlIsFileError(KUrl)), this, SIGNAL(urlIsFileError(KUrl)));
172
173 m_view->installEventFilter(this);
174 connect(m_view, SIGNAL(sortOrderChanged(Qt::SortOrder,Qt::SortOrder)),
175 this, SLOT(slotSortOrderChangedByHeader(Qt::SortOrder,Qt::SortOrder)));
176 connect(m_view, SIGNAL(sortRoleChanged(QByteArray,QByteArray)),
177 this, SLOT(slotSortRoleChangedByHeader(QByteArray,QByteArray)));
178 connect(m_view, SIGNAL(visibleRolesChanged(QList<QByteArray>,QList<QByteArray>)),
179 this, SLOT(slotVisibleRolesChangedByHeader(QList<QByteArray>,QList<QByteArray>)));
180 connect(m_view, SIGNAL(roleEditingCanceled(int,QByteArray,QVariant)),
181 this, SLOT(slotRoleEditingCanceled()));
182 connect(m_view->header(), SIGNAL(columnWidthChanged(QByteArray,qreal,qreal)),
183 this, SLOT(slotHeaderColumnWidthChanged(QByteArray,qreal,qreal)));
184
185 KItemListSelectionManager* selectionManager = controller->selectionManager();
186 connect(selectionManager, SIGNAL(selectionChanged(QSet<int>,QSet<int>)),
187 this, SLOT(slotSelectionChanged(QSet<int>,QSet<int>)));
188
189 m_toolTipManager = new ToolTipManager(this);
190
191 m_versionControlObserver = new VersionControlObserver(this);
192 m_versionControlObserver->setModel(m_model);
193 connect(m_versionControlObserver, SIGNAL(infoMessage(QString)), this, SIGNAL(infoMessage(QString)));
194 connect(m_versionControlObserver, SIGNAL(errorMessage(QString)), this, SIGNAL(errorMessage(QString)));
195 connect(m_versionControlObserver, SIGNAL(operationCompletedMessage(QString)), this, SIGNAL(operationCompletedMessage(QString)));
196
197 applyViewProperties();
198 m_topLayout->addWidget(m_container);
199
200 loadDirectory(url);
201 }
202
203 DolphinView::~DolphinView()
204 {
205 }
206
207 KUrl DolphinView::url() const
208 {
209 return m_url;
210 }
211
212 void DolphinView::setActive(bool active)
213 {
214 if (active == m_active) {
215 return;
216 }
217
218 m_active = active;
219
220 QColor color = KColorScheme(QPalette::Active, KColorScheme::View).background().color();
221 if (!active) {
222 color.setAlpha(150);
223 }
224
225 QWidget* viewport = m_container->viewport();
226 if (viewport) {
227 QPalette palette;
228 palette.setColor(viewport->backgroundRole(), color);
229 viewport->setPalette(palette);
230 }
231
232 update();
233
234 if (active) {
235 m_container->setFocus();
236 emit activated();
237 emit writeStateChanged(m_isFolderWritable);
238 }
239 }
240
241 bool DolphinView::isActive() const
242 {
243 return m_active;
244 }
245
246 void DolphinView::setMode(Mode mode)
247 {
248 if (mode != m_mode) {
249 ViewProperties props(viewPropertiesUrl());
250 props.setViewMode(mode);
251
252 // We pass the new ViewProperties to applyViewProperties, rather than
253 // storing them on disk and letting applyViewProperties() read them
254 // from there, to prevent that changing the view mode fails if the
255 // .directory file is not writable (see bug 318534).
256 applyViewProperties(props);
257 }
258 }
259
260 DolphinView::Mode DolphinView::mode() const
261 {
262 return m_mode;
263 }
264
265 void DolphinView::setPreviewsShown(bool show)
266 {
267 if (previewsShown() == show) {
268 return;
269 }
270
271 ViewProperties props(viewPropertiesUrl());
272 props.setPreviewsShown(show);
273
274 const int oldZoomLevel = m_view->zoomLevel();
275 m_view->setPreviewsShown(show);
276 emit previewsShownChanged(show);
277
278 const int newZoomLevel = m_view->zoomLevel();
279 if (newZoomLevel != oldZoomLevel) {
280 emit zoomLevelChanged(newZoomLevel, oldZoomLevel);
281 }
282 }
283
284 bool DolphinView::previewsShown() const
285 {
286 return m_view->previewsShown();
287 }
288
289 void DolphinView::setHiddenFilesShown(bool show)
290 {
291 if (m_model->showHiddenFiles() == show) {
292 return;
293 }
294
295 const KFileItemList itemList = selectedItems();
296 m_selectedUrls.clear();
297 m_selectedUrls = itemList.urlList();
298
299 ViewProperties props(viewPropertiesUrl());
300 props.setHiddenFilesShown(show);
301
302 m_model->setShowHiddenFiles(show);
303 emit hiddenFilesShownChanged(show);
304 }
305
306 bool DolphinView::hiddenFilesShown() const
307 {
308 return m_model->showHiddenFiles();
309 }
310
311 void DolphinView::setGroupedSorting(bool grouped)
312 {
313 if (grouped == groupedSorting()) {
314 return;
315 }
316
317 ViewProperties props(viewPropertiesUrl());
318 props.setGroupedSorting(grouped);
319 props.save();
320
321 m_container->controller()->model()->setGroupedSorting(grouped);
322
323 emit groupedSortingChanged(grouped);
324 }
325
326 bool DolphinView::groupedSorting() const
327 {
328 return m_model->groupedSorting();
329 }
330
331 KFileItemList DolphinView::items() const
332 {
333 KFileItemList list;
334 const int itemCount = m_model->count();
335 list.reserve(itemCount);
336
337 for (int i = 0; i < itemCount; ++i) {
338 list.append(m_model->fileItem(i));
339 }
340
341 return list;
342 }
343
344 int DolphinView::itemsCount() const
345 {
346 return m_model->count();
347 }
348
349 KFileItemList DolphinView::selectedItems() const
350 {
351 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
352 QList<int> selectedIndexes = selectionManager->selectedItems().toList();
353
354 qSort(selectedIndexes);
355
356 KFileItemList selectedItems;
357 QListIterator<int> it(selectedIndexes);
358 while (it.hasNext()) {
359 const int index = it.next();
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 QSet<int> and
393 // select them in one go after the loop, but we'd need a new function
394 // KItemListSelectionManager::setSelected(QSet<int>, 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 = itemList.urlList();
480
481 setUrl(url());
482 loadDirectory(url(), true);
483
484 QDataStream restoreStream(viewState);
485 restoreState(restoreStream);
486 }
487
488 void DolphinView::stopLoading()
489 {
490 m_model->cancelDirectoryLoading();
491 }
492
493 void DolphinView::readSettings()
494 {
495 const int oldZoomLevel = m_view->zoomLevel();
496
497 GeneralSettings::self()->readConfig();
498 m_view->readSettings();
499 applyViewProperties();
500
501 const int delay = GeneralSettings::autoExpandFolders() ? 750 : -1;
502 m_container->controller()->setAutoActivationDelay(delay);
503
504 const int newZoomLevel = m_view->zoomLevel();
505 if (newZoomLevel != oldZoomLevel) {
506 emit zoomLevelChanged(newZoomLevel, oldZoomLevel);
507 }
508 }
509
510 void DolphinView::writeSettings()
511 {
512 GeneralSettings::self()->writeConfig();
513 m_view->writeSettings();
514 }
515
516 void DolphinView::setNameFilter(const QString& nameFilter)
517 {
518 m_model->setNameFilter(nameFilter);
519 }
520
521 QString DolphinView::nameFilter() const
522 {
523 return m_model->nameFilter();
524 }
525
526 void DolphinView::setMimeTypeFilters(const QStringList& filters)
527 {
528 return m_model->setMimeTypeFilters(filters);
529 }
530
531 QStringList DolphinView::mimeTypeFilters() const
532 {
533 return m_model->mimeTypeFilters();
534 }
535
536 QString DolphinView::statusBarText() const
537 {
538 QString summary;
539 QString foldersText;
540 QString filesText;
541
542 int folderCount = 0;
543 int fileCount = 0;
544 KIO::filesize_t totalFileSize = 0;
545
546 if (m_container->controller()->selectionManager()->hasSelection()) {
547 // Give a summary of the status of the selected files
548 const KFileItemList list = selectedItems();
549 foreach (const KFileItem& item, list) {
550 if (item.isDir()) {
551 ++folderCount;
552 } else {
553 ++fileCount;
554 totalFileSize += item.size();
555 }
556 }
557
558 if (folderCount + fileCount == 1) {
559 // If only one item is selected, show the filename
560 filesText = i18nc("@info:status", "<filename>%1</filename> selected", list.first().text());
561 } else {
562 // At least 2 items are selected
563 foldersText = i18ncp("@info:status", "1 Folder selected", "%1 Folders selected", folderCount);
564 filesText = i18ncp("@info:status", "1 File selected", "%1 Files selected", fileCount);
565 }
566 } else {
567 calculateItemCount(fileCount, folderCount, totalFileSize);
568 foldersText = i18ncp("@info:status", "1 Folder", "%1 Folders", folderCount);
569 filesText = i18ncp("@info:status", "1 File", "%1 Files", fileCount);
570 }
571
572 if (fileCount > 0 && folderCount > 0) {
573 summary = i18nc("@info:status folders, files (size)", "%1, %2 (%3)",
574 foldersText, filesText,
575 KGlobal::locale()->formatByteSize(totalFileSize));
576 } else if (fileCount > 0) {
577 summary = i18nc("@info:status files (size)", "%1 (%2)",
578 filesText,
579 KGlobal::locale()->formatByteSize(totalFileSize));
580 } else if (folderCount > 0) {
581 summary = foldersText;
582 } else {
583 summary = i18nc("@info:status", "0 Folders, 0 Files");
584 }
585
586 return summary;
587 }
588
589 QList<QAction*> DolphinView::versionControlActions(const KFileItemList& items) const
590 {
591 QList<QAction*> actions;
592
593 if (items.isEmpty()) {
594 const KFileItem item = m_model->rootItem();
595 if (!item.isNull()) {
596 actions = m_versionControlObserver->actions(KFileItemList() << item);
597 }
598 } else {
599 actions = m_versionControlObserver->actions(items);
600 }
601
602 return actions;
603 }
604
605 void DolphinView::setUrl(const KUrl& url)
606 {
607 if (url == m_url) {
608 return;
609 }
610
611 clearSelection();
612
613 emit urlAboutToBeChanged(url);
614 m_url = url;
615
616 hideToolTip();
617
618 disconnect(m_view, SIGNAL(roleEditingFinished(int,QByteArray,QVariant)),
619 this, SLOT(slotRoleEditingFinished(int,QByteArray,QVariant)));
620
621 // It is important to clear the items from the model before
622 // applying the view properties, otherwise expensive operations
623 // might be done on the existing items although they get cleared
624 // anyhow afterwards by loadDirectory().
625 m_model->clear();
626 applyViewProperties();
627 loadDirectory(url);
628
629 emit urlChanged(url);
630 }
631
632 void DolphinView::selectAll()
633 {
634 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
635 selectionManager->setSelected(0, m_model->count());
636 }
637
638 void DolphinView::invertSelection()
639 {
640 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
641 selectionManager->setSelected(0, m_model->count(), KItemListSelectionManager::Toggle);
642 }
643
644 void DolphinView::clearSelection()
645 {
646 m_selectedUrls.clear();
647 m_container->controller()->selectionManager()->clearSelection();
648 }
649
650 void DolphinView::renameSelectedItems()
651 {
652 const KFileItemList items = selectedItems();
653 if (items.isEmpty()) {
654 return;
655 }
656
657 if (items.count() == 1 && GeneralSettings::renameInline()) {
658 const int index = m_model->index(items.first());
659 m_view->editRole(index, "text");
660
661 connect(m_view, SIGNAL(roleEditingFinished(int,QByteArray,QVariant)),
662 this, SLOT(slotRoleEditingFinished(int,QByteArray,QVariant)));
663 } else {
664 RenameDialog* dialog = new RenameDialog(this, items);
665 dialog->setAttribute(Qt::WA_DeleteOnClose);
666 dialog->show();
667 dialog->raise();
668 dialog->activateWindow();
669 }
670
671 // Assure that the current index remains visible when KFileItemModel
672 // will notify the view about changed items (which might result in
673 // a changed sorting).
674 m_assureVisibleCurrentIndex = true;
675 }
676
677 void DolphinView::trashSelectedItems()
678 {
679 const KUrl::List list = simplifiedSelectedUrls();
680 KonqOperations::del(this, KonqOperations::TRASH, list);
681 }
682
683 void DolphinView::deleteSelectedItems()
684 {
685 const KUrl::List list = simplifiedSelectedUrls();
686 const bool del = KonqOperations::askDeleteConfirmation(list,
687 KonqOperations::DEL,
688 KonqOperations::DEFAULT_CONFIRMATION,
689 this);
690
691 if (del) {
692 KIO::Job* job = KIO::del(list);
693 if (job->ui()) {
694 job->ui()->setWindow(this);
695 }
696 connect(job, SIGNAL(result(KJob*)),
697 this, SLOT(slotDeleteFileFinished(KJob*)));
698 }
699 }
700
701 void DolphinView::cutSelectedItems()
702 {
703 QMimeData* mimeData = selectionMimeData();
704 KonqMimeData::addIsCutSelection(mimeData, true);
705 QApplication::clipboard()->setMimeData(mimeData);
706 }
707
708 void DolphinView::copySelectedItems()
709 {
710 QMimeData* mimeData = selectionMimeData();
711 QApplication::clipboard()->setMimeData(mimeData);
712 }
713
714 void DolphinView::paste()
715 {
716 pasteToUrl(url());
717 }
718
719 void DolphinView::pasteIntoFolder()
720 {
721 const KFileItemList items = selectedItems();
722 if ((items.count() == 1) && items.first().isDir()) {
723 pasteToUrl(items.first().url());
724 }
725 }
726
727 bool DolphinView::eventFilter(QObject* watched, QEvent* event)
728 {
729 switch (event->type()) {
730 case QEvent::FocusIn:
731 if (watched == m_container) {
732 setActive(true);
733 }
734 break;
735
736 case QEvent::GraphicsSceneDragEnter:
737 if (watched == m_view) {
738 m_dragging = true;
739 }
740 break;
741
742 case QEvent::GraphicsSceneDragLeave:
743 if (watched == m_view) {
744 m_dragging = false;
745 }
746 break;
747
748 case QEvent::GraphicsSceneDrop:
749 if (watched == m_view) {
750 m_dragging = false;
751 }
752 default:
753 break;
754 }
755
756 return QWidget::eventFilter(watched, event);
757 }
758
759 void DolphinView::wheelEvent(QWheelEvent* event)
760 {
761 if (event->modifiers().testFlag(Qt::ControlModifier)) {
762 const int numDegrees = event->delta() / 8;
763 const int numSteps = numDegrees / 15;
764
765 setZoomLevel(zoomLevel() + numSteps);
766 event->accept();
767 } else {
768 event->ignore();
769 }
770 }
771
772 void DolphinView::hideEvent(QHideEvent* event)
773 {
774 hideToolTip();
775 QWidget::hideEvent(event);
776 }
777
778 bool DolphinView::event(QEvent* event)
779 {
780 /* See Bug 297355
781 * Dolphin leaves file preview tooltips open even when is not visible.
782 *
783 * Hide tool-tip when Dolphin loses focus.
784 */
785 if (event->type() == QEvent::WindowDeactivate) {
786 hideToolTip();
787 }
788
789 return QWidget::event(event);
790 }
791
792 void DolphinView::activate()
793 {
794 setActive(true);
795 }
796
797 void DolphinView::slotItemActivated(int index)
798 {
799 const KFileItem item = m_model->fileItem(index);
800 if (!item.isNull()) {
801 emit itemActivated(item);
802 }
803 }
804
805 void DolphinView::slotItemsActivated(const QSet<int>& indexes)
806 {
807 Q_ASSERT(indexes.count() >= 2);
808
809 if (indexes.count() > 5) {
810 QString question = i18np("Are you sure you want to open 1 item?", "Are you sure you want to open %1 items?", indexes.count());
811 const int answer = KMessageBox::warningYesNo(this, question);
812 if (answer != KMessageBox::Yes) {
813 return;
814 }
815 }
816
817 KFileItemList items;
818 items.reserve(indexes.count());
819
820 QSetIterator<int> it(indexes);
821 while (it.hasNext()) {
822 const int index = it.next();
823 KFileItem item = m_model->fileItem(index);
824 const KUrl& url = openItemAsFolderUrl(item);
825
826 if (!url.isEmpty()) { // Open folders in new tabs
827 emit tabRequested(url);
828 } else {
829 items.append(item);
830 }
831 }
832
833 if (items.count() == 1) {
834 emit itemActivated(items.first());
835 } else if (items.count() > 1) {
836 emit itemsActivated(items);
837 }
838 }
839
840 void DolphinView::slotItemMiddleClicked(int index)
841 {
842 const KFileItem& item = m_model->fileItem(index);
843 const KUrl& url = openItemAsFolderUrl(item);
844 if (!url.isEmpty()) {
845 emit tabRequested(url);
846 } else if (isTabsForFilesEnabled()) {
847 emit tabRequested(item.url());
848 }
849 }
850
851 void DolphinView::slotItemContextMenuRequested(int index, const QPointF& pos)
852 {
853 // Force emit of a selection changed signal before we request the
854 // context menu, to update the edit-actions first. (See Bug 294013)
855 if (m_selectionChangedTimer->isActive()) {
856 emitSelectionChangedSignal();
857 }
858
859 const KFileItem item = m_model->fileItem(index);
860 emit requestContextMenu(pos.toPoint(), item, url(), QList<QAction*>());
861 }
862
863 void DolphinView::slotViewContextMenuRequested(const QPointF& pos)
864 {
865 emit requestContextMenu(pos.toPoint(), KFileItem(), url(), QList<QAction*>());
866 }
867
868 void DolphinView::slotHeaderContextMenuRequested(const QPointF& pos)
869 {
870 ViewProperties props(viewPropertiesUrl());
871
872 QPointer<KMenu> menu = new KMenu(QApplication::activeWindow());
873
874 KItemListView* view = m_container->controller()->view();
875 const QSet<QByteArray> visibleRolesSet = view->visibleRoles().toSet();
876
877 bool nepomukRunning = false;
878 bool indexingEnabled = false;
879 #ifdef HAVE_NEPOMUK
880 nepomukRunning = (Nepomuk2::ResourceManager::instance()->initialized());
881 if (nepomukRunning) {
882 KConfig config("nepomukserverrc");
883 indexingEnabled = config.group("Service-nepomukfileindexer").readEntry("autostart", true);
884 }
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.requiresNepomuk && !info.requiresIndexer) ||
916 (info.requiresNepomuk && nepomukRunning) ||
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 connect(op, SIGNAL(urlPasted(KUrl)), this, SLOT(slotUrlPasted(KUrl)));
1058 }
1059
1060 setActive(true);
1061 }
1062
1063 void DolphinView::slotModelChanged(KItemModelBase* current, KItemModelBase* previous)
1064 {
1065 if (previous != 0) {
1066 disconnect(previous, SIGNAL(directoryLoadingCompleted()), this, SLOT(slotDirectoryLoadingCompleted()));
1067 m_versionControlObserver->setModel(0);
1068 }
1069
1070 if (current) {
1071 Q_ASSERT(qobject_cast<KFileItemModel*>(current));
1072 connect(current, SIGNAL(loadingCompleted()), this, SLOT(slotDirectoryLoadingCompleted()));
1073
1074 KFileItemModel* fileItemModel = static_cast<KFileItemModel*>(current);
1075 m_versionControlObserver->setModel(fileItemModel);
1076 }
1077 }
1078
1079 void DolphinView::slotMouseButtonPressed(int itemIndex, Qt::MouseButtons buttons)
1080 {
1081 hideToolTip();
1082
1083 if (itemIndex < 0) {
1084 // Trigger the history navigation only when clicking on the viewport:
1085 // Above an item the XButtons provide a simple way to select items in
1086 // the singleClick mode.
1087 if (buttons & Qt::XButton1) {
1088 emit goBackRequested();
1089 } else if (buttons & Qt::XButton2) {
1090 emit goForwardRequested();
1091 }
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 << urls;
1103 }
1104 }
1105
1106 void DolphinView::slotSelectionChanged(const QSet<int>& current, const QSet<int>& 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 // Restore the current item that had the keyboard focus
1180 stream >> m_currentItemUrl;
1181
1182 // Restore the view position
1183 stream >> m_restoredContentsPosition;
1184
1185 // Restore expanded folders (only relevant for the details view - will be ignored by the view in other view modes)
1186 QSet<KUrl> urls;
1187 stream >> urls;
1188 m_model->restoreExpandedDirectories(urls);
1189 }
1190
1191 void DolphinView::saveState(QDataStream& stream)
1192 {
1193 // Save the current item that has the keyboard focus
1194 const int currentIndex = m_container->controller()->selectionManager()->currentItem();
1195 if (currentIndex != -1) {
1196 KFileItem item = m_model->fileItem(currentIndex);
1197 Q_ASSERT(!item.isNull()); // If the current index is valid a item must exist
1198 KUrl currentItemUrl = item.url();
1199 stream << currentItemUrl;
1200 } else {
1201 stream << KUrl();
1202 }
1203
1204 // Save view position
1205 const qreal x = m_container->horizontalScrollBar()->value();
1206 const qreal y = m_container->verticalScrollBar()->value();
1207 stream << QPoint(x, y);
1208
1209 // Save expanded folders (only relevant for the details view - the set will be empty in other view modes)
1210 stream << m_model->expandedDirectories();
1211 }
1212
1213 KFileItem DolphinView::rootItem() const
1214 {
1215 return m_model->rootItem();
1216 }
1217
1218 void DolphinView::setViewPropertiesContext(const QString& context)
1219 {
1220 m_viewPropertiesContext = context;
1221 }
1222
1223 QString DolphinView::viewPropertiesContext() const
1224 {
1225 return m_viewPropertiesContext;
1226 }
1227
1228 KUrl DolphinView::openItemAsFolderUrl(const KFileItem& item, const bool browseThroughArchives)
1229 {
1230 if (item.isNull()) {
1231 return KUrl();
1232 }
1233
1234 KUrl url = item.targetUrl();
1235
1236 if (item.isDir()) {
1237 return url;
1238 }
1239
1240 if (item.isMimeTypeKnown()) {
1241 const QString& mimetype = item.mimetype();
1242
1243 if (browseThroughArchives && item.isFile() && url.isLocalFile()) {
1244 // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
1245 // zip:/<path>/ when clicking on a zip file, etc.
1246 // The .protocol file specifies the mimetype that the kioslave handles.
1247 // Note that we don't use mimetype inheritance since we don't want to
1248 // open OpenDocument files as zip folders...
1249 const QString& protocol = KProtocolManager::protocolForArchiveMimetype(mimetype);
1250 if (!protocol.isEmpty()) {
1251 url.setProtocol(protocol);
1252 return url;
1253 }
1254 }
1255
1256 if (mimetype == QLatin1String("application/x-desktop")) {
1257 // Redirect to the URL in Type=Link desktop files
1258 KDesktopFile desktopFile(url.toLocalFile());
1259 if (desktopFile.hasLinkType()) {
1260 return desktopFile.readUrl();
1261 }
1262 }
1263 }
1264
1265 return KUrl();
1266 }
1267
1268 void DolphinView::observeCreatedItem(const KUrl& url)
1269 {
1270 if (m_active) {
1271 clearSelection();
1272 markUrlAsCurrent(url);
1273 markUrlsAsSelected(QList<KUrl>() << url);
1274 }
1275 }
1276
1277 void DolphinView::slotDirectoryRedirection(const KUrl& oldUrl, const KUrl& newUrl)
1278 {
1279 if (oldUrl.equals(url(), KUrl::CompareWithoutTrailingSlash)) {
1280 emit redirection(oldUrl, newUrl);
1281 m_url = newUrl; // #186947
1282 }
1283 }
1284
1285 void DolphinView::updateViewState()
1286 {
1287 if (m_currentItemUrl != KUrl()) {
1288 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1289 const int currentIndex = m_model->index(m_currentItemUrl);
1290 if (currentIndex != -1) {
1291 selectionManager->setCurrentItem(currentIndex);
1292
1293 // scroll to current item and reset the state
1294 if (m_scrollToCurrentItem) {
1295 m_view->scrollToItem(currentIndex);
1296 m_scrollToCurrentItem = false;
1297 }
1298
1299 m_currentItemUrl = KUrl();
1300 } else {
1301 selectionManager->setCurrentItem(0);
1302 }
1303 }
1304
1305 if (!m_restoredContentsPosition.isNull()) {
1306 const int x = m_restoredContentsPosition.x();
1307 const int y = m_restoredContentsPosition.y();
1308 m_restoredContentsPosition = QPoint();
1309
1310 m_container->horizontalScrollBar()->setValue(x);
1311 m_container->verticalScrollBar()->setValue(y);
1312 }
1313
1314 if (!m_selectedUrls.isEmpty()) {
1315 KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1316
1317 if (m_clearSelectionBeforeSelectingNewItems) {
1318 selectionManager->clearSelection();
1319 m_clearSelectionBeforeSelectingNewItems = false;
1320 }
1321
1322 QSet<int> selectedItems = selectionManager->selectedItems();
1323
1324 QList<KUrl>::iterator it = m_selectedUrls.begin();
1325 while (it != m_selectedUrls.end()) {
1326 const int index = m_model->index(*it);
1327 if (index >= 0) {
1328 selectedItems.insert(index);
1329 it = m_selectedUrls.erase(it);
1330 } else {
1331 ++it;
1332 }
1333 }
1334
1335 selectionManager->setSelectedItems(selectedItems);
1336 }
1337 }
1338
1339 void DolphinView::hideToolTip()
1340 {
1341 if (GeneralSettings::showToolTips()) {
1342 m_toolTipManager->hideToolTip();
1343 }
1344 }
1345
1346 void DolphinView::calculateItemCount(int& fileCount,
1347 int& folderCount,
1348 KIO::filesize_t& totalFileSize) const
1349 {
1350 const int itemCount = m_model->count();
1351 for (int i = 0; i < itemCount; ++i) {
1352 const KFileItem item = m_model->fileItem(i);
1353 if (item.isDir()) {
1354 ++folderCount;
1355 } else {
1356 ++fileCount;
1357 totalFileSize += item.size();
1358 }
1359 }
1360 }
1361
1362 void DolphinView::showHoverInformation(const KFileItem& item)
1363 {
1364 emit requestItemInfo(item);
1365 }
1366
1367 void DolphinView::clearHoverInformation()
1368 {
1369 emit requestItemInfo(KFileItem());
1370 }
1371
1372 void DolphinView::slotDeleteFileFinished(KJob* job)
1373 {
1374 if (job->error() == 0) {
1375 emit operationCompletedMessage(i18nc("@info:status", "Delete operation completed."));
1376 } else if (job->error() != KIO::ERR_USER_CANCELED) {
1377 emit errorMessage(job->errorString());
1378 }
1379 }
1380
1381 void DolphinView::slotRenamingFailed(const KUrl& oldUrl, const KUrl& newUrl)
1382 {
1383 const int index = m_model->index(newUrl);
1384 if (index >= 0) {
1385 QHash<QByteArray, QVariant> data;
1386 data.insert("text", oldUrl.fileName());
1387 m_model->setData(index, data);
1388 }
1389 }
1390
1391 void DolphinView::slotDirectoryLoadingStarted()
1392 {
1393 // Disable the writestate temporary until it can be determined in a fast way
1394 // in DolphinView::slotLoadingCompleted()
1395 if (m_isFolderWritable) {
1396 m_isFolderWritable = false;
1397 emit writeStateChanged(m_isFolderWritable);
1398 }
1399
1400 emit directoryLoadingStarted();
1401 }
1402
1403 void DolphinView::slotDirectoryLoadingCompleted()
1404 {
1405 // Update the view-state. This has to be done asynchronously
1406 // because the view might not be in its final state yet.
1407 QTimer::singleShot(0, this, SLOT(updateViewState()));
1408
1409 emit directoryLoadingCompleted();
1410
1411 updateWritableState();
1412 }
1413
1414 void DolphinView::slotItemsChanged()
1415 {
1416 m_assureVisibleCurrentIndex = false;
1417 }
1418
1419 void DolphinView::slotSortOrderChangedByHeader(Qt::SortOrder current, Qt::SortOrder previous)
1420 {
1421 Q_UNUSED(previous);
1422 Q_ASSERT(m_model->sortOrder() == current);
1423
1424 ViewProperties props(viewPropertiesUrl());
1425 props.setSortOrder(current);
1426
1427 emit sortOrderChanged(current);
1428 }
1429
1430 void DolphinView::slotSortRoleChangedByHeader(const QByteArray& current, const QByteArray& previous)
1431 {
1432 Q_UNUSED(previous);
1433 Q_ASSERT(m_model->sortRole() == current);
1434
1435 ViewProperties props(viewPropertiesUrl());
1436 props.setSortRole(current);
1437
1438 emit sortRoleChanged(current);
1439 }
1440
1441 void DolphinView::slotVisibleRolesChangedByHeader(const QList<QByteArray>& current,
1442 const QList<QByteArray>& previous)
1443 {
1444 Q_UNUSED(previous);
1445 Q_ASSERT(m_container->controller()->view()->visibleRoles() == current);
1446
1447 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1448
1449 m_visibleRoles = current;
1450
1451 ViewProperties props(viewPropertiesUrl());
1452 props.setVisibleRoles(m_visibleRoles);
1453
1454 emit visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1455 }
1456
1457 void DolphinView::slotRoleEditingCanceled()
1458 {
1459 disconnect(m_view, SIGNAL(roleEditingFinished(int,QByteArray,QVariant)),
1460 this, SLOT(slotRoleEditingFinished(int,QByteArray,QVariant)));
1461 }
1462
1463 void DolphinView::slotRoleEditingFinished(int index, const QByteArray& role, const QVariant& value)
1464 {
1465 disconnect(m_view, SIGNAL(roleEditingFinished(int,QByteArray,QVariant)),
1466 this, SLOT(slotRoleEditingFinished(int,QByteArray,QVariant)));
1467
1468 if (index < 0 || index >= m_model->count()) {
1469 return;
1470 }
1471
1472 if (role == "text") {
1473 const KFileItem oldItem = m_model->fileItem(index);
1474 const QString newName = value.toString();
1475 if (!newName.isEmpty() && newName != oldItem.text() && newName != QLatin1String(".") && newName != QLatin1String("..")) {
1476 const KUrl oldUrl = oldItem.url();
1477
1478 const KUrl newUrl(url().path(KUrl::AddTrailingSlash) + newName);
1479 const bool newNameExistsAlready = (m_model->index(newUrl) >= 0);
1480 if (!newNameExistsAlready) {
1481 // Only change the data in the model if no item with the new name
1482 // is in the model yet. If there is an item with the new name
1483 // already, calling KonqOperations::rename() will open a dialog
1484 // asking for a new name, and KFileItemModel will update the
1485 // data when the dir lister signals that the file name has changed.
1486 QHash<QByteArray, QVariant> data;
1487 data.insert(role, value);
1488 m_model->setData(index, data);
1489 }
1490
1491 KonqOperations* op = KonqOperations::renameV2(this, oldUrl, newName);
1492 if (op) {
1493 connect(op, SIGNAL(renamingFailed(KUrl,KUrl)), SLOT(slotRenamingFailed(KUrl,KUrl)));
1494 }
1495 }
1496 }
1497 }
1498
1499 void DolphinView::loadDirectory(const KUrl& url, bool reload)
1500 {
1501 if (!url.isValid()) {
1502 const QString location(url.pathOrUrl());
1503 if (location.isEmpty()) {
1504 emit errorMessage(i18nc("@info:status", "The location is empty."));
1505 } else {
1506 emit errorMessage(i18nc("@info:status", "The location '%1' is invalid.", location));
1507 }
1508 return;
1509 }
1510
1511 if (reload) {
1512 m_model->refreshDirectory(url);
1513 } else {
1514 m_model->loadDirectory(url);
1515 }
1516 }
1517
1518 void DolphinView::applyViewProperties()
1519 {
1520 const ViewProperties props(viewPropertiesUrl());
1521 applyViewProperties(props);
1522 }
1523
1524 void DolphinView::applyViewProperties(const ViewProperties& props)
1525 {
1526 m_view->beginTransaction();
1527
1528 const Mode mode = props.viewMode();
1529 if (m_mode != mode) {
1530 const Mode previousMode = m_mode;
1531 m_mode = mode;
1532
1533 // Changing the mode might result in changing
1534 // the zoom level. Remember the old zoom level so
1535 // that zoomLevelChanged() can get emitted.
1536 const int oldZoomLevel = m_view->zoomLevel();
1537 applyModeToView();
1538
1539 emit modeChanged(m_mode, previousMode);
1540
1541 if (m_view->zoomLevel() != oldZoomLevel) {
1542 emit zoomLevelChanged(m_view->zoomLevel(), oldZoomLevel);
1543 }
1544 }
1545
1546 const bool hiddenFilesShown = props.hiddenFilesShown();
1547 if (hiddenFilesShown != m_model->showHiddenFiles()) {
1548 m_model->setShowHiddenFiles(hiddenFilesShown);
1549 emit hiddenFilesShownChanged(hiddenFilesShown);
1550 }
1551
1552 const bool groupedSorting = props.groupedSorting();
1553 if (groupedSorting != m_model->groupedSorting()) {
1554 m_model->setGroupedSorting(groupedSorting);
1555 emit groupedSortingChanged(groupedSorting);
1556 }
1557
1558 const QByteArray sortRole = props.sortRole();
1559 if (sortRole != m_model->sortRole()) {
1560 m_model->setSortRole(sortRole);
1561 emit sortRoleChanged(sortRole);
1562 }
1563
1564 const Qt::SortOrder sortOrder = props.sortOrder();
1565 if (sortOrder != m_model->sortOrder()) {
1566 m_model->setSortOrder(sortOrder);
1567 emit sortOrderChanged(sortOrder);
1568 }
1569
1570 const bool sortFoldersFirst = props.sortFoldersFirst();
1571 if (sortFoldersFirst != m_model->sortDirectoriesFirst()) {
1572 m_model->setSortDirectoriesFirst(sortFoldersFirst);
1573 emit sortFoldersFirstChanged(sortFoldersFirst);
1574 }
1575
1576 const QList<QByteArray> visibleRoles = props.visibleRoles();
1577 if (visibleRoles != m_visibleRoles) {
1578 const QList<QByteArray> previousVisibleRoles = m_visibleRoles;
1579 m_visibleRoles = visibleRoles;
1580 m_view->setVisibleRoles(visibleRoles);
1581 emit visibleRolesChanged(m_visibleRoles, previousVisibleRoles);
1582 }
1583
1584 const bool previewsShown = props.previewsShown();
1585 if (previewsShown != m_view->previewsShown()) {
1586 const int oldZoomLevel = zoomLevel();
1587
1588 m_view->setPreviewsShown(previewsShown);
1589 emit previewsShownChanged(previewsShown);
1590
1591 // Changing the preview-state might result in a changed zoom-level
1592 if (oldZoomLevel != zoomLevel()) {
1593 emit zoomLevelChanged(zoomLevel(), oldZoomLevel);
1594 }
1595 }
1596
1597 KItemListView* itemListView = m_container->controller()->view();
1598 if (itemListView->isHeaderVisible()) {
1599 KItemListHeader* header = itemListView->header();
1600 const QList<int> headerColumnWidths = props.headerColumnWidths();
1601 const int rolesCount = m_visibleRoles.count();
1602 if (headerColumnWidths.count() == rolesCount) {
1603 header->setAutomaticColumnResizing(false);
1604
1605 QHash<QByteArray, qreal> columnWidths;
1606 for (int i = 0; i < rolesCount; ++i) {
1607 columnWidths.insert(m_visibleRoles[i], headerColumnWidths[i]);
1608 }
1609 header->setColumnWidths(columnWidths);
1610 } else {
1611 header->setAutomaticColumnResizing(true);
1612 }
1613 }
1614
1615 m_view->endTransaction();
1616 }
1617
1618 void DolphinView::applyModeToView()
1619 {
1620 switch (m_mode) {
1621 case IconsView: m_view->setItemLayout(KFileItemListView::IconsLayout); break;
1622 case CompactView: m_view->setItemLayout(KFileItemListView::CompactLayout); break;
1623 case DetailsView: m_view->setItemLayout(KFileItemListView::DetailsLayout); break;
1624 default: Q_ASSERT(false); break;
1625 }
1626 }
1627
1628 void DolphinView::pasteToUrl(const KUrl& url)
1629 {
1630 KonqOperations* op = KonqOperations::doPasteV2(this, url);
1631 if (op) {
1632 m_clearSelectionBeforeSelectingNewItems = true;
1633 m_markFirstNewlySelectedItemAsCurrent = true;
1634 connect(op, SIGNAL(aboutToCreate(KUrl::List)), this, SLOT(slotAboutToCreate(KUrl::List)));
1635 }
1636 }
1637
1638 KUrl::List DolphinView::simplifiedSelectedUrls() const
1639 {
1640 KUrl::List urls;
1641
1642 const KFileItemList items = selectedItems();
1643 foreach (const KFileItem& item, items) {
1644 urls.append(item.url());
1645 }
1646
1647 if (itemsExpandable()) {
1648 // TODO: Check if we still need KDirModel for this in KDE 5.0
1649 urls = KDirModel::simplifiedUrlList(urls);
1650 }
1651
1652 return urls;
1653 }
1654
1655 QMimeData* DolphinView::selectionMimeData() const
1656 {
1657 const KItemListSelectionManager* selectionManager = m_container->controller()->selectionManager();
1658 const QSet<int> selectedIndexes = selectionManager->selectedItems();
1659
1660 return m_model->createMimeData(selectedIndexes);
1661 }
1662
1663 void DolphinView::updateWritableState()
1664 {
1665 const bool wasFolderWritable = m_isFolderWritable;
1666 m_isFolderWritable = true;
1667
1668 const KFileItem item = m_model->rootItem();
1669 if (!item.isNull()) {
1670 KFileItemListProperties capabilities(KFileItemList() << item);
1671 m_isFolderWritable = capabilities.supportsWriting();
1672 }
1673 if (m_isFolderWritable != wasFolderWritable) {
1674 emit writeStateChanged(m_isFolderWritable);
1675 }
1676 }
1677
1678 KUrl DolphinView::viewPropertiesUrl() const
1679 {
1680 if (m_viewPropertiesContext.isEmpty()) {
1681 return m_url;
1682 }
1683
1684 KUrl url;
1685 url.setProtocol(m_url.protocol());
1686 url.setPath(m_viewPropertiesContext);
1687 return url;
1688 }
1689
1690 #include "dolphinview.moc"