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"
26 #include "dolphin_generalsettings.h"
29 #include <KBookmarkManager>
30 #include "dolphindebug.h"
32 #include <KProtocolInfo>
33 #include <KLocalizedString>
34 #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";
70 PlacesItemModel::PlacesItemModel(QObject
* parent
) :
71 KStandardItemModel(parent
),
72 m_fileIndexingEnabled(false),
73 m_hiddenItemsShown(false),
78 m_systemBookmarksIndexes(),
80 m_hiddenItemToRemove(-1),
81 m_updateBookmarksTimer(0),
82 m_storageSetupInProgress()
85 Baloo::IndexerConfig config
;
86 m_fileIndexingEnabled
= config
.fileIndexingEnabled();
88 const QString file
= QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation
) + "/user-places.xbel";
89 m_bookmarkManager
= KBookmarkManager::managerForExternalFile(file
);
91 createSystemBookmarks();
92 initializeAvailableDevices();
95 const int syncBookmarksTimeout
= 100;
97 m_updateBookmarksTimer
= new QTimer(this);
98 m_updateBookmarksTimer
->setInterval(syncBookmarksTimeout
);
99 m_updateBookmarksTimer
->setSingleShot(true);
100 connect(m_updateBookmarksTimer
, &QTimer::timeout
, this, &PlacesItemModel::updateBookmarks
);
102 connect(m_bookmarkManager
, &KBookmarkManager::changed
,
103 m_updateBookmarksTimer
, static_cast<void(QTimer::*)()>(&QTimer::start
));
106 PlacesItemModel::~PlacesItemModel()
108 qDeleteAll(m_bookmarkedItems
);
109 m_bookmarkedItems
.clear();
112 PlacesItem
* PlacesItemModel::createPlacesItem(const QString
& text
,
114 const QString
& iconName
)
116 const KBookmark bookmark
= PlacesItem::createBookmark(m_bookmarkManager
, text
, url
, iconName
);
117 return new PlacesItem(bookmark
);
120 PlacesItem
* PlacesItemModel::placesItem(int index
) const
122 return dynamic_cast<PlacesItem
*>(item(index
));
125 int PlacesItemModel::hiddenCount() const
128 int hiddenItemCount
= 0;
129 foreach (const PlacesItem
* item
, m_bookmarkedItems
) {
133 if (placesItem(modelIndex
)->isHidden()) {
140 return hiddenItemCount
;
143 void PlacesItemModel::setHiddenItemsShown(bool show
)
145 if (m_hiddenItemsShown
== show
) {
149 m_hiddenItemsShown
= show
;
152 // Move all items that are part of m_bookmarkedItems to the model.
153 QList
<PlacesItem
*> itemsToInsert
;
154 QList
<int> insertPos
;
156 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
157 if (m_bookmarkedItems
[i
]) {
158 itemsToInsert
.append(m_bookmarkedItems
[i
]);
159 m_bookmarkedItems
[i
] = 0;
160 insertPos
.append(modelIndex
);
165 // Inserting the items will automatically insert an item
166 // to m_bookmarkedItems in PlacesItemModel::onItemsInserted().
167 // The items are temporary saved in itemsToInsert, so
168 // m_bookmarkedItems can be shrinked now.
169 m_bookmarkedItems
.erase(m_bookmarkedItems
.begin(),
170 m_bookmarkedItems
.begin() + itemsToInsert
.count());
172 for (int i
= 0; i
< itemsToInsert
.count(); ++i
) {
173 insertItem(insertPos
[i
], itemsToInsert
[i
]);
176 Q_ASSERT(m_bookmarkedItems
.count() == count());
178 // Move all items of the model, where the "isHidden" property is true, to
179 // m_bookmarkedItems.
180 Q_ASSERT(m_bookmarkedItems
.count() == count());
181 for (int i
= count() - 1; i
>= 0; --i
) {
182 if (placesItem(i
)->isHidden()) {
188 #ifdef PLACESITEMMODEL_DEBUG
189 qCDebug(DolphinDebug
) << "Changed visibility of hidden items";
194 bool PlacesItemModel::hiddenItemsShown() const
196 return m_hiddenItemsShown
;
199 int PlacesItemModel::closestItem(const QUrl
& url
) const
204 for (int i
= 0; i
< count(); ++i
) {
205 const QUrl itemUrl
= placesItem(i
)->url();
206 if (url
== itemUrl
) {
207 // We can't find a closer one, so stop here.
210 } else if (itemUrl
.isParentOf(url
)) {
211 const int length
= itemUrl
.path().length();
212 if (length
> maxLength
) {
222 void PlacesItemModel::appendItemToGroup(PlacesItem
* item
)
229 while (i
< count() && placesItem(i
)->group() != item
->group()) {
233 bool inserted
= false;
234 while (!inserted
&& i
< count()) {
235 if (placesItem(i
)->group() != item
->group()) {
248 QAction
* PlacesItemModel::ejectAction(int index
) const
250 const PlacesItem
* item
= placesItem(index
);
251 if (item
&& item
->device().is
<Solid::OpticalDisc
>()) {
252 return new QAction(QIcon::fromTheme(QStringLiteral("media-eject")), i18nc("@item", "Eject '%1'", item
->text()), 0);
258 QAction
* PlacesItemModel::teardownAction(int index
) const
260 const PlacesItem
* item
= placesItem(index
);
265 Solid::Device device
= item
->device();
266 const bool providesTearDown
= device
.is
<Solid::StorageAccess
>() &&
267 device
.as
<Solid::StorageAccess
>()->isAccessible();
268 if (!providesTearDown
) {
272 Solid::StorageDrive
* drive
= device
.as
<Solid::StorageDrive
>();
274 drive
= device
.parent().as
<Solid::StorageDrive
>();
277 bool hotPluggable
= false;
278 bool removable
= false;
280 hotPluggable
= drive
->isHotpluggable();
281 removable
= drive
->isRemovable();
286 const QString label
= item
->text();
287 if (device
.is
<Solid::OpticalDisc
>()) {
288 text
= i18nc("@item", "Release '%1'", label
);
289 } else if (removable
|| hotPluggable
) {
290 text
= i18nc("@item", "Safely Remove '%1'", label
);
291 iconName
= QStringLiteral("media-eject");
293 text
= i18nc("@item", "Unmount '%1'", label
);
294 iconName
= QStringLiteral("media-eject");
297 if (iconName
.isEmpty()) {
298 return new QAction(text
, 0);
301 return new QAction(QIcon::fromTheme(iconName
), text
, 0);
304 void PlacesItemModel::requestEject(int index
)
306 const PlacesItem
* item
= placesItem(index
);
308 Solid::OpticalDrive
* drive
= item
->device().parent().as
<Solid::OpticalDrive
>();
310 connect(drive
, &Solid::OpticalDrive::ejectDone
,
311 this, &PlacesItemModel::slotStorageTeardownDone
);
314 const QString label
= item
->text();
315 const QString message
= i18nc("@info", "The device '%1' is not a disk and cannot be ejected.", label
);
316 emit
errorMessage(message
);
321 void PlacesItemModel::requestTeardown(int index
)
323 const PlacesItem
* item
= placesItem(index
);
325 Solid::StorageAccess
* access
= item
->device().as
<Solid::StorageAccess
>();
327 connect(access
, &Solid::StorageAccess::teardownDone
,
328 this, &PlacesItemModel::slotStorageTeardownDone
);
334 bool PlacesItemModel::storageSetupNeeded(int index
) const
336 const PlacesItem
* item
= placesItem(index
);
337 return item
? item
->storageSetupNeeded() : false;
340 void PlacesItemModel::requestStorageSetup(int index
)
342 const PlacesItem
* item
= placesItem(index
);
347 Solid::Device device
= item
->device();
348 const bool setup
= device
.is
<Solid::StorageAccess
>()
349 && !m_storageSetupInProgress
.contains(device
.as
<Solid::StorageAccess
>())
350 && !device
.as
<Solid::StorageAccess
>()->isAccessible();
352 Solid::StorageAccess
* access
= device
.as
<Solid::StorageAccess
>();
354 m_storageSetupInProgress
[access
] = index
;
356 connect(access
, &Solid::StorageAccess::setupDone
,
357 this, &PlacesItemModel::slotStorageSetupDone
);
363 QMimeData
* PlacesItemModel::createMimeData(const KItemSet
& indexes
) const
368 QDataStream
stream(&itemData
, QIODevice::WriteOnly
);
370 for (int index
: indexes
) {
371 const QUrl itemUrl
= placesItem(index
)->url();
372 if (itemUrl
.isValid()) {
378 QMimeData
* mimeData
= new QMimeData();
379 if (!urls
.isEmpty()) {
380 mimeData
->setUrls(urls
);
382 mimeData
->setData(internalMimeType(), itemData
);
387 bool PlacesItemModel::supportsDropping(int index
) const
389 return index
>= 0 && index
< count();
392 void PlacesItemModel::dropMimeDataBefore(int index
, const QMimeData
* mimeData
)
394 if (mimeData
->hasFormat(internalMimeType())) {
395 // The item has been moved inside the view
396 QByteArray itemData
= mimeData
->data(internalMimeType());
397 QDataStream
stream(&itemData
, QIODevice::ReadOnly
);
400 if (oldIndex
== index
|| oldIndex
== index
- 1) {
401 // No moving has been done
405 PlacesItem
* oldItem
= placesItem(oldIndex
);
410 PlacesItem
* newItem
= new PlacesItem(oldItem
->bookmark());
411 removeItem(oldIndex
);
413 if (oldIndex
< index
) {
417 const int dropIndex
= groupedDropIndex(index
, newItem
);
418 insertItem(dropIndex
, newItem
);
419 } else if (mimeData
->hasFormat(QStringLiteral("text/uri-list"))) {
420 // One or more items must be added to the model
421 const QList
<QUrl
> urls
= KUrlMimeData::urlsFromMimeData(mimeData
);
422 for (int i
= urls
.count() - 1; i
>= 0; --i
) {
423 const QUrl
& url
= urls
[i
];
425 QString text
= url
.fileName();
426 if (text
.isEmpty()) {
430 if ((url
.isLocalFile() && !QFileInfo(url
.toLocalFile()).isDir())
431 || url
.scheme() == QLatin1String("trash")) {
432 // Only directories outside the trash are allowed
436 PlacesItem
* newItem
= createPlacesItem(text
, url
);
437 const int dropIndex
= groupedDropIndex(index
, newItem
);
438 insertItem(dropIndex
, newItem
);
443 QUrl
PlacesItemModel::convertedUrl(const QUrl
& url
)
446 if (url
.scheme() == QLatin1String("timeline")) {
447 newUrl
= createTimelineUrl(url
);
448 } else if (url
.scheme() == QLatin1String("search")) {
449 newUrl
= createSearchUrl(url
);
455 void PlacesItemModel::onItemInserted(int index
)
457 const PlacesItem
* insertedItem
= placesItem(index
);
459 // Take care to apply the PlacesItemModel-order of the inserted item
460 // also to the bookmark-manager.
461 const KBookmark insertedBookmark
= insertedItem
->bookmark();
463 const PlacesItem
* previousItem
= placesItem(index
- 1);
464 KBookmark previousBookmark
;
466 previousBookmark
= previousItem
->bookmark();
469 m_bookmarkManager
->root().moveBookmark(insertedBookmark
, previousBookmark
);
472 if (index
== count() - 1) {
473 // The item has been appended as last item to the list. In this
474 // case assure that it is also appended after the hidden items and
475 // not before (like done otherwise).
476 m_bookmarkedItems
.append(0);
480 int bookmarkIndex
= 0;
481 while (bookmarkIndex
< m_bookmarkedItems
.count()) {
482 if (!m_bookmarkedItems
[bookmarkIndex
]) {
484 if (modelIndex
+ 1 == index
) {
490 m_bookmarkedItems
.insert(bookmarkIndex
, 0);
493 #ifdef PLACESITEMMODEL_DEBUG
494 qCDebug(DolphinDebug
) << "Inserted item" << index
;
499 void PlacesItemModel::onItemRemoved(int index
, KStandardItem
* removedItem
)
501 PlacesItem
* placesItem
= dynamic_cast<PlacesItem
*>(removedItem
);
503 const KBookmark bookmark
= placesItem
->bookmark();
504 m_bookmarkManager
->root().deleteBookmark(bookmark
);
507 const int boomarkIndex
= bookmarkIndex(index
);
508 Q_ASSERT(!m_bookmarkedItems
[boomarkIndex
]);
509 m_bookmarkedItems
.removeAt(boomarkIndex
);
511 #ifdef PLACESITEMMODEL_DEBUG
512 qCDebug(DolphinDebug
) << "Removed item" << index
;
517 void PlacesItemModel::onItemChanged(int index
, const QSet
<QByteArray
>& changedRoles
)
519 const PlacesItem
* changedItem
= placesItem(index
);
521 // Take care to apply the PlacesItemModel-order of the changed item
522 // also to the bookmark-manager.
523 const KBookmark insertedBookmark
= changedItem
->bookmark();
525 const PlacesItem
* previousItem
= placesItem(index
- 1);
526 KBookmark previousBookmark
;
528 previousBookmark
= previousItem
->bookmark();
531 m_bookmarkManager
->root().moveBookmark(insertedBookmark
, previousBookmark
);
534 if (changedRoles
.contains("isHidden")) {
535 if (!m_hiddenItemsShown
&& changedItem
->isHidden()) {
536 m_hiddenItemToRemove
= index
;
537 QTimer::singleShot(0, this, static_cast<void (PlacesItemModel::*)()>(&PlacesItemModel::hideItem
));
542 void PlacesItemModel::slotDeviceAdded(const QString
& udi
)
544 const Solid::Device
device(udi
);
546 if (!m_predicate
.matches(device
)) {
550 m_availableDevices
<< udi
;
551 const KBookmark bookmark
= PlacesItem::createDeviceBookmark(m_bookmarkManager
, udi
);
552 appendItem(new PlacesItem(bookmark
));
555 void PlacesItemModel::slotDeviceRemoved(const QString
& udi
)
557 if (!m_availableDevices
.contains(udi
)) {
561 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
562 PlacesItem
* item
= m_bookmarkedItems
[i
];
563 if (item
&& item
->udi() == udi
) {
564 m_bookmarkedItems
.removeAt(i
);
570 for (int i
= 0; i
< count(); ++i
) {
571 if (placesItem(i
)->udi() == udi
) {
578 void PlacesItemModel::slotStorageTeardownDone(Solid::ErrorType error
, const QVariant
& errorData
)
580 if (error
&& errorData
.isValid()) {
581 emit
errorMessage(errorData
.toString());
585 void PlacesItemModel::slotStorageSetupDone(Solid::ErrorType error
,
586 const QVariant
& errorData
,
591 const int index
= m_storageSetupInProgress
.take(sender());
592 const PlacesItem
* item
= placesItem(index
);
597 if (error
!= Solid::NoError
) {
598 if (errorData
.isValid()) {
599 emit
errorMessage(i18nc("@info", "An error occurred while accessing '%1', the system responded: %2",
601 errorData
.toString()));
603 emit
errorMessage(i18nc("@info", "An error occurred while accessing '%1'",
606 emit
storageSetupDone(index
, false);
608 emit
storageSetupDone(index
, true);
612 void PlacesItemModel::hideItem()
614 hideItem(m_hiddenItemToRemove
);
615 m_hiddenItemToRemove
= -1;
618 void PlacesItemModel::updateBookmarks()
620 // Verify whether new bookmarks have been added or existing
621 // bookmarks have been changed.
622 KBookmarkGroup root
= m_bookmarkManager
->root();
623 KBookmark newBookmark
= root
.first();
624 while (!newBookmark
.isNull()) {
625 if (acceptBookmark(newBookmark
, m_availableDevices
)) {
628 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
629 PlacesItem
* item
= m_bookmarkedItems
[i
];
631 item
= placesItem(modelIndex
);
635 const KBookmark oldBookmark
= item
->bookmark();
636 if (equalBookmarkIdentifiers(newBookmark
, oldBookmark
)) {
637 // The bookmark has been found in the model or as
638 // a hidden item. The content of the bookmark might
639 // have been changed, so an update is done.
641 if (newBookmark
.metaDataItem(QStringLiteral("UDI")).isEmpty()) {
642 item
->setBookmark(newBookmark
);
643 item
->setText(i18nc("KFile System Bookmarks", newBookmark
.text().toUtf8().constData()));
650 const QString udi
= newBookmark
.metaDataItem(QStringLiteral("UDI"));
654 * Only add a new places item, if the item text is not empty
655 * and if the device is available. Fixes the strange behaviour -
656 * add a places item without text in the Places section - when you
657 * remove a device (e.g. a usb stick) without unmounting.
659 if (udi
.isEmpty() || Solid::Device(udi
).isValid()) {
660 PlacesItem
* item
= new PlacesItem(newBookmark
);
661 if (item
->isHidden() && !m_hiddenItemsShown
) {
662 m_bookmarkedItems
.append(item
);
664 appendItemToGroup(item
);
670 newBookmark
= root
.next(newBookmark
);
673 // Remove items that are not part of the bookmark-manager anymore
675 for (int i
= m_bookmarkedItems
.count() - 1; i
>= 0; --i
) {
676 PlacesItem
* item
= m_bookmarkedItems
[i
];
677 const bool itemIsPartOfModel
= (item
== 0);
678 if (itemIsPartOfModel
) {
679 item
= placesItem(modelIndex
);
682 bool hasBeenRemoved
= true;
683 const KBookmark oldBookmark
= item
->bookmark();
684 KBookmark newBookmark
= root
.first();
685 while (!newBookmark
.isNull()) {
686 if (equalBookmarkIdentifiers(newBookmark
, oldBookmark
)) {
687 hasBeenRemoved
= false;
690 newBookmark
= root
.next(newBookmark
);
693 if (hasBeenRemoved
) {
694 if (m_bookmarkedItems
[i
]) {
695 delete m_bookmarkedItems
[i
];
696 m_bookmarkedItems
.removeAt(i
);
698 removeItem(modelIndex
);
703 if (itemIsPartOfModel
) {
709 void PlacesItemModel::saveBookmarks()
711 m_bookmarkManager
->emitChanged(m_bookmarkManager
->root());
714 void PlacesItemModel::loadBookmarks()
716 KBookmarkGroup root
= m_bookmarkManager
->root();
717 KBookmark bookmark
= root
.first();
718 QSet
<QString
> devices
= m_availableDevices
;
720 QSet
<QUrl
> missingSystemBookmarks
;
721 foreach (const SystemBookmarkData
& data
, m_systemBookmarks
) {
722 missingSystemBookmarks
.insert(data
.url
);
725 // The bookmarks might have a mixed order of places, devices and search-groups due
726 // to the compatibility with the KFilePlacesPanel. In Dolphin's places panel the
727 // items should always be collected in one group so the items are collected first
728 // in separate lists before inserting them.
729 QList
<PlacesItem
*> placesItems
;
730 QList
<PlacesItem
*> recentlySavedItems
;
731 QList
<PlacesItem
*> searchForItems
;
732 QList
<PlacesItem
*> devicesItems
;
734 while (!bookmark
.isNull()) {
735 if (acceptBookmark(bookmark
, devices
)) {
736 PlacesItem
* item
= new PlacesItem(bookmark
);
737 if (item
->groupType() == PlacesItem::DevicesType
) {
738 devices
.remove(item
->udi());
739 devicesItems
.append(item
);
741 const QUrl url
= bookmark
.url();
742 if (missingSystemBookmarks
.contains(url
)) {
743 missingSystemBookmarks
.remove(url
);
745 // Try to retranslate the text of system bookmarks to have translated
746 // items when changing the language. In case if the user has applied a custom
747 // text, the retranslation will fail and the users custom text is still used.
748 // It is important to use "KFile System Bookmarks" as context (see
749 // createSystemBookmarks()).
750 item
->setText(i18nc("KFile System Bookmarks", bookmark
.text().toUtf8().constData()));
751 item
->setSystemItem(true);
754 switch (item
->groupType()) {
755 case PlacesItem::PlacesType
: placesItems
.append(item
); break;
756 case PlacesItem::RecentlySavedType
: recentlySavedItems
.append(item
); break;
757 case PlacesItem::SearchForType
: searchForItems
.append(item
); break;
758 case PlacesItem::DevicesType
:
759 default: Q_ASSERT(false); break;
764 bookmark
= root
.next(bookmark
);
767 if (!missingSystemBookmarks
.isEmpty()) {
768 // The current bookmarks don't contain all system-bookmarks. Add the missing
770 foreach (const SystemBookmarkData
& data
, m_systemBookmarks
) {
771 if (missingSystemBookmarks
.contains(data
.url
)) {
772 PlacesItem
* item
= createSystemPlacesItem(data
);
773 switch (item
->groupType()) {
774 case PlacesItem::PlacesType
: placesItems
.append(item
); break;
775 case PlacesItem::RecentlySavedType
: recentlySavedItems
.append(item
); break;
776 case PlacesItem::SearchForType
: searchForItems
.append(item
); break;
777 case PlacesItem::DevicesType
:
778 default: Q_ASSERT(false); break;
784 // Create items for devices that have not been stored as bookmark yet
785 devicesItems
.reserve(devicesItems
.count() + devices
.count());
786 foreach (const QString
& udi
, devices
) {
787 const KBookmark bookmark
= PlacesItem::createDeviceBookmark(m_bookmarkManager
, udi
);
788 devicesItems
.append(new PlacesItem(bookmark
));
791 QList
<PlacesItem
*> items
;
792 items
.append(placesItems
);
793 items
.append(recentlySavedItems
);
794 items
.append(searchForItems
);
795 items
.append(devicesItems
);
797 foreach (PlacesItem
* item
, items
) {
798 if (!m_hiddenItemsShown
&& item
->isHidden()) {
799 m_bookmarkedItems
.append(item
);
805 #ifdef PLACESITEMMODEL_DEBUG
806 qCDebug(DolphinDebug
) << "Loaded bookmarks";
811 bool PlacesItemModel::acceptBookmark(const KBookmark
& bookmark
,
812 const QSet
<QString
>& availableDevices
) const
814 const QString udi
= bookmark
.metaDataItem(QStringLiteral("UDI"));
815 const QUrl url
= bookmark
.url();
816 const QString appName
= bookmark
.metaDataItem(QStringLiteral("OnlyInApp"));
817 const bool deviceAvailable
= availableDevices
.contains(udi
);
819 const bool allowedHere
= (appName
.isEmpty()
820 || appName
== KAboutData::applicationData().componentName()
821 || appName
== KAboutData::applicationData().componentName() + AppNamePrefix
)
822 && (m_fileIndexingEnabled
|| (url
.scheme() != QLatin1String("timeline") &&
823 url
.scheme() != QLatin1String("search")));
825 return (udi
.isEmpty() && allowedHere
) || deviceAvailable
;
828 PlacesItem
* PlacesItemModel::createSystemPlacesItem(const SystemBookmarkData
& data
)
830 KBookmark bookmark
= PlacesItem::createBookmark(m_bookmarkManager
,
835 const QString protocol
= data
.url
.scheme();
836 if (protocol
== QLatin1String("timeline") || protocol
== QLatin1String("search")) {
837 // As long as the KFilePlacesView from kdelibs is available, the system-bookmarks
838 // for "Recently Saved" and "Search For" should be a setting available only
839 // in the Places Panel (see description of AppNamePrefix for more details).
840 const QString appName
= KAboutData::applicationData().componentName() + AppNamePrefix
;
841 bookmark
.setMetaDataItem(QStringLiteral("OnlyInApp"), appName
);
844 PlacesItem
* item
= new PlacesItem(bookmark
);
845 item
->setSystemItem(true);
847 // Create default view-properties for all "Search For" and "Recently Saved" bookmarks
848 // in case if the user has not already created custom view-properties for a corresponding
850 const bool createDefaultViewProperties
= (item
->groupType() == PlacesItem::SearchForType
||
851 item
->groupType() == PlacesItem::RecentlySavedType
) &&
852 !GeneralSettings::self()->globalViewProps();
853 if (createDefaultViewProperties
) {
854 ViewProperties
props(convertedUrl(data
.url
));
855 if (!props
.exist()) {
856 const QString path
= data
.url
.path();
857 if (path
== QLatin1String("/documents")) {
858 props
.setViewMode(DolphinView::DetailsView
);
859 props
.setPreviewsShown(false);
860 props
.setVisibleRoles({"text", "path"});
861 } else if (path
== QLatin1String("/images")) {
862 props
.setViewMode(DolphinView::IconsView
);
863 props
.setPreviewsShown(true);
864 props
.setVisibleRoles({"text", "imageSize"});
865 } else if (path
== QLatin1String("/audio")) {
866 props
.setViewMode(DolphinView::DetailsView
);
867 props
.setPreviewsShown(false);
868 props
.setVisibleRoles({"text", "artist", "album"});
869 } else if (path
== QLatin1String("/videos")) {
870 props
.setViewMode(DolphinView::IconsView
);
871 props
.setPreviewsShown(true);
872 props
.setVisibleRoles({"text"});
873 } else if (data
.url
.scheme() == QLatin1String("timeline")) {
874 props
.setViewMode(DolphinView::DetailsView
);
875 props
.setVisibleRoles({"text", "modificationtime"});
883 void PlacesItemModel::createSystemBookmarks()
885 Q_ASSERT(m_systemBookmarks
.isEmpty());
886 Q_ASSERT(m_systemBookmarksIndexes
.isEmpty());
888 // Note: The context of the I18N_NOOP2 must be "KFile System Bookmarks". The real
889 // i18nc call is done after reading the bookmark. The reason why the i18nc call is not
890 // done here is because otherwise switching the language would not result in retranslating the
892 m_systemBookmarks
.append(SystemBookmarkData(QUrl::fromLocalFile(KUser().homeDir()),
893 QStringLiteral("user-home"),
894 I18N_NOOP2("KFile System Bookmarks", "Home")));
895 m_systemBookmarks
.append(SystemBookmarkData(QUrl(QStringLiteral("remote:/")),
896 QStringLiteral("network-workgroup"),
897 I18N_NOOP2("KFile System Bookmarks", "Network")));
898 m_systemBookmarks
.append(SystemBookmarkData(QUrl::fromLocalFile(QStringLiteral("/")),
899 QStringLiteral("folder-red"),
900 I18N_NOOP2("KFile System Bookmarks", "Root")));
901 m_systemBookmarks
.append(SystemBookmarkData(QUrl(QStringLiteral("trash:/")),
902 QStringLiteral("user-trash"),
903 I18N_NOOP2("KFile System Bookmarks", "Trash")));
905 if (m_fileIndexingEnabled
) {
906 m_systemBookmarks
.append(SystemBookmarkData(QUrl(QStringLiteral("timeline:/today")),
907 QStringLiteral("go-jump-today"),
908 I18N_NOOP2("KFile System Bookmarks", "Today")));
909 m_systemBookmarks
.append(SystemBookmarkData(QUrl(QStringLiteral("timeline:/yesterday")),
910 QStringLiteral("view-calendar-day"),
911 I18N_NOOP2("KFile System Bookmarks", "Yesterday")));
912 m_systemBookmarks
.append(SystemBookmarkData(QUrl(QStringLiteral("timeline:/thismonth")),
913 QStringLiteral("view-calendar-month"),
914 I18N_NOOP2("KFile System Bookmarks", "This Month")));
915 m_systemBookmarks
.append(SystemBookmarkData(QUrl(QStringLiteral("timeline:/lastmonth")),
916 QStringLiteral("view-calendar-month"),
917 I18N_NOOP2("KFile System Bookmarks", "Last Month")));
918 m_systemBookmarks
.append(SystemBookmarkData(QUrl(QStringLiteral("search:/documents")),
919 QStringLiteral("folder-text"),
920 I18N_NOOP2("KFile System Bookmarks", "Documents")));
921 m_systemBookmarks
.append(SystemBookmarkData(QUrl(QStringLiteral("search:/images")),
922 QStringLiteral("folder-images"),
923 I18N_NOOP2("KFile System Bookmarks", "Images")));
924 m_systemBookmarks
.append(SystemBookmarkData(QUrl(QStringLiteral("search:/audio")),
925 QStringLiteral("folder-sound"),
926 I18N_NOOP2("KFile System Bookmarks", "Audio Files")));
927 m_systemBookmarks
.append(SystemBookmarkData(QUrl(QStringLiteral("search:/videos")),
928 QStringLiteral("folder-videos"),
929 I18N_NOOP2("KFile System Bookmarks", "Videos")));
932 for (int i
= 0; i
< m_systemBookmarks
.count(); ++i
) {
933 m_systemBookmarksIndexes
.insert(m_systemBookmarks
[i
].url
, i
);
937 void PlacesItemModel::clear() {
938 m_bookmarkedItems
.clear();
939 KStandardItemModel::clear();
942 void PlacesItemModel::initializeAvailableDevices()
944 QString
predicate(QStringLiteral("[[[[ StorageVolume.ignored == false AND [ StorageVolume.usage == 'FileSystem' OR StorageVolume.usage == 'Encrypted' ]]"
946 "[ IS StorageAccess AND StorageDrive.driveType == 'Floppy' ]]"
948 "OpticalDisc.availableContent & 'Audio' ]"
950 "StorageAccess.ignored == false ]"));
953 if (KProtocolInfo::isKnownProtocol(QStringLiteral("mtp"))) {
954 predicate
.prepend("[");
955 predicate
.append(" OR PortableMediaPlayer.supportedProtocols == 'mtp']");
958 m_predicate
= Solid::Predicate::fromString(predicate
);
959 Q_ASSERT(m_predicate
.isValid());
961 Solid::DeviceNotifier
* notifier
= Solid::DeviceNotifier::instance();
962 connect(notifier
, &Solid::DeviceNotifier::deviceAdded
, this, &PlacesItemModel::slotDeviceAdded
);
963 connect(notifier
, &Solid::DeviceNotifier::deviceRemoved
, this, &PlacesItemModel::slotDeviceRemoved
);
965 const QList
<Solid::Device
>& deviceList
= Solid::Device::listFromQuery(m_predicate
);
966 foreach (const Solid::Device
& device
, deviceList
) {
967 m_availableDevices
<< device
.udi();
971 int PlacesItemModel::bookmarkIndex(int index
) const
973 int bookmarkIndex
= 0;
975 while (bookmarkIndex
< m_bookmarkedItems
.count()) {
976 if (!m_bookmarkedItems
[bookmarkIndex
]) {
977 if (modelIndex
== index
) {
985 return bookmarkIndex
>= m_bookmarkedItems
.count() ? -1 : bookmarkIndex
;
988 void PlacesItemModel::hideItem(int index
)
990 PlacesItem
* shownItem
= placesItem(index
);
995 shownItem
->setHidden(true);
996 if (m_hiddenItemsShown
) {
997 // Removing items from the model is not allowed if all hidden
998 // items should be shown.
1002 const int newIndex
= bookmarkIndex(index
);
1003 if (newIndex
>= 0) {
1004 const KBookmark hiddenBookmark
= shownItem
->bookmark();
1005 PlacesItem
* hiddenItem
= new PlacesItem(hiddenBookmark
);
1007 const PlacesItem
* previousItem
= placesItem(index
- 1);
1008 KBookmark previousBookmark
;
1010 previousBookmark
= previousItem
->bookmark();
1013 const bool updateBookmark
= (m_bookmarkManager
->root().indexOf(hiddenBookmark
) >= 0);
1016 if (updateBookmark
) {
1017 // removeItem() also removed the bookmark from m_bookmarkManager in
1018 // PlacesItemModel::onItemRemoved(). However for hidden items the
1019 // bookmark should still be remembered, so readd it again:
1020 m_bookmarkManager
->root().addBookmark(hiddenBookmark
);
1021 m_bookmarkManager
->root().moveBookmark(hiddenBookmark
, previousBookmark
);
1024 m_bookmarkedItems
.insert(newIndex
, hiddenItem
);
1028 QString
PlacesItemModel::internalMimeType() const
1030 return "application/x-dolphinplacesmodel-" +
1031 QString::number((qptrdiff
)this);
1034 int PlacesItemModel::groupedDropIndex(int index
, const PlacesItem
* item
) const
1038 int dropIndex
= index
;
1039 const PlacesItem::GroupType type
= item
->groupType();
1041 const int itemCount
= count();
1043 dropIndex
= itemCount
;
1046 // Search nearest previous item with the same group
1047 int previousIndex
= -1;
1048 for (int i
= dropIndex
- 1; i
>= 0; --i
) {
1049 if (placesItem(i
)->groupType() == type
) {
1055 // Search nearest next item with the same group
1057 for (int i
= dropIndex
; i
< count(); ++i
) {
1058 if (placesItem(i
)->groupType() == type
) {
1064 // Adjust the drop-index to be inserted to the
1065 // nearest item with the same group.
1066 if (previousIndex
>= 0 && nextIndex
>= 0) {
1067 dropIndex
= (dropIndex
- previousIndex
< nextIndex
- dropIndex
) ?
1068 previousIndex
+ 1 : nextIndex
;
1069 } else if (previousIndex
>= 0) {
1070 dropIndex
= previousIndex
+ 1;
1071 } else if (nextIndex
>= 0) {
1072 dropIndex
= nextIndex
;
1078 bool PlacesItemModel::equalBookmarkIdentifiers(const KBookmark
& b1
, const KBookmark
& b2
)
1080 const QString udi1
= b1
.metaDataItem(QStringLiteral("UDI"));
1081 const QString udi2
= b2
.metaDataItem(QStringLiteral("UDI"));
1082 if (!udi1
.isEmpty() && !udi2
.isEmpty()) {
1083 return udi1
== udi2
;
1085 return b1
.metaDataItem(QStringLiteral("ID")) == b2
.metaDataItem(QStringLiteral("ID"));
1089 QUrl
PlacesItemModel::createTimelineUrl(const QUrl
& url
)
1091 // TODO: Clarify with the Baloo-team whether it makes sense
1092 // provide default-timeline-URLs like 'yesterday', 'this month'
1093 // and 'last month'.
1096 const QString path
= url
.toDisplayString(QUrl::PreferLocalFile
);
1097 if (path
.endsWith(QLatin1String("yesterday"))) {
1098 const QDate date
= QDate::currentDate().addDays(-1);
1099 const int year
= date
.year();
1100 const int month
= date
.month();
1101 const int day
= date
.day();
1102 timelineUrl
= QUrl("timeline:/" + timelineDateString(year
, month
) +
1103 '/' + timelineDateString(year
, month
, day
));
1104 } else if (path
.endsWith(QLatin1String("thismonth"))) {
1105 const QDate date
= QDate::currentDate();
1106 timelineUrl
= QUrl("timeline:/" + timelineDateString(date
.year(), date
.month()));
1107 } else if (path
.endsWith(QLatin1String("lastmonth"))) {
1108 const QDate date
= QDate::currentDate().addMonths(-1);
1109 timelineUrl
= QUrl("timeline:/" + timelineDateString(date
.year(), date
.month()));
1111 Q_ASSERT(path
.endsWith(QLatin1String("today")));
1118 QString
PlacesItemModel::timelineDateString(int year
, int month
, int day
)
1120 QString date
= QString::number(year
) + '-';
1124 date
+= QString::number(month
);
1131 date
+= QString::number(day
);
1137 QUrl
PlacesItemModel::createSearchUrl(const QUrl
& url
)
1142 const QString path
= url
.toDisplayString(QUrl::PreferLocalFile
);
1143 if (path
.endsWith(QLatin1String("documents"))) {
1144 searchUrl
= searchUrlForType(QStringLiteral("Document"));
1145 } else if (path
.endsWith(QLatin1String("images"))) {
1146 searchUrl
= searchUrlForType(QStringLiteral("Image"));
1147 } else if (path
.endsWith(QLatin1String("audio"))) {
1148 searchUrl
= searchUrlForType(QStringLiteral("Audio"));
1149 } else if (path
.endsWith(QLatin1String("videos"))) {
1150 searchUrl
= searchUrlForType(QStringLiteral("Video"));
1162 QUrl
PlacesItemModel::searchUrlForType(const QString
& type
)
1165 query
.addType(type
);
1167 return query
.toSearchUrl();
1171 #ifdef PLACESITEMMODEL_DEBUG
1172 void PlacesItemModel::showModelState()
1174 qCDebug(DolphinDebug
) << "=================================";
1175 qCDebug(DolphinDebug
) << "Model:";
1176 qCDebug(DolphinDebug
) << "hidden-index model-index text";
1178 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
1179 if (m_bookmarkedItems
[i
]) {
1180 qCDebug(DolphinDebug
) << i
<< "(Hidden) " << " " << m_bookmarkedItems
[i
]->dataValue("text").toString();
1182 if (item(modelIndex
)) {
1183 qCDebug(DolphinDebug
) << i
<< " " << modelIndex
<< " " << item(modelIndex
)->dataValue("text").toString();
1185 qCDebug(DolphinDebug
) << i
<< " " << modelIndex
<< " " << "(not available yet)";
1191 qCDebug(DolphinDebug
);
1192 qCDebug(DolphinDebug
) << "Bookmarks:";
1194 int bookmarkIndex
= 0;
1195 KBookmarkGroup root
= m_bookmarkManager
->root();
1196 KBookmark bookmark
= root
.first();
1197 while (!bookmark
.isNull()) {
1198 const QString udi
= bookmark
.metaDataItem("UDI");
1199 const QString text
= udi
.isEmpty() ? bookmark
.text() : udi
;
1200 if (bookmark
.metaDataItem("IsHidden") == QLatin1String("true")) {
1201 qCDebug(DolphinDebug
) << bookmarkIndex
<< "(Hidden)" << text
;
1203 qCDebug(DolphinDebug
) << bookmarkIndex
<< " " << text
;
1206 bookmark
= root
.next(bookmark
);