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