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