]> cloud.milkyroute.net Git - dolphin.git/blob - src/panels/places/placesitemmodel.cpp
Merge branch 'Applications/15.12'
[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("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 = "media-eject";
292 } else {
293 text = i18nc("@item", "Unmount '%1'", label);
294 iconName = "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 foreach (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("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() == "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, SLOT(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("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("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 foreach (const QString& udi, devices) {
786 const KBookmark bookmark = PlacesItem::createDeviceBookmark(m_bookmarkManager, udi);
787 devicesItems.append(new PlacesItem(bookmark));
788 }
789
790 QList<PlacesItem*> items;
791 items.append(placesItems);
792 items.append(recentlySavedItems);
793 items.append(searchForItems);
794 items.append(devicesItems);
795
796 foreach (PlacesItem* item, items) {
797 if (!m_hiddenItemsShown && item->isHidden()) {
798 m_bookmarkedItems.append(item);
799 } else {
800 appendItem(item);
801 }
802 }
803
804 #ifdef PLACESITEMMODEL_DEBUG
805 qCDebug(DolphinDebug) << "Loaded bookmarks";
806 showModelState();
807 #endif
808 }
809
810 bool PlacesItemModel::acceptBookmark(const KBookmark& bookmark,
811 const QSet<QString>& availableDevices) const
812 {
813 const QString udi = bookmark.metaDataItem("UDI");
814 const QUrl url = bookmark.url();
815 const QString appName = bookmark.metaDataItem("OnlyInApp");
816 const bool deviceAvailable = availableDevices.contains(udi);
817
818 const bool allowedHere = (appName.isEmpty()
819 || appName == KAboutData::applicationData().componentName()
820 || appName == KAboutData::applicationData().componentName() + AppNamePrefix)
821 && (m_fileIndexingEnabled || (url.scheme() != QLatin1String("timeline") &&
822 url.scheme() != QLatin1String("search")));
823
824 return (udi.isEmpty() && allowedHere) || deviceAvailable;
825 }
826
827 PlacesItem* PlacesItemModel::createSystemPlacesItem(const SystemBookmarkData& data)
828 {
829 KBookmark bookmark = PlacesItem::createBookmark(m_bookmarkManager,
830 data.text,
831 data.url,
832 data.icon);
833
834 const QString protocol = data.url.scheme();
835 if (protocol == QLatin1String("timeline") || protocol == QLatin1String("search")) {
836 // As long as the KFilePlacesView from kdelibs is available, the system-bookmarks
837 // for "Recently Saved" and "Search For" should be a setting available only
838 // in the Places Panel (see description of AppNamePrefix for more details).
839 const QString appName = KAboutData::applicationData().componentName() + AppNamePrefix;
840 bookmark.setMetaDataItem("OnlyInApp", appName);
841 }
842
843 PlacesItem* item = new PlacesItem(bookmark);
844 item->setSystemItem(true);
845
846 // Create default view-properties for all "Search For" and "Recently Saved" bookmarks
847 // in case if the user has not already created custom view-properties for a corresponding
848 // query yet.
849 const bool createDefaultViewProperties = (item->groupType() == PlacesItem::SearchForType ||
850 item->groupType() == PlacesItem::RecentlySavedType) &&
851 !GeneralSettings::self()->globalViewProps();
852 if (createDefaultViewProperties) {
853 ViewProperties props(convertedUrl(data.url));
854 if (!props.exist()) {
855 const QString path = data.url.path();
856 if (path == QLatin1String("/documents")) {
857 props.setViewMode(DolphinView::DetailsView);
858 props.setPreviewsShown(false);
859 props.setVisibleRoles({"text", "path"});
860 } else if (path == QLatin1String("/images")) {
861 props.setViewMode(DolphinView::IconsView);
862 props.setPreviewsShown(true);
863 props.setVisibleRoles({"text", "imageSize"});
864 } else if (path == QLatin1String("/audio")) {
865 props.setViewMode(DolphinView::DetailsView);
866 props.setPreviewsShown(false);
867 props.setVisibleRoles({"text", "artist", "album"});
868 } else if (path == QLatin1String("/videos")) {
869 props.setViewMode(DolphinView::IconsView);
870 props.setPreviewsShown(true);
871 props.setVisibleRoles({"text"});
872 } else if (data.url.scheme() == "timeline") {
873 props.setViewMode(DolphinView::DetailsView);
874 props.setVisibleRoles({"text", "date"});
875 }
876 }
877 }
878
879 return item;
880 }
881
882 void PlacesItemModel::createSystemBookmarks()
883 {
884 Q_ASSERT(m_systemBookmarks.isEmpty());
885 Q_ASSERT(m_systemBookmarksIndexes.isEmpty());
886
887 // Note: The context of the I18N_NOOP2 must be "KFile System Bookmarks". The real
888 // i18nc call is done after reading the bookmark. The reason why the i18nc call is not
889 // done here is because otherwise switching the language would not result in retranslating the
890 // bookmarks.
891 m_systemBookmarks.append(SystemBookmarkData(QUrl::fromLocalFile(KUser().homeDir()),
892 "user-home",
893 I18N_NOOP2("KFile System Bookmarks", "Home")));
894 m_systemBookmarks.append(SystemBookmarkData(QUrl("remote:/"),
895 "network-workgroup",
896 I18N_NOOP2("KFile System Bookmarks", "Network")));
897 m_systemBookmarks.append(SystemBookmarkData(QUrl::fromLocalFile("/"),
898 "folder-red",
899 I18N_NOOP2("KFile System Bookmarks", "Root")));
900 m_systemBookmarks.append(SystemBookmarkData(QUrl("trash:/"),
901 "user-trash",
902 I18N_NOOP2("KFile System Bookmarks", "Trash")));
903
904 if (m_fileIndexingEnabled) {
905 m_systemBookmarks.append(SystemBookmarkData(QUrl("timeline:/today"),
906 "go-jump-today",
907 I18N_NOOP2("KFile System Bookmarks", "Today")));
908 m_systemBookmarks.append(SystemBookmarkData(QUrl("timeline:/yesterday"),
909 "view-calendar-day",
910 I18N_NOOP2("KFile System Bookmarks", "Yesterday")));
911 m_systemBookmarks.append(SystemBookmarkData(QUrl("timeline:/thismonth"),
912 "view-calendar-month",
913 I18N_NOOP2("KFile System Bookmarks", "This Month")));
914 m_systemBookmarks.append(SystemBookmarkData(QUrl("timeline:/lastmonth"),
915 "view-calendar-month",
916 I18N_NOOP2("KFile System Bookmarks", "Last Month")));
917 m_systemBookmarks.append(SystemBookmarkData(QUrl("search:/documents"),
918 "folder-text",
919 I18N_NOOP2("KFile System Bookmarks", "Documents")));
920 m_systemBookmarks.append(SystemBookmarkData(QUrl("search:/images"),
921 "folder-images",
922 I18N_NOOP2("KFile System Bookmarks", "Images")));
923 m_systemBookmarks.append(SystemBookmarkData(QUrl("search:/audio"),
924 "folder-sound",
925 I18N_NOOP2("KFile System Bookmarks", "Audio Files")));
926 m_systemBookmarks.append(SystemBookmarkData(QUrl("search:/videos"),
927 "folder-videos",
928 I18N_NOOP2("KFile System Bookmarks", "Videos")));
929 }
930
931 for (int i = 0; i < m_systemBookmarks.count(); ++i) {
932 m_systemBookmarksIndexes.insert(m_systemBookmarks[i].url, i);
933 }
934 }
935
936 void PlacesItemModel::clear() {
937 m_bookmarkedItems.clear();
938 KStandardItemModel::clear();
939 }
940
941 void PlacesItemModel::initializeAvailableDevices()
942 {
943 QString predicate("[[[[ StorageVolume.ignored == false AND [ StorageVolume.usage == 'FileSystem' OR StorageVolume.usage == 'Encrypted' ]]"
944 " OR "
945 "[ IS StorageAccess AND StorageDrive.driveType == 'Floppy' ]]"
946 " OR "
947 "OpticalDisc.availableContent & 'Audio' ]"
948 " OR "
949 "StorageAccess.ignored == false ]");
950
951
952 if (KProtocolInfo::isKnownProtocol("mtp")) {
953 predicate.prepend("[");
954 predicate.append(" OR PortableMediaPlayer.supportedProtocols == 'mtp']");
955 }
956
957 m_predicate = Solid::Predicate::fromString(predicate);
958 Q_ASSERT(m_predicate.isValid());
959
960 Solid::DeviceNotifier* notifier = Solid::DeviceNotifier::instance();
961 connect(notifier, &Solid::DeviceNotifier::deviceAdded, this, &PlacesItemModel::slotDeviceAdded);
962 connect(notifier, &Solid::DeviceNotifier::deviceRemoved, this, &PlacesItemModel::slotDeviceRemoved);
963
964 const QList<Solid::Device>& deviceList = Solid::Device::listFromQuery(m_predicate);
965 foreach (const Solid::Device& device, deviceList) {
966 m_availableDevices << device.udi();
967 }
968 }
969
970 int PlacesItemModel::bookmarkIndex(int index) const
971 {
972 int bookmarkIndex = 0;
973 int modelIndex = 0;
974 while (bookmarkIndex < m_bookmarkedItems.count()) {
975 if (!m_bookmarkedItems[bookmarkIndex]) {
976 if (modelIndex == index) {
977 break;
978 }
979 ++modelIndex;
980 }
981 ++bookmarkIndex;
982 }
983
984 return bookmarkIndex >= m_bookmarkedItems.count() ? -1 : bookmarkIndex;
985 }
986
987 void PlacesItemModel::hideItem(int index)
988 {
989 PlacesItem* shownItem = placesItem(index);
990 if (!shownItem) {
991 return;
992 }
993
994 shownItem->setHidden(true);
995 if (m_hiddenItemsShown) {
996 // Removing items from the model is not allowed if all hidden
997 // items should be shown.
998 return;
999 }
1000
1001 const int newIndex = bookmarkIndex(index);
1002 if (newIndex >= 0) {
1003 const KBookmark hiddenBookmark = shownItem->bookmark();
1004 PlacesItem* hiddenItem = new PlacesItem(hiddenBookmark);
1005
1006 const PlacesItem* previousItem = placesItem(index - 1);
1007 KBookmark previousBookmark;
1008 if (previousItem) {
1009 previousBookmark = previousItem->bookmark();
1010 }
1011
1012 const bool updateBookmark = (m_bookmarkManager->root().indexOf(hiddenBookmark) >= 0);
1013 removeItem(index);
1014
1015 if (updateBookmark) {
1016 // removeItem() also removed the bookmark from m_bookmarkManager in
1017 // PlacesItemModel::onItemRemoved(). However for hidden items the
1018 // bookmark should still be remembered, so readd it again:
1019 m_bookmarkManager->root().addBookmark(hiddenBookmark);
1020 m_bookmarkManager->root().moveBookmark(hiddenBookmark, previousBookmark);
1021 }
1022
1023 m_bookmarkedItems.insert(newIndex, hiddenItem);
1024 }
1025 }
1026
1027 QString PlacesItemModel::internalMimeType() const
1028 {
1029 return "application/x-dolphinplacesmodel-" +
1030 QString::number((qptrdiff)this);
1031 }
1032
1033 int PlacesItemModel::groupedDropIndex(int index, const PlacesItem* item) const
1034 {
1035 Q_ASSERT(item);
1036
1037 int dropIndex = index;
1038 const PlacesItem::GroupType type = item->groupType();
1039
1040 const int itemCount = count();
1041 if (index < 0) {
1042 dropIndex = itemCount;
1043 }
1044
1045 // Search nearest previous item with the same group
1046 int previousIndex = -1;
1047 for (int i = dropIndex - 1; i >= 0; --i) {
1048 if (placesItem(i)->groupType() == type) {
1049 previousIndex = i;
1050 break;
1051 }
1052 }
1053
1054 // Search nearest next item with the same group
1055 int nextIndex = -1;
1056 for (int i = dropIndex; i < count(); ++i) {
1057 if (placesItem(i)->groupType() == type) {
1058 nextIndex = i;
1059 break;
1060 }
1061 }
1062
1063 // Adjust the drop-index to be inserted to the
1064 // nearest item with the same group.
1065 if (previousIndex >= 0 && nextIndex >= 0) {
1066 dropIndex = (dropIndex - previousIndex < nextIndex - dropIndex) ?
1067 previousIndex + 1 : nextIndex;
1068 } else if (previousIndex >= 0) {
1069 dropIndex = previousIndex + 1;
1070 } else if (nextIndex >= 0) {
1071 dropIndex = nextIndex;
1072 }
1073
1074 return dropIndex;
1075 }
1076
1077 bool PlacesItemModel::equalBookmarkIdentifiers(const KBookmark& b1, const KBookmark& b2)
1078 {
1079 const QString udi1 = b1.metaDataItem("UDI");
1080 const QString udi2 = b2.metaDataItem("UDI");
1081 if (!udi1.isEmpty() && !udi2.isEmpty()) {
1082 return udi1 == udi2;
1083 } else {
1084 return b1.metaDataItem("ID") == b2.metaDataItem("ID");
1085 }
1086 }
1087
1088 QUrl PlacesItemModel::createTimelineUrl(const QUrl& url)
1089 {
1090 // TODO: Clarify with the Baloo-team whether it makes sense
1091 // provide default-timeline-URLs like 'yesterday', 'this month'
1092 // and 'last month'.
1093 QUrl timelineUrl;
1094
1095 const QString path = url.toDisplayString(QUrl::PreferLocalFile);
1096 if (path.endsWith(QLatin1String("yesterday"))) {
1097 const QDate date = QDate::currentDate().addDays(-1);
1098 const int year = date.year();
1099 const int month = date.month();
1100 const int day = date.day();
1101 timelineUrl = "timeline:/" + timelineDateString(year, month) +
1102 '/' + timelineDateString(year, month, day);
1103 } else if (path.endsWith(QLatin1String("thismonth"))) {
1104 const QDate date = QDate::currentDate();
1105 timelineUrl = "timeline:/" + timelineDateString(date.year(), date.month());
1106 } else if (path.endsWith(QLatin1String("lastmonth"))) {
1107 const QDate date = QDate::currentDate().addMonths(-1);
1108 timelineUrl = "timeline:/" + timelineDateString(date.year(), date.month());
1109 } else {
1110 Q_ASSERT(path.endsWith(QLatin1String("today")));
1111 timelineUrl= url;
1112 }
1113
1114 return timelineUrl;
1115 }
1116
1117 QString PlacesItemModel::timelineDateString(int year, int month, int day)
1118 {
1119 QString date = QString::number(year) + '-';
1120 if (month < 10) {
1121 date += '0';
1122 }
1123 date += QString::number(month);
1124
1125 if (day >= 1) {
1126 date += '-';
1127 if (day < 10) {
1128 date += '0';
1129 }
1130 date += QString::number(day);
1131 }
1132
1133 return date;
1134 }
1135
1136 QUrl PlacesItemModel::createSearchUrl(const QUrl& url)
1137 {
1138 QUrl searchUrl;
1139
1140 #ifdef HAVE_BALOO
1141 const QString path = url.toDisplayString(QUrl::PreferLocalFile);
1142 if (path.endsWith(QLatin1String("documents"))) {
1143 searchUrl = searchUrlForType("Document");
1144 } else if (path.endsWith(QLatin1String("images"))) {
1145 searchUrl = searchUrlForType("Image");
1146 } else if (path.endsWith(QLatin1String("audio"))) {
1147 searchUrl = searchUrlForType("Audio");
1148 } else if (path.endsWith(QLatin1String("videos"))) {
1149 searchUrl = searchUrlForType("Video");
1150 } else {
1151 Q_ASSERT(false);
1152 }
1153 #else
1154 Q_UNUSED(url);
1155 #endif
1156
1157 return searchUrl;
1158 }
1159
1160 #ifdef HAVE_BALOO
1161 QUrl PlacesItemModel::searchUrlForType(const QString& type)
1162 {
1163 Baloo::Query query;
1164 query.addType(type);
1165
1166 return query.toSearchUrl();
1167 }
1168 #endif
1169
1170 #ifdef PLACESITEMMODEL_DEBUG
1171 void PlacesItemModel::showModelState()
1172 {
1173 qCDebug(DolphinDebug) << "=================================";
1174 qCDebug(DolphinDebug) << "Model:";
1175 qCDebug(DolphinDebug) << "hidden-index model-index text";
1176 int modelIndex = 0;
1177 for (int i = 0; i < m_bookmarkedItems.count(); ++i) {
1178 if (m_bookmarkedItems[i]) {
1179 qCDebug(DolphinDebug) << i << "(Hidden) " << " " << m_bookmarkedItems[i]->dataValue("text").toString();
1180 } else {
1181 if (item(modelIndex)) {
1182 qCDebug(DolphinDebug) << i << " " << modelIndex << " " << item(modelIndex)->dataValue("text").toString();
1183 } else {
1184 qCDebug(DolphinDebug) << i << " " << modelIndex << " " << "(not available yet)";
1185 }
1186 ++modelIndex;
1187 }
1188 }
1189
1190 qCDebug(DolphinDebug);
1191 qCDebug(DolphinDebug) << "Bookmarks:";
1192
1193 int bookmarkIndex = 0;
1194 KBookmarkGroup root = m_bookmarkManager->root();
1195 KBookmark bookmark = root.first();
1196 while (!bookmark.isNull()) {
1197 const QString udi = bookmark.metaDataItem("UDI");
1198 const QString text = udi.isEmpty() ? bookmark.text() : udi;
1199 if (bookmark.metaDataItem("IsHidden") == QLatin1String("true")) {
1200 qCDebug(DolphinDebug) << bookmarkIndex << "(Hidden)" << text;
1201 } else {
1202 qCDebug(DolphinDebug) << bookmarkIndex << " " << text;
1203 }
1204
1205 bookmark = root.next(bookmark);
1206 ++bookmarkIndex;
1207 }
1208 }
1209 #endif
1210