]> cloud.milkyroute.net Git - dolphin.git/blob - src/panels/places/placesitemmodel.cpp
Change "Date" to "Modified" and allow access to new "Accessed" time field
[dolphin.git] / src / panels / places / placesitemmodel.cpp
1 /***************************************************************************
2 * Copyright (C) 2012 by Peter Penz <peter.penz19@gmail.com> *
3 * *
4 * Based on KFilePlacesModel from kdelibs: *
5 * Copyright (C) 2007 Kevin Ottens <ervin@kde.org> *
6 * Copyright (C) 2007 David Faure <faure@kde.org> *
7 * *
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. *
12 * *
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. *
17 * *
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 ***************************************************************************/
23
24 #include "placesitemmodel.h"
25
26 #include "dolphin_generalsettings.h"
27
28 #include <KBookmark>
29 #include <KBookmarkManager>
30 #include "dolphindebug.h"
31 #include <QIcon>
32 #include <KProtocolInfo>
33 #include <KLocalizedString>
34 #include <QStandardPaths>
35 #include <KUser>
36 #include <KAboutData>
37 #include "placesitem.h"
38 #include <QAction>
39 #include <QDate>
40 #include <QMimeData>
41 #include <QTimer>
42 #include <KUrlMimeData>
43
44 #include <Solid/Device>
45 #include <Solid/DeviceNotifier>
46 #include <Solid/OpticalDisc>
47 #include <Solid/OpticalDrive>
48 #include <Solid/StorageAccess>
49 #include <Solid/StorageDrive>
50
51 #include <views/dolphinview.h>
52 #include <views/viewproperties.h>
53
54 #ifdef HAVE_BALOO
55 #include <Baloo/Query>
56 #include <Baloo/IndexerConfig>
57 #endif
58
59 namespace {
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";
68 }
69
70 PlacesItemModel::PlacesItemModel(QObject* parent) :
71 KStandardItemModel(parent),
72 m_fileIndexingEnabled(false),
73 m_hiddenItemsShown(false),
74 m_availableDevices(),
75 m_predicate(),
76 m_bookmarkManager(0),
77 m_systemBookmarks(),
78 m_systemBookmarksIndexes(),
79 m_bookmarkedItems(),
80 m_hiddenItemToRemove(-1),
81 m_updateBookmarksTimer(0),
82 m_storageSetupInProgress()
83 {
84 #ifdef HAVE_BALOO
85 Baloo::IndexerConfig config;
86 m_fileIndexingEnabled = config.fileIndexingEnabled();
87 #endif
88 const QString file = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/user-places.xbel";
89 m_bookmarkManager = KBookmarkManager::managerForExternalFile(file);
90
91 createSystemBookmarks();
92 initializeAvailableDevices();
93 loadBookmarks();
94
95 const int syncBookmarksTimeout = 100;
96
97 m_updateBookmarksTimer = new QTimer(this);
98 m_updateBookmarksTimer->setInterval(syncBookmarksTimeout);
99 m_updateBookmarksTimer->setSingleShot(true);
100 connect(m_updateBookmarksTimer, &QTimer::timeout, this, &PlacesItemModel::updateBookmarks);
101
102 connect(m_bookmarkManager, &KBookmarkManager::changed,
103 m_updateBookmarksTimer, static_cast<void(QTimer::*)()>(&QTimer::start));
104 }
105
106 PlacesItemModel::~PlacesItemModel()
107 {
108 qDeleteAll(m_bookmarkedItems);
109 m_bookmarkedItems.clear();
110 }
111
112 PlacesItem* PlacesItemModel::createPlacesItem(const QString& text,
113 const QUrl& url,
114 const QString& iconName)
115 {
116 const KBookmark bookmark = PlacesItem::createBookmark(m_bookmarkManager, text, url, iconName);
117 return new PlacesItem(bookmark);
118 }
119
120 PlacesItem* PlacesItemModel::placesItem(int index) const
121 {
122 return dynamic_cast<PlacesItem*>(item(index));
123 }
124
125 int PlacesItemModel::hiddenCount() const
126 {
127 int modelIndex = 0;
128 int hiddenItemCount = 0;
129 foreach (const PlacesItem* item, m_bookmarkedItems) {
130 if (item) {
131 ++hiddenItemCount;
132 } else {
133 if (placesItem(modelIndex)->isHidden()) {
134 ++hiddenItemCount;
135 }
136 ++modelIndex;
137 }
138 }
139
140 return hiddenItemCount;
141 }
142
143 void PlacesItemModel::setHiddenItemsShown(bool show)
144 {
145 if (m_hiddenItemsShown == show) {
146 return;
147 }
148
149 m_hiddenItemsShown = show;
150
151 if (show) {
152 // Move all items that are part of m_bookmarkedItems to the model.
153 QList<PlacesItem*> itemsToInsert;
154 QList<int> insertPos;
155 int modelIndex = 0;
156 for (int i = 0; i < m_bookmarkedItems.count(); ++i) {
157 if (m_bookmarkedItems[i]) {
158 itemsToInsert.append(m_bookmarkedItems[i]);
159 m_bookmarkedItems[i] = 0;
160 insertPos.append(modelIndex);
161 }
162 ++modelIndex;
163 }
164
165 // Inserting the items will automatically insert an item
166 // to m_bookmarkedItems in PlacesItemModel::onItemsInserted().
167 // The items are temporary saved in itemsToInsert, so
168 // m_bookmarkedItems can be shrinked now.
169 m_bookmarkedItems.erase(m_bookmarkedItems.begin(),
170 m_bookmarkedItems.begin() + itemsToInsert.count());
171
172 for (int i = 0; i < itemsToInsert.count(); ++i) {
173 insertItem(insertPos[i], itemsToInsert[i]);
174 }
175
176 Q_ASSERT(m_bookmarkedItems.count() == count());
177 } else {
178 // Move all items of the model, where the "isHidden" property is true, to
179 // m_bookmarkedItems.
180 Q_ASSERT(m_bookmarkedItems.count() == count());
181 for (int i = count() - 1; i >= 0; --i) {
182 if (placesItem(i)->isHidden()) {
183 hideItem(i);
184 }
185 }
186 }
187
188 #ifdef PLACESITEMMODEL_DEBUG
189 qCDebug(DolphinDebug) << "Changed visibility of hidden items";
190 showModelState();
191 #endif
192 }
193
194 bool PlacesItemModel::hiddenItemsShown() const
195 {
196 return m_hiddenItemsShown;
197 }
198
199 int PlacesItemModel::closestItem(const QUrl& url) const
200 {
201 int foundIndex = -1;
202 int maxLength = 0;
203
204 for (int i = 0; i < count(); ++i) {
205 const QUrl itemUrl = placesItem(i)->url();
206 if (url == itemUrl) {
207 // We can't find a closer one, so stop here.
208 foundIndex = i;
209 break;
210 } else if (itemUrl.isParentOf(url)) {
211 const int length = itemUrl.path().length();
212 if (length > maxLength) {
213 foundIndex = i;
214 maxLength = length;
215 }
216 }
217 }
218
219 return foundIndex;
220 }
221
222 void PlacesItemModel::appendItemToGroup(PlacesItem* item)
223 {
224 if (!item) {
225 return;
226 }
227
228 int i = 0;
229 while (i < count() && placesItem(i)->group() != item->group()) {
230 ++i;
231 }
232
233 bool inserted = false;
234 while (!inserted && i < count()) {
235 if (placesItem(i)->group() != item->group()) {
236 insertItem(i, item);
237 inserted = true;
238 }
239 ++i;
240 }
241
242 if (!inserted) {
243 appendItem(item);
244 }
245 }
246
247
248 QAction* PlacesItemModel::ejectAction(int index) const
249 {
250 const PlacesItem* item = placesItem(index);
251 if (item && item->device().is<Solid::OpticalDisc>()) {
252 return new QAction(QIcon::fromTheme(QStringLiteral("media-eject")), i18nc("@item", "Eject '%1'", item->text()), 0);
253 }
254
255 return 0;
256 }
257
258 QAction* PlacesItemModel::teardownAction(int index) const
259 {
260 const PlacesItem* item = placesItem(index);
261 if (!item) {
262 return 0;
263 }
264
265 Solid::Device device = item->device();
266 const bool providesTearDown = device.is<Solid::StorageAccess>() &&
267 device.as<Solid::StorageAccess>()->isAccessible();
268 if (!providesTearDown) {
269 return 0;
270 }
271
272 Solid::StorageDrive* drive = device.as<Solid::StorageDrive>();
273 if (!drive) {
274 drive = device.parent().as<Solid::StorageDrive>();
275 }
276
277 bool hotPluggable = false;
278 bool removable = false;
279 if (drive) {
280 hotPluggable = drive->isHotpluggable();
281 removable = drive->isRemovable();
282 }
283
284 QString iconName;
285 QString text;
286 const QString label = item->text();
287 if (device.is<Solid::OpticalDisc>()) {
288 text = i18nc("@item", "Release '%1'", label);
289 } else if (removable || hotPluggable) {
290 text = i18nc("@item", "Safely Remove '%1'", label);
291 iconName = QStringLiteral("media-eject");
292 } else {
293 text = i18nc("@item", "Unmount '%1'", label);
294 iconName = QStringLiteral("media-eject");
295 }
296
297 if (iconName.isEmpty()) {
298 return new QAction(text, 0);
299 }
300
301 return new QAction(QIcon::fromTheme(iconName), text, 0);
302 }
303
304 void PlacesItemModel::requestEject(int index)
305 {
306 const PlacesItem* item = placesItem(index);
307 if (item) {
308 Solid::OpticalDrive* drive = item->device().parent().as<Solid::OpticalDrive>();
309 if (drive) {
310 connect(drive, &Solid::OpticalDrive::ejectDone,
311 this, &PlacesItemModel::slotStorageTeardownDone);
312 drive->eject();
313 } else {
314 const QString label = item->text();
315 const QString message = i18nc("@info", "The device '%1' is not a disk and cannot be ejected.", label);
316 emit errorMessage(message);
317 }
318 }
319 }
320
321 void PlacesItemModel::requestTeardown(int index)
322 {
323 const PlacesItem* item = placesItem(index);
324 if (item) {
325 Solid::StorageAccess* access = item->device().as<Solid::StorageAccess>();
326 if (access) {
327 connect(access, &Solid::StorageAccess::teardownDone,
328 this, &PlacesItemModel::slotStorageTeardownDone);
329 access->teardown();
330 }
331 }
332 }
333
334 bool PlacesItemModel::storageSetupNeeded(int index) const
335 {
336 const PlacesItem* item = placesItem(index);
337 return item ? item->storageSetupNeeded() : false;
338 }
339
340 void PlacesItemModel::requestStorageSetup(int index)
341 {
342 const PlacesItem* item = placesItem(index);
343 if (!item) {
344 return;
345 }
346
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();
351 if (setup) {
352 Solid::StorageAccess* access = device.as<Solid::StorageAccess>();
353
354 m_storageSetupInProgress[access] = index;
355
356 connect(access, &Solid::StorageAccess::setupDone,
357 this, &PlacesItemModel::slotStorageSetupDone);
358
359 access->setup();
360 }
361 }
362
363 QMimeData* PlacesItemModel::createMimeData(const KItemSet& indexes) const
364 {
365 QList<QUrl> urls;
366 QByteArray itemData;
367
368 QDataStream stream(&itemData, QIODevice::WriteOnly);
369
370 for (int index : indexes) {
371 const QUrl itemUrl = placesItem(index)->url();
372 if (itemUrl.isValid()) {
373 urls << itemUrl;
374 }
375 stream << index;
376 }
377
378 QMimeData* mimeData = new QMimeData();
379 if (!urls.isEmpty()) {
380 mimeData->setUrls(urls);
381 }
382 mimeData->setData(internalMimeType(), itemData);
383
384 return mimeData;
385 }
386
387 bool PlacesItemModel::supportsDropping(int index) const
388 {
389 return index >= 0 && index < count();
390 }
391
392 void PlacesItemModel::dropMimeDataBefore(int index, const QMimeData* mimeData)
393 {
394 if (mimeData->hasFormat(internalMimeType())) {
395 // The item has been moved inside the view
396 QByteArray itemData = mimeData->data(internalMimeType());
397 QDataStream stream(&itemData, QIODevice::ReadOnly);
398 int oldIndex;
399 stream >> oldIndex;
400 if (oldIndex == index || oldIndex == index - 1) {
401 // No moving has been done
402 return;
403 }
404
405 PlacesItem* oldItem = placesItem(oldIndex);
406 if (!oldItem) {
407 return;
408 }
409
410 PlacesItem* newItem = new PlacesItem(oldItem->bookmark());
411 removeItem(oldIndex);
412
413 if (oldIndex < index) {
414 --index;
415 }
416
417 const int dropIndex = groupedDropIndex(index, newItem);
418 insertItem(dropIndex, newItem);
419 } else if (mimeData->hasFormat(QStringLiteral("text/uri-list"))) {
420 // One or more items must be added to the model
421 const QList<QUrl> urls = KUrlMimeData::urlsFromMimeData(mimeData);
422 for (int i = urls.count() - 1; i >= 0; --i) {
423 const QUrl& url = urls[i];
424
425 QString text = url.fileName();
426 if (text.isEmpty()) {
427 text = url.host();
428 }
429
430 if ((url.isLocalFile() && !QFileInfo(url.toLocalFile()).isDir())
431 || url.scheme() == QLatin1String("trash")) {
432 // Only directories outside the trash are allowed
433 continue;
434 }
435
436 PlacesItem* newItem = createPlacesItem(text, url);
437 const int dropIndex = groupedDropIndex(index, newItem);
438 insertItem(dropIndex, newItem);
439 }
440 }
441 }
442
443 QUrl PlacesItemModel::convertedUrl(const QUrl& url)
444 {
445 QUrl newUrl = url;
446 if (url.scheme() == QLatin1String("timeline")) {
447 newUrl = createTimelineUrl(url);
448 } else if (url.scheme() == QLatin1String("search")) {
449 newUrl = createSearchUrl(url);
450 }
451
452 return newUrl;
453 }
454
455 void PlacesItemModel::onItemInserted(int index)
456 {
457 const PlacesItem* insertedItem = placesItem(index);
458 if (insertedItem) {
459 // Take care to apply the PlacesItemModel-order of the inserted item
460 // also to the bookmark-manager.
461 const KBookmark insertedBookmark = insertedItem->bookmark();
462
463 const PlacesItem* previousItem = placesItem(index - 1);
464 KBookmark previousBookmark;
465 if (previousItem) {
466 previousBookmark = previousItem->bookmark();
467 }
468
469 m_bookmarkManager->root().moveBookmark(insertedBookmark, previousBookmark);
470 }
471
472 if (index == count() - 1) {
473 // The item has been appended as last item to the list. In this
474 // case assure that it is also appended after the hidden items and
475 // not before (like done otherwise).
476 m_bookmarkedItems.append(0);
477 } else {
478
479 int modelIndex = -1;
480 int bookmarkIndex = 0;
481 while (bookmarkIndex < m_bookmarkedItems.count()) {
482 if (!m_bookmarkedItems[bookmarkIndex]) {
483 ++modelIndex;
484 if (modelIndex + 1 == index) {
485 break;
486 }
487 }
488 ++bookmarkIndex;
489 }
490 m_bookmarkedItems.insert(bookmarkIndex, 0);
491 }
492
493 #ifdef PLACESITEMMODEL_DEBUG
494 qCDebug(DolphinDebug) << "Inserted item" << index;
495 showModelState();
496 #endif
497 }
498
499 void PlacesItemModel::onItemRemoved(int index, KStandardItem* removedItem)
500 {
501 PlacesItem* placesItem = dynamic_cast<PlacesItem*>(removedItem);
502 if (placesItem) {
503 const KBookmark bookmark = placesItem->bookmark();
504 m_bookmarkManager->root().deleteBookmark(bookmark);
505 }
506
507 const int boomarkIndex = bookmarkIndex(index);
508 Q_ASSERT(!m_bookmarkedItems[boomarkIndex]);
509 m_bookmarkedItems.removeAt(boomarkIndex);
510
511 #ifdef PLACESITEMMODEL_DEBUG
512 qCDebug(DolphinDebug) << "Removed item" << index;
513 showModelState();
514 #endif
515 }
516
517 void PlacesItemModel::onItemChanged(int index, const QSet<QByteArray>& changedRoles)
518 {
519 const PlacesItem* changedItem = placesItem(index);
520 if (changedItem) {
521 // Take care to apply the PlacesItemModel-order of the changed item
522 // also to the bookmark-manager.
523 const KBookmark insertedBookmark = changedItem->bookmark();
524
525 const PlacesItem* previousItem = placesItem(index - 1);
526 KBookmark previousBookmark;
527 if (previousItem) {
528 previousBookmark = previousItem->bookmark();
529 }
530
531 m_bookmarkManager->root().moveBookmark(insertedBookmark, previousBookmark);
532 }
533
534 if (changedRoles.contains("isHidden")) {
535 if (!m_hiddenItemsShown && changedItem->isHidden()) {
536 m_hiddenItemToRemove = index;
537 QTimer::singleShot(0, this, static_cast<void (PlacesItemModel::*)()>(&PlacesItemModel::hideItem));
538 }
539 }
540 }
541
542 void PlacesItemModel::slotDeviceAdded(const QString& udi)
543 {
544 const Solid::Device device(udi);
545
546 if (!m_predicate.matches(device)) {
547 return;
548 }
549
550 m_availableDevices << udi;
551 const KBookmark bookmark = PlacesItem::createDeviceBookmark(m_bookmarkManager, udi);
552 appendItem(new PlacesItem(bookmark));
553 }
554
555 void PlacesItemModel::slotDeviceRemoved(const QString& udi)
556 {
557 if (!m_availableDevices.contains(udi)) {
558 return;
559 }
560
561 for (int i = 0; i < m_bookmarkedItems.count(); ++i) {
562 PlacesItem* item = m_bookmarkedItems[i];
563 if (item && item->udi() == udi) {
564 m_bookmarkedItems.removeAt(i);
565 delete item;
566 return;
567 }
568 }
569
570 for (int i = 0; i < count(); ++i) {
571 if (placesItem(i)->udi() == udi) {
572 removeItem(i);
573 return;
574 }
575 }
576 }
577
578 void PlacesItemModel::slotStorageTeardownDone(Solid::ErrorType error, const QVariant& errorData)
579 {
580 if (error && errorData.isValid()) {
581 emit errorMessage(errorData.toString());
582 }
583 }
584
585 void PlacesItemModel::slotStorageSetupDone(Solid::ErrorType error,
586 const QVariant& errorData,
587 const QString& udi)
588 {
589 Q_UNUSED(udi);
590
591 const int index = m_storageSetupInProgress.take(sender());
592 const PlacesItem* item = placesItem(index);
593 if (!item) {
594 return;
595 }
596
597 if (error != Solid::NoError) {
598 if (errorData.isValid()) {
599 emit errorMessage(i18nc("@info", "An error occurred while accessing '%1', the system responded: %2",
600 item->text(),
601 errorData.toString()));
602 } else {
603 emit errorMessage(i18nc("@info", "An error occurred while accessing '%1'",
604 item->text()));
605 }
606 emit storageSetupDone(index, false);
607 } else {
608 emit storageSetupDone(index, true);
609 }
610 }
611
612 void PlacesItemModel::hideItem()
613 {
614 hideItem(m_hiddenItemToRemove);
615 m_hiddenItemToRemove = -1;
616 }
617
618 void PlacesItemModel::updateBookmarks()
619 {
620 // Verify whether new bookmarks have been added or existing
621 // bookmarks have been changed.
622 KBookmarkGroup root = m_bookmarkManager->root();
623 KBookmark newBookmark = root.first();
624 while (!newBookmark.isNull()) {
625 if (acceptBookmark(newBookmark, m_availableDevices)) {
626 bool found = false;
627 int modelIndex = 0;
628 for (int i = 0; i < m_bookmarkedItems.count(); ++i) {
629 PlacesItem* item = m_bookmarkedItems[i];
630 if (!item) {
631 item = placesItem(modelIndex);
632 ++modelIndex;
633 }
634
635 const KBookmark oldBookmark = item->bookmark();
636 if (equalBookmarkIdentifiers(newBookmark, oldBookmark)) {
637 // The bookmark has been found in the model or as
638 // a hidden item. The content of the bookmark might
639 // have been changed, so an update is done.
640 found = true;
641 if (newBookmark.metaDataItem(QStringLiteral("UDI")).isEmpty()) {
642 item->setBookmark(newBookmark);
643 item->setText(i18nc("KFile System Bookmarks", newBookmark.text().toUtf8().constData()));
644 }
645 break;
646 }
647 }
648
649 if (!found) {
650 const QString udi = newBookmark.metaDataItem(QStringLiteral("UDI"));
651
652 /*
653 * See Bug 304878
654 * Only add a new places item, if the item text is not empty
655 * and if the device is available. Fixes the strange behaviour -
656 * add a places item without text in the Places section - when you
657 * remove a device (e.g. a usb stick) without unmounting.
658 */
659 if (udi.isEmpty() || Solid::Device(udi).isValid()) {
660 PlacesItem* item = new PlacesItem(newBookmark);
661 if (item->isHidden() && !m_hiddenItemsShown) {
662 m_bookmarkedItems.append(item);
663 } else {
664 appendItemToGroup(item);
665 }
666 }
667 }
668 }
669
670 newBookmark = root.next(newBookmark);
671 }
672
673 // Remove items that are not part of the bookmark-manager anymore
674 int modelIndex = 0;
675 for (int i = m_bookmarkedItems.count() - 1; i >= 0; --i) {
676 PlacesItem* item = m_bookmarkedItems[i];
677 const bool itemIsPartOfModel = (item == 0);
678 if (itemIsPartOfModel) {
679 item = placesItem(modelIndex);
680 }
681
682 bool hasBeenRemoved = true;
683 const KBookmark oldBookmark = item->bookmark();
684 KBookmark newBookmark = root.first();
685 while (!newBookmark.isNull()) {
686 if (equalBookmarkIdentifiers(newBookmark, oldBookmark)) {
687 hasBeenRemoved = false;
688 break;
689 }
690 newBookmark = root.next(newBookmark);
691 }
692
693 if (hasBeenRemoved) {
694 if (m_bookmarkedItems[i]) {
695 delete m_bookmarkedItems[i];
696 m_bookmarkedItems.removeAt(i);
697 } else {
698 removeItem(modelIndex);
699 --modelIndex;
700 }
701 }
702
703 if (itemIsPartOfModel) {
704 ++modelIndex;
705 }
706 }
707 }
708
709 void PlacesItemModel::saveBookmarks()
710 {
711 m_bookmarkManager->emitChanged(m_bookmarkManager->root());
712 }
713
714 void PlacesItemModel::loadBookmarks()
715 {
716 KBookmarkGroup root = m_bookmarkManager->root();
717 KBookmark bookmark = root.first();
718 QSet<QString> devices = m_availableDevices;
719
720 QSet<QUrl> missingSystemBookmarks;
721 foreach (const SystemBookmarkData& data, m_systemBookmarks) {
722 missingSystemBookmarks.insert(data.url);
723 }
724
725 // The bookmarks might have a mixed order of places, devices and search-groups due
726 // to the compatibility with the KFilePlacesPanel. In Dolphin's places panel the
727 // items should always be collected in one group so the items are collected first
728 // in separate lists before inserting them.
729 QList<PlacesItem*> placesItems;
730 QList<PlacesItem*> recentlySavedItems;
731 QList<PlacesItem*> searchForItems;
732 QList<PlacesItem*> devicesItems;
733
734 while (!bookmark.isNull()) {
735 if (acceptBookmark(bookmark, devices)) {
736 PlacesItem* item = new PlacesItem(bookmark);
737 if (item->groupType() == PlacesItem::DevicesType) {
738 devices.remove(item->udi());
739 devicesItems.append(item);
740 } else {
741 const QUrl url = bookmark.url();
742 if (missingSystemBookmarks.contains(url)) {
743 missingSystemBookmarks.remove(url);
744
745 // Try to retranslate the text of system bookmarks to have translated
746 // items when changing the language. In case if the user has applied a custom
747 // text, the retranslation will fail and the users custom text is still used.
748 // It is important to use "KFile System Bookmarks" as context (see
749 // createSystemBookmarks()).
750 item->setText(i18nc("KFile System Bookmarks", bookmark.text().toUtf8().constData()));
751 item->setSystemItem(true);
752 }
753
754 switch (item->groupType()) {
755 case PlacesItem::PlacesType: placesItems.append(item); break;
756 case PlacesItem::RecentlySavedType: recentlySavedItems.append(item); break;
757 case PlacesItem::SearchForType: searchForItems.append(item); break;
758 case PlacesItem::DevicesType:
759 default: Q_ASSERT(false); break;
760 }
761 }
762 }
763
764 bookmark = root.next(bookmark);
765 }
766
767 if (!missingSystemBookmarks.isEmpty()) {
768 // The current bookmarks don't contain all system-bookmarks. Add the missing
769 // bookmarks.
770 foreach (const SystemBookmarkData& data, m_systemBookmarks) {
771 if (missingSystemBookmarks.contains(data.url)) {
772 PlacesItem* item = createSystemPlacesItem(data);
773 switch (item->groupType()) {
774 case PlacesItem::PlacesType: placesItems.append(item); break;
775 case PlacesItem::RecentlySavedType: recentlySavedItems.append(item); break;
776 case PlacesItem::SearchForType: searchForItems.append(item); break;
777 case PlacesItem::DevicesType:
778 default: Q_ASSERT(false); break;
779 }
780 }
781 }
782 }
783
784 // Create items for devices that have not been stored as bookmark yet
785 devicesItems.reserve(devicesItems.count() + devices.count());
786 foreach (const QString& udi, devices) {
787 const KBookmark bookmark = PlacesItem::createDeviceBookmark(m_bookmarkManager, udi);
788 devicesItems.append(new PlacesItem(bookmark));
789 }
790
791 QList<PlacesItem*> items;
792 items.append(placesItems);
793 items.append(recentlySavedItems);
794 items.append(searchForItems);
795 items.append(devicesItems);
796
797 foreach (PlacesItem* item, items) {
798 if (!m_hiddenItemsShown && item->isHidden()) {
799 m_bookmarkedItems.append(item);
800 } else {
801 appendItem(item);
802 }
803 }
804
805 #ifdef PLACESITEMMODEL_DEBUG
806 qCDebug(DolphinDebug) << "Loaded bookmarks";
807 showModelState();
808 #endif
809 }
810
811 bool PlacesItemModel::acceptBookmark(const KBookmark& bookmark,
812 const QSet<QString>& availableDevices) const
813 {
814 const QString udi = bookmark.metaDataItem(QStringLiteral("UDI"));
815 const QUrl url = bookmark.url();
816 const QString appName = bookmark.metaDataItem(QStringLiteral("OnlyInApp"));
817 const bool deviceAvailable = availableDevices.contains(udi);
818
819 const bool allowedHere = (appName.isEmpty()
820 || appName == KAboutData::applicationData().componentName()
821 || appName == KAboutData::applicationData().componentName() + AppNamePrefix)
822 && (m_fileIndexingEnabled || (url.scheme() != QLatin1String("timeline") &&
823 url.scheme() != QLatin1String("search")));
824
825 return (udi.isEmpty() && allowedHere) || deviceAvailable;
826 }
827
828 PlacesItem* PlacesItemModel::createSystemPlacesItem(const SystemBookmarkData& data)
829 {
830 KBookmark bookmark = PlacesItem::createBookmark(m_bookmarkManager,
831 data.text,
832 data.url,
833 data.icon);
834
835 const QString protocol = data.url.scheme();
836 if (protocol == QLatin1String("timeline") || protocol == QLatin1String("search")) {
837 // As long as the KFilePlacesView from kdelibs is available, the system-bookmarks
838 // for "Recently Saved" 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 = KAboutData::applicationData().componentName() + AppNamePrefix;
841 bookmark.setMetaDataItem(QStringLiteral("OnlyInApp"), appName);
842 }
843
844 PlacesItem* item = new PlacesItem(bookmark);
845 item->setSystemItem(true);
846
847 // Create default view-properties for all "Search For" and "Recently Saved" bookmarks
848 // in case if the user has not already created custom view-properties for a corresponding
849 // query yet.
850 const bool createDefaultViewProperties = (item->groupType() == PlacesItem::SearchForType ||
851 item->groupType() == PlacesItem::RecentlySavedType) &&
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({"text", "path"});
861 } else if (path == QLatin1String("/images")) {
862 props.setViewMode(DolphinView::IconsView);
863 props.setPreviewsShown(true);
864 props.setVisibleRoles({"text", "imageSize"});
865 } else if (path == QLatin1String("/audio")) {
866 props.setViewMode(DolphinView::DetailsView);
867 props.setPreviewsShown(false);
868 props.setVisibleRoles({"text", "artist", "album"});
869 } else if (path == QLatin1String("/videos")) {
870 props.setViewMode(DolphinView::IconsView);
871 props.setPreviewsShown(true);
872 props.setVisibleRoles({"text"});
873 } else if (data.url.scheme() == QLatin1String("timeline")) {
874 props.setViewMode(DolphinView::DetailsView);
875 props.setVisibleRoles({"text", "modificationtime"});
876 }
877 }
878 }
879
880 return item;
881 }
882
883 void PlacesItemModel::createSystemBookmarks()
884 {
885 Q_ASSERT(m_systemBookmarks.isEmpty());
886 Q_ASSERT(m_systemBookmarksIndexes.isEmpty());
887
888 // Note: The context of the I18N_NOOP2 must be "KFile System Bookmarks". The real
889 // i18nc call is done after reading the bookmark. The reason why the i18nc call is not
890 // done here is because otherwise switching the language would not result in retranslating the
891 // bookmarks.
892 m_systemBookmarks.append(SystemBookmarkData(QUrl::fromLocalFile(KUser().homeDir()),
893 QStringLiteral("user-home"),
894 I18N_NOOP2("KFile System Bookmarks", "Home")));
895 m_systemBookmarks.append(SystemBookmarkData(QUrl(QStringLiteral("remote:/")),
896 QStringLiteral("network-workgroup"),
897 I18N_NOOP2("KFile System Bookmarks", "Network")));
898 m_systemBookmarks.append(SystemBookmarkData(QUrl::fromLocalFile(QStringLiteral("/")),
899 QStringLiteral("folder-red"),
900 I18N_NOOP2("KFile System Bookmarks", "Root")));
901 m_systemBookmarks.append(SystemBookmarkData(QUrl(QStringLiteral("trash:/")),
902 QStringLiteral("user-trash"),
903 I18N_NOOP2("KFile System Bookmarks", "Trash")));
904
905 if (m_fileIndexingEnabled) {
906 m_systemBookmarks.append(SystemBookmarkData(QUrl(QStringLiteral("timeline:/today")),
907 QStringLiteral("go-jump-today"),
908 I18N_NOOP2("KFile System Bookmarks", "Today")));
909 m_systemBookmarks.append(SystemBookmarkData(QUrl(QStringLiteral("timeline:/yesterday")),
910 QStringLiteral("view-calendar-day"),
911 I18N_NOOP2("KFile System Bookmarks", "Yesterday")));
912 m_systemBookmarks.append(SystemBookmarkData(QUrl(QStringLiteral("timeline:/thismonth")),
913 QStringLiteral("view-calendar-month"),
914 I18N_NOOP2("KFile System Bookmarks", "This Month")));
915 m_systemBookmarks.append(SystemBookmarkData(QUrl(QStringLiteral("timeline:/lastmonth")),
916 QStringLiteral("view-calendar-month"),
917 I18N_NOOP2("KFile System Bookmarks", "Last Month")));
918 m_systemBookmarks.append(SystemBookmarkData(QUrl(QStringLiteral("search:/documents")),
919 QStringLiteral("folder-text"),
920 I18N_NOOP2("KFile System Bookmarks", "Documents")));
921 m_systemBookmarks.append(SystemBookmarkData(QUrl(QStringLiteral("search:/images")),
922 QStringLiteral("folder-images"),
923 I18N_NOOP2("KFile System Bookmarks", "Images")));
924 m_systemBookmarks.append(SystemBookmarkData(QUrl(QStringLiteral("search:/audio")),
925 QStringLiteral("folder-sound"),
926 I18N_NOOP2("KFile System Bookmarks", "Audio Files")));
927 m_systemBookmarks.append(SystemBookmarkData(QUrl(QStringLiteral("search:/videos")),
928 QStringLiteral("folder-videos"),
929 I18N_NOOP2("KFile System Bookmarks", "Videos")));
930 }
931
932 for (int i = 0; i < m_systemBookmarks.count(); ++i) {
933 m_systemBookmarksIndexes.insert(m_systemBookmarks[i].url, i);
934 }
935 }
936
937 void PlacesItemModel::clear() {
938 m_bookmarkedItems.clear();
939 KStandardItemModel::clear();
940 }
941
942 void PlacesItemModel::initializeAvailableDevices()
943 {
944 QString predicate(QStringLiteral("[[[[ StorageVolume.ignored == false AND [ StorageVolume.usage == 'FileSystem' OR StorageVolume.usage == 'Encrypted' ]]"
945 " OR "
946 "[ IS StorageAccess AND StorageDrive.driveType == 'Floppy' ]]"
947 " OR "
948 "OpticalDisc.availableContent & 'Audio' ]"
949 " OR "
950 "StorageAccess.ignored == false ]"));
951
952
953 if (KProtocolInfo::isKnownProtocol(QStringLiteral("mtp"))) {
954 predicate.prepend("[");
955 predicate.append(" OR PortableMediaPlayer.supportedProtocols == 'mtp']");
956 }
957
958 m_predicate = Solid::Predicate::fromString(predicate);
959 Q_ASSERT(m_predicate.isValid());
960
961 Solid::DeviceNotifier* notifier = Solid::DeviceNotifier::instance();
962 connect(notifier, &Solid::DeviceNotifier::deviceAdded, this, &PlacesItemModel::slotDeviceAdded);
963 connect(notifier, &Solid::DeviceNotifier::deviceRemoved, this, &PlacesItemModel::slotDeviceRemoved);
964
965 const QList<Solid::Device>& deviceList = Solid::Device::listFromQuery(m_predicate);
966 foreach (const Solid::Device& device, deviceList) {
967 m_availableDevices << device.udi();
968 }
969 }
970
971 int PlacesItemModel::bookmarkIndex(int index) const
972 {
973 int bookmarkIndex = 0;
974 int modelIndex = 0;
975 while (bookmarkIndex < m_bookmarkedItems.count()) {
976 if (!m_bookmarkedItems[bookmarkIndex]) {
977 if (modelIndex == index) {
978 break;
979 }
980 ++modelIndex;
981 }
982 ++bookmarkIndex;
983 }
984
985 return bookmarkIndex >= m_bookmarkedItems.count() ? -1 : bookmarkIndex;
986 }
987
988 void PlacesItemModel::hideItem(int index)
989 {
990 PlacesItem* shownItem = placesItem(index);
991 if (!shownItem) {
992 return;
993 }
994
995 shownItem->setHidden(true);
996 if (m_hiddenItemsShown) {
997 // Removing items from the model is not allowed if all hidden
998 // items should be shown.
999 return;
1000 }
1001
1002 const int newIndex = bookmarkIndex(index);
1003 if (newIndex >= 0) {
1004 const KBookmark hiddenBookmark = shownItem->bookmark();
1005 PlacesItem* hiddenItem = new PlacesItem(hiddenBookmark);
1006
1007 const PlacesItem* previousItem = placesItem(index - 1);
1008 KBookmark previousBookmark;
1009 if (previousItem) {
1010 previousBookmark = previousItem->bookmark();
1011 }
1012
1013 const bool updateBookmark = (m_bookmarkManager->root().indexOf(hiddenBookmark) >= 0);
1014 removeItem(index);
1015
1016 if (updateBookmark) {
1017 // removeItem() also removed the bookmark from m_bookmarkManager in
1018 // PlacesItemModel::onItemRemoved(). However for hidden items the
1019 // bookmark should still be remembered, so readd it again:
1020 m_bookmarkManager->root().addBookmark(hiddenBookmark);
1021 m_bookmarkManager->root().moveBookmark(hiddenBookmark, previousBookmark);
1022 }
1023
1024 m_bookmarkedItems.insert(newIndex, hiddenItem);
1025 }
1026 }
1027
1028 QString PlacesItemModel::internalMimeType() const
1029 {
1030 return "application/x-dolphinplacesmodel-" +
1031 QString::number((qptrdiff)this);
1032 }
1033
1034 int PlacesItemModel::groupedDropIndex(int index, const PlacesItem* item) const
1035 {
1036 Q_ASSERT(item);
1037
1038 int dropIndex = index;
1039 const PlacesItem::GroupType type = item->groupType();
1040
1041 const int itemCount = count();
1042 if (index < 0) {
1043 dropIndex = itemCount;
1044 }
1045
1046 // Search nearest previous item with the same group
1047 int previousIndex = -1;
1048 for (int i = dropIndex - 1; i >= 0; --i) {
1049 if (placesItem(i)->groupType() == type) {
1050 previousIndex = i;
1051 break;
1052 }
1053 }
1054
1055 // Search nearest next item with the same group
1056 int nextIndex = -1;
1057 for (int i = dropIndex; i < count(); ++i) {
1058 if (placesItem(i)->groupType() == type) {
1059 nextIndex = i;
1060 break;
1061 }
1062 }
1063
1064 // Adjust the drop-index to be inserted to the
1065 // nearest item with the same group.
1066 if (previousIndex >= 0 && nextIndex >= 0) {
1067 dropIndex = (dropIndex - previousIndex < nextIndex - dropIndex) ?
1068 previousIndex + 1 : nextIndex;
1069 } else if (previousIndex >= 0) {
1070 dropIndex = previousIndex + 1;
1071 } else if (nextIndex >= 0) {
1072 dropIndex = nextIndex;
1073 }
1074
1075 return dropIndex;
1076 }
1077
1078 bool PlacesItemModel::equalBookmarkIdentifiers(const KBookmark& b1, const KBookmark& b2)
1079 {
1080 const QString udi1 = b1.metaDataItem(QStringLiteral("UDI"));
1081 const QString udi2 = b2.metaDataItem(QStringLiteral("UDI"));
1082 if (!udi1.isEmpty() && !udi2.isEmpty()) {
1083 return udi1 == udi2;
1084 } else {
1085 return b1.metaDataItem(QStringLiteral("ID")) == b2.metaDataItem(QStringLiteral("ID"));
1086 }
1087 }
1088
1089 QUrl PlacesItemModel::createTimelineUrl(const QUrl& url)
1090 {
1091 // TODO: Clarify with the Baloo-team whether it makes sense
1092 // provide default-timeline-URLs like 'yesterday', 'this month'
1093 // and 'last month'.
1094 QUrl timelineUrl;
1095
1096 const QString path = url.toDisplayString(QUrl::PreferLocalFile);
1097 if (path.endsWith(QLatin1String("yesterday"))) {
1098 const QDate date = QDate::currentDate().addDays(-1);
1099 const int year = date.year();
1100 const int month = date.month();
1101 const int day = date.day();
1102 timelineUrl = QUrl("timeline:/" + timelineDateString(year, month) +
1103 '/' + timelineDateString(year, month, day));
1104 } else if (path.endsWith(QLatin1String("thismonth"))) {
1105 const QDate date = QDate::currentDate();
1106 timelineUrl = QUrl("timeline:/" + timelineDateString(date.year(), date.month()));
1107 } else if (path.endsWith(QLatin1String("lastmonth"))) {
1108 const QDate date = QDate::currentDate().addMonths(-1);
1109 timelineUrl = QUrl("timeline:/" + timelineDateString(date.year(), date.month()));
1110 } else {
1111 Q_ASSERT(path.endsWith(QLatin1String("today")));
1112 timelineUrl = url;
1113 }
1114
1115 return timelineUrl;
1116 }
1117
1118 QString PlacesItemModel::timelineDateString(int year, int month, int day)
1119 {
1120 QString date = QString::number(year) + '-';
1121 if (month < 10) {
1122 date += '0';
1123 }
1124 date += QString::number(month);
1125
1126 if (day >= 1) {
1127 date += '-';
1128 if (day < 10) {
1129 date += '0';
1130 }
1131 date += QString::number(day);
1132 }
1133
1134 return date;
1135 }
1136
1137 QUrl PlacesItemModel::createSearchUrl(const QUrl& url)
1138 {
1139 QUrl searchUrl;
1140
1141 #ifdef HAVE_BALOO
1142 const QString path = url.toDisplayString(QUrl::PreferLocalFile);
1143 if (path.endsWith(QLatin1String("documents"))) {
1144 searchUrl = searchUrlForType(QStringLiteral("Document"));
1145 } else if (path.endsWith(QLatin1String("images"))) {
1146 searchUrl = searchUrlForType(QStringLiteral("Image"));
1147 } else if (path.endsWith(QLatin1String("audio"))) {
1148 searchUrl = searchUrlForType(QStringLiteral("Audio"));
1149 } else if (path.endsWith(QLatin1String("videos"))) {
1150 searchUrl = searchUrlForType(QStringLiteral("Video"));
1151 } else {
1152 Q_ASSERT(false);
1153 }
1154 #else
1155 Q_UNUSED(url);
1156 #endif
1157
1158 return searchUrl;
1159 }
1160
1161 #ifdef HAVE_BALOO
1162 QUrl PlacesItemModel::searchUrlForType(const QString& type)
1163 {
1164 Baloo::Query query;
1165 query.addType(type);
1166
1167 return query.toSearchUrl();
1168 }
1169 #endif
1170
1171 #ifdef PLACESITEMMODEL_DEBUG
1172 void PlacesItemModel::showModelState()
1173 {
1174 qCDebug(DolphinDebug) << "=================================";
1175 qCDebug(DolphinDebug) << "Model:";
1176 qCDebug(DolphinDebug) << "hidden-index model-index text";
1177 int modelIndex = 0;
1178 for (int i = 0; i < m_bookmarkedItems.count(); ++i) {
1179 if (m_bookmarkedItems[i]) {
1180 qCDebug(DolphinDebug) << i << "(Hidden) " << " " << m_bookmarkedItems[i]->dataValue("text").toString();
1181 } else {
1182 if (item(modelIndex)) {
1183 qCDebug(DolphinDebug) << i << " " << modelIndex << " " << item(modelIndex)->dataValue("text").toString();
1184 } else {
1185 qCDebug(DolphinDebug) << i << " " << modelIndex << " " << "(not available yet)";
1186 }
1187 ++modelIndex;
1188 }
1189 }
1190
1191 qCDebug(DolphinDebug);
1192 qCDebug(DolphinDebug) << "Bookmarks:";
1193
1194 int bookmarkIndex = 0;
1195 KBookmarkGroup root = m_bookmarkManager->root();
1196 KBookmark bookmark = root.first();
1197 while (!bookmark.isNull()) {
1198 const QString udi = bookmark.metaDataItem("UDI");
1199 const QString text = udi.isEmpty() ? bookmark.text() : udi;
1200 if (bookmark.metaDataItem("IsHidden") == QLatin1String("true")) {
1201 qCDebug(DolphinDebug) << bookmarkIndex << "(Hidden)" << text;
1202 } else {
1203 qCDebug(DolphinDebug) << bookmarkIndex << " " << text;
1204 }
1205
1206 bookmark = root.next(bookmark);
1207 ++bookmarkIndex;
1208 }
1209 }
1210 #endif
1211