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 <KBookmarkGroup>
30 #include <KBookmarkManager>
33 #include <kprotocolinfo.h>
34 #include <KLocalizedString>
35 #include <KComponentData>
36 #include <QStandardPaths>
39 #include "placesitem.h"
44 #include <KUrlMimeData>
46 #include <Solid/Device>
47 #include <Solid/DeviceNotifier>
48 #include <Solid/OpticalDisc>
49 #include <Solid/OpticalDrive>
50 #include <Solid/StorageAccess>
51 #include <Solid/StorageDrive>
53 #include <views/dolphinview.h>
54 #include <views/viewproperties.h>
57 #include <Baloo/Query>
58 #include <Baloo/IndexerConfig>
62 // As long as KFilePlacesView from kdelibs is available in parallel, the
63 // system-bookmarks for "Recently Saved" and "Search For" should be
64 // shown only inside the Places Panel. This is necessary as the stored
65 // URLs needs to get translated to a Baloo-search-URL on-the-fly to
66 // be independent from changes in the Baloo-search-URL-syntax.
67 // Hence a prefix to the application-name of the stored bookmarks is
68 // added, which is only read by PlacesItemModel.
69 const char AppNamePrefix
[] = "-places-panel";
72 PlacesItemModel::PlacesItemModel(QObject
* parent
) :
73 KStandardItemModel(parent
),
74 m_fileIndexingEnabled(false),
75 m_hiddenItemsShown(false),
80 m_systemBookmarksIndexes(),
82 m_hiddenItemToRemove(-1),
83 m_updateBookmarksTimer(0),
84 m_storageSetupInProgress()
87 Baloo::IndexerConfig config
;
88 m_fileIndexingEnabled
= config
.fileIndexingEnabled();
90 const QString file
= QStandardPaths::locate(QStandardPaths::GenericDataLocation
, "kfileplaces/bookmarks.xml");
91 m_bookmarkManager
= KBookmarkManager::managerForFile(file
, "kfilePlaces");
93 createSystemBookmarks();
94 initializeAvailableDevices();
97 const int syncBookmarksTimeout
= 100;
99 m_updateBookmarksTimer
= new QTimer(this);
100 m_updateBookmarksTimer
->setInterval(syncBookmarksTimeout
);
101 m_updateBookmarksTimer
->setSingleShot(true);
102 connect(m_updateBookmarksTimer
, &QTimer::timeout
, this, &PlacesItemModel::updateBookmarks
);
104 connect(m_bookmarkManager
, &KBookmarkManager::changed
,
105 m_updateBookmarksTimer
, static_cast<void(QTimer::*)()>(&QTimer::start
));
106 connect(m_bookmarkManager
, &KBookmarkManager::bookmarksChanged
,
107 m_updateBookmarksTimer
, static_cast<void(QTimer::*)()>(&QTimer::start
));
110 PlacesItemModel::~PlacesItemModel()
113 qDeleteAll(m_bookmarkedItems
);
114 m_bookmarkedItems
.clear();
117 PlacesItem
* PlacesItemModel::createPlacesItem(const QString
& text
,
119 const QString
& iconName
)
121 const KBookmark bookmark
= PlacesItem::createBookmark(m_bookmarkManager
, text
, url
, iconName
);
122 return new PlacesItem(bookmark
);
125 PlacesItem
* PlacesItemModel::placesItem(int index
) const
127 return dynamic_cast<PlacesItem
*>(item(index
));
130 int PlacesItemModel::hiddenCount() const
133 int hiddenItemCount
= 0;
134 foreach (const PlacesItem
* item
, m_bookmarkedItems
) {
138 if (placesItem(modelIndex
)->isHidden()) {
145 return hiddenItemCount
;
148 void PlacesItemModel::setHiddenItemsShown(bool show
)
150 if (m_hiddenItemsShown
== show
) {
154 m_hiddenItemsShown
= show
;
157 // Move all items that are part of m_bookmarkedItems to the model.
158 QList
<PlacesItem
*> itemsToInsert
;
159 QList
<int> insertPos
;
161 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
162 if (m_bookmarkedItems
[i
]) {
163 itemsToInsert
.append(m_bookmarkedItems
[i
]);
164 m_bookmarkedItems
[i
] = 0;
165 insertPos
.append(modelIndex
);
170 // Inserting the items will automatically insert an item
171 // to m_bookmarkedItems in PlacesItemModel::onItemsInserted().
172 // The items are temporary saved in itemsToInsert, so
173 // m_bookmarkedItems can be shrinked now.
174 m_bookmarkedItems
.erase(m_bookmarkedItems
.begin(),
175 m_bookmarkedItems
.begin() + itemsToInsert
.count());
177 for (int i
= 0; i
< itemsToInsert
.count(); ++i
) {
178 insertItem(insertPos
[i
], itemsToInsert
[i
]);
181 Q_ASSERT(m_bookmarkedItems
.count() == count());
183 // Move all items of the model, where the "isHidden" property is true, to
184 // m_bookmarkedItems.
185 Q_ASSERT(m_bookmarkedItems
.count() == count());
186 for (int i
= count() - 1; i
>= 0; --i
) {
187 if (placesItem(i
)->isHidden()) {
193 #ifdef PLACESITEMMODEL_DEBUG
194 kDebug() << "Changed visibility of hidden items";
199 bool PlacesItemModel::hiddenItemsShown() const
201 return m_hiddenItemsShown
;
204 int PlacesItemModel::closestItem(const QUrl
& url
) const
209 for (int i
= 0; i
< count(); ++i
) {
210 const QUrl itemUrl
= placesItem(i
)->url();
211 if (url
== itemUrl
) {
212 // We can't find a closer one, so stop here.
215 } else if (itemUrl
.isParentOf(url
)) {
216 const int length
= itemUrl
.path().length();
217 if (length
> maxLength
) {
227 void PlacesItemModel::appendItemToGroup(PlacesItem
* item
)
234 while (i
< count() && placesItem(i
)->group() != item
->group()) {
238 bool inserted
= false;
239 while (!inserted
&& i
< count()) {
240 if (placesItem(i
)->group() != item
->group()) {
253 QAction
* PlacesItemModel::ejectAction(int index
) const
255 const PlacesItem
* item
= placesItem(index
);
256 if (item
&& item
->device().is
<Solid::OpticalDisc
>()) {
257 return new QAction(QIcon::fromTheme("media-eject"), i18nc("@item", "Eject '%1'", item
->text()), 0);
263 QAction
* PlacesItemModel::teardownAction(int index
) const
265 const PlacesItem
* item
= placesItem(index
);
270 Solid::Device device
= item
->device();
271 const bool providesTearDown
= device
.is
<Solid::StorageAccess
>() &&
272 device
.as
<Solid::StorageAccess
>()->isAccessible();
273 if (!providesTearDown
) {
277 Solid::StorageDrive
* drive
= device
.as
<Solid::StorageDrive
>();
279 drive
= device
.parent().as
<Solid::StorageDrive
>();
282 bool hotPluggable
= false;
283 bool removable
= false;
285 hotPluggable
= drive
->isHotpluggable();
286 removable
= drive
->isRemovable();
291 const QString label
= item
->text();
292 if (device
.is
<Solid::OpticalDisc
>()) {
293 text
= i18nc("@item", "Release '%1'", label
);
294 } else if (removable
|| hotPluggable
) {
295 text
= i18nc("@item", "Safely Remove '%1'", label
);
296 iconName
= "media-eject";
298 text
= i18nc("@item", "Unmount '%1'", label
);
299 iconName
= "media-eject";
302 if (iconName
.isEmpty()) {
303 return new QAction(text
, 0);
306 return new QAction(QIcon::fromTheme(iconName
), text
, 0);
309 void PlacesItemModel::requestEject(int index
)
311 const PlacesItem
* item
= placesItem(index
);
313 Solid::OpticalDrive
* drive
= item
->device().parent().as
<Solid::OpticalDrive
>();
315 connect(drive
, &Solid::OpticalDrive::ejectDone
,
316 this, &PlacesItemModel::slotStorageTeardownDone
);
319 const QString label
= item
->text();
320 const QString message
= i18nc("@info", "The device '%1' is not a disk and cannot be ejected.", label
);
321 emit
errorMessage(message
);
326 void PlacesItemModel::requestTeardown(int index
)
328 const PlacesItem
* item
= placesItem(index
);
330 Solid::StorageAccess
* access
= item
->device().as
<Solid::StorageAccess
>();
332 connect(access
, &Solid::StorageAccess::teardownDone
,
333 this, &PlacesItemModel::slotStorageTeardownDone
);
339 bool PlacesItemModel::storageSetupNeeded(int index
) const
341 const PlacesItem
* item
= placesItem(index
);
342 return item
? item
->storageSetupNeeded() : false;
345 void PlacesItemModel::requestStorageSetup(int index
)
347 const PlacesItem
* item
= placesItem(index
);
352 Solid::Device device
= item
->device();
353 const bool setup
= device
.is
<Solid::StorageAccess
>()
354 && !m_storageSetupInProgress
.contains(device
.as
<Solid::StorageAccess
>())
355 && !device
.as
<Solid::StorageAccess
>()->isAccessible();
357 Solid::StorageAccess
* access
= device
.as
<Solid::StorageAccess
>();
359 m_storageSetupInProgress
[access
] = index
;
361 connect(access
, &Solid::StorageAccess::setupDone
,
362 this, &PlacesItemModel::slotStorageSetupDone
);
368 QMimeData
* PlacesItemModel::createMimeData(const KItemSet
& indexes
) const
373 QDataStream
stream(&itemData
, QIODevice::WriteOnly
);
375 foreach (int index
, indexes
) {
376 const QUrl itemUrl
= placesItem(index
)->url();
377 if (itemUrl
.isValid()) {
383 QMimeData
* mimeData
= new QMimeData();
384 if (!urls
.isEmpty()) {
385 mimeData
->setUrls(urls
);
387 mimeData
->setData(internalMimeType(), itemData
);
392 bool PlacesItemModel::supportsDropping(int index
) const
394 return index
>= 0 && index
< count();
397 void PlacesItemModel::dropMimeDataBefore(int index
, const QMimeData
* mimeData
)
399 if (mimeData
->hasFormat(internalMimeType())) {
400 // The item has been moved inside the view
401 QByteArray itemData
= mimeData
->data(internalMimeType());
402 QDataStream
stream(&itemData
, QIODevice::ReadOnly
);
405 if (oldIndex
== index
|| oldIndex
== index
- 1) {
406 // No moving has been done
410 PlacesItem
* oldItem
= placesItem(oldIndex
);
415 PlacesItem
* newItem
= new PlacesItem(oldItem
->bookmark());
416 removeItem(oldIndex
);
418 if (oldIndex
< index
) {
422 const int dropIndex
= groupedDropIndex(index
, newItem
);
423 insertItem(dropIndex
, newItem
);
424 } else if (mimeData
->hasFormat("text/uri-list")) {
425 // One or more items must be added to the model
426 const QList
<QUrl
> urls
= KUrlMimeData::urlsFromMimeData(mimeData
);
427 for (int i
= urls
.count() - 1; i
>= 0; --i
) {
428 const QUrl
& url
= urls
[i
];
430 QString text
= url
.fileName();
431 if (text
.isEmpty()) {
435 if ((url
.isLocalFile() && !QFileInfo(url
.toLocalFile()).isDir())
436 || url
.scheme() == "trash") {
437 // Only directories outside the trash are allowed
441 PlacesItem
* newItem
= createPlacesItem(text
, url
);
442 const int dropIndex
= groupedDropIndex(index
, newItem
);
443 insertItem(dropIndex
, newItem
);
448 QUrl
PlacesItemModel::convertedUrl(const QUrl
& url
)
451 if (url
.scheme() == QLatin1String("timeline")) {
452 newUrl
= createTimelineUrl(url
);
453 } else if (url
.scheme() == QLatin1String("search")) {
454 newUrl
= createSearchUrl(url
);
460 void PlacesItemModel::onItemInserted(int index
)
462 const PlacesItem
* insertedItem
= placesItem(index
);
464 // Take care to apply the PlacesItemModel-order of the inserted item
465 // also to the bookmark-manager.
466 const KBookmark insertedBookmark
= insertedItem
->bookmark();
468 const PlacesItem
* previousItem
= placesItem(index
- 1);
469 KBookmark previousBookmark
;
471 previousBookmark
= previousItem
->bookmark();
474 m_bookmarkManager
->root().moveBookmark(insertedBookmark
, previousBookmark
);
477 if (index
== count() - 1) {
478 // The item has been appended as last item to the list. In this
479 // case assure that it is also appended after the hidden items and
480 // not before (like done otherwise).
481 m_bookmarkedItems
.append(0);
485 int bookmarkIndex
= 0;
486 while (bookmarkIndex
< m_bookmarkedItems
.count()) {
487 if (!m_bookmarkedItems
[bookmarkIndex
]) {
489 if (modelIndex
+ 1 == index
) {
495 m_bookmarkedItems
.insert(bookmarkIndex
, 0);
498 #ifdef PLACESITEMMODEL_DEBUG
499 kDebug() << "Inserted item" << index
;
504 void PlacesItemModel::onItemRemoved(int index
, KStandardItem
* removedItem
)
506 PlacesItem
* placesItem
= dynamic_cast<PlacesItem
*>(removedItem
);
508 const KBookmark bookmark
= placesItem
->bookmark();
509 m_bookmarkManager
->root().deleteBookmark(bookmark
);
512 const int boomarkIndex
= bookmarkIndex(index
);
513 Q_ASSERT(!m_bookmarkedItems
[boomarkIndex
]);
514 m_bookmarkedItems
.removeAt(boomarkIndex
);
516 #ifdef PLACESITEMMODEL_DEBUG
517 kDebug() << "Removed item" << index
;
522 void PlacesItemModel::onItemChanged(int index
, const QSet
<QByteArray
>& changedRoles
)
524 const PlacesItem
* changedItem
= placesItem(index
);
526 // Take care to apply the PlacesItemModel-order of the changed item
527 // also to the bookmark-manager.
528 const KBookmark insertedBookmark
= changedItem
->bookmark();
530 const PlacesItem
* previousItem
= placesItem(index
- 1);
531 KBookmark previousBookmark
;
533 previousBookmark
= previousItem
->bookmark();
536 m_bookmarkManager
->root().moveBookmark(insertedBookmark
, previousBookmark
);
539 if (changedRoles
.contains("isHidden")) {
540 if (!m_hiddenItemsShown
&& changedItem
->isHidden()) {
541 m_hiddenItemToRemove
= index
;
542 QTimer::singleShot(0, this, SLOT(hideItem()));
547 void PlacesItemModel::slotDeviceAdded(const QString
& udi
)
549 const Solid::Device
device(udi
);
551 if (!m_predicate
.matches(device
)) {
555 m_availableDevices
<< udi
;
556 const KBookmark bookmark
= PlacesItem::createDeviceBookmark(m_bookmarkManager
, udi
);
557 appendItem(new PlacesItem(bookmark
));
560 void PlacesItemModel::slotDeviceRemoved(const QString
& udi
)
562 if (!m_availableDevices
.contains(udi
)) {
566 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
567 PlacesItem
* item
= m_bookmarkedItems
[i
];
568 if (item
&& item
->udi() == udi
) {
569 m_bookmarkedItems
.removeAt(i
);
575 for (int i
= 0; i
< count(); ++i
) {
576 if (placesItem(i
)->udi() == udi
) {
583 void PlacesItemModel::slotStorageTeardownDone(Solid::ErrorType error
, const QVariant
& errorData
)
585 if (error
&& errorData
.isValid()) {
586 emit
errorMessage(errorData
.toString());
590 void PlacesItemModel::slotStorageSetupDone(Solid::ErrorType error
,
591 const QVariant
& errorData
,
596 const int index
= m_storageSetupInProgress
.take(sender());
597 const PlacesItem
* item
= placesItem(index
);
602 if (error
!= Solid::NoError
) {
603 if (errorData
.isValid()) {
604 emit
errorMessage(i18nc("@info", "An error occurred while accessing '%1', the system responded: %2",
606 errorData
.toString()));
608 emit
errorMessage(i18nc("@info", "An error occurred while accessing '%1'",
611 emit
storageSetupDone(index
, false);
613 emit
storageSetupDone(index
, true);
617 void PlacesItemModel::hideItem()
619 hideItem(m_hiddenItemToRemove
);
620 m_hiddenItemToRemove
= -1;
623 void PlacesItemModel::updateBookmarks()
625 // Verify whether new bookmarks have been added or existing
626 // bookmarks have been changed.
627 KBookmarkGroup root
= m_bookmarkManager
->root();
628 KBookmark newBookmark
= root
.first();
629 while (!newBookmark
.isNull()) {
630 if (acceptBookmark(newBookmark
, m_availableDevices
)) {
633 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
634 PlacesItem
* item
= m_bookmarkedItems
[i
];
636 item
= placesItem(modelIndex
);
640 const KBookmark oldBookmark
= item
->bookmark();
641 if (equalBookmarkIdentifiers(newBookmark
, oldBookmark
)) {
642 // The bookmark has been found in the model or as
643 // a hidden item. The content of the bookmark might
644 // have been changed, so an update is done.
646 if (newBookmark
.metaDataItem("UDI").isEmpty()) {
647 item
->setBookmark(newBookmark
);
648 item
->setText(i18nc("KFile System Bookmarks", newBookmark
.text().toUtf8().constData()));
655 const QString udi
= newBookmark
.metaDataItem("UDI");
659 * Only add a new places item, if the item text is not empty
660 * and if the device is available. Fixes the strange behaviour -
661 * add a places item without text in the Places section - when you
662 * remove a device (e.g. a usb stick) without unmounting.
664 if (udi
.isEmpty() || Solid::Device(udi
).isValid()) {
665 PlacesItem
* item
= new PlacesItem(newBookmark
);
666 if (item
->isHidden() && !m_hiddenItemsShown
) {
667 m_bookmarkedItems
.append(item
);
669 appendItemToGroup(item
);
675 newBookmark
= root
.next(newBookmark
);
678 // Remove items that are not part of the bookmark-manager anymore
680 for (int i
= m_bookmarkedItems
.count() - 1; i
>= 0; --i
) {
681 PlacesItem
* item
= m_bookmarkedItems
[i
];
682 const bool itemIsPartOfModel
= (item
== 0);
683 if (itemIsPartOfModel
) {
684 item
= placesItem(modelIndex
);
687 bool hasBeenRemoved
= true;
688 const KBookmark oldBookmark
= item
->bookmark();
689 KBookmark newBookmark
= root
.first();
690 while (!newBookmark
.isNull()) {
691 if (equalBookmarkIdentifiers(newBookmark
, oldBookmark
)) {
692 hasBeenRemoved
= false;
695 newBookmark
= root
.next(newBookmark
);
698 if (hasBeenRemoved
) {
699 if (m_bookmarkedItems
[i
]) {
700 delete m_bookmarkedItems
[i
];
701 m_bookmarkedItems
.removeAt(i
);
703 removeItem(modelIndex
);
708 if (itemIsPartOfModel
) {
714 void PlacesItemModel::saveBookmarks()
716 m_bookmarkManager
->emitChanged(m_bookmarkManager
->root());
719 void PlacesItemModel::loadBookmarks()
721 KBookmarkGroup root
= m_bookmarkManager
->root();
722 KBookmark bookmark
= root
.first();
723 QSet
<QString
> devices
= m_availableDevices
;
725 QSet
<QUrl
> missingSystemBookmarks
;
726 foreach (const SystemBookmarkData
& data
, m_systemBookmarks
) {
727 missingSystemBookmarks
.insert(data
.url
);
730 // The bookmarks might have a mixed order of places, devices and search-groups due
731 // to the compatibility with the KFilePlacesPanel. In Dolphin's places panel the
732 // items should always be collected in one group so the items are collected first
733 // in separate lists before inserting them.
734 QList
<PlacesItem
*> placesItems
;
735 QList
<PlacesItem
*> recentlySavedItems
;
736 QList
<PlacesItem
*> searchForItems
;
737 QList
<PlacesItem
*> devicesItems
;
739 while (!bookmark
.isNull()) {
740 if (acceptBookmark(bookmark
, devices
)) {
741 PlacesItem
* item
= new PlacesItem(bookmark
);
742 if (item
->groupType() == PlacesItem::DevicesType
) {
743 devices
.remove(item
->udi());
744 devicesItems
.append(item
);
746 const QUrl url
= bookmark
.url();
747 if (missingSystemBookmarks
.contains(url
)) {
748 missingSystemBookmarks
.remove(url
);
750 // Try to retranslate the text of system bookmarks to have translated
751 // items when changing the language. In case if the user has applied a custom
752 // text, the retranslation will fail and the users custom text is still used.
753 // It is important to use "KFile System Bookmarks" as context (see
754 // createSystemBookmarks()).
755 item
->setText(i18nc("KFile System Bookmarks", bookmark
.text().toUtf8().constData()));
756 item
->setSystemItem(true);
759 switch (item
->groupType()) {
760 case PlacesItem::PlacesType
: placesItems
.append(item
); break;
761 case PlacesItem::RecentlySavedType
: recentlySavedItems
.append(item
); break;
762 case PlacesItem::SearchForType
: searchForItems
.append(item
); break;
763 case PlacesItem::DevicesType
:
764 default: Q_ASSERT(false); break;
769 bookmark
= root
.next(bookmark
);
772 if (!missingSystemBookmarks
.isEmpty()) {
773 // The current bookmarks don't contain all system-bookmarks. Add the missing
775 foreach (const SystemBookmarkData
& data
, m_systemBookmarks
) {
776 if (missingSystemBookmarks
.contains(data
.url
)) {
777 PlacesItem
* item
= createSystemPlacesItem(data
);
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;
789 // Create items for devices that have not been stored as bookmark yet
790 foreach (const QString
& udi
, devices
) {
791 const KBookmark bookmark
= PlacesItem::createDeviceBookmark(m_bookmarkManager
, udi
);
792 devicesItems
.append(new PlacesItem(bookmark
));
795 QList
<PlacesItem
*> items
;
796 items
.append(placesItems
);
797 items
.append(recentlySavedItems
);
798 items
.append(searchForItems
);
799 items
.append(devicesItems
);
801 foreach (PlacesItem
* item
, items
) {
802 if (!m_hiddenItemsShown
&& item
->isHidden()) {
803 m_bookmarkedItems
.append(item
);
809 #ifdef PLACESITEMMODEL_DEBUG
810 kDebug() << "Loaded bookmarks";
815 bool PlacesItemModel::acceptBookmark(const KBookmark
& bookmark
,
816 const QSet
<QString
>& availableDevices
) const
818 const QString udi
= bookmark
.metaDataItem("UDI");
819 const QUrl url
= bookmark
.url();
820 const QString appName
= bookmark
.metaDataItem("OnlyInApp");
821 const bool deviceAvailable
= availableDevices
.contains(udi
);
823 const bool allowedHere
= (appName
.isEmpty()
824 || appName
== KAboutData::applicationData().componentName()
825 || appName
== KAboutData::applicationData().componentName() + AppNamePrefix
)
826 && (m_fileIndexingEnabled
|| (url
.scheme() != QLatin1String("timeline") &&
827 url
.scheme() != QLatin1String("search")));
829 return (udi
.isEmpty() && allowedHere
) || deviceAvailable
;
832 PlacesItem
* PlacesItemModel::createSystemPlacesItem(const SystemBookmarkData
& data
)
834 KBookmark bookmark
= PlacesItem::createBookmark(m_bookmarkManager
,
839 const QString protocol
= data
.url
.scheme();
840 if (protocol
== QLatin1String("timeline") || protocol
== QLatin1String("search")) {
841 // As long as the KFilePlacesView from kdelibs is available, the system-bookmarks
842 // for "Recently Saved" and "Search For" should be a setting available only
843 // in the Places Panel (see description of AppNamePrefix for more details).
844 const QString appName
= KAboutData::applicationData().componentName() + AppNamePrefix
;
845 bookmark
.setMetaDataItem("OnlyInApp", appName
);
848 PlacesItem
* item
= new PlacesItem(bookmark
);
849 item
->setSystemItem(true);
851 // Create default view-properties for all "Search For" and "Recently Saved" bookmarks
852 // in case if the user has not already created custom view-properties for a corresponding
854 const bool createDefaultViewProperties
= (item
->groupType() == PlacesItem::SearchForType
||
855 item
->groupType() == PlacesItem::RecentlySavedType
) &&
856 !GeneralSettings::self()->globalViewProps();
857 if (createDefaultViewProperties
) {
858 ViewProperties
props(convertedUrl(data
.url
));
859 if (!props
.exist()) {
860 const QString path
= data
.url
.path();
861 if (path
== QLatin1String("/documents")) {
862 props
.setViewMode(DolphinView::DetailsView
);
863 props
.setPreviewsShown(false);
864 props
.setVisibleRoles({"text", "path"});
865 } else if (path
== QLatin1String("/images")) {
866 props
.setViewMode(DolphinView::IconsView
);
867 props
.setPreviewsShown(true);
868 props
.setVisibleRoles({"text", "imageSize"});
869 } else if (path
== QLatin1String("/audio")) {
870 props
.setViewMode(DolphinView::DetailsView
);
871 props
.setPreviewsShown(false);
872 props
.setVisibleRoles({"text", "artist", "album"});
873 } else if (path
== QLatin1String("/videos")) {
874 props
.setViewMode(DolphinView::IconsView
);
875 props
.setPreviewsShown(true);
876 props
.setVisibleRoles({"text"});
877 } else if (data
.url
.scheme() == "timeline") {
878 props
.setViewMode(DolphinView::DetailsView
);
879 props
.setVisibleRoles({"text", "date"});
887 void PlacesItemModel::createSystemBookmarks()
889 Q_ASSERT(m_systemBookmarks
.isEmpty());
890 Q_ASSERT(m_systemBookmarksIndexes
.isEmpty());
892 // Note: The context of the I18N_NOOP2 must be "KFile System Bookmarks". The real
893 // i18nc call is done after reading the bookmark. The reason why the i18nc call is not
894 // done here is because otherwise switching the language would not result in retranslating the
896 m_systemBookmarks
.append(SystemBookmarkData(QUrl::fromLocalFile(KUser().homeDir()),
898 I18N_NOOP2("KFile System Bookmarks", "Home")));
899 m_systemBookmarks
.append(SystemBookmarkData(QUrl("remote:/"),
901 I18N_NOOP2("KFile System Bookmarks", "Network")));
902 m_systemBookmarks
.append(SystemBookmarkData(QUrl::fromLocalFile("/"),
904 I18N_NOOP2("KFile System Bookmarks", "Root")));
905 m_systemBookmarks
.append(SystemBookmarkData(QUrl("trash:/"),
907 I18N_NOOP2("KFile System Bookmarks", "Trash")));
909 if (m_fileIndexingEnabled
) {
910 m_systemBookmarks
.append(SystemBookmarkData(QUrl("timeline:/today"),
912 I18N_NOOP2("KFile System Bookmarks", "Today")));
913 m_systemBookmarks
.append(SystemBookmarkData(QUrl("timeline:/yesterday"),
915 I18N_NOOP2("KFile System Bookmarks", "Yesterday")));
916 m_systemBookmarks
.append(SystemBookmarkData(QUrl("timeline:/thismonth"),
917 "view-calendar-month",
918 I18N_NOOP2("KFile System Bookmarks", "This Month")));
919 m_systemBookmarks
.append(SystemBookmarkData(QUrl("timeline:/lastmonth"),
920 "view-calendar-month",
921 I18N_NOOP2("KFile System Bookmarks", "Last Month")));
922 m_systemBookmarks
.append(SystemBookmarkData(QUrl("search:/documents"),
924 I18N_NOOP2("KFile System Bookmarks", "Documents")));
925 m_systemBookmarks
.append(SystemBookmarkData(QUrl("search:/images"),
927 I18N_NOOP2("KFile System Bookmarks", "Images")));
928 m_systemBookmarks
.append(SystemBookmarkData(QUrl("search:/audio"),
930 I18N_NOOP2("KFile System Bookmarks", "Audio Files")));
931 m_systemBookmarks
.append(SystemBookmarkData(QUrl("search:/videos"),
933 I18N_NOOP2("KFile System Bookmarks", "Videos")));
936 for (int i
= 0; i
< m_systemBookmarks
.count(); ++i
) {
937 m_systemBookmarksIndexes
.insert(m_systemBookmarks
[i
].url
, i
);
941 void PlacesItemModel::clear() {
942 m_bookmarkedItems
.clear();
943 KStandardItemModel::clear();
946 void PlacesItemModel::initializeAvailableDevices()
948 QString
predicate("[[[[ StorageVolume.ignored == false AND [ StorageVolume.usage == 'FileSystem' OR StorageVolume.usage == 'Encrypted' ]]"
950 "[ IS StorageAccess AND StorageDrive.driveType == 'Floppy' ]]"
952 "OpticalDisc.availableContent & 'Audio' ]"
954 "StorageAccess.ignored == false ]");
957 if (KProtocolInfo::isKnownProtocol("mtp")) {
958 predicate
.prepend("[");
959 predicate
.append(" OR PortableMediaPlayer.supportedProtocols == 'mtp']");
962 m_predicate
= Solid::Predicate::fromString(predicate
);
963 Q_ASSERT(m_predicate
.isValid());
965 Solid::DeviceNotifier
* notifier
= Solid::DeviceNotifier::instance();
966 connect(notifier
, &Solid::DeviceNotifier::deviceAdded
, this, &PlacesItemModel::slotDeviceAdded
);
967 connect(notifier
, &Solid::DeviceNotifier::deviceRemoved
, this, &PlacesItemModel::slotDeviceRemoved
);
969 const QList
<Solid::Device
>& deviceList
= Solid::Device::listFromQuery(m_predicate
);
970 foreach (const Solid::Device
& device
, deviceList
) {
971 m_availableDevices
<< device
.udi();
975 int PlacesItemModel::bookmarkIndex(int index
) const
977 int bookmarkIndex
= 0;
979 while (bookmarkIndex
< m_bookmarkedItems
.count()) {
980 if (!m_bookmarkedItems
[bookmarkIndex
]) {
981 if (modelIndex
== index
) {
989 return bookmarkIndex
>= m_bookmarkedItems
.count() ? -1 : bookmarkIndex
;
992 void PlacesItemModel::hideItem(int index
)
994 PlacesItem
* shownItem
= placesItem(index
);
999 shownItem
->setHidden(true);
1000 if (m_hiddenItemsShown
) {
1001 // Removing items from the model is not allowed if all hidden
1002 // items should be shown.
1006 const int newIndex
= bookmarkIndex(index
);
1007 if (newIndex
>= 0) {
1008 const KBookmark hiddenBookmark
= shownItem
->bookmark();
1009 PlacesItem
* hiddenItem
= new PlacesItem(hiddenBookmark
);
1011 const PlacesItem
* previousItem
= placesItem(index
- 1);
1012 KBookmark previousBookmark
;
1014 previousBookmark
= previousItem
->bookmark();
1017 const bool updateBookmark
= (m_bookmarkManager
->root().indexOf(hiddenBookmark
) >= 0);
1020 if (updateBookmark
) {
1021 // removeItem() also removed the bookmark from m_bookmarkManager in
1022 // PlacesItemModel::onItemRemoved(). However for hidden items the
1023 // bookmark should still be remembered, so readd it again:
1024 m_bookmarkManager
->root().addBookmark(hiddenBookmark
);
1025 m_bookmarkManager
->root().moveBookmark(hiddenBookmark
, previousBookmark
);
1028 m_bookmarkedItems
.insert(newIndex
, hiddenItem
);
1032 QString
PlacesItemModel::internalMimeType() const
1034 return "application/x-dolphinplacesmodel-" +
1035 QString::number((qptrdiff
)this);
1038 int PlacesItemModel::groupedDropIndex(int index
, const PlacesItem
* item
) const
1042 int dropIndex
= index
;
1043 const PlacesItem::GroupType type
= item
->groupType();
1045 const int itemCount
= count();
1047 dropIndex
= itemCount
;
1050 // Search nearest previous item with the same group
1051 int previousIndex
= -1;
1052 for (int i
= dropIndex
- 1; i
>= 0; --i
) {
1053 if (placesItem(i
)->groupType() == type
) {
1059 // Search nearest next item with the same group
1061 for (int i
= dropIndex
; i
< count(); ++i
) {
1062 if (placesItem(i
)->groupType() == type
) {
1068 // Adjust the drop-index to be inserted to the
1069 // nearest item with the same group.
1070 if (previousIndex
>= 0 && nextIndex
>= 0) {
1071 dropIndex
= (dropIndex
- previousIndex
< nextIndex
- dropIndex
) ?
1072 previousIndex
+ 1 : nextIndex
;
1073 } else if (previousIndex
>= 0) {
1074 dropIndex
= previousIndex
+ 1;
1075 } else if (nextIndex
>= 0) {
1076 dropIndex
= nextIndex
;
1082 bool PlacesItemModel::equalBookmarkIdentifiers(const KBookmark
& b1
, const KBookmark
& b2
)
1084 const QString udi1
= b1
.metaDataItem("UDI");
1085 const QString udi2
= b2
.metaDataItem("UDI");
1086 if (!udi1
.isEmpty() && !udi2
.isEmpty()) {
1087 return udi1
== udi2
;
1089 return b1
.metaDataItem("ID") == b2
.metaDataItem("ID");
1093 QUrl
PlacesItemModel::createTimelineUrl(const QUrl
& url
)
1095 // TODO: Clarify with the Baloo-team whether it makes sense
1096 // provide default-timeline-URLs like 'yesterday', 'this month'
1097 // and 'last month'.
1100 const QString path
= url
.toDisplayString(QUrl::PreferLocalFile
);
1101 if (path
.endsWith(QLatin1String("yesterday"))) {
1102 const QDate date
= QDate::currentDate().addDays(-1);
1103 const int year
= date
.year();
1104 const int month
= date
.month();
1105 const int day
= date
.day();
1106 timelineUrl
= "timeline:/" + timelineDateString(year
, month
) +
1107 '/' + timelineDateString(year
, month
, day
);
1108 } else if (path
.endsWith(QLatin1String("thismonth"))) {
1109 const QDate date
= QDate::currentDate();
1110 timelineUrl
= "timeline:/" + timelineDateString(date
.year(), date
.month());
1111 } else if (path
.endsWith(QLatin1String("lastmonth"))) {
1112 const QDate date
= QDate::currentDate().addMonths(-1);
1113 timelineUrl
= "timeline:/" + timelineDateString(date
.year(), date
.month());
1115 Q_ASSERT(path
.endsWith(QLatin1String("today")));
1122 QString
PlacesItemModel::timelineDateString(int year
, int month
, int day
)
1124 QString date
= QString::number(year
) + '-';
1128 date
+= QString::number(month
);
1135 date
+= QString::number(day
);
1141 QUrl
PlacesItemModel::createSearchUrl(const QUrl
& url
)
1146 const QString path
= url
.toDisplayString(QUrl::PreferLocalFile
);
1147 if (path
.endsWith(QLatin1String("documents"))) {
1148 searchUrl
= searchUrlForType("Document");
1149 } else if (path
.endsWith(QLatin1String("images"))) {
1150 searchUrl
= searchUrlForType("Image");
1151 } else if (path
.endsWith(QLatin1String("audio"))) {
1152 searchUrl
= searchUrlForType("Audio");
1153 } else if (path
.endsWith(QLatin1String("videos"))) {
1154 searchUrl
= searchUrlForType("Video");
1166 QUrl
PlacesItemModel::searchUrlForType(const QString
& type
)
1169 query
.addType("File");
1170 query
.addType(type
);
1172 return query
.toSearchUrl();
1176 #ifdef PLACESITEMMODEL_DEBUG
1177 void PlacesItemModel::showModelState()
1179 kDebug() << "=================================";
1180 kDebug() << "Model:";
1181 kDebug() << "hidden-index model-index text";
1183 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
1184 if (m_bookmarkedItems
[i
]) {
1185 kDebug() << i
<< "(Hidden) " << " " << m_bookmarkedItems
[i
]->dataValue("text").toString();
1187 if (item(modelIndex
)) {
1188 kDebug() << i
<< " " << modelIndex
<< " " << item(modelIndex
)->dataValue("text").toString();
1190 kDebug() << i
<< " " << modelIndex
<< " " << "(not available yet)";
1197 kDebug() << "Bookmarks:";
1199 int bookmarkIndex
= 0;
1200 KBookmarkGroup root
= m_bookmarkManager
->root();
1201 KBookmark bookmark
= root
.first();
1202 while (!bookmark
.isNull()) {
1203 const QString udi
= bookmark
.metaDataItem("UDI");
1204 const QString text
= udi
.isEmpty() ? bookmark
.text() : udi
;
1205 if (bookmark
.metaDataItem("IsHidden") == QLatin1String("true")) {
1206 kDebug() << bookmarkIndex
<< "(Hidden)" << text
;
1208 kDebug() << bookmarkIndex
<< " " << text
;
1211 bookmark
= root
.next(bookmark
);