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