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