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>
31 #include "dolphindebug.h"
33 #include <KProtocolInfo>
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()
112 qDeleteAll(m_bookmarkedItems
);
113 m_bookmarkedItems
.clear();
116 PlacesItem
* PlacesItemModel::createPlacesItem(const QString
& text
,
118 const QString
& iconName
)
120 const KBookmark bookmark
= PlacesItem::createBookmark(m_bookmarkManager
, text
, url
, iconName
);
121 return new PlacesItem(bookmark
);
124 PlacesItem
* PlacesItemModel::placesItem(int index
) const
126 return dynamic_cast<PlacesItem
*>(item(index
));
129 int PlacesItemModel::hiddenCount() const
132 int hiddenItemCount
= 0;
133 foreach (const PlacesItem
* item
, m_bookmarkedItems
) {
137 if (placesItem(modelIndex
)->isHidden()) {
144 return hiddenItemCount
;
147 void PlacesItemModel::setHiddenItemsShown(bool show
)
149 if (m_hiddenItemsShown
== show
) {
153 m_hiddenItemsShown
= show
;
156 // Move all items that are part of m_bookmarkedItems to the model.
157 QList
<PlacesItem
*> itemsToInsert
;
158 QList
<int> insertPos
;
160 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
161 if (m_bookmarkedItems
[i
]) {
162 itemsToInsert
.append(m_bookmarkedItems
[i
]);
163 m_bookmarkedItems
[i
] = 0;
164 insertPos
.append(modelIndex
);
169 // Inserting the items will automatically insert an item
170 // to m_bookmarkedItems in PlacesItemModel::onItemsInserted().
171 // The items are temporary saved in itemsToInsert, so
172 // m_bookmarkedItems can be shrinked now.
173 m_bookmarkedItems
.erase(m_bookmarkedItems
.begin(),
174 m_bookmarkedItems
.begin() + itemsToInsert
.count());
176 for (int i
= 0; i
< itemsToInsert
.count(); ++i
) {
177 insertItem(insertPos
[i
], itemsToInsert
[i
]);
180 Q_ASSERT(m_bookmarkedItems
.count() == count());
182 // Move all items of the model, where the "isHidden" property is true, to
183 // m_bookmarkedItems.
184 Q_ASSERT(m_bookmarkedItems
.count() == count());
185 for (int i
= count() - 1; i
>= 0; --i
) {
186 if (placesItem(i
)->isHidden()) {
192 #ifdef PLACESITEMMODEL_DEBUG
193 qCDebug(DolphinDebug
) << "Changed visibility of hidden items";
198 bool PlacesItemModel::hiddenItemsShown() const
200 return m_hiddenItemsShown
;
203 int PlacesItemModel::closestItem(const QUrl
& url
) const
208 for (int i
= 0; i
< count(); ++i
) {
209 const QUrl itemUrl
= placesItem(i
)->url();
210 if (url
== itemUrl
) {
211 // We can't find a closer one, so stop here.
214 } else if (itemUrl
.isParentOf(url
)) {
215 const int length
= itemUrl
.path().length();
216 if (length
> maxLength
) {
226 void PlacesItemModel::appendItemToGroup(PlacesItem
* item
)
233 while (i
< count() && placesItem(i
)->group() != item
->group()) {
237 bool inserted
= false;
238 while (!inserted
&& i
< count()) {
239 if (placesItem(i
)->group() != item
->group()) {
252 QAction
* PlacesItemModel::ejectAction(int index
) const
254 const PlacesItem
* item
= placesItem(index
);
255 if (item
&& item
->device().is
<Solid::OpticalDisc
>()) {
256 return new QAction(QIcon::fromTheme("media-eject"), i18nc("@item", "Eject '%1'", item
->text()), 0);
262 QAction
* PlacesItemModel::teardownAction(int index
) const
264 const PlacesItem
* item
= placesItem(index
);
269 Solid::Device device
= item
->device();
270 const bool providesTearDown
= device
.is
<Solid::StorageAccess
>() &&
271 device
.as
<Solid::StorageAccess
>()->isAccessible();
272 if (!providesTearDown
) {
276 Solid::StorageDrive
* drive
= device
.as
<Solid::StorageDrive
>();
278 drive
= device
.parent().as
<Solid::StorageDrive
>();
281 bool hotPluggable
= false;
282 bool removable
= false;
284 hotPluggable
= drive
->isHotpluggable();
285 removable
= drive
->isRemovable();
290 const QString label
= item
->text();
291 if (device
.is
<Solid::OpticalDisc
>()) {
292 text
= i18nc("@item", "Release '%1'", label
);
293 } else if (removable
|| hotPluggable
) {
294 text
= i18nc("@item", "Safely Remove '%1'", label
);
295 iconName
= "media-eject";
297 text
= i18nc("@item", "Unmount '%1'", label
);
298 iconName
= "media-eject";
301 if (iconName
.isEmpty()) {
302 return new QAction(text
, 0);
305 return new QAction(QIcon::fromTheme(iconName
), text
, 0);
308 void PlacesItemModel::requestEject(int index
)
310 const PlacesItem
* item
= placesItem(index
);
312 Solid::OpticalDrive
* drive
= item
->device().parent().as
<Solid::OpticalDrive
>();
314 connect(drive
, &Solid::OpticalDrive::ejectDone
,
315 this, &PlacesItemModel::slotStorageTeardownDone
);
318 const QString label
= item
->text();
319 const QString message
= i18nc("@info", "The device '%1' is not a disk and cannot be ejected.", label
);
320 emit
errorMessage(message
);
325 void PlacesItemModel::requestTeardown(int index
)
327 const PlacesItem
* item
= placesItem(index
);
329 Solid::StorageAccess
* access
= item
->device().as
<Solid::StorageAccess
>();
331 connect(access
, &Solid::StorageAccess::teardownDone
,
332 this, &PlacesItemModel::slotStorageTeardownDone
);
338 bool PlacesItemModel::storageSetupNeeded(int index
) const
340 const PlacesItem
* item
= placesItem(index
);
341 return item
? item
->storageSetupNeeded() : false;
344 void PlacesItemModel::requestStorageSetup(int index
)
346 const PlacesItem
* item
= placesItem(index
);
351 Solid::Device device
= item
->device();
352 const bool setup
= device
.is
<Solid::StorageAccess
>()
353 && !m_storageSetupInProgress
.contains(device
.as
<Solid::StorageAccess
>())
354 && !device
.as
<Solid::StorageAccess
>()->isAccessible();
356 Solid::StorageAccess
* access
= device
.as
<Solid::StorageAccess
>();
358 m_storageSetupInProgress
[access
] = index
;
360 connect(access
, &Solid::StorageAccess::setupDone
,
361 this, &PlacesItemModel::slotStorageSetupDone
);
367 QMimeData
* PlacesItemModel::createMimeData(const KItemSet
& indexes
) const
372 QDataStream
stream(&itemData
, QIODevice::WriteOnly
);
374 foreach (int index
, indexes
) {
375 const QUrl itemUrl
= placesItem(index
)->url();
376 if (itemUrl
.isValid()) {
382 QMimeData
* mimeData
= new QMimeData();
383 if (!urls
.isEmpty()) {
384 mimeData
->setUrls(urls
);
386 mimeData
->setData(internalMimeType(), itemData
);
391 bool PlacesItemModel::supportsDropping(int index
) const
393 return index
>= 0 && index
< count();
396 void PlacesItemModel::dropMimeDataBefore(int index
, const QMimeData
* mimeData
)
398 if (mimeData
->hasFormat(internalMimeType())) {
399 // The item has been moved inside the view
400 QByteArray itemData
= mimeData
->data(internalMimeType());
401 QDataStream
stream(&itemData
, QIODevice::ReadOnly
);
404 if (oldIndex
== index
|| oldIndex
== index
- 1) {
405 // No moving has been done
409 PlacesItem
* oldItem
= placesItem(oldIndex
);
414 PlacesItem
* newItem
= new PlacesItem(oldItem
->bookmark());
415 removeItem(oldIndex
);
417 if (oldIndex
< index
) {
421 const int dropIndex
= groupedDropIndex(index
, newItem
);
422 insertItem(dropIndex
, newItem
);
423 } else if (mimeData
->hasFormat("text/uri-list")) {
424 // One or more items must be added to the model
425 const QList
<QUrl
> urls
= KUrlMimeData::urlsFromMimeData(mimeData
);
426 for (int i
= urls
.count() - 1; i
>= 0; --i
) {
427 const QUrl
& url
= urls
[i
];
429 QString text
= url
.fileName();
430 if (text
.isEmpty()) {
434 if ((url
.isLocalFile() && !QFileInfo(url
.toLocalFile()).isDir())
435 || url
.scheme() == "trash") {
436 // Only directories outside the trash are allowed
440 PlacesItem
* newItem
= createPlacesItem(text
, url
);
441 const int dropIndex
= groupedDropIndex(index
, newItem
);
442 insertItem(dropIndex
, newItem
);
447 QUrl
PlacesItemModel::convertedUrl(const QUrl
& url
)
450 if (url
.scheme() == QLatin1String("timeline")) {
451 newUrl
= createTimelineUrl(url
);
452 } else if (url
.scheme() == QLatin1String("search")) {
453 newUrl
= createSearchUrl(url
);
459 void PlacesItemModel::onItemInserted(int index
)
461 const PlacesItem
* insertedItem
= placesItem(index
);
463 // Take care to apply the PlacesItemModel-order of the inserted item
464 // also to the bookmark-manager.
465 const KBookmark insertedBookmark
= insertedItem
->bookmark();
467 const PlacesItem
* previousItem
= placesItem(index
- 1);
468 KBookmark previousBookmark
;
470 previousBookmark
= previousItem
->bookmark();
473 m_bookmarkManager
->root().moveBookmark(insertedBookmark
, previousBookmark
);
476 if (index
== count() - 1) {
477 // The item has been appended as last item to the list. In this
478 // case assure that it is also appended after the hidden items and
479 // not before (like done otherwise).
480 m_bookmarkedItems
.append(0);
484 int bookmarkIndex
= 0;
485 while (bookmarkIndex
< m_bookmarkedItems
.count()) {
486 if (!m_bookmarkedItems
[bookmarkIndex
]) {
488 if (modelIndex
+ 1 == index
) {
494 m_bookmarkedItems
.insert(bookmarkIndex
, 0);
497 #ifdef PLACESITEMMODEL_DEBUG
498 qCDebug(DolphinDebug
) << "Inserted item" << index
;
503 void PlacesItemModel::onItemRemoved(int index
, KStandardItem
* removedItem
)
505 PlacesItem
* placesItem
= dynamic_cast<PlacesItem
*>(removedItem
);
507 const KBookmark bookmark
= placesItem
->bookmark();
508 m_bookmarkManager
->root().deleteBookmark(bookmark
);
511 const int boomarkIndex
= bookmarkIndex(index
);
512 Q_ASSERT(!m_bookmarkedItems
[boomarkIndex
]);
513 m_bookmarkedItems
.removeAt(boomarkIndex
);
515 #ifdef PLACESITEMMODEL_DEBUG
516 qCDebug(DolphinDebug
) << "Removed item" << index
;
521 void PlacesItemModel::onItemChanged(int index
, const QSet
<QByteArray
>& changedRoles
)
523 const PlacesItem
* changedItem
= placesItem(index
);
525 // Take care to apply the PlacesItemModel-order of the changed item
526 // also to the bookmark-manager.
527 const KBookmark insertedBookmark
= changedItem
->bookmark();
529 const PlacesItem
* previousItem
= placesItem(index
- 1);
530 KBookmark previousBookmark
;
532 previousBookmark
= previousItem
->bookmark();
535 m_bookmarkManager
->root().moveBookmark(insertedBookmark
, previousBookmark
);
538 if (changedRoles
.contains("isHidden")) {
539 if (!m_hiddenItemsShown
&& changedItem
->isHidden()) {
540 m_hiddenItemToRemove
= index
;
541 QTimer::singleShot(0, this, SLOT(hideItem()));
546 void PlacesItemModel::slotDeviceAdded(const QString
& udi
)
548 const Solid::Device
device(udi
);
550 if (!m_predicate
.matches(device
)) {
554 m_availableDevices
<< udi
;
555 const KBookmark bookmark
= PlacesItem::createDeviceBookmark(m_bookmarkManager
, udi
);
556 appendItem(new PlacesItem(bookmark
));
559 void PlacesItemModel::slotDeviceRemoved(const QString
& udi
)
561 if (!m_availableDevices
.contains(udi
)) {
565 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
566 PlacesItem
* item
= m_bookmarkedItems
[i
];
567 if (item
&& item
->udi() == udi
) {
568 m_bookmarkedItems
.removeAt(i
);
574 for (int i
= 0; i
< count(); ++i
) {
575 if (placesItem(i
)->udi() == udi
) {
582 void PlacesItemModel::slotStorageTeardownDone(Solid::ErrorType error
, const QVariant
& errorData
)
584 if (error
&& errorData
.isValid()) {
585 emit
errorMessage(errorData
.toString());
589 void PlacesItemModel::slotStorageSetupDone(Solid::ErrorType error
,
590 const QVariant
& errorData
,
595 const int index
= m_storageSetupInProgress
.take(sender());
596 const PlacesItem
* item
= placesItem(index
);
601 if (error
!= Solid::NoError
) {
602 if (errorData
.isValid()) {
603 emit
errorMessage(i18nc("@info", "An error occurred while accessing '%1', the system responded: %2",
605 errorData
.toString()));
607 emit
errorMessage(i18nc("@info", "An error occurred while accessing '%1'",
610 emit
storageSetupDone(index
, false);
612 emit
storageSetupDone(index
, true);
616 void PlacesItemModel::hideItem()
618 hideItem(m_hiddenItemToRemove
);
619 m_hiddenItemToRemove
= -1;
622 void PlacesItemModel::updateBookmarks()
624 // Verify whether new bookmarks have been added or existing
625 // bookmarks have been changed.
626 KBookmarkGroup root
= m_bookmarkManager
->root();
627 KBookmark newBookmark
= root
.first();
628 while (!newBookmark
.isNull()) {
629 if (acceptBookmark(newBookmark
, m_availableDevices
)) {
632 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
633 PlacesItem
* item
= m_bookmarkedItems
[i
];
635 item
= placesItem(modelIndex
);
639 const KBookmark oldBookmark
= item
->bookmark();
640 if (equalBookmarkIdentifiers(newBookmark
, oldBookmark
)) {
641 // The bookmark has been found in the model or as
642 // a hidden item. The content of the bookmark might
643 // have been changed, so an update is done.
645 if (newBookmark
.metaDataItem("UDI").isEmpty()) {
646 item
->setBookmark(newBookmark
);
647 item
->setText(i18nc("KFile System Bookmarks", newBookmark
.text().toUtf8().constData()));
654 const QString udi
= newBookmark
.metaDataItem("UDI");
658 * Only add a new places item, if the item text is not empty
659 * and if the device is available. Fixes the strange behaviour -
660 * add a places item without text in the Places section - when you
661 * remove a device (e.g. a usb stick) without unmounting.
663 if (udi
.isEmpty() || Solid::Device(udi
).isValid()) {
664 PlacesItem
* item
= new PlacesItem(newBookmark
);
665 if (item
->isHidden() && !m_hiddenItemsShown
) {
666 m_bookmarkedItems
.append(item
);
668 appendItemToGroup(item
);
674 newBookmark
= root
.next(newBookmark
);
677 // Remove items that are not part of the bookmark-manager anymore
679 for (int i
= m_bookmarkedItems
.count() - 1; i
>= 0; --i
) {
680 PlacesItem
* item
= m_bookmarkedItems
[i
];
681 const bool itemIsPartOfModel
= (item
== 0);
682 if (itemIsPartOfModel
) {
683 item
= placesItem(modelIndex
);
686 bool hasBeenRemoved
= true;
687 const KBookmark oldBookmark
= item
->bookmark();
688 KBookmark newBookmark
= root
.first();
689 while (!newBookmark
.isNull()) {
690 if (equalBookmarkIdentifiers(newBookmark
, oldBookmark
)) {
691 hasBeenRemoved
= false;
694 newBookmark
= root
.next(newBookmark
);
697 if (hasBeenRemoved
) {
698 if (m_bookmarkedItems
[i
]) {
699 delete m_bookmarkedItems
[i
];
700 m_bookmarkedItems
.removeAt(i
);
702 removeItem(modelIndex
);
707 if (itemIsPartOfModel
) {
713 void PlacesItemModel::saveBookmarks()
715 m_bookmarkManager
->emitChanged(m_bookmarkManager
->root());
718 void PlacesItemModel::loadBookmarks()
720 KBookmarkGroup root
= m_bookmarkManager
->root();
721 KBookmark bookmark
= root
.first();
722 QSet
<QString
> devices
= m_availableDevices
;
724 QSet
<QUrl
> missingSystemBookmarks
;
725 foreach (const SystemBookmarkData
& data
, m_systemBookmarks
) {
726 missingSystemBookmarks
.insert(data
.url
);
729 // The bookmarks might have a mixed order of places, devices and search-groups due
730 // to the compatibility with the KFilePlacesPanel. In Dolphin's places panel the
731 // items should always be collected in one group so the items are collected first
732 // in separate lists before inserting them.
733 QList
<PlacesItem
*> placesItems
;
734 QList
<PlacesItem
*> recentlySavedItems
;
735 QList
<PlacesItem
*> searchForItems
;
736 QList
<PlacesItem
*> devicesItems
;
738 while (!bookmark
.isNull()) {
739 if (acceptBookmark(bookmark
, devices
)) {
740 PlacesItem
* item
= new PlacesItem(bookmark
);
741 if (item
->groupType() == PlacesItem::DevicesType
) {
742 devices
.remove(item
->udi());
743 devicesItems
.append(item
);
745 const QUrl url
= bookmark
.url();
746 if (missingSystemBookmarks
.contains(url
)) {
747 missingSystemBookmarks
.remove(url
);
749 // Try to retranslate the text of system bookmarks to have translated
750 // items when changing the language. In case if the user has applied a custom
751 // text, the retranslation will fail and the users custom text is still used.
752 // It is important to use "KFile System Bookmarks" as context (see
753 // createSystemBookmarks()).
754 item
->setText(i18nc("KFile System Bookmarks", bookmark
.text().toUtf8().constData()));
755 item
->setSystemItem(true);
758 switch (item
->groupType()) {
759 case PlacesItem::PlacesType
: placesItems
.append(item
); break;
760 case PlacesItem::RecentlySavedType
: recentlySavedItems
.append(item
); break;
761 case PlacesItem::SearchForType
: searchForItems
.append(item
); break;
762 case PlacesItem::DevicesType
:
763 default: Q_ASSERT(false); break;
768 bookmark
= root
.next(bookmark
);
771 if (!missingSystemBookmarks
.isEmpty()) {
772 // The current bookmarks don't contain all system-bookmarks. Add the missing
774 foreach (const SystemBookmarkData
& data
, m_systemBookmarks
) {
775 if (missingSystemBookmarks
.contains(data
.url
)) {
776 PlacesItem
* item
= createSystemPlacesItem(data
);
777 switch (item
->groupType()) {
778 case PlacesItem::PlacesType
: placesItems
.append(item
); break;
779 case PlacesItem::RecentlySavedType
: recentlySavedItems
.append(item
); break;
780 case PlacesItem::SearchForType
: searchForItems
.append(item
); break;
781 case PlacesItem::DevicesType
:
782 default: Q_ASSERT(false); break;
788 // Create items for devices that have not been stored as bookmark yet
789 foreach (const QString
& udi
, devices
) {
790 const KBookmark bookmark
= PlacesItem::createDeviceBookmark(m_bookmarkManager
, udi
);
791 devicesItems
.append(new PlacesItem(bookmark
));
794 QList
<PlacesItem
*> items
;
795 items
.append(placesItems
);
796 items
.append(recentlySavedItems
);
797 items
.append(searchForItems
);
798 items
.append(devicesItems
);
800 foreach (PlacesItem
* item
, items
) {
801 if (!m_hiddenItemsShown
&& item
->isHidden()) {
802 m_bookmarkedItems
.append(item
);
808 #ifdef PLACESITEMMODEL_DEBUG
809 qCDebug(DolphinDebug
) << "Loaded bookmarks";
814 bool PlacesItemModel::acceptBookmark(const KBookmark
& bookmark
,
815 const QSet
<QString
>& availableDevices
) const
817 const QString udi
= bookmark
.metaDataItem("UDI");
818 const QUrl url
= bookmark
.url();
819 const QString appName
= bookmark
.metaDataItem("OnlyInApp");
820 const bool deviceAvailable
= availableDevices
.contains(udi
);
822 const bool allowedHere
= (appName
.isEmpty()
823 || appName
== KAboutData::applicationData().componentName()
824 || appName
== KAboutData::applicationData().componentName() + AppNamePrefix
)
825 && (m_fileIndexingEnabled
|| (url
.scheme() != QLatin1String("timeline") &&
826 url
.scheme() != QLatin1String("search")));
828 return (udi
.isEmpty() && allowedHere
) || deviceAvailable
;
831 PlacesItem
* PlacesItemModel::createSystemPlacesItem(const SystemBookmarkData
& data
)
833 KBookmark bookmark
= PlacesItem::createBookmark(m_bookmarkManager
,
838 const QString protocol
= data
.url
.scheme();
839 if (protocol
== QLatin1String("timeline") || protocol
== QLatin1String("search")) {
840 // As long as the KFilePlacesView from kdelibs is available, the system-bookmarks
841 // for "Recently Saved" and "Search For" should be a setting available only
842 // in the Places Panel (see description of AppNamePrefix for more details).
843 const QString appName
= KAboutData::applicationData().componentName() + AppNamePrefix
;
844 bookmark
.setMetaDataItem("OnlyInApp", appName
);
847 PlacesItem
* item
= new PlacesItem(bookmark
);
848 item
->setSystemItem(true);
850 // Create default view-properties for all "Search For" and "Recently Saved" bookmarks
851 // in case if the user has not already created custom view-properties for a corresponding
853 const bool createDefaultViewProperties
= (item
->groupType() == PlacesItem::SearchForType
||
854 item
->groupType() == PlacesItem::RecentlySavedType
) &&
855 !GeneralSettings::self()->globalViewProps();
856 if (createDefaultViewProperties
) {
857 ViewProperties
props(convertedUrl(data
.url
));
858 if (!props
.exist()) {
859 const QString path
= data
.url
.path();
860 if (path
== QLatin1String("/documents")) {
861 props
.setViewMode(DolphinView::DetailsView
);
862 props
.setPreviewsShown(false);
863 props
.setVisibleRoles({"text", "path"});
864 } else if (path
== QLatin1String("/images")) {
865 props
.setViewMode(DolphinView::IconsView
);
866 props
.setPreviewsShown(true);
867 props
.setVisibleRoles({"text", "imageSize"});
868 } else if (path
== QLatin1String("/audio")) {
869 props
.setViewMode(DolphinView::DetailsView
);
870 props
.setPreviewsShown(false);
871 props
.setVisibleRoles({"text", "artist", "album"});
872 } else if (path
== QLatin1String("/videos")) {
873 props
.setViewMode(DolphinView::IconsView
);
874 props
.setPreviewsShown(true);
875 props
.setVisibleRoles({"text"});
876 } else if (data
.url
.scheme() == "timeline") {
877 props
.setViewMode(DolphinView::DetailsView
);
878 props
.setVisibleRoles({"text", "date"});
886 void PlacesItemModel::createSystemBookmarks()
888 Q_ASSERT(m_systemBookmarks
.isEmpty());
889 Q_ASSERT(m_systemBookmarksIndexes
.isEmpty());
891 // Note: The context of the I18N_NOOP2 must be "KFile System Bookmarks". The real
892 // i18nc call is done after reading the bookmark. The reason why the i18nc call is not
893 // done here is because otherwise switching the language would not result in retranslating the
895 m_systemBookmarks
.append(SystemBookmarkData(QUrl::fromLocalFile(KUser().homeDir()),
897 I18N_NOOP2("KFile System Bookmarks", "Home")));
898 m_systemBookmarks
.append(SystemBookmarkData(QUrl("remote:/"),
900 I18N_NOOP2("KFile System Bookmarks", "Network")));
901 m_systemBookmarks
.append(SystemBookmarkData(QUrl::fromLocalFile("/"),
903 I18N_NOOP2("KFile System Bookmarks", "Root")));
904 m_systemBookmarks
.append(SystemBookmarkData(QUrl("trash:/"),
906 I18N_NOOP2("KFile System Bookmarks", "Trash")));
908 if (m_fileIndexingEnabled
) {
909 m_systemBookmarks
.append(SystemBookmarkData(QUrl("timeline:/today"),
911 I18N_NOOP2("KFile System Bookmarks", "Today")));
912 m_systemBookmarks
.append(SystemBookmarkData(QUrl("timeline:/yesterday"),
914 I18N_NOOP2("KFile System Bookmarks", "Yesterday")));
915 m_systemBookmarks
.append(SystemBookmarkData(QUrl("timeline:/thismonth"),
916 "view-calendar-month",
917 I18N_NOOP2("KFile System Bookmarks", "This Month")));
918 m_systemBookmarks
.append(SystemBookmarkData(QUrl("timeline:/lastmonth"),
919 "view-calendar-month",
920 I18N_NOOP2("KFile System Bookmarks", "Last Month")));
921 m_systemBookmarks
.append(SystemBookmarkData(QUrl("search:/documents"),
923 I18N_NOOP2("KFile System Bookmarks", "Documents")));
924 m_systemBookmarks
.append(SystemBookmarkData(QUrl("search:/images"),
926 I18N_NOOP2("KFile System Bookmarks", "Images")));
927 m_systemBookmarks
.append(SystemBookmarkData(QUrl("search:/audio"),
929 I18N_NOOP2("KFile System Bookmarks", "Audio Files")));
930 m_systemBookmarks
.append(SystemBookmarkData(QUrl("search:/videos"),
932 I18N_NOOP2("KFile System Bookmarks", "Videos")));
935 for (int i
= 0; i
< m_systemBookmarks
.count(); ++i
) {
936 m_systemBookmarksIndexes
.insert(m_systemBookmarks
[i
].url
, i
);
940 void PlacesItemModel::clear() {
941 m_bookmarkedItems
.clear();
942 KStandardItemModel::clear();
945 void PlacesItemModel::initializeAvailableDevices()
947 QString
predicate("[[[[ StorageVolume.ignored == false AND [ StorageVolume.usage == 'FileSystem' OR StorageVolume.usage == 'Encrypted' ]]"
949 "[ IS StorageAccess AND StorageDrive.driveType == 'Floppy' ]]"
951 "OpticalDisc.availableContent & 'Audio' ]"
953 "StorageAccess.ignored == false ]");
956 if (KProtocolInfo::isKnownProtocol("mtp")) {
957 predicate
.prepend("[");
958 predicate
.append(" OR PortableMediaPlayer.supportedProtocols == 'mtp']");
961 m_predicate
= Solid::Predicate::fromString(predicate
);
962 Q_ASSERT(m_predicate
.isValid());
964 Solid::DeviceNotifier
* notifier
= Solid::DeviceNotifier::instance();
965 connect(notifier
, &Solid::DeviceNotifier::deviceAdded
, this, &PlacesItemModel::slotDeviceAdded
);
966 connect(notifier
, &Solid::DeviceNotifier::deviceRemoved
, this, &PlacesItemModel::slotDeviceRemoved
);
968 const QList
<Solid::Device
>& deviceList
= Solid::Device::listFromQuery(m_predicate
);
969 foreach (const Solid::Device
& device
, deviceList
) {
970 m_availableDevices
<< device
.udi();
974 int PlacesItemModel::bookmarkIndex(int index
) const
976 int bookmarkIndex
= 0;
978 while (bookmarkIndex
< m_bookmarkedItems
.count()) {
979 if (!m_bookmarkedItems
[bookmarkIndex
]) {
980 if (modelIndex
== index
) {
988 return bookmarkIndex
>= m_bookmarkedItems
.count() ? -1 : bookmarkIndex
;
991 void PlacesItemModel::hideItem(int index
)
993 PlacesItem
* shownItem
= placesItem(index
);
998 shownItem
->setHidden(true);
999 if (m_hiddenItemsShown
) {
1000 // Removing items from the model is not allowed if all hidden
1001 // items should be shown.
1005 const int newIndex
= bookmarkIndex(index
);
1006 if (newIndex
>= 0) {
1007 const KBookmark hiddenBookmark
= shownItem
->bookmark();
1008 PlacesItem
* hiddenItem
= new PlacesItem(hiddenBookmark
);
1010 const PlacesItem
* previousItem
= placesItem(index
- 1);
1011 KBookmark previousBookmark
;
1013 previousBookmark
= previousItem
->bookmark();
1016 const bool updateBookmark
= (m_bookmarkManager
->root().indexOf(hiddenBookmark
) >= 0);
1019 if (updateBookmark
) {
1020 // removeItem() also removed the bookmark from m_bookmarkManager in
1021 // PlacesItemModel::onItemRemoved(). However for hidden items the
1022 // bookmark should still be remembered, so readd it again:
1023 m_bookmarkManager
->root().addBookmark(hiddenBookmark
);
1024 m_bookmarkManager
->root().moveBookmark(hiddenBookmark
, previousBookmark
);
1027 m_bookmarkedItems
.insert(newIndex
, hiddenItem
);
1031 QString
PlacesItemModel::internalMimeType() const
1033 return "application/x-dolphinplacesmodel-" +
1034 QString::number((qptrdiff
)this);
1037 int PlacesItemModel::groupedDropIndex(int index
, const PlacesItem
* item
) const
1041 int dropIndex
= index
;
1042 const PlacesItem::GroupType type
= item
->groupType();
1044 const int itemCount
= count();
1046 dropIndex
= itemCount
;
1049 // Search nearest previous item with the same group
1050 int previousIndex
= -1;
1051 for (int i
= dropIndex
- 1; i
>= 0; --i
) {
1052 if (placesItem(i
)->groupType() == type
) {
1058 // Search nearest next item with the same group
1060 for (int i
= dropIndex
; i
< count(); ++i
) {
1061 if (placesItem(i
)->groupType() == type
) {
1067 // Adjust the drop-index to be inserted to the
1068 // nearest item with the same group.
1069 if (previousIndex
>= 0 && nextIndex
>= 0) {
1070 dropIndex
= (dropIndex
- previousIndex
< nextIndex
- dropIndex
) ?
1071 previousIndex
+ 1 : nextIndex
;
1072 } else if (previousIndex
>= 0) {
1073 dropIndex
= previousIndex
+ 1;
1074 } else if (nextIndex
>= 0) {
1075 dropIndex
= nextIndex
;
1081 bool PlacesItemModel::equalBookmarkIdentifiers(const KBookmark
& b1
, const KBookmark
& b2
)
1083 const QString udi1
= b1
.metaDataItem("UDI");
1084 const QString udi2
= b2
.metaDataItem("UDI");
1085 if (!udi1
.isEmpty() && !udi2
.isEmpty()) {
1086 return udi1
== udi2
;
1088 return b1
.metaDataItem("ID") == b2
.metaDataItem("ID");
1092 QUrl
PlacesItemModel::createTimelineUrl(const QUrl
& url
)
1094 // TODO: Clarify with the Baloo-team whether it makes sense
1095 // provide default-timeline-URLs like 'yesterday', 'this month'
1096 // and 'last month'.
1099 const QString path
= url
.toDisplayString(QUrl::PreferLocalFile
);
1100 if (path
.endsWith(QLatin1String("yesterday"))) {
1101 const QDate date
= QDate::currentDate().addDays(-1);
1102 const int year
= date
.year();
1103 const int month
= date
.month();
1104 const int day
= date
.day();
1105 timelineUrl
= "timeline:/" + timelineDateString(year
, month
) +
1106 '/' + timelineDateString(year
, month
, day
);
1107 } else if (path
.endsWith(QLatin1String("thismonth"))) {
1108 const QDate date
= QDate::currentDate();
1109 timelineUrl
= "timeline:/" + timelineDateString(date
.year(), date
.month());
1110 } else if (path
.endsWith(QLatin1String("lastmonth"))) {
1111 const QDate date
= QDate::currentDate().addMonths(-1);
1112 timelineUrl
= "timeline:/" + timelineDateString(date
.year(), date
.month());
1114 Q_ASSERT(path
.endsWith(QLatin1String("today")));
1121 QString
PlacesItemModel::timelineDateString(int year
, int month
, int day
)
1123 QString date
= QString::number(year
) + '-';
1127 date
+= QString::number(month
);
1134 date
+= QString::number(day
);
1140 QUrl
PlacesItemModel::createSearchUrl(const QUrl
& url
)
1145 const QString path
= url
.toDisplayString(QUrl::PreferLocalFile
);
1146 if (path
.endsWith(QLatin1String("documents"))) {
1147 searchUrl
= searchUrlForType("Document");
1148 } else if (path
.endsWith(QLatin1String("images"))) {
1149 searchUrl
= searchUrlForType("Image");
1150 } else if (path
.endsWith(QLatin1String("audio"))) {
1151 searchUrl
= searchUrlForType("Audio");
1152 } else if (path
.endsWith(QLatin1String("videos"))) {
1153 searchUrl
= searchUrlForType("Video");
1165 QUrl
PlacesItemModel::searchUrlForType(const QString
& type
)
1168 query
.addType("File");
1169 query
.addType(type
);
1171 return query
.toSearchUrl();
1175 #ifdef PLACESITEMMODEL_DEBUG
1176 void PlacesItemModel::showModelState()
1178 qCDebug(DolphinDebug
) << "=================================";
1179 qCDebug(DolphinDebug
) << "Model:";
1180 qCDebug(DolphinDebug
) << "hidden-index model-index text";
1182 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
1183 if (m_bookmarkedItems
[i
]) {
1184 qCDebug(DolphinDebug
) << i
<< "(Hidden) " << " " << m_bookmarkedItems
[i
]->dataValue("text").toString();
1186 if (item(modelIndex
)) {
1187 qCDebug(DolphinDebug
) << i
<< " " << modelIndex
<< " " << item(modelIndex
)->dataValue("text").toString();
1189 qCDebug(DolphinDebug
) << i
<< " " << modelIndex
<< " " << "(not available yet)";
1195 qCDebug(DolphinDebug
);
1196 qCDebug(DolphinDebug
) << "Bookmarks:";
1198 int bookmarkIndex
= 0;
1199 KBookmarkGroup root
= m_bookmarkManager
->root();
1200 KBookmark bookmark
= root
.first();
1201 while (!bookmark
.isNull()) {
1202 const QString udi
= bookmark
.metaDataItem("UDI");
1203 const QString text
= udi
.isEmpty() ? bookmark
.text() : udi
;
1204 if (bookmark
.metaDataItem("IsHidden") == QLatin1String("true")) {
1205 qCDebug(DolphinDebug
) << bookmarkIndex
<< "(Hidden)" << text
;
1207 qCDebug(DolphinDebug
) << bookmarkIndex
<< " " << text
;
1210 bookmark
= root
.next(bookmark
);