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