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