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