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("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
= "media-eject";
293 text
= i18nc("@item", "Unmount '%1'", label
);
294 iconName
= "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 foreach (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("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() == "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, SLOT(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("UDI").isEmpty()) {
642 item
->setBookmark(newBookmark
);
643 item
->setText(i18nc("KFile System Bookmarks", newBookmark
.text().toUtf8().constData()));
650 const QString udi
= newBookmark
.metaDataItem("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 foreach (const QString
& udi
, devices
) {
786 const KBookmark bookmark
= PlacesItem::createDeviceBookmark(m_bookmarkManager
, udi
);
787 devicesItems
.append(new PlacesItem(bookmark
));
790 QList
<PlacesItem
*> items
;
791 items
.append(placesItems
);
792 items
.append(recentlySavedItems
);
793 items
.append(searchForItems
);
794 items
.append(devicesItems
);
796 foreach (PlacesItem
* item
, items
) {
797 if (!m_hiddenItemsShown
&& item
->isHidden()) {
798 m_bookmarkedItems
.append(item
);
804 #ifdef PLACESITEMMODEL_DEBUG
805 qCDebug(DolphinDebug
) << "Loaded bookmarks";
810 bool PlacesItemModel::acceptBookmark(const KBookmark
& bookmark
,
811 const QSet
<QString
>& availableDevices
) const
813 const QString udi
= bookmark
.metaDataItem("UDI");
814 const QUrl url
= bookmark
.url();
815 const QString appName
= bookmark
.metaDataItem("OnlyInApp");
816 const bool deviceAvailable
= availableDevices
.contains(udi
);
818 const bool allowedHere
= (appName
.isEmpty()
819 || appName
== KAboutData::applicationData().componentName()
820 || appName
== KAboutData::applicationData().componentName() + AppNamePrefix
)
821 && (m_fileIndexingEnabled
|| (url
.scheme() != QLatin1String("timeline") &&
822 url
.scheme() != QLatin1String("search")));
824 return (udi
.isEmpty() && allowedHere
) || deviceAvailable
;
827 PlacesItem
* PlacesItemModel::createSystemPlacesItem(const SystemBookmarkData
& data
)
829 KBookmark bookmark
= PlacesItem::createBookmark(m_bookmarkManager
,
834 const QString protocol
= data
.url
.scheme();
835 if (protocol
== QLatin1String("timeline") || protocol
== QLatin1String("search")) {
836 // As long as the KFilePlacesView from kdelibs is available, the system-bookmarks
837 // for "Recently Saved" and "Search For" should be a setting available only
838 // in the Places Panel (see description of AppNamePrefix for more details).
839 const QString appName
= KAboutData::applicationData().componentName() + AppNamePrefix
;
840 bookmark
.setMetaDataItem("OnlyInApp", appName
);
843 PlacesItem
* item
= new PlacesItem(bookmark
);
844 item
->setSystemItem(true);
846 // Create default view-properties for all "Search For" and "Recently Saved" bookmarks
847 // in case if the user has not already created custom view-properties for a corresponding
849 const bool createDefaultViewProperties
= (item
->groupType() == PlacesItem::SearchForType
||
850 item
->groupType() == PlacesItem::RecentlySavedType
) &&
851 !GeneralSettings::self()->globalViewProps();
852 if (createDefaultViewProperties
) {
853 ViewProperties
props(convertedUrl(data
.url
));
854 if (!props
.exist()) {
855 const QString path
= data
.url
.path();
856 if (path
== QLatin1String("/documents")) {
857 props
.setViewMode(DolphinView::DetailsView
);
858 props
.setPreviewsShown(false);
859 props
.setVisibleRoles({"text", "path"});
860 } else if (path
== QLatin1String("/images")) {
861 props
.setViewMode(DolphinView::IconsView
);
862 props
.setPreviewsShown(true);
863 props
.setVisibleRoles({"text", "imageSize"});
864 } else if (path
== QLatin1String("/audio")) {
865 props
.setViewMode(DolphinView::DetailsView
);
866 props
.setPreviewsShown(false);
867 props
.setVisibleRoles({"text", "artist", "album"});
868 } else if (path
== QLatin1String("/videos")) {
869 props
.setViewMode(DolphinView::IconsView
);
870 props
.setPreviewsShown(true);
871 props
.setVisibleRoles({"text"});
872 } else if (data
.url
.scheme() == "timeline") {
873 props
.setViewMode(DolphinView::DetailsView
);
874 props
.setVisibleRoles({"text", "date"});
882 void PlacesItemModel::createSystemBookmarks()
884 Q_ASSERT(m_systemBookmarks
.isEmpty());
885 Q_ASSERT(m_systemBookmarksIndexes
.isEmpty());
887 // Note: The context of the I18N_NOOP2 must be "KFile System Bookmarks". The real
888 // i18nc call is done after reading the bookmark. The reason why the i18nc call is not
889 // done here is because otherwise switching the language would not result in retranslating the
891 m_systemBookmarks
.append(SystemBookmarkData(QUrl::fromLocalFile(KUser().homeDir()),
893 I18N_NOOP2("KFile System Bookmarks", "Home")));
894 m_systemBookmarks
.append(SystemBookmarkData(QUrl("remote:/"),
896 I18N_NOOP2("KFile System Bookmarks", "Network")));
897 m_systemBookmarks
.append(SystemBookmarkData(QUrl::fromLocalFile("/"),
899 I18N_NOOP2("KFile System Bookmarks", "Root")));
900 m_systemBookmarks
.append(SystemBookmarkData(QUrl("trash:/"),
902 I18N_NOOP2("KFile System Bookmarks", "Trash")));
904 if (m_fileIndexingEnabled
) {
905 m_systemBookmarks
.append(SystemBookmarkData(QUrl("timeline:/today"),
907 I18N_NOOP2("KFile System Bookmarks", "Today")));
908 m_systemBookmarks
.append(SystemBookmarkData(QUrl("timeline:/yesterday"),
910 I18N_NOOP2("KFile System Bookmarks", "Yesterday")));
911 m_systemBookmarks
.append(SystemBookmarkData(QUrl("timeline:/thismonth"),
912 "view-calendar-month",
913 I18N_NOOP2("KFile System Bookmarks", "This Month")));
914 m_systemBookmarks
.append(SystemBookmarkData(QUrl("timeline:/lastmonth"),
915 "view-calendar-month",
916 I18N_NOOP2("KFile System Bookmarks", "Last Month")));
917 m_systemBookmarks
.append(SystemBookmarkData(QUrl("search:/documents"),
919 I18N_NOOP2("KFile System Bookmarks", "Documents")));
920 m_systemBookmarks
.append(SystemBookmarkData(QUrl("search:/images"),
922 I18N_NOOP2("KFile System Bookmarks", "Images")));
923 m_systemBookmarks
.append(SystemBookmarkData(QUrl("search:/audio"),
925 I18N_NOOP2("KFile System Bookmarks", "Audio Files")));
926 m_systemBookmarks
.append(SystemBookmarkData(QUrl("search:/videos"),
928 I18N_NOOP2("KFile System Bookmarks", "Videos")));
931 for (int i
= 0; i
< m_systemBookmarks
.count(); ++i
) {
932 m_systemBookmarksIndexes
.insert(m_systemBookmarks
[i
].url
, i
);
936 void PlacesItemModel::clear() {
937 m_bookmarkedItems
.clear();
938 KStandardItemModel::clear();
941 void PlacesItemModel::initializeAvailableDevices()
943 QString
predicate("[[[[ StorageVolume.ignored == false AND [ StorageVolume.usage == 'FileSystem' OR StorageVolume.usage == 'Encrypted' ]]"
945 "[ IS StorageAccess AND StorageDrive.driveType == 'Floppy' ]]"
947 "OpticalDisc.availableContent & 'Audio' ]"
949 "StorageAccess.ignored == false ]");
952 if (KProtocolInfo::isKnownProtocol("mtp")) {
953 predicate
.prepend("[");
954 predicate
.append(" OR PortableMediaPlayer.supportedProtocols == 'mtp']");
957 m_predicate
= Solid::Predicate::fromString(predicate
);
958 Q_ASSERT(m_predicate
.isValid());
960 Solid::DeviceNotifier
* notifier
= Solid::DeviceNotifier::instance();
961 connect(notifier
, &Solid::DeviceNotifier::deviceAdded
, this, &PlacesItemModel::slotDeviceAdded
);
962 connect(notifier
, &Solid::DeviceNotifier::deviceRemoved
, this, &PlacesItemModel::slotDeviceRemoved
);
964 const QList
<Solid::Device
>& deviceList
= Solid::Device::listFromQuery(m_predicate
);
965 foreach (const Solid::Device
& device
, deviceList
) {
966 m_availableDevices
<< device
.udi();
970 int PlacesItemModel::bookmarkIndex(int index
) const
972 int bookmarkIndex
= 0;
974 while (bookmarkIndex
< m_bookmarkedItems
.count()) {
975 if (!m_bookmarkedItems
[bookmarkIndex
]) {
976 if (modelIndex
== index
) {
984 return bookmarkIndex
>= m_bookmarkedItems
.count() ? -1 : bookmarkIndex
;
987 void PlacesItemModel::hideItem(int index
)
989 PlacesItem
* shownItem
= placesItem(index
);
994 shownItem
->setHidden(true);
995 if (m_hiddenItemsShown
) {
996 // Removing items from the model is not allowed if all hidden
997 // items should be shown.
1001 const int newIndex
= bookmarkIndex(index
);
1002 if (newIndex
>= 0) {
1003 const KBookmark hiddenBookmark
= shownItem
->bookmark();
1004 PlacesItem
* hiddenItem
= new PlacesItem(hiddenBookmark
);
1006 const PlacesItem
* previousItem
= placesItem(index
- 1);
1007 KBookmark previousBookmark
;
1009 previousBookmark
= previousItem
->bookmark();
1012 const bool updateBookmark
= (m_bookmarkManager
->root().indexOf(hiddenBookmark
) >= 0);
1015 if (updateBookmark
) {
1016 // removeItem() also removed the bookmark from m_bookmarkManager in
1017 // PlacesItemModel::onItemRemoved(). However for hidden items the
1018 // bookmark should still be remembered, so readd it again:
1019 m_bookmarkManager
->root().addBookmark(hiddenBookmark
);
1020 m_bookmarkManager
->root().moveBookmark(hiddenBookmark
, previousBookmark
);
1023 m_bookmarkedItems
.insert(newIndex
, hiddenItem
);
1027 QString
PlacesItemModel::internalMimeType() const
1029 return "application/x-dolphinplacesmodel-" +
1030 QString::number((qptrdiff
)this);
1033 int PlacesItemModel::groupedDropIndex(int index
, const PlacesItem
* item
) const
1037 int dropIndex
= index
;
1038 const PlacesItem::GroupType type
= item
->groupType();
1040 const int itemCount
= count();
1042 dropIndex
= itemCount
;
1045 // Search nearest previous item with the same group
1046 int previousIndex
= -1;
1047 for (int i
= dropIndex
- 1; i
>= 0; --i
) {
1048 if (placesItem(i
)->groupType() == type
) {
1054 // Search nearest next item with the same group
1056 for (int i
= dropIndex
; i
< count(); ++i
) {
1057 if (placesItem(i
)->groupType() == type
) {
1063 // Adjust the drop-index to be inserted to the
1064 // nearest item with the same group.
1065 if (previousIndex
>= 0 && nextIndex
>= 0) {
1066 dropIndex
= (dropIndex
- previousIndex
< nextIndex
- dropIndex
) ?
1067 previousIndex
+ 1 : nextIndex
;
1068 } else if (previousIndex
>= 0) {
1069 dropIndex
= previousIndex
+ 1;
1070 } else if (nextIndex
>= 0) {
1071 dropIndex
= nextIndex
;
1077 bool PlacesItemModel::equalBookmarkIdentifiers(const KBookmark
& b1
, const KBookmark
& b2
)
1079 const QString udi1
= b1
.metaDataItem("UDI");
1080 const QString udi2
= b2
.metaDataItem("UDI");
1081 if (!udi1
.isEmpty() && !udi2
.isEmpty()) {
1082 return udi1
== udi2
;
1084 return b1
.metaDataItem("ID") == b2
.metaDataItem("ID");
1088 QUrl
PlacesItemModel::createTimelineUrl(const QUrl
& url
)
1090 // TODO: Clarify with the Baloo-team whether it makes sense
1091 // provide default-timeline-URLs like 'yesterday', 'this month'
1092 // and 'last month'.
1095 const QString path
= url
.toDisplayString(QUrl::PreferLocalFile
);
1096 if (path
.endsWith(QLatin1String("yesterday"))) {
1097 const QDate date
= QDate::currentDate().addDays(-1);
1098 const int year
= date
.year();
1099 const int month
= date
.month();
1100 const int day
= date
.day();
1101 timelineUrl
= "timeline:/" + timelineDateString(year
, month
) +
1102 '/' + timelineDateString(year
, month
, day
);
1103 } else if (path
.endsWith(QLatin1String("thismonth"))) {
1104 const QDate date
= QDate::currentDate();
1105 timelineUrl
= "timeline:/" + timelineDateString(date
.year(), date
.month());
1106 } else if (path
.endsWith(QLatin1String("lastmonth"))) {
1107 const QDate date
= QDate::currentDate().addMonths(-1);
1108 timelineUrl
= "timeline:/" + timelineDateString(date
.year(), date
.month());
1110 Q_ASSERT(path
.endsWith(QLatin1String("today")));
1117 QString
PlacesItemModel::timelineDateString(int year
, int month
, int day
)
1119 QString date
= QString::number(year
) + '-';
1123 date
+= QString::number(month
);
1130 date
+= QString::number(day
);
1136 QUrl
PlacesItemModel::createSearchUrl(const QUrl
& url
)
1141 const QString path
= url
.toDisplayString(QUrl::PreferLocalFile
);
1142 if (path
.endsWith(QLatin1String("documents"))) {
1143 searchUrl
= searchUrlForType("Document");
1144 } else if (path
.endsWith(QLatin1String("images"))) {
1145 searchUrl
= searchUrlForType("Image");
1146 } else if (path
.endsWith(QLatin1String("audio"))) {
1147 searchUrl
= searchUrlForType("Audio");
1148 } else if (path
.endsWith(QLatin1String("videos"))) {
1149 searchUrl
= searchUrlForType("Video");
1161 QUrl
PlacesItemModel::searchUrlForType(const QString
& type
)
1164 query
.addType(type
);
1166 return query
.toSearchUrl();
1170 #ifdef PLACESITEMMODEL_DEBUG
1171 void PlacesItemModel::showModelState()
1173 qCDebug(DolphinDebug
) << "=================================";
1174 qCDebug(DolphinDebug
) << "Model:";
1175 qCDebug(DolphinDebug
) << "hidden-index model-index text";
1177 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
1178 if (m_bookmarkedItems
[i
]) {
1179 qCDebug(DolphinDebug
) << i
<< "(Hidden) " << " " << m_bookmarkedItems
[i
]->dataValue("text").toString();
1181 if (item(modelIndex
)) {
1182 qCDebug(DolphinDebug
) << i
<< " " << modelIndex
<< " " << item(modelIndex
)->dataValue("text").toString();
1184 qCDebug(DolphinDebug
) << i
<< " " << modelIndex
<< " " << "(not available yet)";
1190 qCDebug(DolphinDebug
);
1191 qCDebug(DolphinDebug
) << "Bookmarks:";
1193 int bookmarkIndex
= 0;
1194 KBookmarkGroup root
= m_bookmarkManager
->root();
1195 KBookmark bookmark
= root
.first();
1196 while (!bookmark
.isNull()) {
1197 const QString udi
= bookmark
.metaDataItem("UDI");
1198 const QString text
= udi
.isEmpty() ? bookmark
.text() : udi
;
1199 if (bookmark
.metaDataItem("IsHidden") == QLatin1String("true")) {
1200 qCDebug(DolphinDebug
) << bookmarkIndex
<< "(Hidden)" << text
;
1202 qCDebug(DolphinDebug
) << bookmarkIndex
<< " " << text
;
1205 bookmark
= root
.next(bookmark
);