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