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