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>
34 #include <kprotocolinfo.h>
36 #include <KStandardDirs>
38 #include "placesitem.h"
44 #include <Solid/Device>
45 #include <Solid/DeviceNotifier>
46 #include <Solid/OpticalDisc>
47 #include <Solid/OpticalDrive>
48 #include <Solid/StorageAccess>
49 #include <Solid/StorageDrive>
51 #include <views/dolphinview.h>
52 #include <views/viewproperties.h>
55 #include <baloo/query.h>
56 #include <baloo/indexerconfig.h>
60 // As long as KFilePlacesView from kdelibs is available in parallel, the
61 // system-bookmarks for "Recently Saved" and "Search For" should be
62 // shown only inside the Places Panel. This is necessary as the stored
63 // URLs needs to get translated to a Baloo-search-URL on-the-fly to
64 // be independent from changes in the Baloo-search-URL-syntax.
65 // Hence a prefix to the application-name of the stored bookmarks is
66 // added, which is only read by PlacesItemModel.
67 const char* AppNamePrefix
= "-places-panel";
70 PlacesItemModel::PlacesItemModel(QObject
* parent
) :
71 KStandardItemModel(parent
),
72 m_fileIndexingEnabled(false),
73 m_hiddenItemsShown(false),
78 m_systemBookmarksIndexes(),
80 m_hiddenItemToRemove(-1),
81 m_updateBookmarksTimer(0),
82 m_storageSetupInProgress()
85 Baloo::IndexerConfig config
;
86 m_fileIndexingEnabled
= config
.fileIndexingEnabled();
88 const QString file
= KStandardDirs::locateLocal("data", "kfileplaces/bookmarks.xml");
89 m_bookmarkManager
= KBookmarkManager::managerForFile(file
, "kfilePlaces");
91 createSystemBookmarks();
92 initializeAvailableDevices();
95 const int syncBookmarksTimeout
= 100;
97 m_updateBookmarksTimer
= new QTimer(this);
98 m_updateBookmarksTimer
->setInterval(syncBookmarksTimeout
);
99 m_updateBookmarksTimer
->setSingleShot(true);
100 connect(m_updateBookmarksTimer
, SIGNAL(timeout()), this, SLOT(updateBookmarks()));
102 connect(m_bookmarkManager
, SIGNAL(changed(QString
,QString
)),
103 m_updateBookmarksTimer
, SLOT(start()));
104 connect(m_bookmarkManager
, SIGNAL(bookmarksChanged(QString
)),
105 m_updateBookmarksTimer
, SLOT(start()));
108 PlacesItemModel::~PlacesItemModel()
110 qDeleteAll(m_bookmarkedItems
);
111 m_bookmarkedItems
.clear();
114 PlacesItem
* PlacesItemModel::createPlacesItem(const QString
& text
,
116 const QString
& iconName
)
118 const KBookmark bookmark
= PlacesItem::createBookmark(m_bookmarkManager
, text
, url
, iconName
);
119 return new PlacesItem(bookmark
);
122 PlacesItem
* PlacesItemModel::placesItem(int index
) const
124 return dynamic_cast<PlacesItem
*>(item(index
));
127 int PlacesItemModel::hiddenCount() const
130 int hiddenItemCount
= 0;
131 foreach (const PlacesItem
* item
, m_bookmarkedItems
) {
135 if (placesItem(modelIndex
)->isHidden()) {
142 return hiddenItemCount
;
145 void PlacesItemModel::setHiddenItemsShown(bool show
)
147 if (m_hiddenItemsShown
== show
) {
151 m_hiddenItemsShown
= show
;
154 // Move all items that are part of m_bookmarkedItems to the model.
155 QList
<PlacesItem
*> itemsToInsert
;
156 QList
<int> insertPos
;
158 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
159 if (m_bookmarkedItems
[i
]) {
160 itemsToInsert
.append(m_bookmarkedItems
[i
]);
161 m_bookmarkedItems
[i
] = 0;
162 insertPos
.append(modelIndex
);
167 // Inserting the items will automatically insert an item
168 // to m_bookmarkedItems in PlacesItemModel::onItemsInserted().
169 // The items are temporary saved in itemsToInsert, so
170 // m_bookmarkedItems can be shrinked now.
171 m_bookmarkedItems
.erase(m_bookmarkedItems
.begin(),
172 m_bookmarkedItems
.begin() + itemsToInsert
.count());
174 for (int i
= 0; i
< itemsToInsert
.count(); ++i
) {
175 insertItem(insertPos
[i
], itemsToInsert
[i
]);
178 Q_ASSERT(m_bookmarkedItems
.count() == count());
180 // Move all items of the model, where the "isHidden" property is true, to
181 // m_bookmarkedItems.
182 Q_ASSERT(m_bookmarkedItems
.count() == count());
183 for (int i
= count() - 1; i
>= 0; --i
) {
184 if (placesItem(i
)->isHidden()) {
190 #ifdef PLACESITEMMODEL_DEBUG
191 kDebug() << "Changed visibility of hidden items";
196 bool PlacesItemModel::hiddenItemsShown() const
198 return m_hiddenItemsShown
;
201 int PlacesItemModel::closestItem(const KUrl
& url
) const
206 for (int i
= 0; i
< count(); ++i
) {
207 const KUrl itemUrl
= placesItem(i
)->url();
208 if (itemUrl
.isParentOf(url
)) {
209 const int length
= itemUrl
.prettyUrl().length();
210 if (length
> maxLength
) {
220 void PlacesItemModel::appendItemToGroup(PlacesItem
* item
)
227 while (i
< count() && placesItem(i
)->group() != item
->group()) {
231 bool inserted
= false;
232 while (!inserted
&& i
< count()) {
233 if (placesItem(i
)->group() != item
->group()) {
246 QAction
* PlacesItemModel::ejectAction(int index
) const
248 const PlacesItem
* item
= placesItem(index
);
249 if (item
&& item
->device().is
<Solid::OpticalDisc
>()) {
250 return new QAction(KIcon("media-eject"), i18nc("@item", "Eject '%1'", item
->text()), 0);
256 QAction
* PlacesItemModel::teardownAction(int index
) const
258 const PlacesItem
* item
= placesItem(index
);
263 Solid::Device device
= item
->device();
264 const bool providesTearDown
= device
.is
<Solid::StorageAccess
>() &&
265 device
.as
<Solid::StorageAccess
>()->isAccessible();
266 if (!providesTearDown
) {
270 Solid::StorageDrive
* drive
= device
.as
<Solid::StorageDrive
>();
272 drive
= device
.parent().as
<Solid::StorageDrive
>();
275 bool hotPluggable
= false;
276 bool removable
= false;
278 hotPluggable
= drive
->isHotpluggable();
279 removable
= drive
->isRemovable();
284 const QString label
= item
->text();
285 if (device
.is
<Solid::OpticalDisc
>()) {
286 text
= i18nc("@item", "Release '%1'", label
);
287 } else if (removable
|| hotPluggable
) {
288 text
= i18nc("@item", "Safely Remove '%1'", label
);
289 iconName
= "media-eject";
291 text
= i18nc("@item", "Unmount '%1'", label
);
292 iconName
= "media-eject";
295 if (iconName
.isEmpty()) {
296 return new QAction(text
, 0);
299 return new QAction(KIcon(iconName
), text
, 0);
302 void PlacesItemModel::requestEject(int index
)
304 const PlacesItem
* item
= placesItem(index
);
306 Solid::OpticalDrive
* drive
= item
->device().parent().as
<Solid::OpticalDrive
>();
308 connect(drive
, SIGNAL(ejectDone(Solid::ErrorType
,QVariant
,QString
)),
309 this, SLOT(slotStorageTeardownDone(Solid::ErrorType
,QVariant
)),
310 Qt::UniqueConnection
);
313 const QString label
= item
->text();
314 const QString message
= i18nc("@info", "The device '%1' is not a disk and cannot be ejected.", label
);
315 emit
errorMessage(message
);
320 void PlacesItemModel::requestTeardown(int index
)
322 const PlacesItem
* item
= placesItem(index
);
324 Solid::StorageAccess
* access
= item
->device().as
<Solid::StorageAccess
>();
326 connect(access
, SIGNAL(teardownDone(Solid::ErrorType
,QVariant
,QString
)),
327 this, SLOT(slotStorageTeardownDone(Solid::ErrorType
,QVariant
)),
328 Qt::UniqueConnection
);
334 bool PlacesItemModel::storageSetupNeeded(int index
) const
336 const PlacesItem
* item
= placesItem(index
);
337 return item
? item
->storageSetupNeeded() : false;
340 void PlacesItemModel::requestStorageSetup(int index
)
342 const PlacesItem
* item
= placesItem(index
);
347 Solid::Device device
= item
->device();
348 const bool setup
= device
.is
<Solid::StorageAccess
>()
349 && !m_storageSetupInProgress
.contains(device
.as
<Solid::StorageAccess
>())
350 && !device
.as
<Solid::StorageAccess
>()->isAccessible();
352 Solid::StorageAccess
* access
= device
.as
<Solid::StorageAccess
>();
354 m_storageSetupInProgress
[access
] = index
;
356 connect(access
, SIGNAL(setupDone(Solid::ErrorType
,QVariant
,QString
)),
357 this, SLOT(slotStorageSetupDone(Solid::ErrorType
,QVariant
,QString
)),
358 Qt::UniqueConnection
);
364 QMimeData
* PlacesItemModel::createMimeData(const KItemSet
& indexes
) const
369 QDataStream
stream(&itemData
, QIODevice::WriteOnly
);
371 foreach (int index
, indexes
) {
372 const KUrl itemUrl
= placesItem(index
)->url();
373 if (itemUrl
.isValid()) {
379 QMimeData
* mimeData
= new QMimeData();
380 if (!urls
.isEmpty()) {
381 urls
.populateMimeData(mimeData
);
383 mimeData
->setData(internalMimeType(), itemData
);
388 bool PlacesItemModel::supportsDropping(int index
) const
390 return index
>= 0 && index
< count();
393 void PlacesItemModel::dropMimeDataBefore(int index
, const QMimeData
* mimeData
)
395 if (mimeData
->hasFormat(internalMimeType())) {
396 // The item has been moved inside the view
397 QByteArray itemData
= mimeData
->data(internalMimeType());
398 QDataStream
stream(&itemData
, QIODevice::ReadOnly
);
401 if (oldIndex
== index
|| oldIndex
== index
- 1) {
402 // No moving has been done
406 PlacesItem
* oldItem
= placesItem(oldIndex
);
411 PlacesItem
* newItem
= new PlacesItem(oldItem
->bookmark());
412 removeItem(oldIndex
);
414 if (oldIndex
< index
) {
418 const int dropIndex
= groupedDropIndex(index
, newItem
);
419 insertItem(dropIndex
, newItem
);
420 } else if (mimeData
->hasFormat("text/uri-list")) {
421 // One or more items must be added to the model
422 const KUrl::List urls
= KUrl::List::fromMimeData(mimeData
);
423 for (int i
= urls
.count() - 1; i
>= 0; --i
) {
424 const KUrl
& url
= urls
[i
];
426 QString text
= url
.fileName();
427 if (text
.isEmpty()) {
431 if ((url
.isLocalFile() && !QFileInfo(url
.toLocalFile()).isDir())
432 || url
.protocol() == "trash") {
433 // Only directories outside the trash are allowed
437 PlacesItem
* newItem
= createPlacesItem(text
, url
);
438 const int dropIndex
= groupedDropIndex(index
, newItem
);
439 insertItem(dropIndex
, newItem
);
444 KUrl
PlacesItemModel::convertedUrl(const KUrl
& url
)
447 if (url
.protocol() == QLatin1String("timeline")) {
448 newUrl
= createTimelineUrl(url
);
449 } else if (url
.protocol() == QLatin1String("search")) {
450 newUrl
= createSearchUrl(url
);
456 void PlacesItemModel::onItemInserted(int index
)
458 const PlacesItem
* insertedItem
= placesItem(index
);
460 // Take care to apply the PlacesItemModel-order of the inserted item
461 // also to the bookmark-manager.
462 const KBookmark insertedBookmark
= insertedItem
->bookmark();
464 const PlacesItem
* previousItem
= placesItem(index
- 1);
465 KBookmark previousBookmark
;
467 previousBookmark
= previousItem
->bookmark();
470 m_bookmarkManager
->root().moveBookmark(insertedBookmark
, previousBookmark
);
473 if (index
== count() - 1) {
474 // The item has been appended as last item to the list. In this
475 // case assure that it is also appended after the hidden items and
476 // not before (like done otherwise).
477 m_bookmarkedItems
.append(0);
481 int bookmarkIndex
= 0;
482 while (bookmarkIndex
< m_bookmarkedItems
.count()) {
483 if (!m_bookmarkedItems
[bookmarkIndex
]) {
485 if (modelIndex
+ 1 == index
) {
491 m_bookmarkedItems
.insert(bookmarkIndex
, 0);
494 #ifdef PLACESITEMMODEL_DEBUG
495 kDebug() << "Inserted item" << index
;
500 void PlacesItemModel::onItemRemoved(int index
, KStandardItem
* removedItem
)
502 PlacesItem
* placesItem
= dynamic_cast<PlacesItem
*>(removedItem
);
504 const KBookmark bookmark
= placesItem
->bookmark();
505 m_bookmarkManager
->root().deleteBookmark(bookmark
);
508 const int boomarkIndex
= bookmarkIndex(index
);
509 Q_ASSERT(!m_bookmarkedItems
[boomarkIndex
]);
510 m_bookmarkedItems
.removeAt(boomarkIndex
);
512 #ifdef PLACESITEMMODEL_DEBUG
513 kDebug() << "Removed item" << index
;
518 void PlacesItemModel::onItemChanged(int index
, const QSet
<QByteArray
>& changedRoles
)
520 const PlacesItem
* changedItem
= placesItem(index
);
522 // Take care to apply the PlacesItemModel-order of the changed item
523 // also to the bookmark-manager.
524 const KBookmark insertedBookmark
= changedItem
->bookmark();
526 const PlacesItem
* previousItem
= placesItem(index
- 1);
527 KBookmark previousBookmark
;
529 previousBookmark
= previousItem
->bookmark();
532 m_bookmarkManager
->root().moveBookmark(insertedBookmark
, previousBookmark
);
535 if (changedRoles
.contains("isHidden")) {
536 if (!m_hiddenItemsShown
&& changedItem
->isHidden()) {
537 m_hiddenItemToRemove
= index
;
538 QTimer::singleShot(0, this, SLOT(hideItem()));
543 void PlacesItemModel::slotDeviceAdded(const QString
& udi
)
545 const Solid::Device
device(udi
);
547 if (!m_predicate
.matches(device
)) {
551 m_availableDevices
<< udi
;
552 const KBookmark bookmark
= PlacesItem::createDeviceBookmark(m_bookmarkManager
, udi
);
553 appendItem(new PlacesItem(bookmark
));
556 void PlacesItemModel::slotDeviceRemoved(const QString
& udi
)
558 if (!m_availableDevices
.contains(udi
)) {
562 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
563 PlacesItem
* item
= m_bookmarkedItems
[i
];
564 if (item
&& item
->udi() == udi
) {
565 m_bookmarkedItems
.removeAt(i
);
571 for (int i
= 0; i
< count(); ++i
) {
572 if (placesItem(i
)->udi() == udi
) {
579 void PlacesItemModel::slotStorageTeardownDone(Solid::ErrorType error
, const QVariant
& errorData
)
581 if (error
&& errorData
.isValid()) {
582 emit
errorMessage(errorData
.toString());
586 void PlacesItemModel::slotStorageSetupDone(Solid::ErrorType error
,
587 const QVariant
& errorData
,
592 Q_ASSERT(!m_storageSetupInProgress
.isEmpty());
593 const int index
= m_storageSetupInProgress
.take(sender());
594 const PlacesItem
* item
= placesItem(index
);
600 if (errorData
.isValid()) {
601 emit
errorMessage(i18nc("@info", "An error occurred while accessing '%1', the system responded: %2",
603 errorData
.toString()));
605 emit
errorMessage(i18nc("@info", "An error occurred while accessing '%1'",
608 emit
storageSetupDone(index
, false);
610 emit
storageSetupDone(index
, true);
614 void PlacesItemModel::hideItem()
616 hideItem(m_hiddenItemToRemove
);
617 m_hiddenItemToRemove
= -1;
620 void PlacesItemModel::updateBookmarks()
622 // Verify whether new bookmarks have been added or existing
623 // bookmarks have been changed.
624 KBookmarkGroup root
= m_bookmarkManager
->root();
625 KBookmark newBookmark
= root
.first();
626 while (!newBookmark
.isNull()) {
627 if (acceptBookmark(newBookmark
, m_availableDevices
)) {
630 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
631 PlacesItem
* item
= m_bookmarkedItems
[i
];
633 item
= placesItem(modelIndex
);
637 const KBookmark oldBookmark
= item
->bookmark();
638 if (equalBookmarkIdentifiers(newBookmark
, oldBookmark
)) {
639 // The bookmark has been found in the model or as
640 // a hidden item. The content of the bookmark might
641 // have been changed, so an update is done.
643 if (newBookmark
.metaDataItem("UDI").isEmpty()) {
644 item
->setBookmark(newBookmark
);
645 item
->setText(i18nc("KFile System Bookmarks", newBookmark
.text().toUtf8().data()));
652 const QString udi
= newBookmark
.metaDataItem("UDI");
656 * Only add a new places item, if the item text is not empty
657 * and if the device is available. Fixes the strange behaviour -
658 * add a places item without text in the Places section - when you
659 * remove a device (e.g. a usb stick) without unmounting.
661 if (udi
.isEmpty() || Solid::Device(udi
).isValid()) {
662 PlacesItem
* item
= new PlacesItem(newBookmark
);
663 if (item
->isHidden() && !m_hiddenItemsShown
) {
664 m_bookmarkedItems
.append(item
);
666 appendItemToGroup(item
);
672 newBookmark
= root
.next(newBookmark
);
675 // Remove items that are not part of the bookmark-manager anymore
677 for (int i
= m_bookmarkedItems
.count() - 1; i
>= 0; --i
) {
678 PlacesItem
* item
= m_bookmarkedItems
[i
];
679 const bool itemIsPartOfModel
= (item
== 0);
680 if (itemIsPartOfModel
) {
681 item
= placesItem(modelIndex
);
684 bool hasBeenRemoved
= true;
685 const KBookmark oldBookmark
= item
->bookmark();
686 KBookmark newBookmark
= root
.first();
687 while (!newBookmark
.isNull()) {
688 if (equalBookmarkIdentifiers(newBookmark
, oldBookmark
)) {
689 hasBeenRemoved
= false;
692 newBookmark
= root
.next(newBookmark
);
695 if (hasBeenRemoved
) {
696 if (m_bookmarkedItems
[i
]) {
697 delete m_bookmarkedItems
[i
];
698 m_bookmarkedItems
.removeAt(i
);
700 removeItem(modelIndex
);
705 if (itemIsPartOfModel
) {
711 void PlacesItemModel::saveBookmarks()
713 m_bookmarkManager
->emitChanged(m_bookmarkManager
->root());
716 void PlacesItemModel::loadBookmarks()
718 KBookmarkGroup root
= m_bookmarkManager
->root();
719 KBookmark bookmark
= root
.first();
720 QSet
<QString
> devices
= m_availableDevices
;
722 QSet
<KUrl
> missingSystemBookmarks
;
723 foreach (const SystemBookmarkData
& data
, m_systemBookmarks
) {
724 missingSystemBookmarks
.insert(data
.url
);
727 // The bookmarks might have a mixed order of places, devices and search-groups due
728 // to the compatibility with the KFilePlacesPanel. In Dolphin's places panel the
729 // items should always be collected in one group so the items are collected first
730 // in separate lists before inserting them.
731 QList
<PlacesItem
*> placesItems
;
732 QList
<PlacesItem
*> recentlySavedItems
;
733 QList
<PlacesItem
*> searchForItems
;
734 QList
<PlacesItem
*> devicesItems
;
736 while (!bookmark
.isNull()) {
737 if (acceptBookmark(bookmark
, devices
)) {
738 PlacesItem
* item
= new PlacesItem(bookmark
);
739 if (item
->groupType() == PlacesItem::DevicesType
) {
740 devices
.remove(item
->udi());
741 devicesItems
.append(item
);
743 const KUrl url
= bookmark
.url();
744 if (missingSystemBookmarks
.contains(url
)) {
745 missingSystemBookmarks
.remove(url
);
747 // Try to retranslate the text of system bookmarks to have translated
748 // items when changing the language. In case if the user has applied a custom
749 // text, the retranslation will fail and the users custom text is still used.
750 // It is important to use "KFile System Bookmarks" as context (see
751 // createSystemBookmarks()).
752 item
->setText(i18nc("KFile System Bookmarks", bookmark
.text().toUtf8().data()));
753 item
->setSystemItem(true);
756 switch (item
->groupType()) {
757 case PlacesItem::PlacesType
: placesItems
.append(item
); break;
758 case PlacesItem::RecentlySavedType
: recentlySavedItems
.append(item
); break;
759 case PlacesItem::SearchForType
: searchForItems
.append(item
); break;
760 case PlacesItem::DevicesType
:
761 default: Q_ASSERT(false); break;
766 bookmark
= root
.next(bookmark
);
769 if (!missingSystemBookmarks
.isEmpty()) {
770 // The current bookmarks don't contain all system-bookmarks. Add the missing
772 foreach (const SystemBookmarkData
& data
, m_systemBookmarks
) {
773 if (missingSystemBookmarks
.contains(data
.url
)) {
774 PlacesItem
* item
= createSystemPlacesItem(data
);
775 switch (item
->groupType()) {
776 case PlacesItem::PlacesType
: placesItems
.append(item
); break;
777 case PlacesItem::RecentlySavedType
: recentlySavedItems
.append(item
); break;
778 case PlacesItem::SearchForType
: searchForItems
.append(item
); break;
779 case PlacesItem::DevicesType
:
780 default: Q_ASSERT(false); break;
786 // Create items for devices that have not been stored as bookmark yet
787 foreach (const QString
& udi
, devices
) {
788 const KBookmark bookmark
= PlacesItem::createDeviceBookmark(m_bookmarkManager
, udi
);
789 devicesItems
.append(new PlacesItem(bookmark
));
792 QList
<PlacesItem
*> items
;
793 items
.append(placesItems
);
794 items
.append(recentlySavedItems
);
795 items
.append(searchForItems
);
796 items
.append(devicesItems
);
798 foreach (PlacesItem
* item
, items
) {
799 if (!m_hiddenItemsShown
&& item
->isHidden()) {
800 m_bookmarkedItems
.append(item
);
806 #ifdef PLACESITEMMODEL_DEBUG
807 kDebug() << "Loaded bookmarks";
812 bool PlacesItemModel::acceptBookmark(const KBookmark
& bookmark
,
813 const QSet
<QString
>& availableDevices
) const
815 const QString udi
= bookmark
.metaDataItem("UDI");
816 const KUrl url
= bookmark
.url();
817 const QString appName
= bookmark
.metaDataItem("OnlyInApp");
818 const bool deviceAvailable
= availableDevices
.contains(udi
);
820 const bool allowedHere
= (appName
.isEmpty()
821 || appName
== KGlobal::mainComponent().componentName()
822 || appName
== KGlobal::mainComponent().componentName() + AppNamePrefix
)
823 && (m_fileIndexingEnabled
|| (url
.protocol() != QLatin1String("timeline") &&
824 url
.protocol() != QLatin1String("search")));
826 return (udi
.isEmpty() && allowedHere
) || deviceAvailable
;
829 PlacesItem
* PlacesItemModel::createSystemPlacesItem(const SystemBookmarkData
& data
)
831 KBookmark bookmark
= PlacesItem::createBookmark(m_bookmarkManager
,
836 const QString protocol
= data
.url
.protocol();
837 if (protocol
== QLatin1String("timeline") || protocol
== QLatin1String("search")) {
838 // As long as the KFilePlacesView from kdelibs is available, the system-bookmarks
839 // for "Recently Saved" and "Search For" should be a setting available only
840 // in the Places Panel (see description of AppNamePrefix for more details).
841 const QString appName
= KGlobal::mainComponent().componentName() + AppNamePrefix
;
842 bookmark
.setMetaDataItem("OnlyInApp", appName
);
845 PlacesItem
* item
= new PlacesItem(bookmark
);
846 item
->setSystemItem(true);
848 // Create default view-properties for all "Search For" and "Recently Saved" bookmarks
849 // in case if the user has not already created custom view-properties for a corresponding
851 const bool createDefaultViewProperties
= (item
->groupType() == PlacesItem::SearchForType
||
852 item
->groupType() == PlacesItem::RecentlySavedType
) &&
853 !GeneralSettings::self()->globalViewProps();
854 if (createDefaultViewProperties
) {
855 ViewProperties
props(convertedUrl(data
.url
));
856 if (!props
.exist()) {
857 const QString path
= data
.url
.path();
858 if (path
== QLatin1String("/documents")) {
859 props
.setViewMode(DolphinView::DetailsView
);
860 props
.setPreviewsShown(false);
861 props
.setVisibleRoles(QList
<QByteArray
>() << "text" << "path");
862 } else if (path
== QLatin1String("/images")) {
863 props
.setViewMode(DolphinView::IconsView
);
864 props
.setPreviewsShown(true);
865 props
.setVisibleRoles(QList
<QByteArray
>() << "text" << "imageSize");
866 } else if (path
== QLatin1String("/audio")) {
867 props
.setViewMode(DolphinView::DetailsView
);
868 props
.setPreviewsShown(false);
869 props
.setVisibleRoles(QList
<QByteArray
>() << "text" << "artist" << "album");
870 } else if (path
== QLatin1String("/videos")) {
871 props
.setViewMode(DolphinView::IconsView
);
872 props
.setPreviewsShown(true);
873 props
.setVisibleRoles(QList
<QByteArray
>() << "text");
874 } else if (data
.url
.protocol() == "timeline") {
875 props
.setViewMode(DolphinView::DetailsView
);
876 props
.setVisibleRoles(QList
<QByteArray
>() << "text" << "date");
884 void PlacesItemModel::createSystemBookmarks()
886 Q_ASSERT(m_systemBookmarks
.isEmpty());
887 Q_ASSERT(m_systemBookmarksIndexes
.isEmpty());
889 // Note: The context of the I18N_NOOP2 must be "KFile System Bookmarks". The real
890 // i18nc call is done after reading the bookmark. The reason why the i18nc call is not
891 // done here is because otherwise switching the language would not result in retranslating the
893 m_systemBookmarks
.append(SystemBookmarkData(KUrl(KUser().homeDir()),
895 I18N_NOOP2("KFile System Bookmarks", "Home")));
896 m_systemBookmarks
.append(SystemBookmarkData(KUrl("remote:/"),
898 I18N_NOOP2("KFile System Bookmarks", "Network")));
899 m_systemBookmarks
.append(SystemBookmarkData(KUrl("/"),
901 I18N_NOOP2("KFile System Bookmarks", "Root")));
902 m_systemBookmarks
.append(SystemBookmarkData(KUrl("trash:/"),
904 I18N_NOOP2("KFile System Bookmarks", "Trash")));
906 if (m_fileIndexingEnabled
) {
907 m_systemBookmarks
.append(SystemBookmarkData(KUrl("timeline:/today"),
909 I18N_NOOP2("KFile System Bookmarks", "Today")));
910 m_systemBookmarks
.append(SystemBookmarkData(KUrl("timeline:/yesterday"),
912 I18N_NOOP2("KFile System Bookmarks", "Yesterday")));
913 m_systemBookmarks
.append(SystemBookmarkData(KUrl("timeline:/thismonth"),
914 "view-calendar-month",
915 I18N_NOOP2("KFile System Bookmarks", "This Month")));
916 m_systemBookmarks
.append(SystemBookmarkData(KUrl("timeline:/lastmonth"),
917 "view-calendar-month",
918 I18N_NOOP2("KFile System Bookmarks", "Last Month")));
919 m_systemBookmarks
.append(SystemBookmarkData(KUrl("search:/documents"),
921 I18N_NOOP2("KFile System Bookmarks", "Documents")));
922 m_systemBookmarks
.append(SystemBookmarkData(KUrl("search:/images"),
924 I18N_NOOP2("KFile System Bookmarks", "Images")));
925 m_systemBookmarks
.append(SystemBookmarkData(KUrl("search:/audio"),
927 I18N_NOOP2("KFile System Bookmarks", "Audio Files")));
928 m_systemBookmarks
.append(SystemBookmarkData(KUrl("search:/videos"),
930 I18N_NOOP2("KFile System Bookmarks", "Videos")));
933 for (int i
= 0; i
< m_systemBookmarks
.count(); ++i
) {
934 m_systemBookmarksIndexes
.insert(m_systemBookmarks
[i
].url
, i
);
938 void PlacesItemModel::clear() {
939 m_bookmarkedItems
.clear();
940 KStandardItemModel::clear();
943 void PlacesItemModel::initializeAvailableDevices()
945 QString
predicate("[[[[ StorageVolume.ignored == false AND [ StorageVolume.usage == 'FileSystem' OR StorageVolume.usage == 'Encrypted' ]]"
947 "[ IS StorageAccess AND StorageDrive.driveType == 'Floppy' ]]"
949 "OpticalDisc.availableContent & 'Audio' ]"
951 "StorageAccess.ignored == false ]");
954 if (KProtocolInfo::isKnownProtocol("mtp")) {
955 predicate
.prepend("[");
956 predicate
.append(" OR PortableMediaPlayer.supportedProtocols == 'mtp']");
959 m_predicate
= Solid::Predicate::fromString(predicate
);
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
);
1025 m_bookmarkedItems
.insert(newIndex
, hiddenItem
);
1029 QString
PlacesItemModel::internalMimeType() const
1031 return "application/x-dolphinplacesmodel-" +
1032 QString::number((qptrdiff
)this);
1035 int PlacesItemModel::groupedDropIndex(int index
, const PlacesItem
* item
) const
1039 int dropIndex
= index
;
1040 const PlacesItem::GroupType type
= item
->groupType();
1042 const int itemCount
= count();
1044 dropIndex
= itemCount
;
1047 // Search nearest previous item with the same group
1048 int previousIndex
= -1;
1049 for (int i
= dropIndex
- 1; i
>= 0; --i
) {
1050 if (placesItem(i
)->groupType() == type
) {
1056 // Search nearest next item with the same group
1058 for (int i
= dropIndex
; i
< count(); ++i
) {
1059 if (placesItem(i
)->groupType() == type
) {
1065 // Adjust the drop-index to be inserted to the
1066 // nearest item with the same group.
1067 if (previousIndex
>= 0 && nextIndex
>= 0) {
1068 dropIndex
= (dropIndex
- previousIndex
< nextIndex
- dropIndex
) ?
1069 previousIndex
+ 1 : nextIndex
;
1070 } else if (previousIndex
>= 0) {
1071 dropIndex
= previousIndex
+ 1;
1072 } else if (nextIndex
>= 0) {
1073 dropIndex
= nextIndex
;
1079 bool PlacesItemModel::equalBookmarkIdentifiers(const KBookmark
& b1
, const KBookmark
& b2
)
1081 const QString udi1
= b1
.metaDataItem("UDI");
1082 const QString udi2
= b2
.metaDataItem("UDI");
1083 if (!udi1
.isEmpty() && !udi2
.isEmpty()) {
1084 return udi1
== udi2
;
1086 return b1
.metaDataItem("ID") == b2
.metaDataItem("ID");
1090 KUrl
PlacesItemModel::createTimelineUrl(const KUrl
& url
)
1092 // TODO: Clarify with the Baloo-team whether it makes sense
1093 // provide default-timeline-URLs like 'yesterday', 'this month'
1094 // and 'last month'.
1097 const QString path
= url
.pathOrUrl();
1098 if (path
.endsWith(QLatin1String("yesterday"))) {
1099 const QDate date
= QDate::currentDate().addDays(-1);
1100 const int year
= date
.year();
1101 const int month
= date
.month();
1102 const int day
= date
.day();
1103 timelineUrl
= "timeline:/" + timelineDateString(year
, month
) +
1104 '/' + timelineDateString(year
, month
, day
);
1105 } else if (path
.endsWith(QLatin1String("thismonth"))) {
1106 const QDate date
= QDate::currentDate();
1107 timelineUrl
= "timeline:/" + timelineDateString(date
.year(), date
.month());
1108 } else if (path
.endsWith(QLatin1String("lastmonth"))) {
1109 const QDate date
= QDate::currentDate().addMonths(-1);
1110 timelineUrl
= "timeline:/" + timelineDateString(date
.year(), date
.month());
1112 Q_ASSERT(path
.endsWith(QLatin1String("today")));
1119 QString
PlacesItemModel::timelineDateString(int year
, int month
, int day
)
1121 QString date
= QString::number(year
) + '-';
1125 date
+= QString::number(month
);
1132 date
+= QString::number(day
);
1138 KUrl
PlacesItemModel::createSearchUrl(const KUrl
& url
)
1143 const QString path
= url
.pathOrUrl();
1144 if (path
.endsWith(QLatin1String("documents"))) {
1145 searchUrl
= searchUrlForType("Document");
1146 } else if (path
.endsWith(QLatin1String("images"))) {
1147 searchUrl
= searchUrlForType("Image");
1148 } else if (path
.endsWith(QLatin1String("audio"))) {
1149 searchUrl
= searchUrlForType("Audio");
1150 } else if (path
.endsWith(QLatin1String("videos"))) {
1151 searchUrl
= searchUrlForType("Video");
1163 KUrl
PlacesItemModel::searchUrlForType(const QString
& type
)
1166 query
.addType("File");
1167 query
.addType(type
);
1169 return query
.toSearchUrl();
1173 #ifdef PLACESITEMMODEL_DEBUG
1174 void PlacesItemModel::showModelState()
1176 kDebug() << "=================================";
1177 kDebug() << "Model:";
1178 kDebug() << "hidden-index model-index text";
1180 for (int i
= 0; i
< m_bookmarkedItems
.count(); ++i
) {
1181 if (m_bookmarkedItems
[i
]) {
1182 kDebug() << i
<< "(Hidden) " << " " << m_bookmarkedItems
[i
]->dataValue("text").toString();
1184 if (item(modelIndex
)) {
1185 kDebug() << i
<< " " << modelIndex
<< " " << item(modelIndex
)->dataValue("text").toString();
1187 kDebug() << i
<< " " << modelIndex
<< " " << "(not available yet)";
1194 kDebug() << "Bookmarks:";
1196 int bookmarkIndex
= 0;
1197 KBookmarkGroup root
= m_bookmarkManager
->root();
1198 KBookmark bookmark
= root
.first();
1199 while (!bookmark
.isNull()) {
1200 const QString udi
= bookmark
.metaDataItem("UDI");
1201 const QString text
= udi
.isEmpty() ? bookmark
.text() : udi
;
1202 if (bookmark
.metaDataItem("IsHidden") == QLatin1String("true")) {
1203 kDebug() << bookmarkIndex
<< "(Hidden)" << text
;
1205 kDebug() << bookmarkIndex
<< " " << text
;
1208 bookmark
= root
.next(bookmark
);
1214 #include "placesitemmodel.moc"