]> cloud.milkyroute.net Git - dolphin.git/blob - src/panels/places/placesitemmodel.cpp
Use user-places.xbel instead of bookmarks.xml in places model.
[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 connect(m_bookmarkManager, &KBookmarkManager::bookmarksChanged,
105 m_updateBookmarksTimer, static_cast<void(QTimer::*)()>(&QTimer::start));
106 }
107
108 PlacesItemModel::~PlacesItemModel()
109 {
110 qDeleteAll(m_bookmarkedItems);
111 m_bookmarkedItems.clear();
112 }
113
114 PlacesItem* PlacesItemModel::createPlacesItem(const QString& text,
115 const QUrl& url,
116 const QString& iconName)
117 {
118 const KBookmark bookmark = PlacesItem::createBookmark(m_bookmarkManager, text, url, iconName);
119 return new PlacesItem(bookmark);
120 }
121
122 PlacesItem* PlacesItemModel::placesItem(int index) const
123 {
124 return dynamic_cast<PlacesItem*>(item(index));
125 }
126
127 int PlacesItemModel::hiddenCount() const
128 {
129 int modelIndex = 0;
130 int hiddenItemCount = 0;
131 foreach (const PlacesItem* item, m_bookmarkedItems) {
132 if (item) {
133 ++hiddenItemCount;
134 } else {
135 if (placesItem(modelIndex)->isHidden()) {
136 ++hiddenItemCount;
137 }
138 ++modelIndex;
139 }
140 }
141
142 return hiddenItemCount;
143 }
144
145 void PlacesItemModel::setHiddenItemsShown(bool show)
146 {
147 if (m_hiddenItemsShown == show) {
148 return;
149 }
150
151 m_hiddenItemsShown = show;
152
153 if (show) {
154 // Move all items that are part of m_bookmarkedItems to the model.
155 QList<PlacesItem*> itemsToInsert;
156 QList<int> insertPos;
157 int modelIndex = 0;
158 for (int i = 0; i < m_bookmarkedItems.count(); ++i) {
159 if (m_bookmarkedItems[i]) {
160 itemsToInsert.append(m_bookmarkedItems[i]);
161 m_bookmarkedItems[i] = 0;
162 insertPos.append(modelIndex);
163 }
164 ++modelIndex;
165 }
166
167 // Inserting the items will automatically insert an item
168 // to m_bookmarkedItems in PlacesItemModel::onItemsInserted().
169 // The items are temporary saved in itemsToInsert, so
170 // m_bookmarkedItems can be shrinked now.
171 m_bookmarkedItems.erase(m_bookmarkedItems.begin(),
172 m_bookmarkedItems.begin() + itemsToInsert.count());
173
174 for (int i = 0; i < itemsToInsert.count(); ++i) {
175 insertItem(insertPos[i], itemsToInsert[i]);
176 }
177
178 Q_ASSERT(m_bookmarkedItems.count() == count());
179 } else {
180 // Move all items of the model, where the "isHidden" property is true, to
181 // m_bookmarkedItems.
182 Q_ASSERT(m_bookmarkedItems.count() == count());
183 for (int i = count() - 1; i >= 0; --i) {
184 if (placesItem(i)->isHidden()) {
185 hideItem(i);
186 }
187 }
188 }
189
190 #ifdef PLACESITEMMODEL_DEBUG
191 qCDebug(DolphinDebug) << "Changed visibility of hidden items";
192 showModelState();
193 #endif
194 }
195
196 bool PlacesItemModel::hiddenItemsShown() const
197 {
198 return m_hiddenItemsShown;
199 }
200
201 int PlacesItemModel::closestItem(const QUrl& url) const
202 {
203 int foundIndex = -1;
204 int maxLength = 0;
205
206 for (int i = 0; i < count(); ++i) {
207 const QUrl itemUrl = placesItem(i)->url();
208 if (url == itemUrl) {
209 // We can't find a closer one, so stop here.
210 foundIndex = i;
211 break;
212 } else if (itemUrl.isParentOf(url)) {
213 const int length = itemUrl.path().length();
214 if (length > maxLength) {
215 foundIndex = i;
216 maxLength = length;
217 }
218 }
219 }
220
221 return foundIndex;
222 }
223
224 void PlacesItemModel::appendItemToGroup(PlacesItem* item)
225 {
226 if (!item) {
227 return;
228 }
229
230 int i = 0;
231 while (i < count() && placesItem(i)->group() != item->group()) {
232 ++i;
233 }
234
235 bool inserted = false;
236 while (!inserted && i < count()) {
237 if (placesItem(i)->group() != item->group()) {
238 insertItem(i, item);
239 inserted = true;
240 }
241 ++i;
242 }
243
244 if (!inserted) {
245 appendItem(item);
246 }
247 }
248
249
250 QAction* PlacesItemModel::ejectAction(int index) const
251 {
252 const PlacesItem* item = placesItem(index);
253 if (item && item->device().is<Solid::OpticalDisc>()) {
254 return new QAction(QIcon::fromTheme("media-eject"), i18nc("@item", "Eject '%1'", item->text()), 0);
255 }
256
257 return 0;
258 }
259
260 QAction* PlacesItemModel::teardownAction(int index) const
261 {
262 const PlacesItem* item = placesItem(index);
263 if (!item) {
264 return 0;
265 }
266
267 Solid::Device device = item->device();
268 const bool providesTearDown = device.is<Solid::StorageAccess>() &&
269 device.as<Solid::StorageAccess>()->isAccessible();
270 if (!providesTearDown) {
271 return 0;
272 }
273
274 Solid::StorageDrive* drive = device.as<Solid::StorageDrive>();
275 if (!drive) {
276 drive = device.parent().as<Solid::StorageDrive>();
277 }
278
279 bool hotPluggable = false;
280 bool removable = false;
281 if (drive) {
282 hotPluggable = drive->isHotpluggable();
283 removable = drive->isRemovable();
284 }
285
286 QString iconName;
287 QString text;
288 const QString label = item->text();
289 if (device.is<Solid::OpticalDisc>()) {
290 text = i18nc("@item", "Release '%1'", label);
291 } else if (removable || hotPluggable) {
292 text = i18nc("@item", "Safely Remove '%1'", label);
293 iconName = "media-eject";
294 } else {
295 text = i18nc("@item", "Unmount '%1'", label);
296 iconName = "media-eject";
297 }
298
299 if (iconName.isEmpty()) {
300 return new QAction(text, 0);
301 }
302
303 return new QAction(QIcon::fromTheme(iconName), text, 0);
304 }
305
306 void PlacesItemModel::requestEject(int index)
307 {
308 const PlacesItem* item = placesItem(index);
309 if (item) {
310 Solid::OpticalDrive* drive = item->device().parent().as<Solid::OpticalDrive>();
311 if (drive) {
312 connect(drive, &Solid::OpticalDrive::ejectDone,
313 this, &PlacesItemModel::slotStorageTeardownDone);
314 drive->eject();
315 } else {
316 const QString label = item->text();
317 const QString message = i18nc("@info", "The device '%1' is not a disk and cannot be ejected.", label);
318 emit errorMessage(message);
319 }
320 }
321 }
322
323 void PlacesItemModel::requestTeardown(int index)
324 {
325 const PlacesItem* item = placesItem(index);
326 if (item) {
327 Solid::StorageAccess* access = item->device().as<Solid::StorageAccess>();
328 if (access) {
329 connect(access, &Solid::StorageAccess::teardownDone,
330 this, &PlacesItemModel::slotStorageTeardownDone);
331 access->teardown();
332 }
333 }
334 }
335
336 bool PlacesItemModel::storageSetupNeeded(int index) const
337 {
338 const PlacesItem* item = placesItem(index);
339 return item ? item->storageSetupNeeded() : false;
340 }
341
342 void PlacesItemModel::requestStorageSetup(int index)
343 {
344 const PlacesItem* item = placesItem(index);
345 if (!item) {
346 return;
347 }
348
349 Solid::Device device = item->device();
350 const bool setup = device.is<Solid::StorageAccess>()
351 && !m_storageSetupInProgress.contains(device.as<Solid::StorageAccess>())
352 && !device.as<Solid::StorageAccess>()->isAccessible();
353 if (setup) {
354 Solid::StorageAccess* access = device.as<Solid::StorageAccess>();
355
356 m_storageSetupInProgress[access] = index;
357
358 connect(access, &Solid::StorageAccess::setupDone,
359 this, &PlacesItemModel::slotStorageSetupDone);
360
361 access->setup();
362 }
363 }
364
365 QMimeData* PlacesItemModel::createMimeData(const KItemSet& indexes) const
366 {
367 QList<QUrl> urls;
368 QByteArray itemData;
369
370 QDataStream stream(&itemData, QIODevice::WriteOnly);
371
372 foreach (int index, indexes) {
373 const QUrl itemUrl = placesItem(index)->url();
374 if (itemUrl.isValid()) {
375 urls << itemUrl;
376 }
377 stream << index;
378 }
379
380 QMimeData* mimeData = new QMimeData();
381 if (!urls.isEmpty()) {
382 mimeData->setUrls(urls);
383 }
384 mimeData->setData(internalMimeType(), itemData);
385
386 return mimeData;
387 }
388
389 bool PlacesItemModel::supportsDropping(int index) const
390 {
391 return index >= 0 && index < count();
392 }
393
394 void PlacesItemModel::dropMimeDataBefore(int index, const QMimeData* mimeData)
395 {
396 if (mimeData->hasFormat(internalMimeType())) {
397 // The item has been moved inside the view
398 QByteArray itemData = mimeData->data(internalMimeType());
399 QDataStream stream(&itemData, QIODevice::ReadOnly);
400 int oldIndex;
401 stream >> oldIndex;
402 if (oldIndex == index || oldIndex == index - 1) {
403 // No moving has been done
404 return;
405 }
406
407 PlacesItem* oldItem = placesItem(oldIndex);
408 if (!oldItem) {
409 return;
410 }
411
412 PlacesItem* newItem = new PlacesItem(oldItem->bookmark());
413 removeItem(oldIndex);
414
415 if (oldIndex < index) {
416 --index;
417 }
418
419 const int dropIndex = groupedDropIndex(index, newItem);
420 insertItem(dropIndex, newItem);
421 } else if (mimeData->hasFormat("text/uri-list")) {
422 // One or more items must be added to the model
423 const QList<QUrl> urls = KUrlMimeData::urlsFromMimeData(mimeData);
424 for (int i = urls.count() - 1; i >= 0; --i) {
425 const QUrl& url = urls[i];
426
427 QString text = url.fileName();
428 if (text.isEmpty()) {
429 text = url.host();
430 }
431
432 if ((url.isLocalFile() && !QFileInfo(url.toLocalFile()).isDir())
433 || url.scheme() == "trash") {
434 // Only directories outside the trash are allowed
435 continue;
436 }
437
438 PlacesItem* newItem = createPlacesItem(text, url);
439 const int dropIndex = groupedDropIndex(index, newItem);
440 insertItem(dropIndex, newItem);
441 }
442 }
443 }
444
445 QUrl PlacesItemModel::convertedUrl(const QUrl& url)
446 {
447 QUrl newUrl = url;
448 if (url.scheme() == QLatin1String("timeline")) {
449 newUrl = createTimelineUrl(url);
450 } else if (url.scheme() == QLatin1String("search")) {
451 newUrl = createSearchUrl(url);
452 }
453
454 return newUrl;
455 }
456
457 void PlacesItemModel::onItemInserted(int index)
458 {
459 const PlacesItem* insertedItem = placesItem(index);
460 if (insertedItem) {
461 // Take care to apply the PlacesItemModel-order of the inserted item
462 // also to the bookmark-manager.
463 const KBookmark insertedBookmark = insertedItem->bookmark();
464
465 const PlacesItem* previousItem = placesItem(index - 1);
466 KBookmark previousBookmark;
467 if (previousItem) {
468 previousBookmark = previousItem->bookmark();
469 }
470
471 m_bookmarkManager->root().moveBookmark(insertedBookmark, previousBookmark);
472 }
473
474 if (index == count() - 1) {
475 // The item has been appended as last item to the list. In this
476 // case assure that it is also appended after the hidden items and
477 // not before (like done otherwise).
478 m_bookmarkedItems.append(0);
479 } else {
480
481 int modelIndex = -1;
482 int bookmarkIndex = 0;
483 while (bookmarkIndex < m_bookmarkedItems.count()) {
484 if (!m_bookmarkedItems[bookmarkIndex]) {
485 ++modelIndex;
486 if (modelIndex + 1 == index) {
487 break;
488 }
489 }
490 ++bookmarkIndex;
491 }
492 m_bookmarkedItems.insert(bookmarkIndex, 0);
493 }
494
495 #ifdef PLACESITEMMODEL_DEBUG
496 qCDebug(DolphinDebug) << "Inserted item" << index;
497 showModelState();
498 #endif
499 }
500
501 void PlacesItemModel::onItemRemoved(int index, KStandardItem* removedItem)
502 {
503 PlacesItem* placesItem = dynamic_cast<PlacesItem*>(removedItem);
504 if (placesItem) {
505 const KBookmark bookmark = placesItem->bookmark();
506 m_bookmarkManager->root().deleteBookmark(bookmark);
507 }
508
509 const int boomarkIndex = bookmarkIndex(index);
510 Q_ASSERT(!m_bookmarkedItems[boomarkIndex]);
511 m_bookmarkedItems.removeAt(boomarkIndex);
512
513 #ifdef PLACESITEMMODEL_DEBUG
514 qCDebug(DolphinDebug) << "Removed item" << index;
515 showModelState();
516 #endif
517 }
518
519 void PlacesItemModel::onItemChanged(int index, const QSet<QByteArray>& changedRoles)
520 {
521 const PlacesItem* changedItem = placesItem(index);
522 if (changedItem) {
523 // Take care to apply the PlacesItemModel-order of the changed item
524 // also to the bookmark-manager.
525 const KBookmark insertedBookmark = changedItem->bookmark();
526
527 const PlacesItem* previousItem = placesItem(index - 1);
528 KBookmark previousBookmark;
529 if (previousItem) {
530 previousBookmark = previousItem->bookmark();
531 }
532
533 m_bookmarkManager->root().moveBookmark(insertedBookmark, previousBookmark);
534 }
535
536 if (changedRoles.contains("isHidden")) {
537 if (!m_hiddenItemsShown && changedItem->isHidden()) {
538 m_hiddenItemToRemove = index;
539 QTimer::singleShot(0, this, SLOT(hideItem()));
540 }
541 }
542 }
543
544 void PlacesItemModel::slotDeviceAdded(const QString& udi)
545 {
546 const Solid::Device device(udi);
547
548 if (!m_predicate.matches(device)) {
549 return;
550 }
551
552 m_availableDevices << udi;
553 const KBookmark bookmark = PlacesItem::createDeviceBookmark(m_bookmarkManager, udi);
554 appendItem(new PlacesItem(bookmark));
555 }
556
557 void PlacesItemModel::slotDeviceRemoved(const QString& udi)
558 {
559 if (!m_availableDevices.contains(udi)) {
560 return;
561 }
562
563 for (int i = 0; i < m_bookmarkedItems.count(); ++i) {
564 PlacesItem* item = m_bookmarkedItems[i];
565 if (item && item->udi() == udi) {
566 m_bookmarkedItems.removeAt(i);
567 delete item;
568 return;
569 }
570 }
571
572 for (int i = 0; i < count(); ++i) {
573 if (placesItem(i)->udi() == udi) {
574 removeItem(i);
575 return;
576 }
577 }
578 }
579
580 void PlacesItemModel::slotStorageTeardownDone(Solid::ErrorType error, const QVariant& errorData)
581 {
582 if (error && errorData.isValid()) {
583 emit errorMessage(errorData.toString());
584 }
585 }
586
587 void PlacesItemModel::slotStorageSetupDone(Solid::ErrorType error,
588 const QVariant& errorData,
589 const QString& udi)
590 {
591 Q_UNUSED(udi);
592
593 const int index = m_storageSetupInProgress.take(sender());
594 const PlacesItem* item = placesItem(index);
595 if (!item) {
596 return;
597 }
598
599 if (error != Solid::NoError) {
600 if (errorData.isValid()) {
601 emit errorMessage(i18nc("@info", "An error occurred while accessing '%1', the system responded: %2",
602 item->text(),
603 errorData.toString()));
604 } else {
605 emit errorMessage(i18nc("@info", "An error occurred while accessing '%1'",
606 item->text()));
607 }
608 emit storageSetupDone(index, false);
609 } else {
610 emit storageSetupDone(index, true);
611 }
612 }
613
614 void PlacesItemModel::hideItem()
615 {
616 hideItem(m_hiddenItemToRemove);
617 m_hiddenItemToRemove = -1;
618 }
619
620 void PlacesItemModel::updateBookmarks()
621 {
622 // Verify whether new bookmarks have been added or existing
623 // bookmarks have been changed.
624 KBookmarkGroup root = m_bookmarkManager->root();
625 KBookmark newBookmark = root.first();
626 while (!newBookmark.isNull()) {
627 if (acceptBookmark(newBookmark, m_availableDevices)) {
628 bool found = false;
629 int modelIndex = 0;
630 for (int i = 0; i < m_bookmarkedItems.count(); ++i) {
631 PlacesItem* item = m_bookmarkedItems[i];
632 if (!item) {
633 item = placesItem(modelIndex);
634 ++modelIndex;
635 }
636
637 const KBookmark oldBookmark = item->bookmark();
638 if (equalBookmarkIdentifiers(newBookmark, oldBookmark)) {
639 // The bookmark has been found in the model or as
640 // a hidden item. The content of the bookmark might
641 // have been changed, so an update is done.
642 found = true;
643 if (newBookmark.metaDataItem("UDI").isEmpty()) {
644 item->setBookmark(newBookmark);
645 item->setText(i18nc("KFile System Bookmarks", newBookmark.text().toUtf8().constData()));
646 }
647 break;
648 }
649 }
650
651 if (!found) {
652 const QString udi = newBookmark.metaDataItem("UDI");
653
654 /*
655 * See Bug 304878
656 * Only add a new places item, if the item text is not empty
657 * and if the device is available. Fixes the strange behaviour -
658 * add a places item without text in the Places section - when you
659 * remove a device (e.g. a usb stick) without unmounting.
660 */
661 if (udi.isEmpty() || Solid::Device(udi).isValid()) {
662 PlacesItem* item = new PlacesItem(newBookmark);
663 if (item->isHidden() && !m_hiddenItemsShown) {
664 m_bookmarkedItems.append(item);
665 } else {
666 appendItemToGroup(item);
667 }
668 }
669 }
670 }
671
672 newBookmark = root.next(newBookmark);
673 }
674
675 // Remove items that are not part of the bookmark-manager anymore
676 int modelIndex = 0;
677 for (int i = m_bookmarkedItems.count() - 1; i >= 0; --i) {
678 PlacesItem* item = m_bookmarkedItems[i];
679 const bool itemIsPartOfModel = (item == 0);
680 if (itemIsPartOfModel) {
681 item = placesItem(modelIndex);
682 }
683
684 bool hasBeenRemoved = true;
685 const KBookmark oldBookmark = item->bookmark();
686 KBookmark newBookmark = root.first();
687 while (!newBookmark.isNull()) {
688 if (equalBookmarkIdentifiers(newBookmark, oldBookmark)) {
689 hasBeenRemoved = false;
690 break;
691 }
692 newBookmark = root.next(newBookmark);
693 }
694
695 if (hasBeenRemoved) {
696 if (m_bookmarkedItems[i]) {
697 delete m_bookmarkedItems[i];
698 m_bookmarkedItems.removeAt(i);
699 } else {
700 removeItem(modelIndex);
701 --modelIndex;
702 }
703 }
704
705 if (itemIsPartOfModel) {
706 ++modelIndex;
707 }
708 }
709 }
710
711 void PlacesItemModel::saveBookmarks()
712 {
713 m_bookmarkManager->emitChanged(m_bookmarkManager->root());
714 }
715
716 void PlacesItemModel::loadBookmarks()
717 {
718 KBookmarkGroup root = m_bookmarkManager->root();
719 KBookmark bookmark = root.first();
720 QSet<QString> devices = m_availableDevices;
721
722 QSet<QUrl> missingSystemBookmarks;
723 foreach (const SystemBookmarkData& data, m_systemBookmarks) {
724 missingSystemBookmarks.insert(data.url);
725 }
726
727 // The bookmarks might have a mixed order of places, devices and search-groups due
728 // to the compatibility with the KFilePlacesPanel. In Dolphin's places panel the
729 // items should always be collected in one group so the items are collected first
730 // in separate lists before inserting them.
731 QList<PlacesItem*> placesItems;
732 QList<PlacesItem*> recentlySavedItems;
733 QList<PlacesItem*> searchForItems;
734 QList<PlacesItem*> devicesItems;
735
736 while (!bookmark.isNull()) {
737 if (acceptBookmark(bookmark, devices)) {
738 PlacesItem* item = new PlacesItem(bookmark);
739 if (item->groupType() == PlacesItem::DevicesType) {
740 devices.remove(item->udi());
741 devicesItems.append(item);
742 } else {
743 const QUrl url = bookmark.url();
744 if (missingSystemBookmarks.contains(url)) {
745 missingSystemBookmarks.remove(url);
746
747 // Try to retranslate the text of system bookmarks to have translated
748 // items when changing the language. In case if the user has applied a custom
749 // text, the retranslation will fail and the users custom text is still used.
750 // It is important to use "KFile System Bookmarks" as context (see
751 // createSystemBookmarks()).
752 item->setText(i18nc("KFile System Bookmarks", bookmark.text().toUtf8().constData()));
753 item->setSystemItem(true);
754 }
755
756 switch (item->groupType()) {
757 case PlacesItem::PlacesType: placesItems.append(item); break;
758 case PlacesItem::RecentlySavedType: recentlySavedItems.append(item); break;
759 case PlacesItem::SearchForType: searchForItems.append(item); break;
760 case PlacesItem::DevicesType:
761 default: Q_ASSERT(false); break;
762 }
763 }
764 }
765
766 bookmark = root.next(bookmark);
767 }
768
769 if (!missingSystemBookmarks.isEmpty()) {
770 // The current bookmarks don't contain all system-bookmarks. Add the missing
771 // bookmarks.
772 foreach (const SystemBookmarkData& data, m_systemBookmarks) {
773 if (missingSystemBookmarks.contains(data.url)) {
774 PlacesItem* item = createSystemPlacesItem(data);
775 switch (item->groupType()) {
776 case PlacesItem::PlacesType: placesItems.append(item); break;
777 case PlacesItem::RecentlySavedType: recentlySavedItems.append(item); break;
778 case PlacesItem::SearchForType: searchForItems.append(item); break;
779 case PlacesItem::DevicesType:
780 default: Q_ASSERT(false); break;
781 }
782 }
783 }
784 }
785
786 // Create items for devices that have not been stored as bookmark yet
787 foreach (const QString& udi, devices) {
788 const KBookmark bookmark = PlacesItem::createDeviceBookmark(m_bookmarkManager, udi);
789 devicesItems.append(new PlacesItem(bookmark));
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("UDI");
816 const QUrl url = bookmark.url();
817 const QString appName = bookmark.metaDataItem("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("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() == "timeline") {
875 props.setViewMode(DolphinView::DetailsView);
876 props.setVisibleRoles({"text", "date"});
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(KUser().homeDir()),
894 "user-home",
895 I18N_NOOP2("KFile System Bookmarks", "Home")));
896 m_systemBookmarks.append(SystemBookmarkData(QUrl("remote:/"),
897 "network-workgroup",
898 I18N_NOOP2("KFile System Bookmarks", "Network")));
899 m_systemBookmarks.append(SystemBookmarkData(QUrl::fromLocalFile("/"),
900 "folder-red",
901 I18N_NOOP2("KFile System Bookmarks", "Root")));
902 m_systemBookmarks.append(SystemBookmarkData(QUrl("trash:/"),
903 "user-trash",
904 I18N_NOOP2("KFile System Bookmarks", "Trash")));
905
906 if (m_fileIndexingEnabled) {
907 m_systemBookmarks.append(SystemBookmarkData(QUrl("timeline:/today"),
908 "go-jump-today",
909 I18N_NOOP2("KFile System Bookmarks", "Today")));
910 m_systemBookmarks.append(SystemBookmarkData(QUrl("timeline:/yesterday"),
911 "view-calendar-day",
912 I18N_NOOP2("KFile System Bookmarks", "Yesterday")));
913 m_systemBookmarks.append(SystemBookmarkData(QUrl("timeline:/thismonth"),
914 "view-calendar-month",
915 I18N_NOOP2("KFile System Bookmarks", "This Month")));
916 m_systemBookmarks.append(SystemBookmarkData(QUrl("timeline:/lastmonth"),
917 "view-calendar-month",
918 I18N_NOOP2("KFile System Bookmarks", "Last Month")));
919 m_systemBookmarks.append(SystemBookmarkData(QUrl("search:/documents"),
920 "folder-txt",
921 I18N_NOOP2("KFile System Bookmarks", "Documents")));
922 m_systemBookmarks.append(SystemBookmarkData(QUrl("search:/images"),
923 "folder-image",
924 I18N_NOOP2("KFile System Bookmarks", "Images")));
925 m_systemBookmarks.append(SystemBookmarkData(QUrl("search:/audio"),
926 "folder-sound",
927 I18N_NOOP2("KFile System Bookmarks", "Audio Files")));
928 m_systemBookmarks.append(SystemBookmarkData(QUrl("search:/videos"),
929 "folder-video",
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("[[[[ 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("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("UDI");
1082 const QString udi2 = b2.metaDataItem("UDI");
1083 if (!udi1.isEmpty() && !udi2.isEmpty()) {
1084 return udi1 == udi2;
1085 } else {
1086 return b1.metaDataItem("ID") == b2.metaDataItem("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 = "timeline:/" + timelineDateString(year, month) +
1104 '/' + timelineDateString(year, month, day);
1105 } else if (path.endsWith(QLatin1String("thismonth"))) {
1106 const QDate date = QDate::currentDate();
1107 timelineUrl = "timeline:/" + timelineDateString(date.year(), date.month());
1108 } else if (path.endsWith(QLatin1String("lastmonth"))) {
1109 const QDate date = QDate::currentDate().addMonths(-1);
1110 timelineUrl = "timeline:/" + timelineDateString(date.year(), date.month());
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("Document");
1146 } else if (path.endsWith(QLatin1String("images"))) {
1147 searchUrl = searchUrlForType("Image");
1148 } else if (path.endsWith(QLatin1String("audio"))) {
1149 searchUrl = searchUrlForType("Audio");
1150 } else if (path.endsWith(QLatin1String("videos"))) {
1151 searchUrl = searchUrlForType("Video");
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("File");
1167 query.addType(type);
1168
1169 return query.toSearchUrl();
1170 }
1171 #endif
1172
1173 #ifdef PLACESITEMMODEL_DEBUG
1174 void PlacesItemModel::showModelState()
1175 {
1176 qCDebug(DolphinDebug) << "=================================";
1177 qCDebug(DolphinDebug) << "Model:";
1178 qCDebug(DolphinDebug) << "hidden-index model-index text";
1179 int modelIndex = 0;
1180 for (int i = 0; i < m_bookmarkedItems.count(); ++i) {
1181 if (m_bookmarkedItems[i]) {
1182 qCDebug(DolphinDebug) << i << "(Hidden) " << " " << m_bookmarkedItems[i]->dataValue("text").toString();
1183 } else {
1184 if (item(modelIndex)) {
1185 qCDebug(DolphinDebug) << i << " " << modelIndex << " " << item(modelIndex)->dataValue("text").toString();
1186 } else {
1187 qCDebug(DolphinDebug) << i << " " << modelIndex << " " << "(not available yet)";
1188 }
1189 ++modelIndex;
1190 }
1191 }
1192
1193 qCDebug(DolphinDebug);
1194 qCDebug(DolphinDebug) << "Bookmarks:";
1195
1196 int bookmarkIndex = 0;
1197 KBookmarkGroup root = m_bookmarkManager->root();
1198 KBookmark bookmark = root.first();
1199 while (!bookmark.isNull()) {
1200 const QString udi = bookmark.metaDataItem("UDI");
1201 const QString text = udi.isEmpty() ? bookmark.text() : udi;
1202 if (bookmark.metaDataItem("IsHidden") == QLatin1String("true")) {
1203 qCDebug(DolphinDebug) << bookmarkIndex << "(Hidden)" << text;
1204 } else {
1205 qCDebug(DolphinDebug) << bookmarkIndex << " " << text;
1206 }
1207
1208 bookmark = root.next(bookmark);
1209 ++bookmarkIndex;
1210 }
1211 }
1212 #endif
1213