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 <Nepomuk/ResourceManager>
55 #include <Nepomuk/Query/ComparisonTerm>
56 #include <Nepomuk/Query/LiteralTerm>
57 #include <Nepomuk/Query/Query>
58 #include <Nepomuk/Query/ResourceTypeTerm>
59 #include <Nepomuk/Vocabulary/NFO>
60 #include <Nepomuk/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 (Nepomuk::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 PlacesItem
* item
= new PlacesItem(newBookmark
);
663 if (item
->isHidden() && !m_hiddenItemsShown
) {
664 m_bookmarkedItems
.append(item
);
666 appendItemToGroup(item
);
671 newBookmark
= root
.next(newBookmark
);
674 // Remove items that are not part of the bookmark-manager anymore
676 for (int i
= m_bookmarkedItems
.count() - 1; i
>= 0; --i
) {
677 PlacesItem
* item
= m_bookmarkedItems
[i
];
678 const bool itemIsPartOfModel
= (item
== 0);
679 if (itemIsPartOfModel
) {
680 item
= placesItem(modelIndex
);
683 bool hasBeenRemoved
= true;
684 const KBookmark oldBookmark
= item
->bookmark();
685 KBookmark newBookmark
= root
.first();
686 while (!newBookmark
.isNull()) {
687 if (equalBookmarkIdentifiers(newBookmark
, oldBookmark
)) {
688 hasBeenRemoved
= false;
691 newBookmark
= root
.next(newBookmark
);
694 if (hasBeenRemoved
) {
695 if (m_bookmarkedItems
[i
]) {
696 delete m_bookmarkedItems
[i
];
697 m_bookmarkedItems
.removeAt(i
);
699 removeItem(modelIndex
);
704 if (itemIsPartOfModel
) {
710 void PlacesItemModel::saveBookmarks()
712 m_bookmarkManager
->emitChanged(m_bookmarkManager
->root());
715 void PlacesItemModel::loadBookmarks()
717 KBookmarkGroup root
= m_bookmarkManager
->root();
718 KBookmark bookmark
= root
.first();
719 QSet
<QString
> devices
= m_availableDevices
;
721 QSet
<KUrl
> missingSystemBookmarks
;
722 foreach (const SystemBookmarkData
& data
, m_systemBookmarks
) {
723 missingSystemBookmarks
.insert(data
.url
);
726 // The bookmarks might have a mixed order of places, devices and search-groups due
727 // to the compatibility with the KFilePlacesPanel. In Dolphin's places panel the
728 // items should always be collected in one group so the items are collected first
729 // in separate lists before inserting them.
730 QList
<PlacesItem
*> placesItems
;
731 QList
<PlacesItem
*> recentlyAccessedItems
;
732 QList
<PlacesItem
*> searchForItems
;
733 QList
<PlacesItem
*> devicesItems
;
735 while (!bookmark
.isNull()) {
736 if (acceptBookmark(bookmark
, devices
)) {
737 PlacesItem
* item
= new PlacesItem(bookmark
);
738 if (item
->groupType() == PlacesItem::DevicesType
) {
739 devices
.remove(item
->udi());
740 devicesItems
.append(item
);
742 const KUrl url
= bookmark
.url();
743 if (missingSystemBookmarks
.contains(url
)) {
744 missingSystemBookmarks
.remove(url
);
746 // Try to retranslate the text of system bookmarks to have translated
747 // items when changing the language. In case if the user has applied a custom
748 // text, the retranslation will fail and the users custom text is still used.
749 // It is important to use "KFile System Bookmarks" as context (see
750 // createSystemBookmarks()).
751 item
->setText(i18nc("KFile System Bookmarks", bookmark
.text().toUtf8().data()));
752 item
->setSystemItem(true);
755 switch (item
->groupType()) {
756 case PlacesItem::PlacesType
: placesItems
.append(item
); break;
757 case PlacesItem::RecentlyAccessedType
: recentlyAccessedItems
.append(item
); break;
758 case PlacesItem::SearchForType
: searchForItems
.append(item
); break;
759 case PlacesItem::DevicesType
:
760 default: Q_ASSERT(false); break;
765 bookmark
= root
.next(bookmark
);
768 if (!missingSystemBookmarks
.isEmpty()) {
769 // The current bookmarks don't contain all system-bookmarks. Add the missing
771 foreach (const SystemBookmarkData
& data
, m_systemBookmarks
) {
772 if (missingSystemBookmarks
.contains(data
.url
)) {
773 PlacesItem
* item
= createSystemPlacesItem(data
);
774 switch (item
->groupType()) {
775 case PlacesItem::PlacesType
: placesItems
.append(item
); break;
776 case PlacesItem::RecentlyAccessedType
: recentlyAccessedItems
.append(item
); break;
777 case PlacesItem::SearchForType
: searchForItems
.append(item
); break;
778 case PlacesItem::DevicesType
:
779 default: Q_ASSERT(false); break;
785 // Create items for devices that have not been stored as bookmark yet
786 foreach (const QString
& udi
, devices
) {
787 const KBookmark bookmark
= PlacesItem::createDeviceBookmark(m_bookmarkManager
, udi
);
788 devicesItems
.append(new PlacesItem(bookmark
));
791 QList
<PlacesItem
*> items
;
792 items
.append(placesItems
);
793 items
.append(recentlyAccessedItems
);
794 items
.append(searchForItems
);
795 items
.append(devicesItems
);
797 foreach (PlacesItem
* item
, items
) {
798 if (!m_hiddenItemsShown
&& item
->isHidden()) {
799 m_bookmarkedItems
.append(item
);
805 #ifdef PLACESITEMMODEL_DEBUG
806 kDebug() << "Loaded bookmarks";
811 bool PlacesItemModel::acceptBookmark(const KBookmark
& bookmark
,
812 const QSet
<QString
>& availableDevices
) const
814 const QString udi
= bookmark
.metaDataItem("UDI");
815 const KUrl url
= bookmark
.url();
816 const QString appName
= bookmark
.metaDataItem("OnlyInApp");
817 const bool deviceAvailable
= availableDevices
.contains(udi
);
819 const bool allowedHere
= (appName
.isEmpty()
820 || appName
== KGlobal::mainComponent().componentName()
821 || appName
== KGlobal::mainComponent().componentName() + AppNamePrefix
)
822 && (m_fileIndexingEnabled
|| (url
.protocol() != QLatin1String("timeline") &&
823 url
.protocol() != QLatin1String("search")));
825 return (udi
.isEmpty() && allowedHere
) || deviceAvailable
;
828 PlacesItem
* PlacesItemModel::createSystemPlacesItem(const SystemBookmarkData
& data
)
830 KBookmark bookmark
= PlacesItem::createBookmark(m_bookmarkManager
,
835 const QString protocol
= data
.url
.protocol();
836 if (protocol
== QLatin1String("timeline") || protocol
== QLatin1String("search")) {
837 // As long as the KFilePlacesView from kdelibs is available, the system-bookmarks
838 // for "Recently Accessed" and "Search For" should be a setting available only
839 // in the Places Panel (see description of AppNamePrefix for more details).
840 const QString appName
= KGlobal::mainComponent().componentName() + AppNamePrefix
;
841 bookmark
.setMetaDataItem("OnlyInApp", appName
);
844 PlacesItem
* item
= new PlacesItem(bookmark
);
845 item
->setSystemItem(true);
847 // Create default view-properties for all "Search For" and "Recently Accessed" bookmarks
848 // in case if the user has not already created custom view-properties for a corresponding
850 const bool createDefaultViewProperties
= (item
->groupType() == PlacesItem::SearchForType
||
851 item
->groupType() == PlacesItem::RecentlyAccessedType
) &&
852 !GeneralSettings::self()->globalViewProps();
853 if (createDefaultViewProperties
) {
854 ViewProperties
props(convertedUrl(data
.url
));
855 if (!props
.exist()) {
856 const QString path
= data
.url
.path();
857 if (path
== QLatin1String("/documents")) {
858 props
.setViewMode(DolphinView::DetailsView
);
859 props
.setPreviewsShown(false);
860 props
.setVisibleRoles(QList
<QByteArray
>() << "text" << "path");
861 } else if (path
== QLatin1String("/images")) {
862 props
.setViewMode(DolphinView::IconsView
);
863 props
.setPreviewsShown(true);
864 props
.setVisibleRoles(QList
<QByteArray
>() << "text" << "imageSize");
865 } else if (path
== QLatin1String("/audio")) {
866 props
.setViewMode(DolphinView::DetailsView
);
867 props
.setPreviewsShown(false);
868 props
.setVisibleRoles(QList
<QByteArray
>() << "text" << "artist" << "album");
869 } else if (path
== QLatin1String("/videos")) {
870 props
.setViewMode(DolphinView::IconsView
);
871 props
.setPreviewsShown(true);
872 props
.setVisibleRoles(QList
<QByteArray
>() << "text");
873 } else if (data
.url
.protocol() == "timeline") {
874 props
.setViewMode(DolphinView::DetailsView
);
875 props
.setVisibleRoles(QList
<QByteArray
>() << "text" << "date");
883 void PlacesItemModel::createSystemBookmarks()
885 Q_ASSERT(m_systemBookmarks
.isEmpty());
886 Q_ASSERT(m_systemBookmarksIndexes
.isEmpty());
888 const QString timeLineIcon
= "package_utility_time"; // TODO: Ask the Oxygen team to create
889 // a custom icon for the timeline-protocol
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(KUrl(KUser().homeDir()),
897 I18N_NOOP2("KFile System Bookmarks", "Home")));
898 m_systemBookmarks
.append(SystemBookmarkData(KUrl("remote:/"),
900 I18N_NOOP2("KFile System Bookmarks", "Network")));
901 m_systemBookmarks
.append(SystemBookmarkData(KUrl("/"),
903 I18N_NOOP2("KFile System Bookmarks", "Root")));
904 m_systemBookmarks
.append(SystemBookmarkData(KUrl("trash:/"),
906 I18N_NOOP2("KFile System Bookmarks", "Trash")));
908 if (m_fileIndexingEnabled
) {
909 m_systemBookmarks
.append(SystemBookmarkData(KUrl("timeline:/today"),
911 I18N_NOOP2("KFile System Bookmarks", "Today")));
912 m_systemBookmarks
.append(SystemBookmarkData(KUrl("timeline:/yesterday"),
914 I18N_NOOP2("KFile System Bookmarks", "Yesterday")));
915 m_systemBookmarks
.append(SystemBookmarkData(KUrl("timeline:/thismonth"),
917 I18N_NOOP2("KFile System Bookmarks", "This Month")));
918 m_systemBookmarks
.append(SystemBookmarkData(KUrl("timeline:/lastmonth"),
920 I18N_NOOP2("KFile System Bookmarks", "Last Month")));
921 m_systemBookmarks
.append(SystemBookmarkData(KUrl("search:/documents"),
923 I18N_NOOP2("KFile System Bookmarks", "Documents")));
924 m_systemBookmarks
.append(SystemBookmarkData(KUrl("search:/images"),
926 I18N_NOOP2("KFile System Bookmarks", "Images")));
927 m_systemBookmarks
.append(SystemBookmarkData(KUrl("search:/audio"),
929 I18N_NOOP2("KFile System Bookmarks", "Audio Files")));
930 m_systemBookmarks
.append(SystemBookmarkData(KUrl("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::initializeAvailableDevices()
942 m_predicate
= Solid::Predicate::fromString(
943 "[[[[ StorageVolume.ignored == false AND [ StorageVolume.usage == 'FileSystem' OR StorageVolume.usage == 'Encrypted' ]]"
945 "[ IS StorageAccess AND StorageDrive.driveType == 'Floppy' ]]"
947 "OpticalDisc.availableContent & 'Audio' ]"
949 "StorageAccess.ignored == false ]");
950 Q_ASSERT(m_predicate
.isValid());
952 Solid::DeviceNotifier
* notifier
= Solid::DeviceNotifier::instance();
953 connect(notifier
, SIGNAL(deviceAdded(QString
)), this, SLOT(slotDeviceAdded(QString
)));
954 connect(notifier
, SIGNAL(deviceRemoved(QString
)), this, SLOT(slotDeviceRemoved(QString
)));
956 const QList
<Solid::Device
>& deviceList
= Solid::Device::listFromQuery(m_predicate
);
957 foreach (const Solid::Device
& device
, deviceList
) {
958 m_availableDevices
<< device
.udi();
962 int PlacesItemModel::bookmarkIndex(int index
) const
964 int bookmarkIndex
= 0;
966 while (bookmarkIndex
< m_bookmarkedItems
.count()) {
967 if (!m_bookmarkedItems
[bookmarkIndex
]) {
968 if (modelIndex
== index
) {
976 return bookmarkIndex
>= m_bookmarkedItems
.count() ? -1 : bookmarkIndex
;
979 void PlacesItemModel::hideItem(int index
)
981 PlacesItem
* shownItem
= placesItem(index
);
986 shownItem
->setHidden(true);
987 if (m_hiddenItemsShown
) {
988 // Removing items from the model is not allowed if all hidden
989 // items should be shown.
993 const int newIndex
= bookmarkIndex(index
);
995 const KBookmark hiddenBookmark
= shownItem
->bookmark();
996 PlacesItem
* hiddenItem
= new PlacesItem(hiddenBookmark
);
998 const PlacesItem
* previousItem
= placesItem(index
- 1);
999 KBookmark previousBookmark
;
1001 previousBookmark
= previousItem
->bookmark();
1004 const bool updateBookmark
= (m_bookmarkManager
->root().indexOf(hiddenBookmark
) >= 0);
1007 if (updateBookmark
) {
1008 // removeItem() also removed the bookmark from m_bookmarkManager in
1009 // PlacesItemModel::onItemRemoved(). However for hidden items the
1010 // bookmark should still be remembered, so readd it again:
1011 m_bookmarkManager
->root().addBookmark(hiddenBookmark
);
1012 m_bookmarkManager
->root().moveBookmark(hiddenBookmark
, previousBookmark
);
1013 triggerBookmarksSaving();
1016 m_bookmarkedItems
.insert(newIndex
, hiddenItem
);
1020 void PlacesItemModel::triggerBookmarksSaving()
1022 if (m_saveBookmarksTimer
) {
1023 m_saveBookmarksTimer
->start();
1027 QString
PlacesItemModel::internalMimeType() const
1029 return "application/x-dolphinplacesmodel-" +
1030 QString::number((qptrdiff
)this);
1033 int PlacesItemModel::groupedDropIndex(int index
, const PlacesItem
* item
) const
1037 int dropIndex
= index
;
1038 const PlacesItem::GroupType type
= item
->groupType();
1040 const int itemCount
= count();
1042 dropIndex
= itemCount
;
1045 // Search nearest previous item with the same group
1046 int previousIndex
= -1;
1047 for (int i
= dropIndex
- 1; i
>= 0; --i
) {
1048 if (placesItem(i
)->groupType() == type
) {
1054 // Search nearest next item with the same group
1056 for (int i
= dropIndex
; i
< count(); ++i
) {
1057 if (placesItem(i
)->groupType() == type
) {
1063 // Adjust the drop-index to be inserted to the
1064 // nearest item with the same group.
1065 if (previousIndex
>= 0 && nextIndex
>= 0) {
1066 dropIndex
= (dropIndex
- previousIndex
< nextIndex
- dropIndex
) ?
1067 previousIndex
+ 1 : nextIndex
;
1068 } else if (previousIndex
>= 0) {
1069 dropIndex
= previousIndex
+ 1;
1070 } else if (nextIndex
>= 0) {
1071 dropIndex
= nextIndex
;
1077 bool PlacesItemModel::equalBookmarkIdentifiers(const KBookmark
& b1
, const KBookmark
& b2
)
1079 const QString udi1
= b1
.metaDataItem("UDI");
1080 const QString udi2
= b2
.metaDataItem("UDI");
1081 if (!udi1
.isEmpty() && !udi2
.isEmpty()) {
1082 return udi1
== udi2
;
1084 return b1
.metaDataItem("ID") == b2
.metaDataItem("ID");
1088 KUrl
PlacesItemModel::createTimelineUrl(const KUrl
& url
)
1090 // TODO: Clarify with the Nepomuk-team whether it makes sense
1091 // provide default-timeline-URLs like 'yesterday', 'this month'
1092 // and 'last month'.
1095 const QString path
= url
.pathOrUrl();
1096 if (path
.endsWith(QLatin1String("yesterday"))) {
1097 const QDate date
= QDate::currentDate().addDays(-1);
1098 const int year
= date
.year();
1099 const int month
= date
.month();
1100 const int day
= date
.day();
1101 timelineUrl
= "timeline:/" + timelineDateString(year
, month
) +
1102 '/' + timelineDateString(year
, month
, day
);
1103 } else if (path
.endsWith(QLatin1String("thismonth"))) {
1104 const QDate date
= QDate::currentDate();
1105 timelineUrl
= "timeline:/" + timelineDateString(date
.year(), date
.month());
1106 } else if (path
.endsWith(QLatin1String("lastmonth"))) {
1107 const QDate date
= QDate::currentDate().addMonths(-1);
1108 timelineUrl
= "timeline:/" + timelineDateString(date
.year(), date
.month());
1110 Q_ASSERT(path
.endsWith(QLatin1String("today")));
1117 QString
PlacesItemModel::timelineDateString(int year
, int month
, int day
)
1119 QString date
= QString::number(year
) + '-';
1123 date
+= QString::number(month
);
1130 date
+= QString::number(day
);
1136 KUrl
PlacesItemModel::createSearchUrl(const KUrl
& url
)
1141 const QString path
= url
.pathOrUrl();
1142 if (path
.endsWith(QLatin1String("documents"))) {
1143 searchUrl
= searchUrlForTerm(Nepomuk::Query::ResourceTypeTerm(Nepomuk::Vocabulary::NFO::Document()));
1144 } else if (path
.endsWith(QLatin1String("images"))) {
1145 searchUrl
= searchUrlForTerm(Nepomuk::Query::ResourceTypeTerm(Nepomuk::Vocabulary::NFO::Image()));
1146 } else if (path
.endsWith(QLatin1String("audio"))) {
1147 searchUrl
= searchUrlForTerm(Nepomuk::Query::ComparisonTerm(Nepomuk::Vocabulary::NIE::mimeType(),
1148 Nepomuk::Query::LiteralTerm("audio")));
1149 } else if (path
.endsWith(QLatin1String("videos"))) {
1150 searchUrl
= searchUrlForTerm(Nepomuk::Query::ComparisonTerm(Nepomuk::Vocabulary::NIE::mimeType(),
1151 Nepomuk::Query::LiteralTerm("video")));
1163 KUrl
PlacesItemModel::searchUrlForTerm(const Nepomuk::Query::Term
& term
)
1165 const Nepomuk::Query::Query
query(term
);
1166 return query
.toSearchUrl();
1170 #ifdef PLACESITEMMODEL_DEBUG
1171 void PlacesItemModel::showModelState()
1173 kDebug() << "=================================";
1174 kDebug() << "Model:";
1175 kDebug() << "hidden-index model-index text";
1177 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
1178 if (m_bookmarkedItems
[i
]) {
1179 kDebug() << i
<< "(Hidden) " << " " << m_bookmarkedItems
[i
]->dataValue("text").toString();
1181 if (item(modelIndex
)) {
1182 kDebug() << i
<< " " << modelIndex
<< " " << item(modelIndex
)->dataValue("text").toString();
1184 kDebug() << i
<< " " << modelIndex
<< " " << "(not available yet)";
1191 kDebug() << "Bookmarks:";
1193 int bookmarkIndex
= 0;
1194 KBookmarkGroup root
= m_bookmarkManager
->root();
1195 KBookmark bookmark
= root
.first();
1196 while (!bookmark
.isNull()) {
1197 const QString udi
= bookmark
.metaDataItem("UDI");
1198 const QString text
= udi
.isEmpty() ? bookmark
.text() : udi
;
1199 if (bookmark
.metaDataItem("IsHidden") == QLatin1String("true")) {
1200 kDebug() << bookmarkIndex
<< "(Hidden)" << text
;
1202 kDebug() << bookmarkIndex
<< " " << text
;
1205 bookmark
= root
.next(bookmark
);
1211 #include "placesitemmodel.moc"