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_saveBookmarksTimer(0),
84 m_updateBookmarksTimer(0),
85 m_storageSetupInProgress()
88 Baloo::IndexerConfig config
;
89 m_fileIndexingEnabled
= config
.fileIndexingEnabled();
91 const QString file
= QStandardPaths::locate(QStandardPaths::GenericDataLocation
, "kfileplaces/bookmarks.xml");
92 m_bookmarkManager
= KBookmarkManager::managerForFile(file
, "kfilePlaces");
94 createSystemBookmarks();
95 initializeAvailableDevices();
98 const int syncBookmarksTimeout
= 100;
100 m_saveBookmarksTimer
= new QTimer(this);
101 m_saveBookmarksTimer
->setInterval(syncBookmarksTimeout
);
102 m_saveBookmarksTimer
->setSingleShot(true);
103 connect(m_saveBookmarksTimer
, &QTimer::timeout
, this, &PlacesItemModel::saveBookmarks
);
105 m_updateBookmarksTimer
= new QTimer(this);
106 m_updateBookmarksTimer
->setInterval(syncBookmarksTimeout
);
107 m_updateBookmarksTimer
->setSingleShot(true);
108 connect(m_updateBookmarksTimer
, &QTimer::timeout
, this, &PlacesItemModel::updateBookmarks
);
110 connect(m_bookmarkManager
, &KBookmarkManager::changed
,
111 m_updateBookmarksTimer
, static_cast<void(QTimer::*)()>(&QTimer::start
));
112 connect(m_bookmarkManager
, &KBookmarkManager::bookmarksChanged
,
113 m_updateBookmarksTimer
, static_cast<void(QTimer::*)()>(&QTimer::start
));
116 PlacesItemModel::~PlacesItemModel()
119 qDeleteAll(m_bookmarkedItems
);
120 m_bookmarkedItems
.clear();
123 PlacesItem
* PlacesItemModel::createPlacesItem(const QString
& text
,
125 const QString
& iconName
)
127 const KBookmark bookmark
= PlacesItem::createBookmark(m_bookmarkManager
, text
, url
, iconName
);
128 return new PlacesItem(bookmark
);
131 PlacesItem
* PlacesItemModel::placesItem(int index
) const
133 return dynamic_cast<PlacesItem
*>(item(index
));
136 int PlacesItemModel::hiddenCount() const
139 int hiddenItemCount
= 0;
140 foreach (const PlacesItem
* item
, m_bookmarkedItems
) {
144 if (placesItem(modelIndex
)->isHidden()) {
151 return hiddenItemCount
;
154 void PlacesItemModel::setHiddenItemsShown(bool show
)
156 if (m_hiddenItemsShown
== show
) {
160 m_hiddenItemsShown
= show
;
163 // Move all items that are part of m_bookmarkedItems to the model.
164 QList
<PlacesItem
*> itemsToInsert
;
165 QList
<int> insertPos
;
167 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
168 if (m_bookmarkedItems
[i
]) {
169 itemsToInsert
.append(m_bookmarkedItems
[i
]);
170 m_bookmarkedItems
[i
] = 0;
171 insertPos
.append(modelIndex
);
176 // Inserting the items will automatically insert an item
177 // to m_bookmarkedItems in PlacesItemModel::onItemsInserted().
178 // The items are temporary saved in itemsToInsert, so
179 // m_bookmarkedItems can be shrinked now.
180 m_bookmarkedItems
.erase(m_bookmarkedItems
.begin(),
181 m_bookmarkedItems
.begin() + itemsToInsert
.count());
183 for (int i
= 0; i
< itemsToInsert
.count(); ++i
) {
184 insertItem(insertPos
[i
], itemsToInsert
[i
]);
187 Q_ASSERT(m_bookmarkedItems
.count() == count());
189 // Move all items of the model, where the "isHidden" property is true, to
190 // m_bookmarkedItems.
191 Q_ASSERT(m_bookmarkedItems
.count() == count());
192 for (int i
= count() - 1; i
>= 0; --i
) {
193 if (placesItem(i
)->isHidden()) {
199 #ifdef PLACESITEMMODEL_DEBUG
200 kDebug() << "Changed visibility of hidden items";
205 bool PlacesItemModel::hiddenItemsShown() const
207 return m_hiddenItemsShown
;
210 int PlacesItemModel::closestItem(const QUrl
& url
) const
215 for (int i
= 0; i
< count(); ++i
) {
216 const QUrl itemUrl
= placesItem(i
)->url();
217 if (url
== itemUrl
) {
218 // We can't find a closer one, so stop here.
221 } else if (itemUrl
.isParentOf(url
)) {
222 const int length
= itemUrl
.path().length();
223 if (length
> maxLength
) {
233 void PlacesItemModel::appendItemToGroup(PlacesItem
* item
)
240 while (i
< count() && placesItem(i
)->group() != item
->group()) {
244 bool inserted
= false;
245 while (!inserted
&& i
< count()) {
246 if (placesItem(i
)->group() != item
->group()) {
259 QAction
* PlacesItemModel::ejectAction(int index
) const
261 const PlacesItem
* item
= placesItem(index
);
262 if (item
&& item
->device().is
<Solid::OpticalDisc
>()) {
263 return new QAction(QIcon::fromTheme("media-eject"), i18nc("@item", "Eject '%1'", item
->text()), 0);
269 QAction
* PlacesItemModel::teardownAction(int index
) const
271 const PlacesItem
* item
= placesItem(index
);
276 Solid::Device device
= item
->device();
277 const bool providesTearDown
= device
.is
<Solid::StorageAccess
>() &&
278 device
.as
<Solid::StorageAccess
>()->isAccessible();
279 if (!providesTearDown
) {
283 Solid::StorageDrive
* drive
= device
.as
<Solid::StorageDrive
>();
285 drive
= device
.parent().as
<Solid::StorageDrive
>();
288 bool hotPluggable
= false;
289 bool removable
= false;
291 hotPluggable
= drive
->isHotpluggable();
292 removable
= drive
->isRemovable();
297 const QString label
= item
->text();
298 if (device
.is
<Solid::OpticalDisc
>()) {
299 text
= i18nc("@item", "Release '%1'", label
);
300 } else if (removable
|| hotPluggable
) {
301 text
= i18nc("@item", "Safely Remove '%1'", label
);
302 iconName
= "media-eject";
304 text
= i18nc("@item", "Unmount '%1'", label
);
305 iconName
= "media-eject";
308 if (iconName
.isEmpty()) {
309 return new QAction(text
, 0);
312 return new QAction(QIcon::fromTheme(iconName
), text
, 0);
315 void PlacesItemModel::requestEject(int index
)
317 const PlacesItem
* item
= placesItem(index
);
319 Solid::OpticalDrive
* drive
= item
->device().parent().as
<Solid::OpticalDrive
>();
321 connect(drive
, &Solid::OpticalDrive::ejectDone
,
322 this, &PlacesItemModel::slotStorageTeardownDone
);
325 const QString label
= item
->text();
326 const QString message
= i18nc("@info", "The device '%1' is not a disk and cannot be ejected.", label
);
327 emit
errorMessage(message
);
332 void PlacesItemModel::requestTeardown(int index
)
334 const PlacesItem
* item
= placesItem(index
);
336 Solid::StorageAccess
* access
= item
->device().as
<Solid::StorageAccess
>();
338 connect(access
, &Solid::StorageAccess::teardownDone
,
339 this, &PlacesItemModel::slotStorageTeardownDone
);
345 bool PlacesItemModel::storageSetupNeeded(int index
) const
347 const PlacesItem
* item
= placesItem(index
);
348 return item
? item
->storageSetupNeeded() : false;
351 void PlacesItemModel::requestStorageSetup(int index
)
353 const PlacesItem
* item
= placesItem(index
);
358 Solid::Device device
= item
->device();
359 const bool setup
= device
.is
<Solid::StorageAccess
>()
360 && !m_storageSetupInProgress
.contains(device
.as
<Solid::StorageAccess
>())
361 && !device
.as
<Solid::StorageAccess
>()->isAccessible();
363 Solid::StorageAccess
* access
= device
.as
<Solid::StorageAccess
>();
365 m_storageSetupInProgress
[access
] = index
;
367 connect(access
, &Solid::StorageAccess::setupDone
,
368 this, &PlacesItemModel::slotStorageSetupDone
);
374 QMimeData
* PlacesItemModel::createMimeData(const KItemSet
& indexes
) const
379 QDataStream
stream(&itemData
, QIODevice::WriteOnly
);
381 foreach (int index
, indexes
) {
382 const QUrl itemUrl
= placesItem(index
)->url();
383 if (itemUrl
.isValid()) {
389 QMimeData
* mimeData
= new QMimeData();
390 if (!urls
.isEmpty()) {
391 mimeData
->setUrls(urls
);
393 mimeData
->setData(internalMimeType(), itemData
);
398 bool PlacesItemModel::supportsDropping(int index
) const
400 return index
>= 0 && index
< count();
403 void PlacesItemModel::dropMimeDataBefore(int index
, const QMimeData
* mimeData
)
405 if (mimeData
->hasFormat(internalMimeType())) {
406 // The item has been moved inside the view
407 QByteArray itemData
= mimeData
->data(internalMimeType());
408 QDataStream
stream(&itemData
, QIODevice::ReadOnly
);
411 if (oldIndex
== index
|| oldIndex
== index
- 1) {
412 // No moving has been done
416 PlacesItem
* oldItem
= placesItem(oldIndex
);
421 PlacesItem
* newItem
= new PlacesItem(oldItem
->bookmark());
422 removeItem(oldIndex
);
424 if (oldIndex
< index
) {
428 const int dropIndex
= groupedDropIndex(index
, newItem
);
429 insertItem(dropIndex
, newItem
);
430 } else if (mimeData
->hasFormat("text/uri-list")) {
431 // One or more items must be added to the model
432 const QList
<QUrl
> urls
= KUrlMimeData::urlsFromMimeData(mimeData
);
433 for (int i
= urls
.count() - 1; i
>= 0; --i
) {
434 const QUrl
& url
= urls
[i
];
436 QString text
= url
.fileName();
437 if (text
.isEmpty()) {
441 if ((url
.isLocalFile() && !QFileInfo(url
.toLocalFile()).isDir())
442 || url
.scheme() == "trash") {
443 // Only directories outside the trash are allowed
447 PlacesItem
* newItem
= createPlacesItem(text
, url
);
448 const int dropIndex
= groupedDropIndex(index
, newItem
);
449 insertItem(dropIndex
, newItem
);
454 QUrl
PlacesItemModel::convertedUrl(const QUrl
& url
)
457 if (url
.scheme() == QLatin1String("timeline")) {
458 newUrl
= createTimelineUrl(url
);
459 } else if (url
.scheme() == QLatin1String("search")) {
460 newUrl
= createSearchUrl(url
);
466 void PlacesItemModel::onItemInserted(int index
)
468 const PlacesItem
* insertedItem
= placesItem(index
);
470 // Take care to apply the PlacesItemModel-order of the inserted item
471 // also to the bookmark-manager.
472 const KBookmark insertedBookmark
= insertedItem
->bookmark();
474 const PlacesItem
* previousItem
= placesItem(index
- 1);
475 KBookmark previousBookmark
;
477 previousBookmark
= previousItem
->bookmark();
480 m_bookmarkManager
->root().moveBookmark(insertedBookmark
, previousBookmark
);
483 if (index
== count() - 1) {
484 // The item has been appended as last item to the list. In this
485 // case assure that it is also appended after the hidden items and
486 // not before (like done otherwise).
487 m_bookmarkedItems
.append(0);
491 int bookmarkIndex
= 0;
492 while (bookmarkIndex
< m_bookmarkedItems
.count()) {
493 if (!m_bookmarkedItems
[bookmarkIndex
]) {
495 if (modelIndex
+ 1 == index
) {
501 m_bookmarkedItems
.insert(bookmarkIndex
, 0);
504 triggerBookmarksSaving();
506 #ifdef PLACESITEMMODEL_DEBUG
507 kDebug() << "Inserted item" << index
;
512 void PlacesItemModel::onItemRemoved(int index
, KStandardItem
* removedItem
)
514 PlacesItem
* placesItem
= dynamic_cast<PlacesItem
*>(removedItem
);
516 const KBookmark bookmark
= placesItem
->bookmark();
517 m_bookmarkManager
->root().deleteBookmark(bookmark
);
520 const int boomarkIndex
= bookmarkIndex(index
);
521 Q_ASSERT(!m_bookmarkedItems
[boomarkIndex
]);
522 m_bookmarkedItems
.removeAt(boomarkIndex
);
524 triggerBookmarksSaving();
526 #ifdef PLACESITEMMODEL_DEBUG
527 kDebug() << "Removed item" << index
;
532 void PlacesItemModel::onItemChanged(int index
, const QSet
<QByteArray
>& changedRoles
)
534 const PlacesItem
* changedItem
= placesItem(index
);
536 // Take care to apply the PlacesItemModel-order of the changed item
537 // also to the bookmark-manager.
538 const KBookmark insertedBookmark
= changedItem
->bookmark();
540 const PlacesItem
* previousItem
= placesItem(index
- 1);
541 KBookmark previousBookmark
;
543 previousBookmark
= previousItem
->bookmark();
546 m_bookmarkManager
->root().moveBookmark(insertedBookmark
, previousBookmark
);
549 if (changedRoles
.contains("isHidden")) {
550 if (!m_hiddenItemsShown
&& changedItem
->isHidden()) {
551 m_hiddenItemToRemove
= index
;
552 QTimer::singleShot(0, this, SLOT(hideItem()));
556 triggerBookmarksSaving();
559 void PlacesItemModel::slotDeviceAdded(const QString
& udi
)
561 const Solid::Device
device(udi
);
563 if (!m_predicate
.matches(device
)) {
567 m_availableDevices
<< udi
;
568 const KBookmark bookmark
= PlacesItem::createDeviceBookmark(m_bookmarkManager
, udi
);
569 appendItem(new PlacesItem(bookmark
));
572 void PlacesItemModel::slotDeviceRemoved(const QString
& udi
)
574 if (!m_availableDevices
.contains(udi
)) {
578 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
579 PlacesItem
* item
= m_bookmarkedItems
[i
];
580 if (item
&& item
->udi() == udi
) {
581 m_bookmarkedItems
.removeAt(i
);
587 for (int i
= 0; i
< count(); ++i
) {
588 if (placesItem(i
)->udi() == udi
) {
595 void PlacesItemModel::slotStorageTeardownDone(Solid::ErrorType error
, const QVariant
& errorData
)
597 if (error
&& errorData
.isValid()) {
598 emit
errorMessage(errorData
.toString());
602 void PlacesItemModel::slotStorageSetupDone(Solid::ErrorType error
,
603 const QVariant
& errorData
,
608 const int index
= m_storageSetupInProgress
.take(sender());
609 const PlacesItem
* item
= placesItem(index
);
614 if (error
!= Solid::NoError
) {
615 if (errorData
.isValid()) {
616 emit
errorMessage(i18nc("@info", "An error occurred while accessing '%1', the system responded: %2",
618 errorData
.toString()));
620 emit
errorMessage(i18nc("@info", "An error occurred while accessing '%1'",
623 emit
storageSetupDone(index
, false);
625 emit
storageSetupDone(index
, true);
629 void PlacesItemModel::hideItem()
631 hideItem(m_hiddenItemToRemove
);
632 m_hiddenItemToRemove
= -1;
635 void PlacesItemModel::updateBookmarks()
637 // Verify whether new bookmarks have been added or existing
638 // bookmarks have been changed.
639 KBookmarkGroup root
= m_bookmarkManager
->root();
640 KBookmark newBookmark
= root
.first();
641 while (!newBookmark
.isNull()) {
642 if (acceptBookmark(newBookmark
, m_availableDevices
)) {
645 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
646 PlacesItem
* item
= m_bookmarkedItems
[i
];
648 item
= placesItem(modelIndex
);
652 const KBookmark oldBookmark
= item
->bookmark();
653 if (equalBookmarkIdentifiers(newBookmark
, oldBookmark
)) {
654 // The bookmark has been found in the model or as
655 // a hidden item. The content of the bookmark might
656 // have been changed, so an update is done.
658 if (newBookmark
.metaDataItem("UDI").isEmpty()) {
659 item
->setBookmark(newBookmark
);
660 item
->setText(i18nc("KFile System Bookmarks", newBookmark
.text().toUtf8().constData()));
667 const QString udi
= newBookmark
.metaDataItem("UDI");
671 * Only add a new places item, if the item text is not empty
672 * and if the device is available. Fixes the strange behaviour -
673 * add a places item without text in the Places section - when you
674 * remove a device (e.g. a usb stick) without unmounting.
676 if (udi
.isEmpty() || Solid::Device(udi
).isValid()) {
677 PlacesItem
* item
= new PlacesItem(newBookmark
);
678 if (item
->isHidden() && !m_hiddenItemsShown
) {
679 m_bookmarkedItems
.append(item
);
681 appendItemToGroup(item
);
687 newBookmark
= root
.next(newBookmark
);
690 // Remove items that are not part of the bookmark-manager anymore
692 for (int i
= m_bookmarkedItems
.count() - 1; i
>= 0; --i
) {
693 PlacesItem
* item
= m_bookmarkedItems
[i
];
694 const bool itemIsPartOfModel
= (item
== 0);
695 if (itemIsPartOfModel
) {
696 item
= placesItem(modelIndex
);
699 bool hasBeenRemoved
= true;
700 const KBookmark oldBookmark
= item
->bookmark();
701 KBookmark newBookmark
= root
.first();
702 while (!newBookmark
.isNull()) {
703 if (equalBookmarkIdentifiers(newBookmark
, oldBookmark
)) {
704 hasBeenRemoved
= false;
707 newBookmark
= root
.next(newBookmark
);
710 if (hasBeenRemoved
) {
711 if (m_bookmarkedItems
[i
]) {
712 delete m_bookmarkedItems
[i
];
713 m_bookmarkedItems
.removeAt(i
);
715 removeItem(modelIndex
);
720 if (itemIsPartOfModel
) {
726 void PlacesItemModel::saveBookmarks()
728 m_bookmarkManager
->emitChanged(m_bookmarkManager
->root());
731 void PlacesItemModel::loadBookmarks()
733 KBookmarkGroup root
= m_bookmarkManager
->root();
734 KBookmark bookmark
= root
.first();
735 QSet
<QString
> devices
= m_availableDevices
;
737 QSet
<QUrl
> missingSystemBookmarks
;
738 foreach (const SystemBookmarkData
& data
, m_systemBookmarks
) {
739 missingSystemBookmarks
.insert(data
.url
);
742 // The bookmarks might have a mixed order of places, devices and search-groups due
743 // to the compatibility with the KFilePlacesPanel. In Dolphin's places panel the
744 // items should always be collected in one group so the items are collected first
745 // in separate lists before inserting them.
746 QList
<PlacesItem
*> placesItems
;
747 QList
<PlacesItem
*> recentlySavedItems
;
748 QList
<PlacesItem
*> searchForItems
;
749 QList
<PlacesItem
*> devicesItems
;
751 while (!bookmark
.isNull()) {
752 if (acceptBookmark(bookmark
, devices
)) {
753 PlacesItem
* item
= new PlacesItem(bookmark
);
754 if (item
->groupType() == PlacesItem::DevicesType
) {
755 devices
.remove(item
->udi());
756 devicesItems
.append(item
);
758 const QUrl url
= bookmark
.url();
759 if (missingSystemBookmarks
.contains(url
)) {
760 missingSystemBookmarks
.remove(url
);
762 // Try to retranslate the text of system bookmarks to have translated
763 // items when changing the language. In case if the user has applied a custom
764 // text, the retranslation will fail and the users custom text is still used.
765 // It is important to use "KFile System Bookmarks" as context (see
766 // createSystemBookmarks()).
767 item
->setText(i18nc("KFile System Bookmarks", bookmark
.text().toUtf8().constData()));
768 item
->setSystemItem(true);
771 switch (item
->groupType()) {
772 case PlacesItem::PlacesType
: placesItems
.append(item
); break;
773 case PlacesItem::RecentlySavedType
: recentlySavedItems
.append(item
); break;
774 case PlacesItem::SearchForType
: searchForItems
.append(item
); break;
775 case PlacesItem::DevicesType
:
776 default: Q_ASSERT(false); break;
781 bookmark
= root
.next(bookmark
);
784 if (!missingSystemBookmarks
.isEmpty()) {
785 // The current bookmarks don't contain all system-bookmarks. Add the missing
787 foreach (const SystemBookmarkData
& data
, m_systemBookmarks
) {
788 if (missingSystemBookmarks
.contains(data
.url
)) {
789 PlacesItem
* item
= createSystemPlacesItem(data
);
790 switch (item
->groupType()) {
791 case PlacesItem::PlacesType
: placesItems
.append(item
); break;
792 case PlacesItem::RecentlySavedType
: recentlySavedItems
.append(item
); break;
793 case PlacesItem::SearchForType
: searchForItems
.append(item
); break;
794 case PlacesItem::DevicesType
:
795 default: Q_ASSERT(false); break;
801 // Create items for devices that have not been stored as bookmark yet
802 foreach (const QString
& udi
, devices
) {
803 const KBookmark bookmark
= PlacesItem::createDeviceBookmark(m_bookmarkManager
, udi
);
804 devicesItems
.append(new PlacesItem(bookmark
));
807 QList
<PlacesItem
*> items
;
808 items
.append(placesItems
);
809 items
.append(recentlySavedItems
);
810 items
.append(searchForItems
);
811 items
.append(devicesItems
);
813 foreach (PlacesItem
* item
, items
) {
814 if (!m_hiddenItemsShown
&& item
->isHidden()) {
815 m_bookmarkedItems
.append(item
);
821 #ifdef PLACESITEMMODEL_DEBUG
822 kDebug() << "Loaded bookmarks";
827 bool PlacesItemModel::acceptBookmark(const KBookmark
& bookmark
,
828 const QSet
<QString
>& availableDevices
) const
830 const QString udi
= bookmark
.metaDataItem("UDI");
831 const QUrl url
= bookmark
.url();
832 const QString appName
= bookmark
.metaDataItem("OnlyInApp");
833 const bool deviceAvailable
= availableDevices
.contains(udi
);
835 const bool allowedHere
= (appName
.isEmpty()
836 || appName
== KGlobal::mainComponent().componentName()
837 || appName
== KGlobal::mainComponent().componentName() + AppNamePrefix
)
838 && (m_fileIndexingEnabled
|| (url
.scheme() != QLatin1String("timeline") &&
839 url
.scheme() != QLatin1String("search")));
841 return (udi
.isEmpty() && allowedHere
) || deviceAvailable
;
844 PlacesItem
* PlacesItemModel::createSystemPlacesItem(const SystemBookmarkData
& data
)
846 KBookmark bookmark
= PlacesItem::createBookmark(m_bookmarkManager
,
851 const QString protocol
= data
.url
.scheme();
852 if (protocol
== QLatin1String("timeline") || protocol
== QLatin1String("search")) {
853 // As long as the KFilePlacesView from kdelibs is available, the system-bookmarks
854 // for "Recently Saved" and "Search For" should be a setting available only
855 // in the Places Panel (see description of AppNamePrefix for more details).
856 const QString appName
= KGlobal::mainComponent().componentName() + AppNamePrefix
;
857 bookmark
.setMetaDataItem("OnlyInApp", appName
);
860 PlacesItem
* item
= new PlacesItem(bookmark
);
861 item
->setSystemItem(true);
863 // Create default view-properties for all "Search For" and "Recently Saved" bookmarks
864 // in case if the user has not already created custom view-properties for a corresponding
866 const bool createDefaultViewProperties
= (item
->groupType() == PlacesItem::SearchForType
||
867 item
->groupType() == PlacesItem::RecentlySavedType
) &&
868 !GeneralSettings::self()->globalViewProps();
869 if (createDefaultViewProperties
) {
870 ViewProperties
props(convertedUrl(data
.url
));
871 if (!props
.exist()) {
872 const QString path
= data
.url
.path();
873 if (path
== QLatin1String("/documents")) {
874 props
.setViewMode(DolphinView::DetailsView
);
875 props
.setPreviewsShown(false);
876 props
.setVisibleRoles({"text", "path"});
877 } else if (path
== QLatin1String("/images")) {
878 props
.setViewMode(DolphinView::IconsView
);
879 props
.setPreviewsShown(true);
880 props
.setVisibleRoles({"text", "imageSize"});
881 } else if (path
== QLatin1String("/audio")) {
882 props
.setViewMode(DolphinView::DetailsView
);
883 props
.setPreviewsShown(false);
884 props
.setVisibleRoles({"text", "artist", "album"});
885 } else if (path
== QLatin1String("/videos")) {
886 props
.setViewMode(DolphinView::IconsView
);
887 props
.setPreviewsShown(true);
888 props
.setVisibleRoles({"text"});
889 } else if (data
.url
.scheme() == "timeline") {
890 props
.setViewMode(DolphinView::DetailsView
);
891 props
.setVisibleRoles({"text", "date"});
899 void PlacesItemModel::createSystemBookmarks()
901 Q_ASSERT(m_systemBookmarks
.isEmpty());
902 Q_ASSERT(m_systemBookmarksIndexes
.isEmpty());
904 // Note: The context of the I18N_NOOP2 must be "KFile System Bookmarks". The real
905 // i18nc call is done after reading the bookmark. The reason why the i18nc call is not
906 // done here is because otherwise switching the language would not result in retranslating the
908 m_systemBookmarks
.append(SystemBookmarkData(QUrl::fromLocalFile(KUser().homeDir()),
910 I18N_NOOP2("KFile System Bookmarks", "Home")));
911 m_systemBookmarks
.append(SystemBookmarkData(QUrl("remote:/"),
913 I18N_NOOP2("KFile System Bookmarks", "Network")));
914 m_systemBookmarks
.append(SystemBookmarkData(QUrl::fromLocalFile("/"),
916 I18N_NOOP2("KFile System Bookmarks", "Root")));
917 m_systemBookmarks
.append(SystemBookmarkData(QUrl("trash:/"),
919 I18N_NOOP2("KFile System Bookmarks", "Trash")));
921 if (m_fileIndexingEnabled
) {
922 m_systemBookmarks
.append(SystemBookmarkData(QUrl("timeline:/today"),
924 I18N_NOOP2("KFile System Bookmarks", "Today")));
925 m_systemBookmarks
.append(SystemBookmarkData(QUrl("timeline:/yesterday"),
927 I18N_NOOP2("KFile System Bookmarks", "Yesterday")));
928 m_systemBookmarks
.append(SystemBookmarkData(QUrl("timeline:/thismonth"),
929 "view-calendar-month",
930 I18N_NOOP2("KFile System Bookmarks", "This Month")));
931 m_systemBookmarks
.append(SystemBookmarkData(QUrl("timeline:/lastmonth"),
932 "view-calendar-month",
933 I18N_NOOP2("KFile System Bookmarks", "Last Month")));
934 m_systemBookmarks
.append(SystemBookmarkData(QUrl("search:/documents"),
936 I18N_NOOP2("KFile System Bookmarks", "Documents")));
937 m_systemBookmarks
.append(SystemBookmarkData(QUrl("search:/images"),
939 I18N_NOOP2("KFile System Bookmarks", "Images")));
940 m_systemBookmarks
.append(SystemBookmarkData(QUrl("search:/audio"),
942 I18N_NOOP2("KFile System Bookmarks", "Audio Files")));
943 m_systemBookmarks
.append(SystemBookmarkData(QUrl("search:/videos"),
945 I18N_NOOP2("KFile System Bookmarks", "Videos")));
948 for (int i
= 0; i
< m_systemBookmarks
.count(); ++i
) {
949 m_systemBookmarksIndexes
.insert(m_systemBookmarks
[i
].url
, i
);
953 void PlacesItemModel::clear() {
954 m_bookmarkedItems
.clear();
955 KStandardItemModel::clear();
958 void PlacesItemModel::initializeAvailableDevices()
960 QString
predicate("[[[[ StorageVolume.ignored == false AND [ StorageVolume.usage == 'FileSystem' OR StorageVolume.usage == 'Encrypted' ]]"
962 "[ IS StorageAccess AND StorageDrive.driveType == 'Floppy' ]]"
964 "OpticalDisc.availableContent & 'Audio' ]"
966 "StorageAccess.ignored == false ]");
969 if (KProtocolInfo::isKnownProtocol("mtp")) {
970 predicate
.prepend("[");
971 predicate
.append(" OR PortableMediaPlayer.supportedProtocols == 'mtp']");
974 m_predicate
= Solid::Predicate::fromString(predicate
);
975 Q_ASSERT(m_predicate
.isValid());
977 Solid::DeviceNotifier
* notifier
= Solid::DeviceNotifier::instance();
978 connect(notifier
, &Solid::DeviceNotifier::deviceAdded
, this, &PlacesItemModel::slotDeviceAdded
);
979 connect(notifier
, &Solid::DeviceNotifier::deviceRemoved
, this, &PlacesItemModel::slotDeviceRemoved
);
981 const QList
<Solid::Device
>& deviceList
= Solid::Device::listFromQuery(m_predicate
);
982 foreach (const Solid::Device
& device
, deviceList
) {
983 m_availableDevices
<< device
.udi();
987 int PlacesItemModel::bookmarkIndex(int index
) const
989 int bookmarkIndex
= 0;
991 while (bookmarkIndex
< m_bookmarkedItems
.count()) {
992 if (!m_bookmarkedItems
[bookmarkIndex
]) {
993 if (modelIndex
== index
) {
1001 return bookmarkIndex
>= m_bookmarkedItems
.count() ? -1 : bookmarkIndex
;
1004 void PlacesItemModel::hideItem(int index
)
1006 PlacesItem
* shownItem
= placesItem(index
);
1011 shownItem
->setHidden(true);
1012 if (m_hiddenItemsShown
) {
1013 // Removing items from the model is not allowed if all hidden
1014 // items should be shown.
1018 const int newIndex
= bookmarkIndex(index
);
1019 if (newIndex
>= 0) {
1020 const KBookmark hiddenBookmark
= shownItem
->bookmark();
1021 PlacesItem
* hiddenItem
= new PlacesItem(hiddenBookmark
);
1023 const PlacesItem
* previousItem
= placesItem(index
- 1);
1024 KBookmark previousBookmark
;
1026 previousBookmark
= previousItem
->bookmark();
1029 const bool updateBookmark
= (m_bookmarkManager
->root().indexOf(hiddenBookmark
) >= 0);
1032 if (updateBookmark
) {
1033 // removeItem() also removed the bookmark from m_bookmarkManager in
1034 // PlacesItemModel::onItemRemoved(). However for hidden items the
1035 // bookmark should still be remembered, so readd it again:
1036 m_bookmarkManager
->root().addBookmark(hiddenBookmark
);
1037 m_bookmarkManager
->root().moveBookmark(hiddenBookmark
, previousBookmark
);
1038 triggerBookmarksSaving();
1041 m_bookmarkedItems
.insert(newIndex
, hiddenItem
);
1045 void PlacesItemModel::triggerBookmarksSaving()
1047 if (m_saveBookmarksTimer
) {
1048 m_saveBookmarksTimer
->start();
1052 QString
PlacesItemModel::internalMimeType() const
1054 return "application/x-dolphinplacesmodel-" +
1055 QString::number((qptrdiff
)this);
1058 int PlacesItemModel::groupedDropIndex(int index
, const PlacesItem
* item
) const
1062 int dropIndex
= index
;
1063 const PlacesItem::GroupType type
= item
->groupType();
1065 const int itemCount
= count();
1067 dropIndex
= itemCount
;
1070 // Search nearest previous item with the same group
1071 int previousIndex
= -1;
1072 for (int i
= dropIndex
- 1; i
>= 0; --i
) {
1073 if (placesItem(i
)->groupType() == type
) {
1079 // Search nearest next item with the same group
1081 for (int i
= dropIndex
; i
< count(); ++i
) {
1082 if (placesItem(i
)->groupType() == type
) {
1088 // Adjust the drop-index to be inserted to the
1089 // nearest item with the same group.
1090 if (previousIndex
>= 0 && nextIndex
>= 0) {
1091 dropIndex
= (dropIndex
- previousIndex
< nextIndex
- dropIndex
) ?
1092 previousIndex
+ 1 : nextIndex
;
1093 } else if (previousIndex
>= 0) {
1094 dropIndex
= previousIndex
+ 1;
1095 } else if (nextIndex
>= 0) {
1096 dropIndex
= nextIndex
;
1102 bool PlacesItemModel::equalBookmarkIdentifiers(const KBookmark
& b1
, const KBookmark
& b2
)
1104 const QString udi1
= b1
.metaDataItem("UDI");
1105 const QString udi2
= b2
.metaDataItem("UDI");
1106 if (!udi1
.isEmpty() && !udi2
.isEmpty()) {
1107 return udi1
== udi2
;
1109 return b1
.metaDataItem("ID") == b2
.metaDataItem("ID");
1113 QUrl
PlacesItemModel::createTimelineUrl(const QUrl
& url
)
1115 // TODO: Clarify with the Baloo-team whether it makes sense
1116 // provide default-timeline-URLs like 'yesterday', 'this month'
1117 // and 'last month'.
1120 const QString path
= url
.toDisplayString(QUrl::PreferLocalFile
);
1121 if (path
.endsWith(QLatin1String("yesterday"))) {
1122 const QDate date
= QDate::currentDate().addDays(-1);
1123 const int year
= date
.year();
1124 const int month
= date
.month();
1125 const int day
= date
.day();
1126 timelineUrl
= "timeline:/" + timelineDateString(year
, month
) +
1127 '/' + timelineDateString(year
, month
, day
);
1128 } else if (path
.endsWith(QLatin1String("thismonth"))) {
1129 const QDate date
= QDate::currentDate();
1130 timelineUrl
= "timeline:/" + timelineDateString(date
.year(), date
.month());
1131 } else if (path
.endsWith(QLatin1String("lastmonth"))) {
1132 const QDate date
= QDate::currentDate().addMonths(-1);
1133 timelineUrl
= "timeline:/" + timelineDateString(date
.year(), date
.month());
1135 Q_ASSERT(path
.endsWith(QLatin1String("today")));
1142 QString
PlacesItemModel::timelineDateString(int year
, int month
, int day
)
1144 QString date
= QString::number(year
) + '-';
1148 date
+= QString::number(month
);
1155 date
+= QString::number(day
);
1161 QUrl
PlacesItemModel::createSearchUrl(const QUrl
& url
)
1166 const QString path
= url
.toDisplayString(QUrl::PreferLocalFile
);
1167 if (path
.endsWith(QLatin1String("documents"))) {
1168 searchUrl
= searchUrlForType("Document");
1169 } else if (path
.endsWith(QLatin1String("images"))) {
1170 searchUrl
= searchUrlForType("Image");
1171 } else if (path
.endsWith(QLatin1String("audio"))) {
1172 searchUrl
= searchUrlForType("Audio");
1173 } else if (path
.endsWith(QLatin1String("videos"))) {
1174 searchUrl
= searchUrlForType("Video");
1186 QUrl
PlacesItemModel::searchUrlForType(const QString
& type
)
1189 query
.addType("File");
1190 query
.addType(type
);
1192 return query
.toSearchUrl();
1196 #ifdef PLACESITEMMODEL_DEBUG
1197 void PlacesItemModel::showModelState()
1199 kDebug() << "=================================";
1200 kDebug() << "Model:";
1201 kDebug() << "hidden-index model-index text";
1203 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
1204 if (m_bookmarkedItems
[i
]) {
1205 kDebug() << i
<< "(Hidden) " << " " << m_bookmarkedItems
[i
]->dataValue("text").toString();
1207 if (item(modelIndex
)) {
1208 kDebug() << i
<< " " << modelIndex
<< " " << item(modelIndex
)->dataValue("text").toString();
1210 kDebug() << i
<< " " << modelIndex
<< " " << "(not available yet)";
1217 kDebug() << "Bookmarks:";
1219 int bookmarkIndex
= 0;
1220 KBookmarkGroup root
= m_bookmarkManager
->root();
1221 KBookmark bookmark
= root
.first();
1222 while (!bookmark
.isNull()) {
1223 const QString udi
= bookmark
.metaDataItem("UDI");
1224 const QString text
= udi
.isEmpty() ? bookmark
.text() : udi
;
1225 if (bookmark
.metaDataItem("IsHidden") == QLatin1String("true")) {
1226 kDebug() << bookmarkIndex
<< "(Hidden)" << text
;
1228 kDebug() << bookmarkIndex
<< " " << text
;
1231 bookmark
= root
.next(bookmark
);