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 <KComponentData>
35 #include <KStandardDirs>
37 #include "placesitem.h"
43 #include <Solid/Device>
44 #include <Solid/DeviceNotifier>
45 #include <Solid/OpticalDisc>
46 #include <Solid/OpticalDrive>
47 #include <Solid/StorageAccess>
48 #include <Solid/StorageDrive>
50 #include <views/dolphinview.h>
51 #include <views/viewproperties.h>
54 #include <Nepomuk2/ResourceManager>
55 #include <Nepomuk2/Query/ComparisonTerm>
56 #include <Nepomuk2/Query/LiteralTerm>
57 #include <Nepomuk2/Query/FileQuery>
58 #include <Nepomuk2/Query/ResourceTypeTerm>
59 #include <Nepomuk2/Vocabulary/NFO>
60 #include <Nepomuk2/Vocabulary/NIE>
64 // As long as KFilePlacesView from kdelibs is available in parallel, the
65 // system-bookmarks for "Recently Accessed" and "Search For" should be
66 // shown only inside the Places Panel. This is necessary as the stored
67 // URLs needs to get translated to a Nepomuk-search-URL on-the-fly to
68 // be independent from changes in the Nepomuk-search-URL-syntax.
69 // Hence a prefix to the application-name of the stored bookmarks is
70 // added, which is only read by PlacesItemModel.
71 const char* AppNamePrefix
= "-places-panel";
74 PlacesItemModel::PlacesItemModel(QObject
* parent
) :
75 KStandardItemModel(parent
),
76 m_fileIndexingEnabled(false),
77 m_hiddenItemsShown(false),
82 m_systemBookmarksIndexes(),
84 m_hiddenItemToRemove(-1),
85 m_saveBookmarksTimer(0),
86 m_updateBookmarksTimer(0),
87 m_storageSetupInProgress()
90 if (Nepomuk2::ResourceManager::instance()->initialized()) {
91 KConfig
config("nepomukserverrc");
92 m_fileIndexingEnabled
= config
.group("Service-nepomukfileindexer").readEntry("autostart", false);
96 const QString file
= KStandardDirs::locateLocal("data", "kfileplaces/bookmarks.xml");
97 m_bookmarkManager
= KBookmarkManager::managerForFile(file
, "kfilePlaces");
99 createSystemBookmarks();
100 initializeAvailableDevices();
103 const int syncBookmarksTimeout
= 100;
105 m_saveBookmarksTimer
= new QTimer(this);
106 m_saveBookmarksTimer
->setInterval(syncBookmarksTimeout
);
107 m_saveBookmarksTimer
->setSingleShot(true);
108 connect(m_saveBookmarksTimer
, SIGNAL(timeout()), this, SLOT(saveBookmarks()));
110 m_updateBookmarksTimer
= new QTimer(this);
111 m_updateBookmarksTimer
->setInterval(syncBookmarksTimeout
);
112 m_updateBookmarksTimer
->setSingleShot(true);
113 connect(m_updateBookmarksTimer
, SIGNAL(timeout()), this, SLOT(updateBookmarks()));
115 connect(m_bookmarkManager
, SIGNAL(changed(QString
,QString
)),
116 m_updateBookmarksTimer
, SLOT(start()));
117 connect(m_bookmarkManager
, SIGNAL(bookmarksChanged(QString
)),
118 m_updateBookmarksTimer
, SLOT(start()));
121 PlacesItemModel::~PlacesItemModel()
124 qDeleteAll(m_bookmarkedItems
);
125 m_bookmarkedItems
.clear();
128 PlacesItem
* PlacesItemModel::createPlacesItem(const QString
& text
,
130 const QString
& iconName
)
132 const KBookmark bookmark
= PlacesItem::createBookmark(m_bookmarkManager
, text
, url
, iconName
);
133 return new PlacesItem(bookmark
);
136 PlacesItem
* PlacesItemModel::placesItem(int index
) const
138 return dynamic_cast<PlacesItem
*>(item(index
));
141 int PlacesItemModel::hiddenCount() const
144 int hiddenItemCount
= 0;
145 foreach (const PlacesItem
* item
, m_bookmarkedItems
) {
149 if (placesItem(modelIndex
)->isHidden()) {
156 return hiddenItemCount
;
159 void PlacesItemModel::setHiddenItemsShown(bool show
)
161 if (m_hiddenItemsShown
== show
) {
165 m_hiddenItemsShown
= show
;
168 // Move all items that are part of m_bookmarkedItems to the model.
169 QList
<PlacesItem
*> itemsToInsert
;
170 QList
<int> insertPos
;
172 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
173 if (m_bookmarkedItems
[i
]) {
174 itemsToInsert
.append(m_bookmarkedItems
[i
]);
175 m_bookmarkedItems
[i
] = 0;
176 insertPos
.append(modelIndex
);
181 // Inserting the items will automatically insert an item
182 // to m_bookmarkedItems in PlacesItemModel::onItemsInserted().
183 // The items are temporary saved in itemsToInsert, so
184 // m_bookmarkedItems can be shrinked now.
185 m_bookmarkedItems
.erase(m_bookmarkedItems
.begin(),
186 m_bookmarkedItems
.begin() + itemsToInsert
.count());
188 for (int i
= 0; i
< itemsToInsert
.count(); ++i
) {
189 insertItem(insertPos
[i
], itemsToInsert
[i
]);
192 Q_ASSERT(m_bookmarkedItems
.count() == count());
194 // Move all items of the model, where the "isHidden" property is true, to
195 // m_bookmarkedItems.
196 Q_ASSERT(m_bookmarkedItems
.count() == count());
197 for (int i
= count() - 1; i
>= 0; --i
) {
198 if (placesItem(i
)->isHidden()) {
204 #ifdef PLACESITEMMODEL_DEBUG
205 kDebug() << "Changed visibility of hidden items";
210 bool PlacesItemModel::hiddenItemsShown() const
212 return m_hiddenItemsShown
;
215 int PlacesItemModel::closestItem(const KUrl
& url
) const
220 for (int i
= 0; i
< count(); ++i
) {
221 const KUrl itemUrl
= placesItem(i
)->url();
222 if (itemUrl
.isParentOf(url
)) {
223 const int length
= itemUrl
.prettyUrl().length();
224 if (length
> maxLength
) {
234 void PlacesItemModel::appendItemToGroup(PlacesItem
* item
)
241 while (i
< count() && placesItem(i
)->group() != item
->group()) {
245 bool inserted
= false;
246 while (!inserted
&& i
< count()) {
247 if (placesItem(i
)->group() != item
->group()) {
260 QAction
* PlacesItemModel::ejectAction(int index
) const
262 const PlacesItem
* item
= placesItem(index
);
263 if (item
&& item
->device().is
<Solid::OpticalDisc
>()) {
264 return new QAction(KIcon("media-eject"), i18nc("@item", "Eject '%1'", item
->text()), 0);
270 QAction
* PlacesItemModel::teardownAction(int index
) const
272 const PlacesItem
* item
= placesItem(index
);
277 Solid::Device device
= item
->device();
278 const bool providesTearDown
= device
.is
<Solid::StorageAccess
>() &&
279 device
.as
<Solid::StorageAccess
>()->isAccessible();
280 if (!providesTearDown
) {
284 Solid::StorageDrive
* drive
= device
.as
<Solid::StorageDrive
>();
286 drive
= device
.parent().as
<Solid::StorageDrive
>();
289 bool hotPluggable
= false;
290 bool removable
= false;
292 hotPluggable
= drive
->isHotpluggable();
293 removable
= drive
->isRemovable();
298 const QString label
= item
->text();
299 if (device
.is
<Solid::OpticalDisc
>()) {
300 text
= i18nc("@item", "Release '%1'", label
);
301 } else if (removable
|| hotPluggable
) {
302 text
= i18nc("@item", "Safely Remove '%1'", label
);
303 iconName
= "media-eject";
305 text
= i18nc("@item", "Unmount '%1'", label
);
306 iconName
= "media-eject";
309 if (iconName
.isEmpty()) {
310 return new QAction(text
, 0);
313 return new QAction(KIcon(iconName
), text
, 0);
316 void PlacesItemModel::requestEject(int index
)
318 const PlacesItem
* item
= placesItem(index
);
320 Solid::OpticalDrive
* drive
= item
->device().parent().as
<Solid::OpticalDrive
>();
322 connect(drive
, SIGNAL(ejectDone(Solid::ErrorType
,QVariant
,QString
)),
323 this, SLOT(slotStorageTeardownDone(Solid::ErrorType
,QVariant
)));
326 const QString label
= item
->text();
327 const QString message
= i18nc("@info", "The device '%1' is not a disk and cannot be ejected.", label
);
328 emit
errorMessage(message
);
333 void PlacesItemModel::requestTeardown(int index
)
335 const PlacesItem
* item
= placesItem(index
);
337 Solid::StorageAccess
* access
= item
->device().as
<Solid::StorageAccess
>();
339 connect(access
, SIGNAL(teardownDone(Solid::ErrorType
,QVariant
,QString
)),
340 this, SLOT(slotStorageTeardownDone(Solid::ErrorType
,QVariant
)));
346 bool PlacesItemModel::storageSetupNeeded(int index
) const
348 const PlacesItem
* item
= placesItem(index
);
349 return item
? item
->storageSetupNeeded() : false;
352 void PlacesItemModel::requestStorageSetup(int index
)
354 const PlacesItem
* item
= placesItem(index
);
359 Solid::Device device
= item
->device();
360 const bool setup
= device
.is
<Solid::StorageAccess
>()
361 && !m_storageSetupInProgress
.contains(device
.as
<Solid::StorageAccess
>())
362 && !device
.as
<Solid::StorageAccess
>()->isAccessible();
364 Solid::StorageAccess
* access
= device
.as
<Solid::StorageAccess
>();
366 m_storageSetupInProgress
[access
] = index
;
368 connect(access
, SIGNAL(setupDone(Solid::ErrorType
,QVariant
,QString
)),
369 this, SLOT(slotStorageSetupDone(Solid::ErrorType
,QVariant
,QString
)));
375 QMimeData
* PlacesItemModel::createMimeData(const QSet
<int>& indexes
) const
380 QDataStream
stream(&itemData
, QIODevice::WriteOnly
);
382 foreach (int index
, indexes
) {
383 const KUrl itemUrl
= placesItem(index
)->url();
384 if (itemUrl
.isValid()) {
390 QMimeData
* mimeData
= new QMimeData();
391 if (!urls
.isEmpty()) {
392 urls
.populateMimeData(mimeData
);
394 mimeData
->setData(internalMimeType(), itemData
);
399 bool PlacesItemModel::supportsDropping(int index
) const
401 return index
>= 0 && index
< count();
404 void PlacesItemModel::dropMimeDataBefore(int index
, const QMimeData
* mimeData
)
406 if (mimeData
->hasFormat(internalMimeType())) {
407 // The item has been moved inside the view
408 QByteArray itemData
= mimeData
->data(internalMimeType());
409 QDataStream
stream(&itemData
, QIODevice::ReadOnly
);
412 if (oldIndex
== index
|| oldIndex
== index
- 1) {
413 // No moving has been done
417 PlacesItem
* oldItem
= placesItem(oldIndex
);
422 PlacesItem
* newItem
= new PlacesItem(oldItem
->bookmark());
423 removeItem(oldIndex
);
425 if (oldIndex
< index
) {
429 const int dropIndex
= groupedDropIndex(index
, newItem
);
430 insertItem(dropIndex
, newItem
);
431 } else if (mimeData
->hasFormat("text/uri-list")) {
432 // One or more items must be added to the model
433 const KUrl::List urls
= KUrl::List::fromMimeData(mimeData
);
434 for (int i
= urls
.count() - 1; i
>= 0; --i
) {
435 const KUrl
& url
= urls
[i
];
437 QString text
= url
.fileName();
438 if (text
.isEmpty()) {
442 PlacesItem
* newItem
= createPlacesItem(text
, url
);
443 const int dropIndex
= groupedDropIndex(index
, newItem
);
444 insertItem(dropIndex
, newItem
);
449 KUrl
PlacesItemModel::convertedUrl(const KUrl
& url
)
452 if (url
.protocol() == QLatin1String("timeline")) {
453 newUrl
= createTimelineUrl(url
);
454 } else if (url
.protocol() == QLatin1String("search")) {
455 newUrl
= createSearchUrl(url
);
461 void PlacesItemModel::onItemInserted(int index
)
463 const PlacesItem
* insertedItem
= placesItem(index
);
465 // Take care to apply the PlacesItemModel-order of the inserted item
466 // also to the bookmark-manager.
467 const KBookmark insertedBookmark
= insertedItem
->bookmark();
469 const PlacesItem
* previousItem
= placesItem(index
- 1);
470 KBookmark previousBookmark
;
472 previousBookmark
= previousItem
->bookmark();
475 m_bookmarkManager
->root().moveBookmark(insertedBookmark
, previousBookmark
);
478 if (index
== count() - 1) {
479 // The item has been appended as last item to the list. In this
480 // case assure that it is also appended after the hidden items and
481 // not before (like done otherwise).
482 m_bookmarkedItems
.append(0);
486 int bookmarkIndex
= 0;
487 while (bookmarkIndex
< m_bookmarkedItems
.count()) {
488 if (!m_bookmarkedItems
[bookmarkIndex
]) {
490 if (modelIndex
+ 1 == index
) {
496 m_bookmarkedItems
.insert(bookmarkIndex
, 0);
499 triggerBookmarksSaving();
501 #ifdef PLACESITEMMODEL_DEBUG
502 kDebug() << "Inserted item" << index
;
507 void PlacesItemModel::onItemRemoved(int index
, KStandardItem
* removedItem
)
509 PlacesItem
* placesItem
= dynamic_cast<PlacesItem
*>(removedItem
);
511 const KBookmark bookmark
= placesItem
->bookmark();
512 m_bookmarkManager
->root().deleteBookmark(bookmark
);
515 const int boomarkIndex
= bookmarkIndex(index
);
516 Q_ASSERT(!m_bookmarkedItems
[boomarkIndex
]);
517 m_bookmarkedItems
.removeAt(boomarkIndex
);
519 triggerBookmarksSaving();
521 #ifdef PLACESITEMMODEL_DEBUG
522 kDebug() << "Removed item" << index
;
527 void PlacesItemModel::onItemChanged(int index
, const QSet
<QByteArray
>& changedRoles
)
529 const PlacesItem
* changedItem
= placesItem(index
);
531 // Take care to apply the PlacesItemModel-order of the changed item
532 // also to the bookmark-manager.
533 const KBookmark insertedBookmark
= changedItem
->bookmark();
535 const PlacesItem
* previousItem
= placesItem(index
- 1);
536 KBookmark previousBookmark
;
538 previousBookmark
= previousItem
->bookmark();
541 m_bookmarkManager
->root().moveBookmark(insertedBookmark
, previousBookmark
);
544 if (changedRoles
.contains("isHidden")) {
545 if (!m_hiddenItemsShown
&& changedItem
->isHidden()) {
546 m_hiddenItemToRemove
= index
;
547 QTimer::singleShot(0, this, SLOT(hideItem()));
551 triggerBookmarksSaving();
554 void PlacesItemModel::slotDeviceAdded(const QString
& udi
)
556 const Solid::Device
device(udi
);
557 if (m_predicate
.matches(device
)) {
558 m_availableDevices
<< udi
;
559 const KBookmark bookmark
= PlacesItem::createDeviceBookmark(m_bookmarkManager
, udi
);
560 appendItem(new PlacesItem(bookmark
));
564 void PlacesItemModel::slotDeviceRemoved(const QString
& udi
)
566 if (!m_availableDevices
.contains(udi
)) {
570 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
571 PlacesItem
* item
= m_bookmarkedItems
[i
];
572 if (item
&& item
->udi() == udi
) {
573 m_bookmarkedItems
.removeAt(i
);
579 for (int i
= 0; i
< count(); ++i
) {
580 if (placesItem(i
)->udi() == udi
) {
587 void PlacesItemModel::slotStorageTeardownDone(Solid::ErrorType error
, const QVariant
& errorData
)
589 if (error
&& errorData
.isValid()) {
590 emit
errorMessage(errorData
.toString());
594 void PlacesItemModel::slotStorageSetupDone(Solid::ErrorType error
,
595 const QVariant
& errorData
,
600 const int index
= m_storageSetupInProgress
.take(sender());
601 const PlacesItem
* item
= placesItem(index
);
607 // TODO: Request message-freeze exception
608 if (errorData
.isValid()) {
609 // emit errorMessage(i18nc("@info", "An error occurred while accessing '%1', the system responded: %2",
611 // errorData.toString()));
612 emit
errorMessage(QString("An error occurred while accessing '%1', the system responded: %2")
613 .arg(item
->text()).arg(errorData
.toString()));
615 // emit errorMessage(i18nc("@info", "An error occurred while accessing '%1'",
617 emit
errorMessage(QString("An error occurred while accessing '%1'").arg(item
->text()));
619 emit
storageSetupDone(index
, false);
621 emit
storageSetupDone(index
, true);
625 void PlacesItemModel::hideItem()
627 hideItem(m_hiddenItemToRemove
);
628 m_hiddenItemToRemove
= -1;
631 void PlacesItemModel::updateBookmarks()
633 // Verify whether new bookmarks have been added or existing
634 // bookmarks have been changed.
635 KBookmarkGroup root
= m_bookmarkManager
->root();
636 KBookmark newBookmark
= root
.first();
637 while (!newBookmark
.isNull()) {
638 if (acceptBookmark(newBookmark
, m_availableDevices
)) {
641 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
642 PlacesItem
* item
= m_bookmarkedItems
[i
];
644 item
= placesItem(modelIndex
);
648 const KBookmark oldBookmark
= item
->bookmark();
649 if (equalBookmarkIdentifiers(newBookmark
, oldBookmark
)) {
650 // The bookmark has been found in the model or as
651 // a hidden item. The content of the bookmark might
652 // have been changed, so an update is done.
654 if (newBookmark
.metaDataItem("UDI").isEmpty()) {
655 item
->setBookmark(newBookmark
);
662 const QString udi
= newBookmark
.metaDataItem("UDI");
666 * Only add a new places item, if the item text is not empty
667 * and if the device is available. Fixes the strange behaviour -
668 * add a places item without text in the Places section - when you
669 * remove a device (e.g. a usb stick) without unmounting.
671 if (udi
.isEmpty() || Solid::Device(udi
).isValid()) {
672 PlacesItem
* item
= new PlacesItem(newBookmark
);
673 if (item
->isHidden() && !m_hiddenItemsShown
) {
674 m_bookmarkedItems
.append(item
);
676 appendItemToGroup(item
);
682 newBookmark
= root
.next(newBookmark
);
685 // Remove items that are not part of the bookmark-manager anymore
687 for (int i
= m_bookmarkedItems
.count() - 1; i
>= 0; --i
) {
688 PlacesItem
* item
= m_bookmarkedItems
[i
];
689 const bool itemIsPartOfModel
= (item
== 0);
690 if (itemIsPartOfModel
) {
691 item
= placesItem(modelIndex
);
694 bool hasBeenRemoved
= true;
695 const KBookmark oldBookmark
= item
->bookmark();
696 KBookmark newBookmark
= root
.first();
697 while (!newBookmark
.isNull()) {
698 if (equalBookmarkIdentifiers(newBookmark
, oldBookmark
)) {
699 hasBeenRemoved
= false;
702 newBookmark
= root
.next(newBookmark
);
705 if (hasBeenRemoved
) {
706 if (m_bookmarkedItems
[i
]) {
707 delete m_bookmarkedItems
[i
];
708 m_bookmarkedItems
.removeAt(i
);
710 removeItem(modelIndex
);
715 if (itemIsPartOfModel
) {
721 void PlacesItemModel::saveBookmarks()
723 m_bookmarkManager
->emitChanged(m_bookmarkManager
->root());
726 void PlacesItemModel::loadBookmarks()
728 KBookmarkGroup root
= m_bookmarkManager
->root();
729 KBookmark bookmark
= root
.first();
730 QSet
<QString
> devices
= m_availableDevices
;
732 QSet
<KUrl
> missingSystemBookmarks
;
733 foreach (const SystemBookmarkData
& data
, m_systemBookmarks
) {
734 missingSystemBookmarks
.insert(data
.url
);
737 // The bookmarks might have a mixed order of places, devices and search-groups due
738 // to the compatibility with the KFilePlacesPanel. In Dolphin's places panel the
739 // items should always be collected in one group so the items are collected first
740 // in separate lists before inserting them.
741 QList
<PlacesItem
*> placesItems
;
742 QList
<PlacesItem
*> recentlyAccessedItems
;
743 QList
<PlacesItem
*> searchForItems
;
744 QList
<PlacesItem
*> devicesItems
;
746 while (!bookmark
.isNull()) {
747 if (acceptBookmark(bookmark
, devices
)) {
748 PlacesItem
* item
= new PlacesItem(bookmark
);
749 if (item
->groupType() == PlacesItem::DevicesType
) {
750 devices
.remove(item
->udi());
751 devicesItems
.append(item
);
753 const KUrl url
= bookmark
.url();
754 if (missingSystemBookmarks
.contains(url
)) {
755 missingSystemBookmarks
.remove(url
);
757 // Try to retranslate the text of system bookmarks to have translated
758 // items when changing the language. In case if the user has applied a custom
759 // text, the retranslation will fail and the users custom text is still used.
760 // It is important to use "KFile System Bookmarks" as context (see
761 // createSystemBookmarks()).
762 item
->setText(i18nc("KFile System Bookmarks", bookmark
.text().toUtf8().data()));
763 item
->setSystemItem(true);
766 switch (item
->groupType()) {
767 case PlacesItem::PlacesType
: placesItems
.append(item
); break;
768 case PlacesItem::RecentlyAccessedType
: recentlyAccessedItems
.append(item
); break;
769 case PlacesItem::SearchForType
: searchForItems
.append(item
); break;
770 case PlacesItem::DevicesType
:
771 default: Q_ASSERT(false); break;
776 bookmark
= root
.next(bookmark
);
779 if (!missingSystemBookmarks
.isEmpty()) {
780 // The current bookmarks don't contain all system-bookmarks. Add the missing
782 foreach (const SystemBookmarkData
& data
, m_systemBookmarks
) {
783 if (missingSystemBookmarks
.contains(data
.url
)) {
784 PlacesItem
* item
= createSystemPlacesItem(data
);
785 switch (item
->groupType()) {
786 case PlacesItem::PlacesType
: placesItems
.append(item
); break;
787 case PlacesItem::RecentlyAccessedType
: recentlyAccessedItems
.append(item
); break;
788 case PlacesItem::SearchForType
: searchForItems
.append(item
); break;
789 case PlacesItem::DevicesType
:
790 default: Q_ASSERT(false); break;
796 // Create items for devices that have not been stored as bookmark yet
797 foreach (const QString
& udi
, devices
) {
798 const KBookmark bookmark
= PlacesItem::createDeviceBookmark(m_bookmarkManager
, udi
);
799 devicesItems
.append(new PlacesItem(bookmark
));
802 QList
<PlacesItem
*> items
;
803 items
.append(placesItems
);
804 items
.append(recentlyAccessedItems
);
805 items
.append(searchForItems
);
806 items
.append(devicesItems
);
808 foreach (PlacesItem
* item
, items
) {
809 if (!m_hiddenItemsShown
&& item
->isHidden()) {
810 m_bookmarkedItems
.append(item
);
816 #ifdef PLACESITEMMODEL_DEBUG
817 kDebug() << "Loaded bookmarks";
822 bool PlacesItemModel::acceptBookmark(const KBookmark
& bookmark
,
823 const QSet
<QString
>& availableDevices
) const
825 const QString udi
= bookmark
.metaDataItem("UDI");
826 const KUrl url
= bookmark
.url();
827 const QString appName
= bookmark
.metaDataItem("OnlyInApp");
828 const bool deviceAvailable
= availableDevices
.contains(udi
);
830 const bool allowedHere
= (appName
.isEmpty()
831 || appName
== KGlobal::mainComponent().componentName()
832 || appName
== KGlobal::mainComponent().componentName() + AppNamePrefix
)
833 && (m_fileIndexingEnabled
|| (url
.protocol() != QLatin1String("timeline") &&
834 url
.protocol() != QLatin1String("search")));
836 return (udi
.isEmpty() && allowedHere
) || deviceAvailable
;
839 PlacesItem
* PlacesItemModel::createSystemPlacesItem(const SystemBookmarkData
& data
)
841 KBookmark bookmark
= PlacesItem::createBookmark(m_bookmarkManager
,
846 const QString protocol
= data
.url
.protocol();
847 if (protocol
== QLatin1String("timeline") || protocol
== QLatin1String("search")) {
848 // As long as the KFilePlacesView from kdelibs is available, the system-bookmarks
849 // for "Recently Accessed" and "Search For" should be a setting available only
850 // in the Places Panel (see description of AppNamePrefix for more details).
851 const QString appName
= KGlobal::mainComponent().componentName() + AppNamePrefix
;
852 bookmark
.setMetaDataItem("OnlyInApp", appName
);
855 PlacesItem
* item
= new PlacesItem(bookmark
);
856 item
->setSystemItem(true);
858 // Create default view-properties for all "Search For" and "Recently Accessed" bookmarks
859 // in case if the user has not already created custom view-properties for a corresponding
861 const bool createDefaultViewProperties
= (item
->groupType() == PlacesItem::SearchForType
||
862 item
->groupType() == PlacesItem::RecentlyAccessedType
) &&
863 !GeneralSettings::self()->globalViewProps();
864 if (createDefaultViewProperties
) {
865 ViewProperties
props(convertedUrl(data
.url
));
866 if (!props
.exist()) {
867 const QString path
= data
.url
.path();
868 if (path
== QLatin1String("/documents")) {
869 props
.setViewMode(DolphinView::DetailsView
);
870 props
.setPreviewsShown(false);
871 props
.setVisibleRoles(QList
<QByteArray
>() << "text" << "path");
872 } else if (path
== QLatin1String("/images")) {
873 props
.setViewMode(DolphinView::IconsView
);
874 props
.setPreviewsShown(true);
875 props
.setVisibleRoles(QList
<QByteArray
>() << "text" << "imageSize");
876 } else if (path
== QLatin1String("/audio")) {
877 props
.setViewMode(DolphinView::DetailsView
);
878 props
.setPreviewsShown(false);
879 props
.setVisibleRoles(QList
<QByteArray
>() << "text" << "artist" << "album");
880 } else if (path
== QLatin1String("/videos")) {
881 props
.setViewMode(DolphinView::IconsView
);
882 props
.setPreviewsShown(true);
883 props
.setVisibleRoles(QList
<QByteArray
>() << "text");
884 } else if (data
.url
.protocol() == "timeline") {
885 props
.setViewMode(DolphinView::DetailsView
);
886 props
.setVisibleRoles(QList
<QByteArray
>() << "text" << "date");
894 void PlacesItemModel::createSystemBookmarks()
896 Q_ASSERT(m_systemBookmarks
.isEmpty());
897 Q_ASSERT(m_systemBookmarksIndexes
.isEmpty());
899 const QString timeLineIcon
= "chronometer";
901 // Note: The context of the I18N_NOOP2 must be "KFile System Bookmarks". The real
902 // i18nc call is done after reading the bookmark. The reason why the i18nc call is not
903 // done here is because otherwise switching the language would not result in retranslating the
905 m_systemBookmarks
.append(SystemBookmarkData(KUrl(KUser().homeDir()),
907 I18N_NOOP2("KFile System Bookmarks", "Home")));
908 m_systemBookmarks
.append(SystemBookmarkData(KUrl("remote:/"),
910 I18N_NOOP2("KFile System Bookmarks", "Network")));
911 m_systemBookmarks
.append(SystemBookmarkData(KUrl("/"),
913 I18N_NOOP2("KFile System Bookmarks", "Root")));
914 m_systemBookmarks
.append(SystemBookmarkData(KUrl("trash:/"),
916 I18N_NOOP2("KFile System Bookmarks", "Trash")));
918 if (m_fileIndexingEnabled
) {
919 m_systemBookmarks
.append(SystemBookmarkData(KUrl("timeline:/today"),
921 I18N_NOOP2("KFile System Bookmarks", "Today")));
922 m_systemBookmarks
.append(SystemBookmarkData(KUrl("timeline:/yesterday"),
924 I18N_NOOP2("KFile System Bookmarks", "Yesterday")));
925 m_systemBookmarks
.append(SystemBookmarkData(KUrl("timeline:/thismonth"),
927 I18N_NOOP2("KFile System Bookmarks", "This Month")));
928 m_systemBookmarks
.append(SystemBookmarkData(KUrl("timeline:/lastmonth"),
930 I18N_NOOP2("KFile System Bookmarks", "Last Month")));
931 m_systemBookmarks
.append(SystemBookmarkData(KUrl("search:/documents"),
933 I18N_NOOP2("KFile System Bookmarks", "Documents")));
934 m_systemBookmarks
.append(SystemBookmarkData(KUrl("search:/images"),
936 I18N_NOOP2("KFile System Bookmarks", "Images")));
937 m_systemBookmarks
.append(SystemBookmarkData(KUrl("search:/audio"),
939 I18N_NOOP2("KFile System Bookmarks", "Audio Files")));
940 m_systemBookmarks
.append(SystemBookmarkData(KUrl("search:/videos"),
942 I18N_NOOP2("KFile System Bookmarks", "Videos")));
945 for (int i
= 0; i
< m_systemBookmarks
.count(); ++i
) {
946 m_systemBookmarksIndexes
.insert(m_systemBookmarks
[i
].url
, i
);
950 void PlacesItemModel::initializeAvailableDevices()
952 m_predicate
= Solid::Predicate::fromString(
953 "[[[[ StorageVolume.ignored == false AND [ StorageVolume.usage == 'FileSystem' OR StorageVolume.usage == 'Encrypted' ]]"
955 "[ IS StorageAccess AND StorageDrive.driveType == 'Floppy' ]]"
957 "OpticalDisc.availableContent & 'Audio' ]"
959 "StorageAccess.ignored == false ]");
960 Q_ASSERT(m_predicate
.isValid());
962 Solid::DeviceNotifier
* notifier
= Solid::DeviceNotifier::instance();
963 connect(notifier
, SIGNAL(deviceAdded(QString
)), this, SLOT(slotDeviceAdded(QString
)));
964 connect(notifier
, SIGNAL(deviceRemoved(QString
)), this, SLOT(slotDeviceRemoved(QString
)));
966 const QList
<Solid::Device
>& deviceList
= Solid::Device::listFromQuery(m_predicate
);
967 foreach (const Solid::Device
& device
, deviceList
) {
968 m_availableDevices
<< device
.udi();
972 int PlacesItemModel::bookmarkIndex(int index
) const
974 int bookmarkIndex
= 0;
976 while (bookmarkIndex
< m_bookmarkedItems
.count()) {
977 if (!m_bookmarkedItems
[bookmarkIndex
]) {
978 if (modelIndex
== index
) {
986 return bookmarkIndex
>= m_bookmarkedItems
.count() ? -1 : bookmarkIndex
;
989 void PlacesItemModel::hideItem(int index
)
991 PlacesItem
* shownItem
= placesItem(index
);
996 shownItem
->setHidden(true);
997 if (m_hiddenItemsShown
) {
998 // Removing items from the model is not allowed if all hidden
999 // items should be shown.
1003 const int newIndex
= bookmarkIndex(index
);
1004 if (newIndex
>= 0) {
1005 const KBookmark hiddenBookmark
= shownItem
->bookmark();
1006 PlacesItem
* hiddenItem
= new PlacesItem(hiddenBookmark
);
1008 const PlacesItem
* previousItem
= placesItem(index
- 1);
1009 KBookmark previousBookmark
;
1011 previousBookmark
= previousItem
->bookmark();
1014 const bool updateBookmark
= (m_bookmarkManager
->root().indexOf(hiddenBookmark
) >= 0);
1017 if (updateBookmark
) {
1018 // removeItem() also removed the bookmark from m_bookmarkManager in
1019 // PlacesItemModel::onItemRemoved(). However for hidden items the
1020 // bookmark should still be remembered, so readd it again:
1021 m_bookmarkManager
->root().addBookmark(hiddenBookmark
);
1022 m_bookmarkManager
->root().moveBookmark(hiddenBookmark
, previousBookmark
);
1023 triggerBookmarksSaving();
1026 m_bookmarkedItems
.insert(newIndex
, hiddenItem
);
1030 void PlacesItemModel::triggerBookmarksSaving()
1032 if (m_saveBookmarksTimer
) {
1033 m_saveBookmarksTimer
->start();
1037 QString
PlacesItemModel::internalMimeType() const
1039 return "application/x-dolphinplacesmodel-" +
1040 QString::number((qptrdiff
)this);
1043 int PlacesItemModel::groupedDropIndex(int index
, const PlacesItem
* item
) const
1047 int dropIndex
= index
;
1048 const PlacesItem::GroupType type
= item
->groupType();
1050 const int itemCount
= count();
1052 dropIndex
= itemCount
;
1055 // Search nearest previous item with the same group
1056 int previousIndex
= -1;
1057 for (int i
= dropIndex
- 1; i
>= 0; --i
) {
1058 if (placesItem(i
)->groupType() == type
) {
1064 // Search nearest next item with the same group
1066 for (int i
= dropIndex
; i
< count(); ++i
) {
1067 if (placesItem(i
)->groupType() == type
) {
1073 // Adjust the drop-index to be inserted to the
1074 // nearest item with the same group.
1075 if (previousIndex
>= 0 && nextIndex
>= 0) {
1076 dropIndex
= (dropIndex
- previousIndex
< nextIndex
- dropIndex
) ?
1077 previousIndex
+ 1 : nextIndex
;
1078 } else if (previousIndex
>= 0) {
1079 dropIndex
= previousIndex
+ 1;
1080 } else if (nextIndex
>= 0) {
1081 dropIndex
= nextIndex
;
1087 bool PlacesItemModel::equalBookmarkIdentifiers(const KBookmark
& b1
, const KBookmark
& b2
)
1089 const QString udi1
= b1
.metaDataItem("UDI");
1090 const QString udi2
= b2
.metaDataItem("UDI");
1091 if (!udi1
.isEmpty() && !udi2
.isEmpty()) {
1092 return udi1
== udi2
;
1094 return b1
.metaDataItem("ID") == b2
.metaDataItem("ID");
1098 KUrl
PlacesItemModel::createTimelineUrl(const KUrl
& url
)
1100 // TODO: Clarify with the Nepomuk-team whether it makes sense
1101 // provide default-timeline-URLs like 'yesterday', 'this month'
1102 // and 'last month'.
1105 const QString path
= url
.pathOrUrl();
1106 if (path
.endsWith(QLatin1String("yesterday"))) {
1107 const QDate date
= QDate::currentDate().addDays(-1);
1108 const int year
= date
.year();
1109 const int month
= date
.month();
1110 const int day
= date
.day();
1111 timelineUrl
= "timeline:/" + timelineDateString(year
, month
) +
1112 '/' + timelineDateString(year
, month
, day
);
1113 } else if (path
.endsWith(QLatin1String("thismonth"))) {
1114 const QDate date
= QDate::currentDate();
1115 timelineUrl
= "timeline:/" + timelineDateString(date
.year(), date
.month());
1116 } else if (path
.endsWith(QLatin1String("lastmonth"))) {
1117 const QDate date
= QDate::currentDate().addMonths(-1);
1118 timelineUrl
= "timeline:/" + timelineDateString(date
.year(), date
.month());
1120 Q_ASSERT(path
.endsWith(QLatin1String("today")));
1127 QString
PlacesItemModel::timelineDateString(int year
, int month
, int day
)
1129 QString date
= QString::number(year
) + '-';
1133 date
+= QString::number(month
);
1140 date
+= QString::number(day
);
1146 KUrl
PlacesItemModel::createSearchUrl(const KUrl
& url
)
1151 const QString path
= url
.pathOrUrl();
1152 if (path
.endsWith(QLatin1String("documents"))) {
1153 searchUrl
= searchUrlForTerm(Nepomuk2::Query::ResourceTypeTerm(Nepomuk2::Vocabulary::NFO::Document()));
1154 } else if (path
.endsWith(QLatin1String("images"))) {
1155 searchUrl
= searchUrlForTerm(Nepomuk2::Query::ResourceTypeTerm(Nepomuk2::Vocabulary::NFO::Image()));
1156 } else if (path
.endsWith(QLatin1String("audio"))) {
1157 searchUrl
= searchUrlForTerm(Nepomuk2::Query::ComparisonTerm(Nepomuk2::Vocabulary::NIE::mimeType(),
1158 Nepomuk2::Query::LiteralTerm("audio")));
1159 } else if (path
.endsWith(QLatin1String("videos"))) {
1160 searchUrl
= searchUrlForTerm(Nepomuk2::Query::ComparisonTerm(Nepomuk2::Vocabulary::NIE::mimeType(),
1161 Nepomuk2::Query::LiteralTerm("video")));
1173 KUrl
PlacesItemModel::searchUrlForTerm(const Nepomuk2::Query::Term
& term
)
1175 const Nepomuk2::Query::FileQuery
query(term
);
1176 return query
.toSearchUrl();
1180 #ifdef PLACESITEMMODEL_DEBUG
1181 void PlacesItemModel::showModelState()
1183 kDebug() << "=================================";
1184 kDebug() << "Model:";
1185 kDebug() << "hidden-index model-index text";
1187 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
1188 if (m_bookmarkedItems
[i
]) {
1189 kDebug() << i
<< "(Hidden) " << " " << m_bookmarkedItems
[i
]->dataValue("text").toString();
1191 if (item(modelIndex
)) {
1192 kDebug() << i
<< " " << modelIndex
<< " " << item(modelIndex
)->dataValue("text").toString();
1194 kDebug() << i
<< " " << modelIndex
<< " " << "(not available yet)";
1201 kDebug() << "Bookmarks:";
1203 int bookmarkIndex
= 0;
1204 KBookmarkGroup root
= m_bookmarkManager
->root();
1205 KBookmark bookmark
= root
.first();
1206 while (!bookmark
.isNull()) {
1207 const QString udi
= bookmark
.metaDataItem("UDI");
1208 const QString text
= udi
.isEmpty() ? bookmark
.text() : udi
;
1209 if (bookmark
.metaDataItem("IsHidden") == QLatin1String("true")) {
1210 kDebug() << bookmarkIndex
<< "(Hidden)" << text
;
1212 kDebug() << bookmarkIndex
<< " " << text
;
1215 bookmark
= root
.next(bookmark
);
1221 #include "placesitemmodel.moc"