1 /***************************************************************************
2 * Copyright (C) 2012 by Peter Penz <peter.penz19@gmail.com> *
4 * Based on KFilePlacesModel from kdelibs: *
5 * Copyright (C) 2007 Kevin Ottens <ervin@kde.org> *
6 * Copyright (C) 2007 David Faure <faure@kde.org> *
8 * This program is free software; you can redistribute it and/or modify *
9 * it under the terms of the GNU General Public License as published by *
10 * the Free Software Foundation; either version 2 of the License, or *
11 * (at your option) any later version. *
13 * This program is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU General Public License for more details. *
18 * You should have received a copy of the GNU General Public License *
19 * along with this program; if not, write to the *
20 * Free Software Foundation, Inc., *
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
22 ***************************************************************************/
24 #include "placesitemmodel.h"
25 #include "placesitemsignalhandler.h"
27 #include "dolphin_generalsettings.h"
30 #include <KBookmarkManager>
31 #include "dolphindebug.h"
33 #include <KProtocolInfo>
34 #include <KLocalizedString>
35 #include <QStandardPaths>
37 #include "placesitem.h"
42 #include <KUrlMimeData>
44 #include <Solid/Device>
45 #include <Solid/DeviceNotifier>
46 #include <Solid/OpticalDisc>
47 #include <Solid/OpticalDrive>
48 #include <Solid/StorageAccess>
49 #include <Solid/StorageDrive>
51 #include <views/dolphinview.h>
52 #include <views/viewproperties.h>
55 #include <Baloo/Query>
56 #include <Baloo/IndexerConfig>
60 // As long as KFilePlacesView from kdelibs is available in parallel, the
61 // system-bookmarks for "Recently Saved" and "Search For" should be
62 // shown only inside the Places Panel. This is necessary as the stored
63 // URLs needs to get translated to a Baloo-search-URL on-the-fly to
64 // be independent from changes in the Baloo-search-URL-syntax.
65 // Hence a prefix to the application-name of the stored bookmarks is
66 // added, which is only read by PlacesItemModel.
67 const char AppNamePrefix
[] = "-places-panel";
69 static QList
<QUrl
> balooURLs
= {
70 QUrl(QStringLiteral("timeline:/today")),
71 QUrl(QStringLiteral("timeline:/yesterday")),
72 QUrl(QStringLiteral("timeline:/thismonth")),
73 QUrl(QStringLiteral("timeline:/lastmonth")),
74 QUrl(QStringLiteral("search:/documents")),
75 QUrl(QStringLiteral("search:/images")),
76 QUrl(QStringLiteral("search:/audio")),
77 QUrl(QStringLiteral("search:/videos"))
81 PlacesItemModel::PlacesItemModel(QObject
* parent
) :
82 KStandardItemModel(parent
),
83 m_fileIndexingEnabled(false),
84 m_hiddenItemsShown(false),
89 m_systemBookmarksIndexes(),
91 m_hiddenItemToRemove(-1),
92 m_deviceToTearDown(0),
93 m_updateBookmarksTimer(0),
94 m_storageSetupInProgress()
97 Baloo::IndexerConfig config
;
98 m_fileIndexingEnabled
= config
.fileIndexingEnabled();
100 const QString file
= QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation
) + "/user-places.xbel";
101 m_bookmarkManager
= KBookmarkManager::managerForExternalFile(file
);
103 createSystemBookmarks();
104 initializeAvailableDevices();
107 const int syncBookmarksTimeout
= 100;
109 m_updateBookmarksTimer
= new QTimer(this);
110 m_updateBookmarksTimer
->setInterval(syncBookmarksTimeout
);
111 m_updateBookmarksTimer
->setSingleShot(true);
112 connect(m_updateBookmarksTimer
, &QTimer::timeout
, this, &PlacesItemModel::updateBookmarks
);
114 connect(m_bookmarkManager
, &KBookmarkManager::changed
,
115 m_updateBookmarksTimer
, static_cast<void(QTimer::*)()>(&QTimer::start
));
118 PlacesItemModel::~PlacesItemModel()
120 qDeleteAll(m_bookmarkedItems
);
121 m_bookmarkedItems
.clear();
124 PlacesItem
* PlacesItemModel::createPlacesItem(const QString
& text
,
126 const QString
& iconName
)
128 const KBookmark bookmark
= PlacesItem::createBookmark(m_bookmarkManager
, text
, url
, iconName
);
129 return new PlacesItem(bookmark
);
132 PlacesItem
* PlacesItemModel::placesItem(int index
) const
134 return dynamic_cast<PlacesItem
*>(item(index
));
137 int PlacesItemModel::hiddenCount() const
140 int hiddenItemCount
= 0;
141 foreach (const PlacesItem
* item
, m_bookmarkedItems
) {
145 if (placesItem(modelIndex
)->isHidden()) {
152 return hiddenItemCount
;
155 void PlacesItemModel::setHiddenItemsShown(bool show
)
157 if (m_hiddenItemsShown
== show
) {
161 m_hiddenItemsShown
= show
;
164 // Move all items that are part of m_bookmarkedItems to the model.
165 QList
<PlacesItem
*> itemsToInsert
;
166 QList
<int> insertPos
;
168 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
169 if (m_bookmarkedItems
[i
]) {
170 itemsToInsert
.append(m_bookmarkedItems
[i
]);
171 m_bookmarkedItems
[i
] = 0;
172 insertPos
.append(modelIndex
);
177 // Inserting the items will automatically insert an item
178 // to m_bookmarkedItems in PlacesItemModel::onItemsInserted().
179 // The items are temporary saved in itemsToInsert, so
180 // m_bookmarkedItems can be shrinked now.
181 m_bookmarkedItems
.erase(m_bookmarkedItems
.begin(),
182 m_bookmarkedItems
.begin() + itemsToInsert
.count());
184 for (int i
= 0; i
< itemsToInsert
.count(); ++i
) {
185 insertItem(insertPos
[i
], itemsToInsert
[i
]);
188 Q_ASSERT(m_bookmarkedItems
.count() == count());
190 // Move all items of the model, where the "isHidden" property is true, to
191 // m_bookmarkedItems.
192 Q_ASSERT(m_bookmarkedItems
.count() == count());
193 for (int i
= count() - 1; i
>= 0; --i
) {
194 if (placesItem(i
)->isHidden()) {
200 #ifdef PLACESITEMMODEL_DEBUG
201 qCDebug(DolphinDebug
) << "Changed visibility of hidden items";
206 bool PlacesItemModel::hiddenItemsShown() const
208 return m_hiddenItemsShown
;
211 int PlacesItemModel::closestItem(const QUrl
& url
) const
216 for (int i
= 0; i
< count(); ++i
) {
217 const QUrl itemUrl
= placesItem(i
)->url();
218 if (url
== itemUrl
) {
219 // We can't find a closer one, so stop here.
222 } else if (itemUrl
.isParentOf(url
)) {
223 const int length
= itemUrl
.path().length();
224 if (length
> maxLength
) {
234 void PlacesItemModel::appendItemToGroup(PlacesItem
* item
)
241 while (i
< count() && placesItem(i
)->group() != item
->group()) {
245 bool inserted
= false;
246 while (!inserted
&& i
< count()) {
247 if (placesItem(i
)->group() != item
->group()) {
260 QAction
* PlacesItemModel::ejectAction(int index
) const
262 const PlacesItem
* item
= placesItem(index
);
263 if (item
&& item
->device().is
<Solid::OpticalDisc
>()) {
264 return new QAction(QIcon::fromTheme(QStringLiteral("media-eject")), i18nc("@item", "Eject"), 0);
270 QAction
* PlacesItemModel::teardownAction(int index
) const
272 const PlacesItem
* item
= placesItem(index
);
277 Solid::Device device
= item
->device();
278 const bool providesTearDown
= device
.is
<Solid::StorageAccess
>() &&
279 device
.as
<Solid::StorageAccess
>()->isAccessible();
280 if (!providesTearDown
) {
284 Solid::StorageDrive
* drive
= device
.as
<Solid::StorageDrive
>();
286 drive
= device
.parent().as
<Solid::StorageDrive
>();
289 bool hotPluggable
= false;
290 bool removable
= false;
292 hotPluggable
= drive
->isHotpluggable();
293 removable
= drive
->isRemovable();
298 if (device
.is
<Solid::OpticalDisc
>()) {
299 text
= i18nc("@item", "Release");
300 } else if (removable
|| hotPluggable
) {
301 text
= i18nc("@item", "Safely Remove");
302 iconName
= QStringLiteral("media-eject");
304 text
= i18nc("@item", "Unmount");
305 iconName
= QStringLiteral("media-eject");
308 if (iconName
.isEmpty()) {
309 return new QAction(text
, 0);
312 return new QAction(QIcon::fromTheme(iconName
), text
, 0);
315 void PlacesItemModel::requestEject(int index
)
317 const PlacesItem
* item
= placesItem(index
);
319 Solid::OpticalDrive
* drive
= item
->device().parent().as
<Solid::OpticalDrive
>();
321 connect(drive
, &Solid::OpticalDrive::ejectDone
,
322 this, &PlacesItemModel::slotStorageTearDownDone
);
325 const QString label
= item
->text();
326 const QString message
= i18nc("@info", "The device '%1' is not a disk and cannot be ejected.", label
);
327 emit
errorMessage(message
);
332 void PlacesItemModel::requestTearDown(int index
)
334 const PlacesItem
* item
= placesItem(index
);
336 Solid::StorageAccess
*tmp
= item
->device().as
<Solid::StorageAccess
>();
338 m_deviceToTearDown
= tmp
;
339 // disconnect the Solid::StorageAccess::teardownRequested
340 // to prevent emitting PlacesItemModel::storageTearDownExternallyRequested
341 // after we have emitted PlacesItemModel::storageTearDownRequested
342 disconnect(tmp
, &Solid::StorageAccess::teardownRequested
,
343 item
->signalHandler(), &PlacesItemSignalHandler::onTearDownRequested
);
344 emit
storageTearDownRequested(tmp
->filePath());
349 bool PlacesItemModel::storageSetupNeeded(int index
) const
351 const PlacesItem
* item
= placesItem(index
);
352 return item
? item
->storageSetupNeeded() : false;
355 void PlacesItemModel::requestStorageSetup(int index
)
357 const PlacesItem
* item
= placesItem(index
);
362 Solid::Device device
= item
->device();
363 const bool setup
= device
.is
<Solid::StorageAccess
>()
364 && !m_storageSetupInProgress
.contains(device
.as
<Solid::StorageAccess
>())
365 && !device
.as
<Solid::StorageAccess
>()->isAccessible();
367 Solid::StorageAccess
* access
= device
.as
<Solid::StorageAccess
>();
369 m_storageSetupInProgress
[access
] = index
;
371 connect(access
, &Solid::StorageAccess::setupDone
,
372 this, &PlacesItemModel::slotStorageSetupDone
);
378 QMimeData
* PlacesItemModel::createMimeData(const KItemSet
& indexes
) const
383 QDataStream
stream(&itemData
, QIODevice::WriteOnly
);
385 for (int index
: indexes
) {
386 const QUrl itemUrl
= placesItem(index
)->url();
387 if (itemUrl
.isValid()) {
393 QMimeData
* mimeData
= new QMimeData();
394 if (!urls
.isEmpty()) {
395 mimeData
->setUrls(urls
);
397 // #378954: prevent itemDropEvent() drops if there isn't a source url.
398 mimeData
->setData(blacklistItemDropEventMimeType(), QByteArrayLiteral("true"));
400 mimeData
->setData(internalMimeType(), itemData
);
405 bool PlacesItemModel::supportsDropping(int index
) const
407 return index
>= 0 && index
< count();
410 void PlacesItemModel::dropMimeDataBefore(int index
, const QMimeData
* mimeData
)
412 if (mimeData
->hasFormat(internalMimeType())) {
413 // The item has been moved inside the view
414 QByteArray itemData
= mimeData
->data(internalMimeType());
415 QDataStream
stream(&itemData
, QIODevice::ReadOnly
);
418 if (oldIndex
== index
|| oldIndex
== index
- 1) {
419 // No moving has been done
423 PlacesItem
* oldItem
= placesItem(oldIndex
);
428 PlacesItem
* newItem
= new PlacesItem(oldItem
->bookmark());
429 removeItem(oldIndex
);
431 if (oldIndex
< index
) {
435 const int dropIndex
= groupedDropIndex(index
, newItem
);
436 insertItem(dropIndex
, newItem
);
437 } else if (mimeData
->hasFormat(QStringLiteral("text/uri-list"))) {
438 // One or more items must be added to the model
439 const QList
<QUrl
> urls
= KUrlMimeData::urlsFromMimeData(mimeData
);
440 for (int i
= urls
.count() - 1; i
>= 0; --i
) {
441 const QUrl
& url
= urls
[i
];
443 QString text
= url
.fileName();
444 if (text
.isEmpty()) {
448 if ((url
.isLocalFile() && !QFileInfo(url
.toLocalFile()).isDir())
449 || url
.scheme() == QLatin1String("trash")) {
450 // Only directories outside the trash are allowed
454 PlacesItem
* newItem
= createPlacesItem(text
, url
);
455 const int dropIndex
= groupedDropIndex(index
, newItem
);
456 insertItem(dropIndex
, newItem
);
461 QUrl
PlacesItemModel::convertedUrl(const QUrl
& url
)
464 if (url
.scheme() == QLatin1String("timeline")) {
465 newUrl
= createTimelineUrl(url
);
466 } else if (url
.scheme() == QLatin1String("search")) {
467 newUrl
= createSearchUrl(url
);
473 void PlacesItemModel::onItemInserted(int index
)
475 const PlacesItem
* insertedItem
= placesItem(index
);
477 // Take care to apply the PlacesItemModel-order of the inserted item
478 // also to the bookmark-manager.
479 const KBookmark insertedBookmark
= insertedItem
->bookmark();
481 const PlacesItem
* previousItem
= placesItem(index
- 1);
482 KBookmark previousBookmark
;
484 previousBookmark
= previousItem
->bookmark();
487 m_bookmarkManager
->root().moveBookmark(insertedBookmark
, previousBookmark
);
490 if (index
== count() - 1) {
491 // The item has been appended as last item to the list. In this
492 // case assure that it is also appended after the hidden items and
493 // not before (like done otherwise).
494 m_bookmarkedItems
.append(0);
498 int bookmarkIndex
= 0;
499 while (bookmarkIndex
< m_bookmarkedItems
.count()) {
500 if (!m_bookmarkedItems
[bookmarkIndex
]) {
502 if (modelIndex
+ 1 == index
) {
508 m_bookmarkedItems
.insert(bookmarkIndex
, 0);
511 #ifdef PLACESITEMMODEL_DEBUG
512 qCDebug(DolphinDebug
) << "Inserted item" << index
;
517 void PlacesItemModel::onItemRemoved(int index
, KStandardItem
* removedItem
)
519 PlacesItem
* placesItem
= dynamic_cast<PlacesItem
*>(removedItem
);
521 const KBookmark bookmark
= placesItem
->bookmark();
522 m_bookmarkManager
->root().deleteBookmark(bookmark
);
525 const int boomarkIndex
= bookmarkIndex(index
);
526 Q_ASSERT(!m_bookmarkedItems
[boomarkIndex
]);
527 m_bookmarkedItems
.removeAt(boomarkIndex
);
529 #ifdef PLACESITEMMODEL_DEBUG
530 qCDebug(DolphinDebug
) << "Removed item" << index
;
535 void PlacesItemModel::onItemChanged(int index
, const QSet
<QByteArray
>& changedRoles
)
537 const PlacesItem
* changedItem
= placesItem(index
);
539 // Take care to apply the PlacesItemModel-order of the changed item
540 // also to the bookmark-manager.
541 const KBookmark insertedBookmark
= changedItem
->bookmark();
543 const PlacesItem
* previousItem
= placesItem(index
- 1);
544 KBookmark previousBookmark
;
546 previousBookmark
= previousItem
->bookmark();
549 m_bookmarkManager
->root().moveBookmark(insertedBookmark
, previousBookmark
);
552 if (changedRoles
.contains("isHidden")) {
553 if (!m_hiddenItemsShown
&& changedItem
->isHidden()) {
554 m_hiddenItemToRemove
= index
;
555 QTimer::singleShot(0, this, static_cast<void (PlacesItemModel::*)()>(&PlacesItemModel::hideItem
));
560 void PlacesItemModel::slotDeviceAdded(const QString
& udi
)
562 const Solid::Device
device(udi
);
564 if (!m_predicate
.matches(device
)) {
568 m_availableDevices
<< udi
;
569 const KBookmark bookmark
= PlacesItem::createDeviceBookmark(m_bookmarkManager
, udi
);
571 PlacesItem
*item
= new PlacesItem(bookmark
);
573 connect(item
->signalHandler(), &PlacesItemSignalHandler::tearDownExternallyRequested
,
574 this, &PlacesItemModel::storageTearDownExternallyRequested
);
577 void PlacesItemModel::slotDeviceRemoved(const QString
& udi
)
579 if (!m_availableDevices
.contains(udi
)) {
583 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
584 PlacesItem
* item
= m_bookmarkedItems
[i
];
585 if (item
&& item
->udi() == udi
) {
586 m_bookmarkedItems
.removeAt(i
);
592 for (int i
= 0; i
< count(); ++i
) {
593 if (placesItem(i
)->udi() == udi
) {
600 void PlacesItemModel::slotStorageTearDownDone(Solid::ErrorType error
, const QVariant
& errorData
)
602 if (error
&& errorData
.isValid()) {
603 emit
errorMessage(errorData
.toString());
605 m_deviceToTearDown
->disconnect();
606 m_deviceToTearDown
= nullptr;
609 void PlacesItemModel::slotStorageSetupDone(Solid::ErrorType error
,
610 const QVariant
& errorData
,
615 const int index
= m_storageSetupInProgress
.take(sender());
616 const PlacesItem
* item
= placesItem(index
);
621 if (error
!= Solid::NoError
) {
622 if (errorData
.isValid()) {
623 emit
errorMessage(i18nc("@info", "An error occurred while accessing '%1', the system responded: %2",
625 errorData
.toString()));
627 emit
errorMessage(i18nc("@info", "An error occurred while accessing '%1'",
630 emit
storageSetupDone(index
, false);
632 emit
storageSetupDone(index
, true);
636 void PlacesItemModel::hideItem()
638 hideItem(m_hiddenItemToRemove
);
639 m_hiddenItemToRemove
= -1;
642 void PlacesItemModel::updateBookmarks()
644 // Verify whether new bookmarks have been added or existing
645 // bookmarks have been changed.
646 KBookmarkGroup root
= m_bookmarkManager
->root();
647 KBookmark newBookmark
= root
.first();
648 while (!newBookmark
.isNull()) {
649 if (acceptBookmark(newBookmark
, m_availableDevices
)) {
652 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
653 PlacesItem
* item
= m_bookmarkedItems
[i
];
655 item
= placesItem(modelIndex
);
659 const KBookmark oldBookmark
= item
->bookmark();
660 if (equalBookmarkIdentifiers(newBookmark
, oldBookmark
)) {
661 // The bookmark has been found in the model or as
662 // a hidden item. The content of the bookmark might
663 // have been changed, so an update is done.
665 if (newBookmark
.metaDataItem(QStringLiteral("UDI")).isEmpty()) {
666 item
->setBookmark(newBookmark
);
667 item
->setText(i18nc("KFile System Bookmarks", newBookmark
.text().toUtf8().constData()));
674 const QString udi
= newBookmark
.metaDataItem(QStringLiteral("UDI"));
678 * Only add a new places item, if the item text is not empty
679 * and if the device is available. Fixes the strange behaviour -
680 * add a places item without text in the Places section - when you
681 * remove a device (e.g. a usb stick) without unmounting.
683 if (udi
.isEmpty() || Solid::Device(udi
).isValid()) {
684 PlacesItem
* item
= new PlacesItem(newBookmark
);
685 if (item
->isHidden() && !m_hiddenItemsShown
) {
686 m_bookmarkedItems
.append(item
);
688 appendItemToGroup(item
);
694 newBookmark
= root
.next(newBookmark
);
697 // Remove items that are not part of the bookmark-manager anymore
699 for (int i
= m_bookmarkedItems
.count() - 1; i
>= 0; --i
) {
700 PlacesItem
* item
= m_bookmarkedItems
[i
];
701 const bool itemIsPartOfModel
= (item
== 0);
702 if (itemIsPartOfModel
) {
703 item
= placesItem(modelIndex
);
706 bool hasBeenRemoved
= true;
707 const KBookmark oldBookmark
= item
->bookmark();
708 KBookmark newBookmark
= root
.first();
709 while (!newBookmark
.isNull()) {
710 if (equalBookmarkIdentifiers(newBookmark
, oldBookmark
)) {
711 hasBeenRemoved
= false;
714 newBookmark
= root
.next(newBookmark
);
717 if (hasBeenRemoved
) {
718 if (m_bookmarkedItems
[i
]) {
719 delete m_bookmarkedItems
[i
];
720 m_bookmarkedItems
.removeAt(i
);
722 removeItem(modelIndex
);
727 if (itemIsPartOfModel
) {
733 void PlacesItemModel::saveBookmarks()
735 m_bookmarkManager
->emitChanged(m_bookmarkManager
->root());
738 void PlacesItemModel::loadBookmarks()
740 KBookmarkGroup root
= m_bookmarkManager
->root();
741 KBookmark bookmark
= root
.first();
742 QSet
<QString
> devices
= m_availableDevices
;
744 QSet
<QUrl
> missingSystemBookmarks
;
745 foreach (const SystemBookmarkData
& data
, m_systemBookmarks
) {
746 missingSystemBookmarks
.insert(data
.url
);
749 // The bookmarks might have a mixed order of places, devices and search-groups due
750 // to the compatibility with the KFilePlacesPanel. In Dolphin's places panel the
751 // items should always be collected in one group so the items are collected first
752 // in separate lists before inserting them.
753 QList
<PlacesItem
*> placesItems
;
754 QList
<PlacesItem
*> recentlySavedItems
;
755 QList
<PlacesItem
*> searchForItems
;
756 QList
<PlacesItem
*> devicesItems
;
758 while (!bookmark
.isNull()) {
759 if (acceptBookmark(bookmark
, devices
)) {
760 PlacesItem
* item
= new PlacesItem(bookmark
);
761 if (item
->groupType() == PlacesItem::DevicesType
) {
762 devices
.remove(item
->udi());
763 devicesItems
.append(item
);
765 const QUrl url
= bookmark
.url();
766 if (missingSystemBookmarks
.contains(url
)) {
767 missingSystemBookmarks
.remove(url
);
769 // Try to retranslate the text of system bookmarks to have translated
770 // items when changing the language. In case if the user has applied a custom
771 // text, the retranslation will fail and the users custom text is still used.
772 // It is important to use "KFile System Bookmarks" as context (see
773 // createSystemBookmarks()).
774 item
->setText(i18nc("KFile System Bookmarks", bookmark
.text().toUtf8().constData()));
775 item
->setSystemItem(true);
778 switch (item
->groupType()) {
779 case PlacesItem::PlacesType
: placesItems
.append(item
); break;
780 case PlacesItem::RecentlySavedType
: recentlySavedItems
.append(item
); break;
781 case PlacesItem::SearchForType
: searchForItems
.append(item
); break;
782 case PlacesItem::DevicesType
:
783 default: Q_ASSERT(false); break;
788 bookmark
= root
.next(bookmark
);
791 if (!missingSystemBookmarks
.isEmpty()) {
792 // The current bookmarks don't contain all system-bookmarks. Add the missing
794 foreach (const SystemBookmarkData
& data
, m_systemBookmarks
) {
795 if (missingSystemBookmarks
.contains(data
.url
)) {
796 PlacesItem
* item
= createSystemPlacesItem(data
);
797 switch (item
->groupType()) {
798 case PlacesItem::PlacesType
: placesItems
.append(item
); break;
799 case PlacesItem::RecentlySavedType
: recentlySavedItems
.append(item
); break;
800 case PlacesItem::SearchForType
: searchForItems
.append(item
); break;
801 case PlacesItem::DevicesType
:
802 default: Q_ASSERT(false); break;
808 // Create items for devices that have not been stored as bookmark yet
809 devicesItems
.reserve(devicesItems
.count() + devices
.count());
810 foreach (const QString
& udi
, devices
) {
811 const KBookmark bookmark
= PlacesItem::createDeviceBookmark(m_bookmarkManager
, udi
);
812 PlacesItem
*item
= new PlacesItem(bookmark
);
813 devicesItems
.append(item
);
814 connect(item
->signalHandler(), &PlacesItemSignalHandler::tearDownExternallyRequested
,
815 this, &PlacesItemModel::storageTearDownExternallyRequested
);
818 QList
<PlacesItem
*> items
;
819 items
.append(placesItems
);
820 items
.append(recentlySavedItems
);
821 items
.append(searchForItems
);
822 items
.append(devicesItems
);
824 foreach (PlacesItem
* item
, items
) {
825 if (!m_hiddenItemsShown
&& item
->isHidden()) {
826 m_bookmarkedItems
.append(item
);
832 #ifdef PLACESITEMMODEL_DEBUG
833 qCDebug(DolphinDebug
) << "Loaded bookmarks";
838 bool PlacesItemModel::acceptBookmark(const KBookmark
& bookmark
,
839 const QSet
<QString
>& availableDevices
) const
841 const QString udi
= bookmark
.metaDataItem(QStringLiteral("UDI"));
842 const QUrl url
= bookmark
.url();
843 const QString appName
= bookmark
.metaDataItem(QStringLiteral("OnlyInApp"));
844 const bool deviceAvailable
= availableDevices
.contains(udi
);
846 if (balooURLs
.contains(url
) && appName
.isEmpty()) {
847 // Does not accept baloo URLS with empty appName, this came from new KIO model and will cause duplications
848 qCWarning(DolphinDebug
) << "Ignore KIO url:" << url
;
852 const bool allowedHere
= (appName
.isEmpty()
853 || appName
== KAboutData::applicationData().componentName()
854 || appName
== KAboutData::applicationData().componentName() + AppNamePrefix
)
855 && (m_fileIndexingEnabled
|| (url
.scheme() != QLatin1String("timeline") &&
856 url
.scheme() != QLatin1String("search")));
858 return (udi
.isEmpty() && allowedHere
) || deviceAvailable
;
861 PlacesItem
* PlacesItemModel::createSystemPlacesItem(const SystemBookmarkData
& data
)
863 KBookmark bookmark
= PlacesItem::createBookmark(m_bookmarkManager
,
868 const QString protocol
= data
.url
.scheme();
869 if (protocol
== QLatin1String("timeline") || protocol
== QLatin1String("search")) {
870 // As long as the KFilePlacesView from kdelibs is available, the system-bookmarks
871 // for "Recently Saved" and "Search For" should be a setting available only
872 // in the Places Panel (see description of AppNamePrefix for more details).
873 const QString appName
= KAboutData::applicationData().componentName() + AppNamePrefix
;
874 bookmark
.setMetaDataItem(QStringLiteral("OnlyInApp"), appName
);
877 PlacesItem
* item
= new PlacesItem(bookmark
);
878 item
->setSystemItem(true);
880 // Create default view-properties for all "Search For" and "Recently Saved" bookmarks
881 // in case if the user has not already created custom view-properties for a corresponding
883 const bool createDefaultViewProperties
= (item
->groupType() == PlacesItem::SearchForType
||
884 item
->groupType() == PlacesItem::RecentlySavedType
) &&
885 !GeneralSettings::self()->globalViewProps();
886 if (createDefaultViewProperties
) {
887 ViewProperties
props(convertedUrl(data
.url
));
888 if (!props
.exist()) {
889 const QString path
= data
.url
.path();
890 if (path
== QLatin1String("/documents")) {
891 props
.setViewMode(DolphinView::DetailsView
);
892 props
.setPreviewsShown(false);
893 props
.setVisibleRoles({"text", "path"});
894 } else if (path
== QLatin1String("/images")) {
895 props
.setViewMode(DolphinView::IconsView
);
896 props
.setPreviewsShown(true);
897 props
.setVisibleRoles({"text", "imageSize"});
898 } else if (path
== QLatin1String("/audio")) {
899 props
.setViewMode(DolphinView::DetailsView
);
900 props
.setPreviewsShown(false);
901 props
.setVisibleRoles({"text", "artist", "album"});
902 } else if (path
== QLatin1String("/videos")) {
903 props
.setViewMode(DolphinView::IconsView
);
904 props
.setPreviewsShown(true);
905 props
.setVisibleRoles({"text"});
906 } else if (data
.url
.scheme() == QLatin1String("timeline")) {
907 props
.setViewMode(DolphinView::DetailsView
);
908 props
.setVisibleRoles({"text", "modificationtime"});
916 void PlacesItemModel::createSystemBookmarks()
918 Q_ASSERT(m_systemBookmarks
.isEmpty());
919 Q_ASSERT(m_systemBookmarksIndexes
.isEmpty());
921 // Note: The context of the I18N_NOOP2 must be "KFile System Bookmarks". The real
922 // i18nc call is done after reading the bookmark. The reason why the i18nc call is not
923 // done here is because otherwise switching the language would not result in retranslating the
925 m_systemBookmarks
.append(SystemBookmarkData(QUrl::fromLocalFile(QDir::homePath()),
926 QStringLiteral("user-home"),
927 I18N_NOOP2("KFile System Bookmarks", "Home")));
928 m_systemBookmarks
.append(SystemBookmarkData(QUrl(QStringLiteral("remote:/")),
929 QStringLiteral("network-workgroup"),
930 I18N_NOOP2("KFile System Bookmarks", "Network")));
931 m_systemBookmarks
.append(SystemBookmarkData(QUrl::fromLocalFile(QStringLiteral("/")),
932 QStringLiteral("folder-red"),
933 I18N_NOOP2("KFile System Bookmarks", "Root")));
934 m_systemBookmarks
.append(SystemBookmarkData(QUrl(QStringLiteral("trash:/")),
935 QStringLiteral("user-trash"),
936 I18N_NOOP2("KFile System Bookmarks", "Trash")));
938 if (m_fileIndexingEnabled
) {
939 m_systemBookmarks
.append(SystemBookmarkData(QUrl(QStringLiteral("timeline:/today")),
940 QStringLiteral("go-jump-today"),
941 I18N_NOOP2("KFile System Bookmarks", "Today")));
942 m_systemBookmarks
.append(SystemBookmarkData(QUrl(QStringLiteral("timeline:/yesterday")),
943 QStringLiteral("view-calendar-day"),
944 I18N_NOOP2("KFile System Bookmarks", "Yesterday")));
945 m_systemBookmarks
.append(SystemBookmarkData(QUrl(QStringLiteral("timeline:/thismonth")),
946 QStringLiteral("view-calendar-month"),
947 I18N_NOOP2("KFile System Bookmarks", "This Month")));
948 m_systemBookmarks
.append(SystemBookmarkData(QUrl(QStringLiteral("timeline:/lastmonth")),
949 QStringLiteral("view-calendar-month"),
950 I18N_NOOP2("KFile System Bookmarks", "Last Month")));
951 m_systemBookmarks
.append(SystemBookmarkData(QUrl(QStringLiteral("search:/documents")),
952 QStringLiteral("folder-text"),
953 I18N_NOOP2("KFile System Bookmarks", "Documents")));
954 m_systemBookmarks
.append(SystemBookmarkData(QUrl(QStringLiteral("search:/images")),
955 QStringLiteral("folder-images"),
956 I18N_NOOP2("KFile System Bookmarks", "Images")));
957 m_systemBookmarks
.append(SystemBookmarkData(QUrl(QStringLiteral("search:/audio")),
958 QStringLiteral("folder-sound"),
959 I18N_NOOP2("KFile System Bookmarks", "Audio Files")));
960 m_systemBookmarks
.append(SystemBookmarkData(QUrl(QStringLiteral("search:/videos")),
961 QStringLiteral("folder-videos"),
962 I18N_NOOP2("KFile System Bookmarks", "Videos")));
965 for (int i
= 0; i
< m_systemBookmarks
.count(); ++i
) {
966 m_systemBookmarksIndexes
.insert(m_systemBookmarks
[i
].url
, i
);
970 void PlacesItemModel::clear() {
971 m_bookmarkedItems
.clear();
972 KStandardItemModel::clear();
975 void PlacesItemModel::proceedWithTearDown()
977 Q_ASSERT(m_deviceToTearDown
);
979 connect(m_deviceToTearDown
, &Solid::StorageAccess::teardownDone
,
980 this, &PlacesItemModel::slotStorageTearDownDone
);
981 m_deviceToTearDown
->teardown();
984 void PlacesItemModel::initializeAvailableDevices()
986 QString
predicate(QStringLiteral("[[[[ StorageVolume.ignored == false AND [ StorageVolume.usage == 'FileSystem' OR StorageVolume.usage == 'Encrypted' ]]"
988 "[ IS StorageAccess AND StorageDrive.driveType == 'Floppy' ]]"
990 "OpticalDisc.availableContent & 'Audio' ]"
992 "StorageAccess.ignored == false ]"));
995 if (KProtocolInfo::isKnownProtocol(QStringLiteral("mtp"))) {
996 predicate
.prepend("[");
997 predicate
.append(" OR PortableMediaPlayer.supportedProtocols == 'mtp']");
1000 m_predicate
= Solid::Predicate::fromString(predicate
);
1001 Q_ASSERT(m_predicate
.isValid());
1003 Solid::DeviceNotifier
* notifier
= Solid::DeviceNotifier::instance();
1004 connect(notifier
, &Solid::DeviceNotifier::deviceAdded
, this, &PlacesItemModel::slotDeviceAdded
);
1005 connect(notifier
, &Solid::DeviceNotifier::deviceRemoved
, this, &PlacesItemModel::slotDeviceRemoved
);
1007 const QList
<Solid::Device
>& deviceList
= Solid::Device::listFromQuery(m_predicate
);
1008 foreach (const Solid::Device
& device
, deviceList
) {
1009 m_availableDevices
<< device
.udi();
1013 int PlacesItemModel::bookmarkIndex(int index
) const
1015 int bookmarkIndex
= 0;
1017 while (bookmarkIndex
< m_bookmarkedItems
.count()) {
1018 if (!m_bookmarkedItems
[bookmarkIndex
]) {
1019 if (modelIndex
== index
) {
1027 return bookmarkIndex
>= m_bookmarkedItems
.count() ? -1 : bookmarkIndex
;
1030 void PlacesItemModel::hideItem(int index
)
1032 PlacesItem
* shownItem
= placesItem(index
);
1037 shownItem
->setHidden(true);
1038 if (m_hiddenItemsShown
) {
1039 // Removing items from the model is not allowed if all hidden
1040 // items should be shown.
1044 const int newIndex
= bookmarkIndex(index
);
1045 if (newIndex
>= 0) {
1046 const KBookmark hiddenBookmark
= shownItem
->bookmark();
1047 PlacesItem
* hiddenItem
= new PlacesItem(hiddenBookmark
);
1049 const PlacesItem
* previousItem
= placesItem(index
- 1);
1050 KBookmark previousBookmark
;
1052 previousBookmark
= previousItem
->bookmark();
1055 const bool updateBookmark
= (m_bookmarkManager
->root().indexOf(hiddenBookmark
) >= 0);
1058 if (updateBookmark
) {
1059 // removeItem() also removed the bookmark from m_bookmarkManager in
1060 // PlacesItemModel::onItemRemoved(). However for hidden items the
1061 // bookmark should still be remembered, so readd it again:
1062 m_bookmarkManager
->root().addBookmark(hiddenBookmark
);
1063 m_bookmarkManager
->root().moveBookmark(hiddenBookmark
, previousBookmark
);
1066 m_bookmarkedItems
.insert(newIndex
, hiddenItem
);
1070 QString
PlacesItemModel::internalMimeType() const
1072 return "application/x-dolphinplacesmodel-" +
1073 QString::number((qptrdiff
)this);
1076 int PlacesItemModel::groupedDropIndex(int index
, const PlacesItem
* item
) const
1080 int dropIndex
= index
;
1081 const PlacesItem::GroupType type
= item
->groupType();
1083 const int itemCount
= count();
1085 dropIndex
= itemCount
;
1088 // Search nearest previous item with the same group
1089 int previousIndex
= -1;
1090 for (int i
= dropIndex
- 1; i
>= 0; --i
) {
1091 if (placesItem(i
)->groupType() == type
) {
1097 // Search nearest next item with the same group
1099 for (int i
= dropIndex
; i
< count(); ++i
) {
1100 if (placesItem(i
)->groupType() == type
) {
1106 // Adjust the drop-index to be inserted to the
1107 // nearest item with the same group.
1108 if (previousIndex
>= 0 && nextIndex
>= 0) {
1109 dropIndex
= (dropIndex
- previousIndex
< nextIndex
- dropIndex
) ?
1110 previousIndex
+ 1 : nextIndex
;
1111 } else if (previousIndex
>= 0) {
1112 dropIndex
= previousIndex
+ 1;
1113 } else if (nextIndex
>= 0) {
1114 dropIndex
= nextIndex
;
1120 bool PlacesItemModel::equalBookmarkIdentifiers(const KBookmark
& b1
, const KBookmark
& b2
)
1122 const QString udi1
= b1
.metaDataItem(QStringLiteral("UDI"));
1123 const QString udi2
= b2
.metaDataItem(QStringLiteral("UDI"));
1124 if (!udi1
.isEmpty() && !udi2
.isEmpty()) {
1125 return udi1
== udi2
;
1127 return b1
.metaDataItem(QStringLiteral("ID")) == b2
.metaDataItem(QStringLiteral("ID"));
1131 QUrl
PlacesItemModel::createTimelineUrl(const QUrl
& url
)
1133 // TODO: Clarify with the Baloo-team whether it makes sense
1134 // provide default-timeline-URLs like 'yesterday', 'this month'
1135 // and 'last month'.
1138 const QString path
= url
.toDisplayString(QUrl::PreferLocalFile
);
1139 if (path
.endsWith(QLatin1String("yesterday"))) {
1140 const QDate date
= QDate::currentDate().addDays(-1);
1141 const int year
= date
.year();
1142 const int month
= date
.month();
1143 const int day
= date
.day();
1144 timelineUrl
= QUrl("timeline:/" + timelineDateString(year
, month
) +
1145 '/' + timelineDateString(year
, month
, day
));
1146 } else if (path
.endsWith(QLatin1String("thismonth"))) {
1147 const QDate date
= QDate::currentDate();
1148 timelineUrl
= QUrl("timeline:/" + timelineDateString(date
.year(), date
.month()));
1149 } else if (path
.endsWith(QLatin1String("lastmonth"))) {
1150 const QDate date
= QDate::currentDate().addMonths(-1);
1151 timelineUrl
= QUrl("timeline:/" + timelineDateString(date
.year(), date
.month()));
1153 Q_ASSERT(path
.endsWith(QLatin1String("today")));
1160 QString
PlacesItemModel::timelineDateString(int year
, int month
, int day
)
1162 QString date
= QString::number(year
) + '-';
1166 date
+= QString::number(month
);
1173 date
+= QString::number(day
);
1179 bool PlacesItemModel::isDir(int index
) const
1185 QUrl
PlacesItemModel::createSearchUrl(const QUrl
& url
)
1190 const QString path
= url
.toDisplayString(QUrl::PreferLocalFile
);
1191 if (path
.endsWith(QLatin1String("documents"))) {
1192 searchUrl
= searchUrlForType(QStringLiteral("Document"));
1193 } else if (path
.endsWith(QLatin1String("images"))) {
1194 searchUrl
= searchUrlForType(QStringLiteral("Image"));
1195 } else if (path
.endsWith(QLatin1String("audio"))) {
1196 searchUrl
= searchUrlForType(QStringLiteral("Audio"));
1197 } else if (path
.endsWith(QLatin1String("videos"))) {
1198 searchUrl
= searchUrlForType(QStringLiteral("Video"));
1210 QUrl
PlacesItemModel::searchUrlForType(const QString
& type
)
1213 query
.addType(type
);
1215 return query
.toSearchUrl();
1219 #ifdef PLACESITEMMODEL_DEBUG
1220 void PlacesItemModel::showModelState()
1222 qCDebug(DolphinDebug
) << "=================================";
1223 qCDebug(DolphinDebug
) << "Model:";
1224 qCDebug(DolphinDebug
) << "hidden-index model-index text";
1226 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
1227 if (m_bookmarkedItems
[i
]) {
1228 qCDebug(DolphinDebug
) << i
<< "(Hidden) " << " " << m_bookmarkedItems
[i
]->dataValue("text").toString();
1230 if (item(modelIndex
)) {
1231 qCDebug(DolphinDebug
) << i
<< " " << modelIndex
<< " " << item(modelIndex
)->dataValue("text").toString();
1233 qCDebug(DolphinDebug
) << i
<< " " << modelIndex
<< " " << "(not available yet)";
1239 qCDebug(DolphinDebug
);
1240 qCDebug(DolphinDebug
) << "Bookmarks:";
1242 int bookmarkIndex
= 0;
1243 KBookmarkGroup root
= m_bookmarkManager
->root();
1244 KBookmark bookmark
= root
.first();
1245 while (!bookmark
.isNull()) {
1246 const QString udi
= bookmark
.metaDataItem("UDI");
1247 const QString text
= udi
.isEmpty() ? bookmark
.text() : udi
;
1248 if (bookmark
.metaDataItem("IsHidden") == QLatin1String("true")) {
1249 qCDebug(DolphinDebug
) << bookmarkIndex
<< "(Hidden)" << text
;
1251 qCDebug(DolphinDebug
) << bookmarkIndex
<< " " << text
;
1254 bookmark
= root
.next(bookmark
);