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